{"text":"\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkGLWidget.h\"\n\n#if SK_SUPPORT_GPU\n\nSkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {\n fDebugger = debugger;\n}\n\nSkGLWidget::~SkGLWidget() {\n}\n\nvoid SkGLWidget::setSampleCount(int sampleCount) {\n QGLFormat currentFormat = format();\n currentFormat.setSampleBuffers(sampleCount > 0);\n currentFormat.setSamples(sampleCount);\n setFormat(currentFormat);\n}\n\nvoid SkGLWidget::initializeGL() {\n if (!fCurIntf) {\n fCurIntf.reset(GrGLCreateNativeInterface());\n }\n if (!fCurIntf) {\n return;\n }\n if (!fCurContext) {\n fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));\n }\n if (!fCurContext) {\n return;\n }\n\n \/\/ The call may come multiple times, for example after setSampleCount(). The QGLContext will be\n \/\/ different, but we do not have a mechanism to catch the destroying of QGLContext, so that\n \/\/ proper resource cleanup could be made. Instead, we assume that the underlying GL context\n \/\/ never actually changes. If it would, we could not destroy the resources.\n fGpuDevice.reset(NULL);\n fCanvas.reset(NULL);\n}\n\nvoid SkGLWidget::createRenderTarget() {\n if (!fCurContext) {\n return;\n }\n\n glDisable(GL_SCISSOR_TEST);\n glStencilMask(0xffffffff);\n glClearStencil(0);\n glClear(GL_STENCIL_BUFFER_BIT);\n fCurContext->resetContext();\n\n fGpuDevice.reset(NULL);\n fCanvas.reset(NULL);\n\n GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());\n desc.fOrigin = kBottomLeft_GrSurfaceOrigin;\n SkAutoTUnref curRenderTarget(fCurContext->wrapBackendRenderTarget(desc));\n SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType);\n fGpuDevice.reset(SkGpuDevice::Create(curRenderTarget, &props));\n fCanvas.reset(new SkCanvas(fGpuDevice));\n}\n\nvoid SkGLWidget::resizeGL(int w, int h) {\n SkASSERT(w == this->width() && h == this->height());\n this->createRenderTarget();\n}\n\nvoid SkGLWidget::paintGL() {\n if (!this->isHidden() && fCanvas) {\n fDebugger->draw(fCanvas.get());\n \/\/ TODO(chudy): Implement an optional flush button in Gui.\n fCanvas->flush();\n emit drawComplete();\n }\n}\n\nGrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {\n GrBackendRenderTargetDesc desc;\n desc.fWidth = SkScalarRoundToInt(this->width());\n desc.fHeight = SkScalarRoundToInt(this->height());\n desc.fConfig = kSkia8888_GrPixelConfig;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);\n GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);\n GrGLint buffer;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);\n desc.fRenderTargetHandle = buffer;\n\n return desc;\n}\n\n#endif\ndebugger: Abandon context when Qt changes it without notice\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkGLWidget.h\"\n\n#if SK_SUPPORT_GPU\n\nSkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {\n fDebugger = debugger;\n}\n\nSkGLWidget::~SkGLWidget() {\n}\n\nvoid SkGLWidget::setSampleCount(int sampleCount) {\n QGLFormat currentFormat = format();\n currentFormat.setSampleBuffers(sampleCount > 0);\n currentFormat.setSamples(sampleCount);\n setFormat(currentFormat);\n}\n\nvoid SkGLWidget::initializeGL() {\n if (!fCurIntf) {\n fCurIntf.reset(GrGLCreateNativeInterface());\n }\n if (!fCurIntf) {\n return;\n }\n \/\/ The call may come multiple times, for example after setSampleCount(). The QGLContext will be\n \/\/ different, but we do not have a mechanism to catch the destroying of QGLContext, so that\n \/\/ proper resource cleanup could be made.\n if (fCurContext) {\n fCurContext->abandonContext();\n }\n fGpuDevice.reset(NULL);\n fCanvas.reset(NULL);\n\n fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));\n}\n\nvoid SkGLWidget::createRenderTarget() {\n if (!fCurContext) {\n return;\n }\n\n glDisable(GL_SCISSOR_TEST);\n glStencilMask(0xffffffff);\n glClearStencil(0);\n glClear(GL_STENCIL_BUFFER_BIT);\n fCurContext->resetContext();\n\n fGpuDevice.reset(NULL);\n fCanvas.reset(NULL);\n\n GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());\n desc.fOrigin = kBottomLeft_GrSurfaceOrigin;\n SkAutoTUnref curRenderTarget(fCurContext->wrapBackendRenderTarget(desc));\n SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType);\n fGpuDevice.reset(SkGpuDevice::Create(curRenderTarget, &props));\n fCanvas.reset(new SkCanvas(fGpuDevice));\n}\n\nvoid SkGLWidget::resizeGL(int w, int h) {\n SkASSERT(w == this->width() && h == this->height());\n this->createRenderTarget();\n}\n\nvoid SkGLWidget::paintGL() {\n if (!this->isHidden() && fCanvas) {\n fCurContext->resetContext();\n fDebugger->draw(fCanvas.get());\n \/\/ TODO(chudy): Implement an optional flush button in Gui.\n fCanvas->flush();\n emit drawComplete();\n }\n}\n\nGrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {\n GrBackendRenderTargetDesc desc;\n desc.fWidth = SkScalarRoundToInt(this->width());\n desc.fHeight = SkScalarRoundToInt(this->height());\n desc.fConfig = kSkia8888_GrPixelConfig;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);\n GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);\n GrGLint buffer;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);\n desc.fRenderTargetHandle = buffer;\n\n return desc;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===\/\/\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 utility may be invoked in the following manner:\n\/\/ llvm-as --help - Output information about command line switches\n\/\/ llvm-as [options] - Read LLVM asm from stdin, write bytecode to stdout\n\/\/ llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bytecode\n\/\/ to the x.bc file.\n\/\/ \n\/\/===------------------------------------------------------------------------===\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/Writer.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"Support\/CommandLine.h\"\n#include \"llvm\/System\/Signals.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\n\nstatic cl::opt \nInputFilename(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::opt\nOutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\nstatic cl::opt\nForce(\"f\", cl::desc(\"Overwrite output files\"));\n\nstatic cl::opt\nDumpAsm(\"d\", cl::desc(\"Print assembly as parsed\"), cl::Hidden);\n\nstatic cl::opt\nDisableVerify(\"disable-verify\", cl::Hidden,\n cl::desc(\"Do not run verifier on input LLVM (dangerous!)\"));\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .ll -> .bc assembler\\n\");\n PrintStackTraceOnErrorSignal();\n\n std::ostream *Out = 0;\n try {\n \/\/ Parse the file now...\n std::auto_ptr M(ParseAssemblyFile(InputFilename));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n\n if (!DisableVerify && verifyModule(*M.get())) {\n std::cerr << argv[0]\n << \": assembly parsed, but does not verify as correct!\\n\";\n return 1;\n }\n \n if (DumpAsm) std::cerr << \"Here's the assembly:\\n\" << M.get();\n\n if (OutputFilename != \"\") { \/\/ Specified an output filename?\n if (OutputFilename != \"-\") { \/\/ Not stdout?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str(), std::ios_base::out | \n std::ios_base::trunc | std::ios_base::binary);\n } else { \/\/ Specified stdout\n\tOut = &std::cout; \n }\n } else {\n if (InputFilename == \"-\") {\n\tOutputFilename = \"-\";\n\tOut = &std::cout;\n } else {\n\tstd::string IFN = InputFilename;\n\tint Len = IFN.length();\n\tif (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {\n\t \/\/ Source ends in .ll\n\t OutputFilename = std::string(IFN.begin(), IFN.end()-3);\n } else {\n\t OutputFilename = IFN; \/\/ Append a .bc to it\n\t}\n\tOutputFilename += \".bc\";\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n\n\tOut = new std::ofstream(OutputFilename.c_str(), std::ios_base::out | \n std::ios_base::trunc | std::ios_base::binary);\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n }\n \n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n \n WriteBytecodeToFile(M.get(), *Out);\n } catch (const ParseException &E) {\n std::cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (Out != &std::cout) delete Out;\n return 0;\n}\n\nThere is no reason to abort and print a stack trace if there is a verification error. Just print the message like a good little tool.\/\/===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===\/\/\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 utility may be invoked in the following manner:\n\/\/ llvm-as --help - Output information about command line switches\n\/\/ llvm-as [options] - Read LLVM asm from stdin, write bytecode to stdout\n\/\/ llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bytecode\n\/\/ to the x.bc file.\n\/\/ \n\/\/===------------------------------------------------------------------------===\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/Writer.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"Support\/CommandLine.h\"\n#include \"llvm\/System\/Signals.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\n\nstatic cl::opt \nInputFilename(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::opt\nOutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\nstatic cl::opt\nForce(\"f\", cl::desc(\"Overwrite output files\"));\n\nstatic cl::opt\nDumpAsm(\"d\", cl::desc(\"Print assembly as parsed\"), cl::Hidden);\n\nstatic cl::opt\nDisableVerify(\"disable-verify\", cl::Hidden,\n cl::desc(\"Do not run verifier on input LLVM (dangerous!)\"));\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .ll -> .bc assembler\\n\");\n PrintStackTraceOnErrorSignal();\n\n std::ostream *Out = 0;\n try {\n \/\/ Parse the file now...\n std::auto_ptr M(ParseAssemblyFile(InputFilename));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n\n if (!DisableVerify && verifyModule(*M.get(), PrintMessageAction)) {\n std::cerr << argv[0]\n << \": assembly parsed, but does not verify as correct!\\n\";\n return 1;\n }\n \n if (DumpAsm) std::cerr << \"Here's the assembly:\\n\" << M.get();\n\n if (OutputFilename != \"\") { \/\/ Specified an output filename?\n if (OutputFilename != \"-\") { \/\/ Not stdout?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str(), std::ios_base::out | \n std::ios_base::trunc | std::ios_base::binary);\n } else { \/\/ Specified stdout\n\tOut = &std::cout; \n }\n } else {\n if (InputFilename == \"-\") {\n\tOutputFilename = \"-\";\n\tOut = &std::cout;\n } else {\n\tstd::string IFN = InputFilename;\n\tint Len = IFN.length();\n\tif (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {\n\t \/\/ Source ends in .ll\n\t OutputFilename = std::string(IFN.begin(), IFN.end()-3);\n } else {\n\t OutputFilename = IFN; \/\/ Append a .bc to it\n\t}\n\tOutputFilename += \".bc\";\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n\n\tOut = new std::ofstream(OutputFilename.c_str(), std::ios_base::out | \n std::ios_base::trunc | std::ios_base::binary);\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n }\n \n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n \n WriteBytecodeToFile(M.get(), *Out);\n } catch (const ParseException &E) {\n std::cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (Out != &std::cout) delete Out;\n return 0;\n}\n\n<|endoftext|>"} {"text":"mipgen: Disambiguated string with std:: prefix. (#741)<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char** argv)\n{\n\tstd::vector gccArgs;\n\tstd::string source;\n\tstd::string outfile;\n\n\tif(argc <= 1)\n\t{\n\t\treturn system(\"g++\");\n\t}\n\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\tif(strstr(argv[i], \"-gencode\")\n\t\t\t|| strstr(argv[i], \"-X\")\n\t\t\t|| strstr(argv[i], \"-arch\"))\n\t\t\tcontinue;\n\n\t\tif(!strcmp(\"-o\", argv[i]) && i < argc - 1)\n\t\t{\n\t\t\toutfile = argv[++i];\n\t\t\tcontinue;\n\t\t}\n\t\telse if(!strcmp(\"-isystem\", argv[i]))\n\t\t{\n\t\t\tgccArgs.push_back(\"-I\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tgccArgs.push_back(argv[i]);\n\t}\n\n\tstd::stringstream args;\n\tif(gccArgs.empty())\n\t{\n\t\treturn 1;\n\t}\n\n\tsource = gccArgs.back();\n\tgccArgs.pop_back();\n\n\tfor(auto& s : gccArgs)\n\t\targs << \" \" << s;\n\n\targs << \" -I\/usr\/include -I\/usr\/include\/cudalibre -lOpenCL -Wl,-rpath=. -lclruntime\";\n\n\tstd::string culccArgs = \"culcc \";\n\n\t\/\/ produces something like \"culcc -o -- \"\n\tculccArgs += source + \" -o \" + source + \".cpp -- \" + args.str();\n\n\tif(system(culccArgs.c_str()))\n\t{\n\t\tstd::cerr << \"Could not preprocess CUDA file!\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Add source file here so it does not interfere with the culccArgs earlier\n\n\tif(!outfile.empty())\n\t\targs << \" -o \" << outfile;\n\n\targs << \" \" << source << \".cpp\";\n\treturn system((\"g++ \" + args.str()).c_str());\n}* Improved culccd argument handling#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/ Some default flags so gcc and culcc can find headers and libraries\nconst std::string g_defaultFlags =\n\"-I\/usr\/include -I\/usr\/include\/cudalibre -lOpenCL -Wl,-rpath=. -lclruntime\";\n\n\/\/ Switch-case on strings\n#define SWITCH(x) { auto value = (x); if(false) {\n#define CASE(x) } else if(std::regex_match(value, std::regex(x))) {\n#define DEFAULT } else {\n#define IGNORE(x) CASE(x){}\n#define HCTIWS }}\n\nvoid usage(const char* name)\n{\n\tstd::cout << name << \" [options] \" << std::endl;\n\tstd::cout << \"\\t\" << std::endl;\n}\n\nbool isArgnameEq(const char* name, const char* str)\n{\n\tstd::regex e(name);\n\treturn !strcmp(name, str) || (*str == '-' && !strcmp(name, str+1));\n}\n\nstruct Arguments\n{\n\tstd::string output;\n\tstd::string input;\n\tbool hasC;\n\tbool verbose;\n};\n\nvoid parseArgs(int argc, \n\t char** argv,\n\t std::stringstream& culccArgs,\n\t std::stringstream& gccArgs,\n\t Arguments& args)\n{\n\targs.hasC = false;\n\targs.verbose = false;\n\t\n\tfor(size_t i = 1; i < argc - 1; i++)\n\t{\n\t\tchar* arg = argv[i];\n\t\t\n\t\tSWITCH(arg)\n\t\t\tIGNORE(\"-?-cuda\")\n\t\t\tIGNORE(\"-?-gencode=.*\")\n\t\t\tIGNORE(\"-X.*\")\n\t\t\tIGNORE(\"-arch.*\")\n\t\t\tCASE(\"-isystem.*\")\n\t\t\t{\n\t\t\t\tgccArgs << \"-I\" << argv[++i] << \" \";\n\t\t\t}\n\t\t\tCASE(\"-c|-?-compile\")\n\t\t\t{\n\t\t\t\targs.hasC = true;\n\t\t\t}\n\t\t\tCASE(\"-o\")\n\t\t\t{\n\t\t\t\tif(++i < argc)\n\t\t\t\t{\n\t\t\t\t\targs.output = argv[i];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"-o expects an argument!\" << std::endl;\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tCASE(\"-v|-?-verbose\")\n\t\t\t{\n\t\t\t\targs.verbose = true;\n\t\t\t}\n\t\t\tDEFAULT \n\t\t\t{\n\t\t\t\tgccArgs << arg << \" \";\n\t\t\t}\n\t\tHCTIWS\n\t}\n\t\n\targs.input = argv[argc - 1];\n\t\n\tgccArgs << g_defaultFlags;\n\tculccArgs << \" -- \" << gccArgs.str();\n}\n\nint main(int argc, char** argv)\n{\n\tif (argc <= 1)\n\t{\n\t\tusage(argv[0]);\n\t\treturn 0;\n\t}\n\n\tstd::stringstream culccArgs, gccArgs;\n\tArguments args;\n\tparseArgs(argc, argv, culccArgs, gccArgs, args);\n\t\n\t\/\/ produces something like \"culcc -o -- \"\n\tstd::string command = \"culcc \" + args.input + \" -o \" + args.input + \".cpp\" + culccArgs.str();\n\tif(args.verbose)\n\t\tstd::cout << command << std::endl;\n\t\n\tif (system(command.c_str()))\n\t{\n\t\tstd::cerr << \"Could not preprocess CUDA file!\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Add source file here so it does not interfere with the culccArgs earlier\n\n\tif (!args.output.empty())\n\t\tgccArgs << \" -o \" << args.output;\n\n\tgccArgs << \" \" << (args.hasC ? \"-c \" : \"\") << args.input << \".cpp\";\n\t\n\tcommand = \"g++ \" + gccArgs.str();\n\tif(args.verbose)\n\t\tstd::cout << command << std::endl;\n\t\t\n\treturn system(command.c_str());\n}\n<|endoftext|>"} {"text":"\/\/ sg_path.cxx -- routines to abstract out path separator differences\n\/\/ between MacOS and the rest of the world\n\/\/\n\/\/ Written by Curtis L. Olson, started April 1999.\n\/\/\n\/\/ Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Library General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\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\/\/ Library General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Library General Public\n\/\/ License along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n\/\/ Boston, MA 02111-1307, USA.\n\/\/\n\/\/ $Id$\n\n\n#include \n#include \n\n#include \"sg_path.hxx\"\n\n\n\/\/ If Unix, replace all \":\" with \"\/\". If MacOS, replace all \"\/\" with\n\/\/ \":\" it should go without saying that neither of these characters\n\/\/ should be used in file or directory names. In windoze, allow the\n\/\/ second character to be a \":\" for things like c:\\foo\\bar\n\nvoid\nSGPath::fix()\n{\n for ( string::size_type i = 0; i < path.size(); ++i ) {\n#if defined( WIN32 )\n\t\/\/ for windoze, don't replace the \":\" for the second character\n\tif ( i == 1 ) {\n\t continue;\n\t}\n#endif\n\tif ( path[i] == SG_BAD_PATH_SEP ) {\n\t path[i] = SG_PATH_SEP;\n\t}\n }\n}\n\n\n\/\/ default constructor\nSGPath::SGPath()\n : path(\"\")\n{\n}\n\n\n\/\/ create a path based on \"path\"\nSGPath::SGPath( const std::string& p )\n : path(p)\n{\n fix();\n}\n\n\n\/\/ destructor\nSGPath::~SGPath() {\n}\n\n\n\/\/ set path\nvoid SGPath::set( const string& p ) {\n path = p;\n fix();\n}\n\n\n\/\/ append another piece to the existing path\nvoid SGPath::append( const string& p ) {\n if ( path.size() == 0 ) {\n\tpath = p;\n } else {\n\tif ( p[0] != SG_PATH_SEP ) {\n\t path += SG_PATH_SEP;\n\t}\n\tpath += p;\n }\n fix();\n}\n\n\n\/\/ concatenate a string to the end of the path without inserting a\n\/\/ path separator\nvoid SGPath::concat( const string& p ) {\n if ( path.size() == 0 ) {\n\tpath = p;\n } else {\n\tpath += p;\n }\n fix();\n}\n\n\n\/\/ get the directory part of the path.\nstring SGPath::dir() {\n int index = path.rfind(SG_PATH_SEP);\n if (index >= 0) {\n\treturn path.substr(0, index);\n } else {\n\treturn \"\";\n }\n}\n\nbool SGPath::exists() const {\n FILE* fp = fopen( path.c_str(), \"r\");\n if (fp == 0) {\n\treturn false;\n }\n fclose(fp);\n return true;\n}\nOops, missed this the first time.\/\/ sg_path.cxx -- routines to abstract out path separator differences\n\/\/ between MacOS and the rest of the world\n\/\/\n\/\/ Written by Curtis L. Olson, started April 1999.\n\/\/\n\/\/ Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Library General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\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\/\/ Library General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Library General Public\n\/\/ License along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n\/\/ Boston, MA 02111-1307, USA.\n\/\/\n\/\/ $Id$\n\n\n#include \n#include \n\n#include \"sg_path.hxx\"\n\n\n\/\/ If Unix, replace all \":\" with \"\/\". If MacOS, replace all \"\/\" with\n\/\/ \":\" it should go without saying that neither of these characters\n\/\/ should be used in file or directory names. In windoze, allow the\n\/\/ second character to be a \":\" for things like c:\\foo\\bar\n\nvoid\nSGPath::fix()\n{\n for ( string::size_type i = 0; i < path.size(); ++i ) {\n#if defined( WIN32 )\n\t\/\/ for windoze, don't replace the \":\" for the second character\n\tif ( i == 1 ) {\n\t continue;\n\t}\n#endif\n\tif ( path[i] == SG_BAD_PATH_SEP ) {\n\t path[i] = SG_PATH_SEP;\n\t}\n }\n}\n\n\n\/\/ default constructor\nSGPath::SGPath()\n : path(\"\")\n{\n}\n\n\n\/\/ create a path based on \"path\"\nSGPath::SGPath( const std::string& p )\n : path(p)\n{\n fix();\n}\n\n\n\/\/ destructor\nSGPath::~SGPath() {\n}\n\n\n\/\/ set path\nvoid SGPath::set( const string& p ) {\n path = p;\n fix();\n}\n\n\n\/\/ append another piece to the existing path\nvoid SGPath::append( const string& p ) {\n if ( path.size() == 0 ) {\n\tpath = p;\n } else {\n\tif ( p[0] != SG_PATH_SEP ) {\n\t path += SG_PATH_SEP;\n\t}\n\tpath += p;\n }\n fix();\n}\n\n\n\/\/ concatenate a string to the end of the path without inserting a\n\/\/ path separator\nvoid SGPath::concat( const string& p ) {\n if ( path.size() == 0 ) {\n\tpath = p;\n } else {\n\tpath += p;\n }\n fix();\n}\n\n\n\/\/ get the directory part of the path.\nstring SGPath::dir() {\n int index = path.rfind(SG_PATH_SEP);\n if (index >= 0) {\n\treturn path.substr(0, index);\n } else {\n\treturn \"\";\n }\n}\n\nstring SGPath::filename() {\n int index = path.rfind(SG_PATH_SEP);\n if (index < 0) index = 0;\n return path.substr(index);\n}\n\nbool SGPath::exists() const {\n FILE* fp = fopen( path.c_str(), \"r\");\n if (fp == 0) {\n\treturn false;\n }\n fclose(fp);\n return true;\n}\n<|endoftext|>"} {"text":"\/\/===----------------------- LSUnit.cpp --------------------------*- C++-*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ A Load-Store Unit for the llvm-mca tool.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LSUnit.h\"\n#include \"Instruction.h\"\n\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"llvm-mca\"\n\nnamespace mca {\n\n#ifndef NDEBUG\nvoid LSUnit::dump() const {\n dbgs() << \"[LSUnit] LQ_Size = \" << LQ_Size << '\\n';\n dbgs() << \"[LSUnit] SQ_Size = \" << SQ_Size << '\\n';\n dbgs() << \"[LSUnit] NextLQSlotIdx = \" << LoadQueue.size() << '\\n';\n dbgs() << \"[LSUnit] NextSQSlotIdx = \" << StoreQueue.size() << '\\n';\n}\n#endif\n\nvoid LSUnit::assignLQSlot(unsigned Index) {\n assert(!isLQFull());\n assert(LoadQueue.count(Index) == 0);\n\n LLVM_DEBUG(dbgs() << \"[LSUnit] - AssignLQSlot \\n\");\n LoadQueue.insert(Index);\n}\n\nvoid LSUnit::assignSQSlot(unsigned Index) {\n assert(!isSQFull());\n assert(StoreQueue.count(Index) == 0);\n\n LLVM_DEBUG(dbgs() << \"[LSUnit] - AssignSQSlot \\n\");\n StoreQueue.insert(Index);\n}\n\nbool LSUnit::reserve(const InstRef &IR) {\n const InstrDesc Desc = IR.getInstruction()->getDesc();\n unsigned MayLoad = Desc.MayLoad;\n unsigned MayStore = Desc.MayStore;\n unsigned IsMemBarrier = Desc.HasSideEffects;\n if (!MayLoad && !MayStore)\n return false;\n\n const unsigned Index = IR.getSourceIndex();\n if (MayLoad) {\n if (IsMemBarrier)\n LoadBarriers.insert(Index);\n assignLQSlot(Index);\n }\n if (MayStore) {\n if (IsMemBarrier)\n StoreBarriers.insert(Index);\n assignSQSlot(Index);\n }\n return true;\n}\n\nbool LSUnit::isReady(const InstRef &IR) const {\n const unsigned Index = IR.getSourceIndex();\n bool IsALoad = LoadQueue.count(Index) != 0;\n bool IsAStore = StoreQueue.count(Index) != 0;\n assert((IsALoad || IsAStore) && \"Instruction is not in queue!\");\n\n if (IsALoad && !LoadBarriers.empty()) {\n unsigned LoadBarrierIndex = *LoadBarriers.begin();\n if (Index > LoadBarrierIndex)\n return false;\n if (Index == LoadBarrierIndex && Index != *LoadQueue.begin())\n return false;\n }\n\n if (IsAStore && !StoreBarriers.empty()) {\n unsigned StoreBarrierIndex = *StoreBarriers.begin();\n if (Index > StoreBarrierIndex)\n return false;\n if (Index == StoreBarrierIndex && Index != *StoreQueue.begin())\n return false;\n }\n\n if (NoAlias && IsALoad)\n return true;\n\n if (StoreQueue.size()) {\n \/\/ Check if this memory operation is younger than the older store.\n if (Index > *StoreQueue.begin())\n return false;\n }\n\n \/\/ Okay, we are older than the oldest store in the queue.\n \/\/ If there are no pending loads, then we can say for sure that this\n \/\/ instruction is ready.\n if (isLQEmpty())\n return true;\n\n \/\/ Check if there are no older loads.\n if (Index <= *LoadQueue.begin())\n return true;\n\n \/\/ There is at least one younger load.\n return !IsAStore;\n}\n\nvoid LSUnit::onInstructionExecuted(const InstRef &IR) {\n const unsigned Index = IR.getSourceIndex();\n std::set::iterator it = LoadQueue.find(Index);\n if (it != LoadQueue.end()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the load queue.\\n\");\n LoadQueue.erase(it);\n }\n\n it = StoreQueue.find(Index);\n if (it != StoreQueue.end()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the store queue.\\n\");\n StoreQueue.erase(it);\n }\n\n if (!StoreBarriers.empty() && Index == *StoreBarriers.begin()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the set of store barriers.\\n\");\n StoreBarriers.erase(StoreBarriers.begin());\n }\n if (!LoadBarriers.empty() && Index == *LoadBarriers.begin()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the set of load barriers.\\n\");\n LoadBarriers.erase(LoadBarriers.begin());\n }\n}\n} \/\/ namespace mca\n[MCA] Avoid an InstrDesc copy in mca::LSUnit::reserve.\/\/===----------------------- LSUnit.cpp --------------------------*- C++-*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ A Load-Store Unit for the llvm-mca tool.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LSUnit.h\"\n#include \"Instruction.h\"\n\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"llvm-mca\"\n\nnamespace mca {\n\n#ifndef NDEBUG\nvoid LSUnit::dump() const {\n dbgs() << \"[LSUnit] LQ_Size = \" << LQ_Size << '\\n';\n dbgs() << \"[LSUnit] SQ_Size = \" << SQ_Size << '\\n';\n dbgs() << \"[LSUnit] NextLQSlotIdx = \" << LoadQueue.size() << '\\n';\n dbgs() << \"[LSUnit] NextSQSlotIdx = \" << StoreQueue.size() << '\\n';\n}\n#endif\n\nvoid LSUnit::assignLQSlot(unsigned Index) {\n assert(!isLQFull());\n assert(LoadQueue.count(Index) == 0);\n\n LLVM_DEBUG(dbgs() << \"[LSUnit] - AssignLQSlot \\n\");\n LoadQueue.insert(Index);\n}\n\nvoid LSUnit::assignSQSlot(unsigned Index) {\n assert(!isSQFull());\n assert(StoreQueue.count(Index) == 0);\n\n LLVM_DEBUG(dbgs() << \"[LSUnit] - AssignSQSlot \\n\");\n StoreQueue.insert(Index);\n}\n\nbool LSUnit::reserve(const InstRef &IR) {\n const InstrDesc &Desc = IR.getInstruction()->getDesc();\n unsigned MayLoad = Desc.MayLoad;\n unsigned MayStore = Desc.MayStore;\n unsigned IsMemBarrier = Desc.HasSideEffects;\n if (!MayLoad && !MayStore)\n return false;\n\n const unsigned Index = IR.getSourceIndex();\n if (MayLoad) {\n if (IsMemBarrier)\n LoadBarriers.insert(Index);\n assignLQSlot(Index);\n }\n if (MayStore) {\n if (IsMemBarrier)\n StoreBarriers.insert(Index);\n assignSQSlot(Index);\n }\n return true;\n}\n\nbool LSUnit::isReady(const InstRef &IR) const {\n const unsigned Index = IR.getSourceIndex();\n bool IsALoad = LoadQueue.count(Index) != 0;\n bool IsAStore = StoreQueue.count(Index) != 0;\n assert((IsALoad || IsAStore) && \"Instruction is not in queue!\");\n\n if (IsALoad && !LoadBarriers.empty()) {\n unsigned LoadBarrierIndex = *LoadBarriers.begin();\n if (Index > LoadBarrierIndex)\n return false;\n if (Index == LoadBarrierIndex && Index != *LoadQueue.begin())\n return false;\n }\n\n if (IsAStore && !StoreBarriers.empty()) {\n unsigned StoreBarrierIndex = *StoreBarriers.begin();\n if (Index > StoreBarrierIndex)\n return false;\n if (Index == StoreBarrierIndex && Index != *StoreQueue.begin())\n return false;\n }\n\n if (NoAlias && IsALoad)\n return true;\n\n if (StoreQueue.size()) {\n \/\/ Check if this memory operation is younger than the older store.\n if (Index > *StoreQueue.begin())\n return false;\n }\n\n \/\/ Okay, we are older than the oldest store in the queue.\n \/\/ If there are no pending loads, then we can say for sure that this\n \/\/ instruction is ready.\n if (isLQEmpty())\n return true;\n\n \/\/ Check if there are no older loads.\n if (Index <= *LoadQueue.begin())\n return true;\n\n \/\/ There is at least one younger load.\n return !IsAStore;\n}\n\nvoid LSUnit::onInstructionExecuted(const InstRef &IR) {\n const unsigned Index = IR.getSourceIndex();\n std::set::iterator it = LoadQueue.find(Index);\n if (it != LoadQueue.end()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the load queue.\\n\");\n LoadQueue.erase(it);\n }\n\n it = StoreQueue.find(Index);\n if (it != StoreQueue.end()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the store queue.\\n\");\n StoreQueue.erase(it);\n }\n\n if (!StoreBarriers.empty() && Index == *StoreBarriers.begin()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the set of store barriers.\\n\");\n StoreBarriers.erase(StoreBarriers.begin());\n }\n if (!LoadBarriers.empty() && Index == *LoadBarriers.begin()) {\n LLVM_DEBUG(dbgs() << \"[LSUnit]: Instruction idx=\" << Index\n << \" has been removed from the set of load barriers.\\n\");\n LoadBarriers.erase(LoadBarriers.begin());\n }\n}\n} \/\/ namespace mca\n<|endoftext|>"} {"text":"\/\/===-- Immediate.cpp - the swift immediate mode --------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the implementation of the swift interpreter, which takes a\n\/\/ TranslationUnit and JITs it.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Immediate.h\"\n#include \"Frontend.h\"\n#include \"swift\/Subsystems.h\"\n#include \"swift\/IRGen\/Options.h\"\n#include \"swift\/Parse\/Lexer.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Component.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/Diagnostics.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/Stmt.h\"\n#include \"swift\/Basic\/DiagnosticConsumer.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Process.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Linker.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n\n#include \n#include \n\nstatic void LoadSwiftRuntime() {\n \/\/ FIXME: Need error-checking.\n llvm::sys::Path LibPath =\n llvm::sys::Path::GetMainExecutable(0, (void*)&swift::RunImmediately);\n LibPath.eraseComponent();\n LibPath.eraseComponent();\n LibPath.appendComponent(\"lib\");\n LibPath.appendComponent(\"libswift_abi.dylib\");\n dlopen(LibPath.c_str(), 0);\n}\n\nvoid swift::RunImmediately(TranslationUnit *TU) {\n ASTContext &Context = TU->Ctx;\n irgen::Options Options;\n Options.OutputFilename = \"\";\n Options.Triple = llvm::sys::getDefaultTargetTriple();\n Options.OptLevel = 0;\n Options.OutputKind = irgen::OutputKind::Module;\n\n \/\/ IRGen the main module.\n llvm::LLVMContext LLVMContext;\n llvm::Module Module(TU->Name.str(), LLVMContext);\n performCaptureAnalysis(TU);\n performIRGeneration(Options, &Module, TU);\n\n if (Context.hadError())\n return;\n\n llvm::SmallPtrSet ImportedModules;\n llvm::SmallVector InitFuncs;\n \/\/ IRGen the modules this module depends on.\n for (auto ModPair : TU->getImportedModules()) {\n if (isa(ModPair.second))\n continue;\n\n TranslationUnit *SubTU = cast(ModPair.second);\n if (!ImportedModules.insert(SubTU))\n continue;\n\n \/\/ FIXME: Need to check whether this is actually safe in general.\n llvm::Module SubModule(SubTU->Name.str(), LLVMContext);\n performCaptureAnalysis(SubTU);\n performIRGeneration(Options, &SubModule, SubTU);\n\n if (Context.hadError())\n return;\n\n std::string ErrorMessage;\n if (llvm::Linker::LinkModules(&Module, &SubModule,\n llvm::Linker::DestroySource,\n &ErrorMessage)) {\n llvm::errs() << \"Error linking swift modules\\n\";\n llvm::errs() << ErrorMessage << \"\\n\";\n return;\n }\n\n \/\/ FIXME: This is an ugly hack; need to figure out how this should\n \/\/ actually work.\n SmallVector NameBuf;\n StringRef InitFnName = (SubTU->Name.str() + \".init\").toStringRef(NameBuf);\n llvm::Function *InitFn = Module.getFunction(InitFnName);\n if (InitFn)\n InitFuncs.push_back(InitFn);\n }\n\n LoadSwiftRuntime();\n\n \/\/ Run the generated program.\n\n llvm::EngineBuilder builder(&Module);\n std::string ErrorMsg;\n builder.setErrorStr(&ErrorMsg);\n builder.setEngineKind(llvm::EngineKind::JIT);\n\n llvm::ExecutionEngine *EE = builder.create();\n for (auto InitFn : InitFuncs)\n EE->runFunctionAsMain(InitFn, std::vector(), 0);\n\n llvm::Function *EntryFn = Module.getFunction(\"main\");\n EE->runFunctionAsMain(EntryFn, std::vector(), 0);\n}\n\nstruct EditLineWrapper {\n EditLine *e;\n size_t PromptContinuationLevel;\n \n llvm::SmallString<80> PromptString;\n\n EditLineWrapper() {\n e = el_init(\"swift\", stdin, stdout, stderr);\n PromptContinuationLevel = 0;\n el_set(e, EL_EDITOR, \"emacs\");\n el_set(e, EL_PROMPT, PromptFn);\n el_set(e, EL_CLIENTDATA, (void*)this);\n }\n \n static char *PromptFn(EditLine *e) {\n void* clientdata;\n el_get(e, EL_CLIENTDATA, &clientdata);\n return (char*)((EditLineWrapper*)clientdata)->getPrompt();\n }\n \n const char *getPrompt() {\n if (PromptContinuationLevel == 0)\n return \"swift> \";\n \n PromptString = \"swift| \";\n PromptString.append(2*PromptContinuationLevel, ' ');\n return PromptString.c_str();\n };\n \n\n ~EditLineWrapper() {\n el_end(e);\n }\n operator EditLine*() { return e; }\n};\n\nvoid swift::REPL(ASTContext &Context) {\n if (llvm::sys::Process::FileDescriptorIsDisplayed(2))\n llvm::errs() << \"Welcome to swift. Type 'help' for assistance.\\n\";\n \n \/\/ FIXME: We should do something a bit more elaborate than\n \/\/ \"allocate a 1MB buffer and hope it's enough\".\n llvm::MemoryBuffer *Buffer =\n llvm::MemoryBuffer::getNewMemBuffer(1 << 20, \"\");\n\n Component *Comp = new (Context.Allocate(1)) Component();\n unsigned BufferID =\n Context.SourceMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());\n Identifier ID = Context.getIdentifier(\"REPL\");\n TranslationUnit *TU = new (Context) TranslationUnit(ID, Comp, Context,\n \/*IsMainModule=*\/true,\n \/*IsReplModule=*\/true);\n\n llvm::SmallPtrSet ImportedModules;\n llvm::LLVMContext LLVMContext;\n llvm::Module Module(\"REPL\", LLVMContext);\n std::string ErrorMessage;\n\n LoadSwiftRuntime();\n\n llvm::EngineBuilder builder(&Module);\n std::string ErrorMsg;\n builder.setErrorStr(&ErrorMsg);\n builder.setEngineKind(llvm::EngineKind::JIT);\n llvm::ExecutionEngine *EE = builder.create();\n\n irgen::Options Options;\n Options.OutputFilename = \"\";\n Options.Triple = llvm::sys::getDefaultTargetTriple();\n Options.OptLevel = 0;\n Options.OutputKind = irgen::OutputKind::Module;\n Options.IsREPL = true;\n\n EditLineWrapper e;\n\n char* CurBuffer = const_cast(Buffer->getBufferStart());\n unsigned CurBufferOffset = 0;\n unsigned CurBufferEndOffset = 0;\n \n unsigned CurTUElem = 0;\n unsigned BraceCount = 0;\n unsigned CurChunkLines = 0;\n\n while (1) {\n \/\/ Read one line.\n e.PromptContinuationLevel = BraceCount;\n int LineCount;\n const char* Line = el_gets(e, &LineCount);\n if (!Line)\n return;\n\n strcpy(CurBuffer, Line);\n CurBuffer += strlen(Line);\n CurBufferEndOffset += strlen(Line);\n ++CurChunkLines;\n\n \/\/ If we detect unbalanced braces, keep reading before we start parsing.\n Lexer L(Line, Context.SourceMgr, nullptr);\n Token Tok;\n do {\n L.lex(Tok);\n if (Tok.is(tok::l_brace))\n ++BraceCount;\n else if (Tok.is(tok::r_brace) && BraceCount > 0)\n --BraceCount;\n } while (!Tok.is(tok::eof));\n\n if (BraceCount)\n continue;\n\n \/\/ Parse the current line(s).\n bool ShouldRun =\n swift::appendToMainTranslationUnit(TU, BufferID, CurTUElem,\n CurBufferOffset,\n CurBufferEndOffset);\n\n if (Context.hadError()) {\n Context.Diags.resetHadAnyError();\n while (TU->Decls.size() > CurTUElem)\n TU->Decls.pop_back();\n TU->clearUnresolvedIdentifierTypes();\n\n \/\/ FIXME: Handling of \"import\" declarations? Is there any other\n \/\/ state which needs to be reset?\n\n if (CurChunkLines > 1)\n llvm::errs() << \"(discarded \" << CurChunkLines << \" lines)\\n\";\n CurChunkLines = 0;\n continue;\n }\n\n \/\/ If we didn't see an expression, statement, or decl which might have\n \/\/ side-effects, keep reading.\n if (!ShouldRun)\n continue;\n\n \/\/ IRGen the current line(s).\n llvm::Module LineModule(\"REPLLine\", LLVMContext);\n performCaptureAnalysis(TU, CurTUElem);\n performIRGeneration(Options, &LineModule, TU, CurTUElem);\n\n if (Context.hadError())\n return;\n\n CurTUElem = TU->Decls.size();\n CurChunkLines = 0;\n\n if (llvm::Linker::LinkModules(&Module, &LineModule,\n llvm::Linker::DestroySource,\n &ErrorMessage)) {\n llvm::errs() << \"Error linking swift modules\\n\";\n llvm::errs() << ErrorMessage << \"\\n\";\n return;\n }\n\n \/\/ IRGen the modules this module depends on.\n llvm::SmallVector InitFuncs;\n for (auto ModPair : TU->getImportedModules()) {\n if (isa(ModPair.second))\n continue;\n\n TranslationUnit *SubTU = cast(ModPair.second);\n if (!ImportedModules.insert(SubTU))\n continue;\n\n \/\/ FIXME: Need to check whether this is actually safe in general.\n llvm::Module SubModule(SubTU->Name.str(), LLVMContext);\n performCaptureAnalysis(SubTU);\n performIRGeneration(Options, &SubModule, SubTU);\n\n if (Context.hadError())\n return;\n\n if (llvm::Linker::LinkModules(&Module, &SubModule,\n llvm::Linker::DestroySource,\n &ErrorMessage)) {\n llvm::errs() << \"Error linking swift modules\\n\";\n llvm::errs() << ErrorMessage << \"\\n\";\n return;\n }\n\n \/\/ FIXME: This is an ugly hack; need to figure out how this should\n \/\/ actually work.\n SmallVector NameBuf;\n StringRef InitFnName = (SubTU->Name.str() + \".init\").toStringRef(NameBuf);\n llvm::Function *InitFn = Module.getFunction(InitFnName);\n if (InitFn)\n InitFuncs.push_back(InitFn);\n }\n\n for (auto InitFn : InitFuncs)\n EE->runFunctionAsMain(InitFn, std::vector(), 0);\n\n \/\/ FIXME: The way we do this is really ugly... we should be able to\n \/\/ improve this.\n llvm::Function *EntryFn = Module.getFunction(\"main\");\n EE->runFunctionAsMain(EntryFn, std::vector(), 0);\n EE->freeMachineCodeForFunction(EntryFn);\n EntryFn->eraseFromParent();\n }\n}\n\n\n\/\/ FIXME: We shouldn't be writing implemenetations for functions in the swift\n\/\/ module in C, and this isn't really an ideal place to put those\n\/\/ implementations.\nextern \"C\" void _TSs5printFT3valNSs5Int64_T_(int64_t l) {\n printf(\"%lld\", l);\n}\n\nextern \"C\" void _TSs5printFT3valNSs6Double_T_(double l) {\n printf(\"%f\", l);\n}\n\nextern \"C\" void _TSs9printCharFT9characterNSs5Int64_T_(int64_t l) {\n printf(\"%c\", (char)l);\n}\n\nextern \"C\" void _TSs5printFT3valNSs6String_T_(char* l) {\n printf(\"%s\", l);\n}\n\n\/\/ func Strlen(value : Builtin.RawPointer) -> Int\nextern \"C\" int64_t _TSs6StrlenFT5valuep_NSs5Int64(char* s) {\n return strlen(s);\n}\n\n\/\/ func [infix_left=190] + (lhs : String,\n\/\/ rhs : String) -> String\nextern \"C\" char* _TSsop1pFT3lhsNSs6String3rhsS__S_(char* lhs, char* rhs) {\n size_t ls = strlen(lhs);\n size_t rs = strlen(rhs);\n char* s = (char*)malloc(ls+rs+1);\n memcpy(s, lhs, ls);\n strcpy(s+ls, rhs);\n return s;\n}\n\nextern \"C\" bool _TNSs4Bool13getLogicValuefRS_FT_i1(bool* b) {\n return *b;\n}\n\nextern \"C\" void _TSs4exitFT8exitCodeNSs5Int64_T_(int64_t l) {\n exit(l);\n}\nadd a new UnsafePointerInt8 type, use it to implement String.size in swift instead of in C++.\/\/===-- Immediate.cpp - the swift immediate mode --------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the implementation of the swift interpreter, which takes a\n\/\/ TranslationUnit and JITs it.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Immediate.h\"\n#include \"Frontend.h\"\n#include \"swift\/Subsystems.h\"\n#include \"swift\/IRGen\/Options.h\"\n#include \"swift\/Parse\/Lexer.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Component.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/Diagnostics.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/Stmt.h\"\n#include \"swift\/Basic\/DiagnosticConsumer.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Process.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Linker.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n\n#include \n#include \n\nstatic void LoadSwiftRuntime() {\n \/\/ FIXME: Need error-checking.\n llvm::sys::Path LibPath =\n llvm::sys::Path::GetMainExecutable(0, (void*)&swift::RunImmediately);\n LibPath.eraseComponent();\n LibPath.eraseComponent();\n LibPath.appendComponent(\"lib\");\n LibPath.appendComponent(\"libswift_abi.dylib\");\n dlopen(LibPath.c_str(), 0);\n}\n\nvoid swift::RunImmediately(TranslationUnit *TU) {\n ASTContext &Context = TU->Ctx;\n irgen::Options Options;\n Options.OutputFilename = \"\";\n Options.Triple = llvm::sys::getDefaultTargetTriple();\n Options.OptLevel = 0;\n Options.OutputKind = irgen::OutputKind::Module;\n\n \/\/ IRGen the main module.\n llvm::LLVMContext LLVMContext;\n llvm::Module Module(TU->Name.str(), LLVMContext);\n performCaptureAnalysis(TU);\n performIRGeneration(Options, &Module, TU);\n\n if (Context.hadError())\n return;\n\n llvm::SmallPtrSet ImportedModules;\n llvm::SmallVector InitFuncs;\n \/\/ IRGen the modules this module depends on.\n for (auto ModPair : TU->getImportedModules()) {\n if (isa(ModPair.second))\n continue;\n\n TranslationUnit *SubTU = cast(ModPair.second);\n if (!ImportedModules.insert(SubTU))\n continue;\n\n \/\/ FIXME: Need to check whether this is actually safe in general.\n llvm::Module SubModule(SubTU->Name.str(), LLVMContext);\n performCaptureAnalysis(SubTU);\n performIRGeneration(Options, &SubModule, SubTU);\n\n if (Context.hadError())\n return;\n\n std::string ErrorMessage;\n if (llvm::Linker::LinkModules(&Module, &SubModule,\n llvm::Linker::DestroySource,\n &ErrorMessage)) {\n llvm::errs() << \"Error linking swift modules\\n\";\n llvm::errs() << ErrorMessage << \"\\n\";\n return;\n }\n\n \/\/ FIXME: This is an ugly hack; need to figure out how this should\n \/\/ actually work.\n SmallVector NameBuf;\n StringRef InitFnName = (SubTU->Name.str() + \".init\").toStringRef(NameBuf);\n llvm::Function *InitFn = Module.getFunction(InitFnName);\n if (InitFn)\n InitFuncs.push_back(InitFn);\n }\n\n LoadSwiftRuntime();\n\n \/\/ Run the generated program.\n\n llvm::EngineBuilder builder(&Module);\n std::string ErrorMsg;\n builder.setErrorStr(&ErrorMsg);\n builder.setEngineKind(llvm::EngineKind::JIT);\n\n llvm::ExecutionEngine *EE = builder.create();\n for (auto InitFn : InitFuncs)\n EE->runFunctionAsMain(InitFn, std::vector(), 0);\n\n llvm::Function *EntryFn = Module.getFunction(\"main\");\n EE->runFunctionAsMain(EntryFn, std::vector(), 0);\n}\n\nstruct EditLineWrapper {\n EditLine *e;\n size_t PromptContinuationLevel;\n \n llvm::SmallString<80> PromptString;\n\n EditLineWrapper() {\n e = el_init(\"swift\", stdin, stdout, stderr);\n PromptContinuationLevel = 0;\n el_set(e, EL_EDITOR, \"emacs\");\n el_set(e, EL_PROMPT, PromptFn);\n el_set(e, EL_CLIENTDATA, (void*)this);\n }\n \n static char *PromptFn(EditLine *e) {\n void* clientdata;\n el_get(e, EL_CLIENTDATA, &clientdata);\n return (char*)((EditLineWrapper*)clientdata)->getPrompt();\n }\n \n const char *getPrompt() {\n if (PromptContinuationLevel == 0)\n return \"swift> \";\n \n PromptString = \"swift| \";\n PromptString.append(2*PromptContinuationLevel, ' ');\n return PromptString.c_str();\n };\n \n\n ~EditLineWrapper() {\n el_end(e);\n }\n operator EditLine*() { return e; }\n};\n\nvoid swift::REPL(ASTContext &Context) {\n if (llvm::sys::Process::FileDescriptorIsDisplayed(2))\n llvm::errs() << \"Welcome to swift. Type 'help' for assistance.\\n\";\n \n \/\/ FIXME: We should do something a bit more elaborate than\n \/\/ \"allocate a 1MB buffer and hope it's enough\".\n llvm::MemoryBuffer *Buffer =\n llvm::MemoryBuffer::getNewMemBuffer(1 << 20, \"\");\n\n Component *Comp = new (Context.Allocate(1)) Component();\n unsigned BufferID =\n Context.SourceMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());\n Identifier ID = Context.getIdentifier(\"REPL\");\n TranslationUnit *TU = new (Context) TranslationUnit(ID, Comp, Context,\n \/*IsMainModule=*\/true,\n \/*IsReplModule=*\/true);\n\n llvm::SmallPtrSet ImportedModules;\n llvm::LLVMContext LLVMContext;\n llvm::Module Module(\"REPL\", LLVMContext);\n std::string ErrorMessage;\n\n LoadSwiftRuntime();\n\n llvm::EngineBuilder builder(&Module);\n std::string ErrorMsg;\n builder.setErrorStr(&ErrorMsg);\n builder.setEngineKind(llvm::EngineKind::JIT);\n llvm::ExecutionEngine *EE = builder.create();\n\n irgen::Options Options;\n Options.OutputFilename = \"\";\n Options.Triple = llvm::sys::getDefaultTargetTriple();\n Options.OptLevel = 0;\n Options.OutputKind = irgen::OutputKind::Module;\n Options.IsREPL = true;\n\n EditLineWrapper e;\n\n char* CurBuffer = const_cast(Buffer->getBufferStart());\n unsigned CurBufferOffset = 0;\n unsigned CurBufferEndOffset = 0;\n \n unsigned CurTUElem = 0;\n unsigned BraceCount = 0;\n unsigned CurChunkLines = 0;\n\n while (1) {\n \/\/ Read one line.\n e.PromptContinuationLevel = BraceCount;\n int LineCount;\n const char* Line = el_gets(e, &LineCount);\n if (!Line)\n return;\n\n strcpy(CurBuffer, Line);\n CurBuffer += strlen(Line);\n CurBufferEndOffset += strlen(Line);\n ++CurChunkLines;\n\n \/\/ If we detect unbalanced braces, keep reading before we start parsing.\n Lexer L(Line, Context.SourceMgr, nullptr);\n Token Tok;\n do {\n L.lex(Tok);\n if (Tok.is(tok::l_brace))\n ++BraceCount;\n else if (Tok.is(tok::r_brace) && BraceCount > 0)\n --BraceCount;\n } while (!Tok.is(tok::eof));\n\n if (BraceCount)\n continue;\n\n \/\/ Parse the current line(s).\n bool ShouldRun =\n swift::appendToMainTranslationUnit(TU, BufferID, CurTUElem,\n CurBufferOffset,\n CurBufferEndOffset);\n\n if (Context.hadError()) {\n Context.Diags.resetHadAnyError();\n while (TU->Decls.size() > CurTUElem)\n TU->Decls.pop_back();\n TU->clearUnresolvedIdentifierTypes();\n\n \/\/ FIXME: Handling of \"import\" declarations? Is there any other\n \/\/ state which needs to be reset?\n\n if (CurChunkLines > 1)\n llvm::errs() << \"(discarded \" << CurChunkLines << \" lines)\\n\";\n CurChunkLines = 0;\n continue;\n }\n\n \/\/ If we didn't see an expression, statement, or decl which might have\n \/\/ side-effects, keep reading.\n if (!ShouldRun)\n continue;\n\n \/\/ IRGen the current line(s).\n llvm::Module LineModule(\"REPLLine\", LLVMContext);\n performCaptureAnalysis(TU, CurTUElem);\n performIRGeneration(Options, &LineModule, TU, CurTUElem);\n\n if (Context.hadError())\n return;\n\n CurTUElem = TU->Decls.size();\n CurChunkLines = 0;\n\n if (llvm::Linker::LinkModules(&Module, &LineModule,\n llvm::Linker::DestroySource,\n &ErrorMessage)) {\n llvm::errs() << \"Error linking swift modules\\n\";\n llvm::errs() << ErrorMessage << \"\\n\";\n return;\n }\n\n \/\/ IRGen the modules this module depends on.\n llvm::SmallVector InitFuncs;\n for (auto ModPair : TU->getImportedModules()) {\n if (isa(ModPair.second))\n continue;\n\n TranslationUnit *SubTU = cast(ModPair.second);\n if (!ImportedModules.insert(SubTU))\n continue;\n\n \/\/ FIXME: Need to check whether this is actually safe in general.\n llvm::Module SubModule(SubTU->Name.str(), LLVMContext);\n performCaptureAnalysis(SubTU);\n performIRGeneration(Options, &SubModule, SubTU);\n\n if (Context.hadError())\n return;\n\n if (llvm::Linker::LinkModules(&Module, &SubModule,\n llvm::Linker::DestroySource,\n &ErrorMessage)) {\n llvm::errs() << \"Error linking swift modules\\n\";\n llvm::errs() << ErrorMessage << \"\\n\";\n return;\n }\n\n \/\/ FIXME: This is an ugly hack; need to figure out how this should\n \/\/ actually work.\n SmallVector NameBuf;\n StringRef InitFnName = (SubTU->Name.str() + \".init\").toStringRef(NameBuf);\n llvm::Function *InitFn = Module.getFunction(InitFnName);\n if (InitFn)\n InitFuncs.push_back(InitFn);\n }\n\n for (auto InitFn : InitFuncs)\n EE->runFunctionAsMain(InitFn, std::vector(), 0);\n\n \/\/ FIXME: The way we do this is really ugly... we should be able to\n \/\/ improve this.\n llvm::Function *EntryFn = Module.getFunction(\"main\");\n EE->runFunctionAsMain(EntryFn, std::vector(), 0);\n EE->freeMachineCodeForFunction(EntryFn);\n EntryFn->eraseFromParent();\n }\n}\n\n\n\/\/ FIXME: We shouldn't be writing implemenetations for functions in the swift\n\/\/ module in C, and this isn't really an ideal place to put those\n\/\/ implementations.\nextern \"C\" void _TSs5printFT3valNSs5Int64_T_(int64_t l) {\n printf(\"%lld\", l);\n}\n\nextern \"C\" void _TSs5printFT3valNSs6Double_T_(double l) {\n printf(\"%f\", l);\n}\n\nextern \"C\" void _TSs9printCharFT9characterNSs5Int64_T_(int64_t l) {\n printf(\"%c\", (char)l);\n}\n\nextern \"C\" void _TSs5printFT3valNSs6String_T_(char* l) {\n printf(\"%s\", l);\n}\n\n\/\/ func [infix_left=190] + (lhs : String,\n\/\/ rhs : String) -> String\nextern \"C\" char* _TSsop1pFT3lhsNSs6String3rhsS__S_(char* lhs, char* rhs) {\n size_t ls = strlen(lhs);\n size_t rs = strlen(rhs);\n char* s = (char*)malloc(ls+rs+1);\n memcpy(s, lhs, ls);\n strcpy(s+ls, rhs);\n return s;\n}\n\nextern \"C\" bool _TNSs4Bool13getLogicValuefRS_FT_i1(bool* b) {\n return *b;\n}\n\nextern \"C\" void _TSs4exitFT8exitCodeNSs5Int64_T_(int64_t l) {\n exit(l);\n}\n<|endoftext|>"} {"text":"\/*\n *\/\n#include \"manifest.h\"\n#include \"build.h\"\n#include \"debug.h\"\n#include \n#include \n#include \/\/ stringstream\n#ifdef _WIN32\n# include \n#else\n# include \n# include \n# include \n# include \n# include \n#endif\n\nstruct BuildList\n{\n struct BuildEnt {\n const PackageManifest* package;\n unsigned level;\n };\n ::std::vector m_list;\n\n void add_dependencies(const PackageManifest& p, unsigned level);\n void add_package(const PackageManifest& p, unsigned level);\n void sort_list();\n\n struct Iter {\n const BuildList& l;\n size_t i;\n\n const PackageManifest& operator*() const {\n return *this->l.m_list[this->i].package;\n }\n void operator++() {\n this->i++;\n }\n bool operator!=(const Iter& x) const {\n return this->i != x.i;\n }\n Iter begin() const {\n return *this;\n }\n Iter end() {\n return Iter{ this->l, this->l.m_list.size() };\n }\n };\n\n Iter iter() const {\n return Iter { *this, 0 };\n }\n};\n\nclass StringList\n{\n ::std::vector<::std::string> m_cached;\n ::std::vector m_strings;\npublic:\n StringList()\n {\n }\n StringList(const StringList&) = delete;\n\n const ::std::vector& get_vec() const\n {\n return m_strings;\n }\n\n void push_back(::std::string s)\n {\n#if _WIN32\n \/\/ NOTE: MSVC's STL changes the pointer on move it seems\n if(m_cached.capacity() == m_cached.size())\n {\n ::std::vector b;\n b.reserve(m_strings.size());\n size_t j = 0;\n for(const auto* s : m_strings)\n {\n if(j == m_cached.size())\n break;\n if(s == m_cached[j].c_str())\n b.push_back(true);\n else\n b.push_back(false);\n }\n\n m_cached.push_back(::std::move(s));\n j = 0;\n for(size_t i = 0; i < b.size(); i ++)\n {\n if(b[i])\n m_strings[i] = m_cached[j++].c_str();\n }\n }\n else\n#endif\n m_cached.push_back(::std::move(s));\n m_strings.push_back(m_cached.back().c_str());\n }\n void push_back(const char* s)\n {\n m_strings.push_back(s);\n }\n};\n\nstruct Timestamp\n{\n#if _WIN32\n uint64_t m_val;\n\n Timestamp(FILETIME ft):\n m_val( (static_cast(ft.dwHighDateTime) << 32) | static_cast(ft.dwLowDateTime) )\n {\n }\n#else\n time_t m_val;\n#endif\n static Timestamp infinite_past() {\n#if _WIN32\n return Timestamp { FILETIME { 0, 0 } };\n#else\n return Timestamp { 0 };\n#endif\n }\n\n bool operator==(const Timestamp& x) const {\n return m_val == x.m_val;\n }\n bool operator<(const Timestamp& x) const {\n return m_val < x.m_val;\n }\n\n friend ::std::ostream& operator<<(::std::ostream& os, const Timestamp& x) {\n#if _WIN32\n os << ::std::hex << x.m_val << ::std::dec;\n#else\n os << x.m_val;\n#endif\n return os;\n }\n};\n\n#if _WIN32\nconst char* const Builder::MRUSTC_PATH = \"x64\\\\Release\\\\mrustc.exe\";\n#else\nconst char* const Builder::MRUSTC_PATH = \"..\/bin\/mrustc\";\n#endif\n\nvoid MiniCargo_Build(const PackageManifest& manifest, ::helpers::path override_path)\n{\n BuildList list;\n\n list.add_dependencies(manifest, 0);\n\n list.sort_list();\n \/\/ dedup?\n for(const auto& p : list.iter())\n {\n DEBUG(\"WILL BUILD \" << p.name() << \" from \" << p.manifest_path());\n }\n\n \/\/ Build dependencies\n Builder builder { \"output\", override_path };\n for(const auto& p : list.iter())\n {\n if( ! builder.build_library(p) )\n {\n return;\n }\n }\n\n \/\/ TODO: If the manifest doesn't have a library, build the binary\n builder.build_library(manifest);\n}\n\nvoid BuildList::add_dependencies(const PackageManifest& p, unsigned level)\n{\n TRACE_FUNCTION_F(p.name());\n for (const auto& dep : p.dependencies())\n {\n if( dep.is_optional() )\n {\n continue ;\n }\n DEBUG(\"Depenency \" << dep.name());\n add_package(dep.get_package(), level+1);\n }\n}\nvoid BuildList::add_package(const PackageManifest& p, unsigned level)\n{\n TRACE_FUNCTION_F(p.name());\n \/\/ If the package is already loaded\n for(auto& ent : m_list)\n {\n if(ent.package == &p && ent.level >= level)\n {\n \/\/ NOTE: Only skip if this package will be built before we needed (i.e. the level is greater)\n return ;\n }\n \/\/ Keep searching (might already have a higher entry)\n }\n m_list.push_back({ &p, level });\n add_dependencies(p, level);\n}\nvoid BuildList::sort_list()\n{\n ::std::sort(m_list.begin(), m_list.end(), [](const auto& a, const auto& b){ return a.level > b.level; });\n\n \/\/ Needed to deduplicate after sorting (`add_package` doesn't fully dedup)\n for(auto it = m_list.begin(); it != m_list.end(); )\n {\n auto it2 = ::std::find_if(m_list.begin(), it, [&](const auto& x){ return x.package == it->package; });\n if( it2 != it )\n {\n DEBUG((it - m_list.begin()) << \": Duplicate \" << it->package->name() << \" - Already at pos \" << (it2 - m_list.begin()));\n it = m_list.erase(it);\n }\n else\n {\n DEBUG((it - m_list.begin()) << \": Keep \" << it->package->name() << \", level = \" << it->level);\n ++it;\n }\n }\n}\n\nbool Builder::build_target(const PackageManifest& manifest, const PackageTarget& target) const\n{\n auto outfile = m_output_dir \/ ::format(\"lib\", target.m_name, \".hir\");\n \/\/DEBUG(\"Building \" << manifest.name() << \":\" << target.m_name << \" as \" << outfile);\n\n \/\/ TODO: Determine if it needs re-running\n \/\/ Rerun if:\n \/\/ > `outfile` is missing\n \/\/ > mrustc\/minicargo is newer than `outfile`\n \/\/ > build script has changed\n \/\/ > any input file has changed (requires depfile from mrustc)\n bool force_rebuild = false;\n auto ts_result = this->get_timestamp(outfile);\n if( force_rebuild ) {\n DEBUG(\"Building \" << outfile << \" - Force\");\n }\n else if( ts_result == Timestamp::infinite_past() ) {\n \/\/ Rebuild (missing)\n DEBUG(\"Building \" << outfile << \" - Missing\");\n }\n else if( ts_result < this->get_timestamp(MRUSTC_PATH) \/*|| ts_result < this->get_timestamp(\"bin\/minicargo\")*\/ ) {\n \/\/ Rebuild (older than mrustc\/minicargo)\n DEBUG(\"Building \" << outfile << \" - Older than mrustc ( \" << ts_result << \" < \" << this->get_timestamp(MRUSTC_PATH) << \")\");\n }\n else {\n \/\/ TODO: Check dependencies. (from depfile)\n \/\/ Don't rebuild (no need to)\n DEBUG(\"Not building \" << outfile << \" - not out of date\");\n return true;\n }\n \n\n for(const auto& cmd : manifest.build_script_output().pre_build_commands)\n {\n \/\/ TODO: Run commands specified by build script (override)\n }\n\n StringList args;\n args.push_back(::helpers::path(manifest.manifest_path()).parent() \/ ::helpers::path(target.m_path));\n args.push_back(\"--crate-name\"); args.push_back(target.m_name.c_str());\n args.push_back(\"--crate-type\"); args.push_back(\"rlib\");\n args.push_back(\"-o\"); args.push_back(outfile);\n args.push_back(\"-L\"); args.push_back(m_output_dir.str().c_str());\n for(const auto& dir : manifest.build_script_output().rustc_link_search) {\n args.push_back(\"-L\"); args.push_back(dir.second.c_str());\n }\n for(const auto& lib : manifest.build_script_output().rustc_link_lib) {\n args.push_back(\"-l\"); args.push_back(lib.second.c_str());\n }\n for(const auto& cfg : manifest.build_script_output().rustc_cfg) {\n args.push_back(\"--cfg\"); args.push_back(cfg.c_str());\n }\n for(const auto& flag : manifest.build_script_output().rustc_flags) {\n args.push_back(flag.c_str());\n }\n \/\/ TODO: Environment variables (rustc_env)\n\n return this->spawn_process(args, outfile + \"_dbg.txt\");\n}\nbool Builder::build_library(const PackageManifest& manifest) const\n{\n if( manifest.build_script() != \"\" )\n {\n \/\/ Locate a build script override file\n if(this->m_build_script_overrides.is_valid())\n {\n auto override_file = this->m_build_script_overrides \/ \"build_\" + manifest.name().c_str() + \".txt\";\n \/\/ TODO: Should this test if it exists? or just assume and let it error?\n \n \/\/ > Note, override file can specify a list of commands to run.\n const_cast(manifest).load_build_script( override_file.str() );\n }\n else\n {\n \/\/ Otherwise, compile and run build script\n \/\/ - Load dependencies for the build script\n \/\/ - Build the script itself\n \/\/this->build_build_script( manifest );\n \/\/ - Run the script and put output in the right dir\n \/\/manifest.load_build_script( m_output_dir \/ \"build_\" + manifest.name().c_str() + \".txt\" );\n throw ::std::runtime_error(\"TODO: Build script for \" + manifest.name());\n }\n }\n\n return this->build_target(manifest, manifest.get_library());\n}\nbool Builder::spawn_process(const StringList& args, const ::helpers::path& logfile) const\n{\n#ifdef _WIN32\n ::std::stringstream cmdline;\n cmdline << \"mrustc.exe\";\n for (const auto& arg : args.get_vec())\n cmdline << \" \" << arg;\n auto cmdline_str = cmdline.str();\n DEBUG(\"Calling \" << cmdline_str);\n\n CreateDirectory(static_cast<::std::string>(logfile.parent()).c_str(), NULL);\n\n STARTUPINFO si = { 0 };\n si.cb = sizeof(si);\n si.dwFlags = STARTF_USESTDHANDLES;\n si.hStdInput = NULL;\n si.hStdError = GetStdHandle(STD_ERROR_HANDLE);\n {\n SECURITY_ATTRIBUTES sa = { 0 };\n sa.nLength = sizeof(sa);\n sa.bInheritHandle = TRUE;\n si.hStdOutput = CreateFile( static_cast<::std::string>(logfile).c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n DWORD tmp;\n WriteFile(si.hStdOutput, cmdline_str.data(), cmdline_str.size(), &tmp, NULL);\n WriteFile(si.hStdOutput, \"\\n\", 1, &tmp, NULL);\n }\n PROCESS_INFORMATION pi = { 0 };\n char env[] =\n \"MRUSTC_DEBUG=\"\"\\0\"\n ;\n CreateProcessA(MRUSTC_PATH, (LPSTR)cmdline_str.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);\n CloseHandle(si.hStdOutput);\n WaitForSingleObject(pi.hProcess, INFINITE);\n DWORD status = 1;\n GetExitCodeProcess(pi.hProcess, &status);\n if (status != 0)\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << status);\n return false;\n }\n#else\n\n \/\/ Create logfile output directory\n mkdir(static_cast<::std::string>(logfile.parent()).c_str(), 0755);\n\n \/\/ Create handles such that the log file is on stdout\n ::std::string logfile_str = logfile;\n pid_t pid;\n posix_spawn_file_actions_t fa;\n {\n posix_spawn_file_actions_init(&fa);\n posix_spawn_file_actions_addopen(&fa, 1, logfile_str.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0644);\n }\n\n \/\/ Generate `argv`\n auto argv = args.get_vec();\n argv.insert(argv.begin(), \"mrustc\");\n DEBUG(\"Calling \" << argv);\n argv.push_back(nullptr);\n\n \/\/ Generate `envp`\n ::std::vector envp;\n extern char **environ;\n for(auto p = environ; *p; p++)\n {\n envp.push_back(*p);\n }\n envp.push_back(nullptr);\n\n if( posix_spawn(&pid, \"..\/bin\/mrustc\", &fa, \/*attr=*\/nullptr, (char* const*)argv.data(), (char* const*)envp.data()) != 0 )\n {\n perror(\"posix_spawn\");\n DEBUG(\"Unable to spawn compiler\");\n posix_spawn_file_actions_destroy(&fa);\n return false;\n }\n posix_spawn_file_actions_destroy(&fa);\n int status = -1;\n waitpid(pid, &status, 0);\n if( WEXITSTATUS(status) != 0 )\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << WEXITSTATUS(status));\n return false;\n }\n#endif\n return true;\n}\n\nTimestamp Builder::get_timestamp(const ::helpers::path& path) const\n{\n#if _WIN32\n FILETIME out;\n auto handle = CreateFile(path.str().c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);\n if(handle == INVALID_HANDLE_VALUE) {\n \/\/DEBUG(\"Can't find \" << path);\n return Timestamp::infinite_past();\n }\n if( GetFileTime(handle, NULL, NULL, &out) == FALSE ) {\n \/\/DEBUG(\"Can't GetFileTime on \" << path);\n CloseHandle(handle);\n return Timestamp::infinite_past();\n }\n CloseHandle(handle);\n \/\/DEBUG(Timestamp{out} << \" \" << path);\n return Timestamp { out };\n#else\n struct stat s;\n if( stat(path.str().c_str(), &s) == 0 )\n {\n return Timestamp { s.st_mtime };\n }\n else\n {\n return Timestamp::infinite_past();\n }\n#endif\n}\n\nminicargo build - Fix exit detection\/*\n *\/\n#include \"manifest.h\"\n#include \"build.h\"\n#include \"debug.h\"\n#include \n#include \n#include \/\/ stringstream\n#ifdef _WIN32\n# include \n#else\n# include \n# include \n# include \n# include \n# include \n#endif\n\nstruct BuildList\n{\n struct BuildEnt {\n const PackageManifest* package;\n unsigned level;\n };\n ::std::vector m_list;\n\n void add_dependencies(const PackageManifest& p, unsigned level);\n void add_package(const PackageManifest& p, unsigned level);\n void sort_list();\n\n struct Iter {\n const BuildList& l;\n size_t i;\n\n const PackageManifest& operator*() const {\n return *this->l.m_list[this->i].package;\n }\n void operator++() {\n this->i++;\n }\n bool operator!=(const Iter& x) const {\n return this->i != x.i;\n }\n Iter begin() const {\n return *this;\n }\n Iter end() {\n return Iter{ this->l, this->l.m_list.size() };\n }\n };\n\n Iter iter() const {\n return Iter { *this, 0 };\n }\n};\n\nclass StringList\n{\n ::std::vector<::std::string> m_cached;\n ::std::vector m_strings;\npublic:\n StringList()\n {\n }\n StringList(const StringList&) = delete;\n\n const ::std::vector& get_vec() const\n {\n return m_strings;\n }\n\n void push_back(::std::string s)\n {\n#if _WIN32\n \/\/ NOTE: MSVC's STL changes the pointer on move it seems\n if(m_cached.capacity() == m_cached.size())\n {\n ::std::vector b;\n b.reserve(m_strings.size());\n size_t j = 0;\n for(const auto* s : m_strings)\n {\n if(j == m_cached.size())\n break;\n if(s == m_cached[j].c_str())\n b.push_back(true);\n else\n b.push_back(false);\n }\n\n m_cached.push_back(::std::move(s));\n j = 0;\n for(size_t i = 0; i < b.size(); i ++)\n {\n if(b[i])\n m_strings[i] = m_cached[j++].c_str();\n }\n }\n else\n#endif\n m_cached.push_back(::std::move(s));\n m_strings.push_back(m_cached.back().c_str());\n }\n void push_back(const char* s)\n {\n m_strings.push_back(s);\n }\n};\n\nstruct Timestamp\n{\n#if _WIN32\n uint64_t m_val;\n\n Timestamp(FILETIME ft):\n m_val( (static_cast(ft.dwHighDateTime) << 32) | static_cast(ft.dwLowDateTime) )\n {\n }\n#else\n time_t m_val;\n#endif\n static Timestamp infinite_past() {\n#if _WIN32\n return Timestamp { FILETIME { 0, 0 } };\n#else\n return Timestamp { 0 };\n#endif\n }\n\n bool operator==(const Timestamp& x) const {\n return m_val == x.m_val;\n }\n bool operator<(const Timestamp& x) const {\n return m_val < x.m_val;\n }\n\n friend ::std::ostream& operator<<(::std::ostream& os, const Timestamp& x) {\n#if _WIN32\n os << ::std::hex << x.m_val << ::std::dec;\n#else\n os << x.m_val;\n#endif\n return os;\n }\n};\n\n#if _WIN32\nconst char* const Builder::MRUSTC_PATH = \"x64\\\\Release\\\\mrustc.exe\";\n#else\nconst char* const Builder::MRUSTC_PATH = \"..\/bin\/mrustc\";\n#endif\n\nvoid MiniCargo_Build(const PackageManifest& manifest, ::helpers::path override_path)\n{\n BuildList list;\n\n list.add_dependencies(manifest, 0);\n\n list.sort_list();\n \/\/ dedup?\n for(const auto& p : list.iter())\n {\n DEBUG(\"WILL BUILD \" << p.name() << \" from \" << p.manifest_path());\n }\n\n \/\/ Build dependencies\n Builder builder { \"output\", override_path };\n for(const auto& p : list.iter())\n {\n if( ! builder.build_library(p) )\n {\n return;\n }\n }\n\n \/\/ TODO: If the manifest doesn't have a library, build the binary\n builder.build_library(manifest);\n}\n\nvoid BuildList::add_dependencies(const PackageManifest& p, unsigned level)\n{\n TRACE_FUNCTION_F(p.name());\n for (const auto& dep : p.dependencies())\n {\n if( dep.is_optional() )\n {\n continue ;\n }\n DEBUG(\"Depenency \" << dep.name());\n add_package(dep.get_package(), level+1);\n }\n}\nvoid BuildList::add_package(const PackageManifest& p, unsigned level)\n{\n TRACE_FUNCTION_F(p.name());\n \/\/ If the package is already loaded\n for(auto& ent : m_list)\n {\n if(ent.package == &p && ent.level >= level)\n {\n \/\/ NOTE: Only skip if this package will be built before we needed (i.e. the level is greater)\n return ;\n }\n \/\/ Keep searching (might already have a higher entry)\n }\n m_list.push_back({ &p, level });\n add_dependencies(p, level);\n}\nvoid BuildList::sort_list()\n{\n ::std::sort(m_list.begin(), m_list.end(), [](const auto& a, const auto& b){ return a.level > b.level; });\n\n \/\/ Needed to deduplicate after sorting (`add_package` doesn't fully dedup)\n for(auto it = m_list.begin(); it != m_list.end(); )\n {\n auto it2 = ::std::find_if(m_list.begin(), it, [&](const auto& x){ return x.package == it->package; });\n if( it2 != it )\n {\n DEBUG((it - m_list.begin()) << \": Duplicate \" << it->package->name() << \" - Already at pos \" << (it2 - m_list.begin()));\n it = m_list.erase(it);\n }\n else\n {\n DEBUG((it - m_list.begin()) << \": Keep \" << it->package->name() << \", level = \" << it->level);\n ++it;\n }\n }\n}\n\nbool Builder::build_target(const PackageManifest& manifest, const PackageTarget& target) const\n{\n auto outfile = m_output_dir \/ ::format(\"lib\", target.m_name, \".hir\");\n \/\/DEBUG(\"Building \" << manifest.name() << \":\" << target.m_name << \" as \" << outfile);\n\n \/\/ TODO: Determine if it needs re-running\n \/\/ Rerun if:\n \/\/ > `outfile` is missing\n \/\/ > mrustc\/minicargo is newer than `outfile`\n \/\/ > build script has changed\n \/\/ > any input file has changed (requires depfile from mrustc)\n bool force_rebuild = false;\n auto ts_result = this->get_timestamp(outfile);\n if( force_rebuild ) {\n DEBUG(\"Building \" << outfile << \" - Force\");\n }\n else if( ts_result == Timestamp::infinite_past() ) {\n \/\/ Rebuild (missing)\n DEBUG(\"Building \" << outfile << \" - Missing\");\n }\n else if( ts_result < this->get_timestamp(MRUSTC_PATH) \/*|| ts_result < this->get_timestamp(\"bin\/minicargo\")*\/ ) {\n \/\/ Rebuild (older than mrustc\/minicargo)\n DEBUG(\"Building \" << outfile << \" - Older than mrustc ( \" << ts_result << \" < \" << this->get_timestamp(MRUSTC_PATH) << \")\");\n }\n else {\n \/\/ TODO: Check dependencies. (from depfile)\n \/\/ Don't rebuild (no need to)\n DEBUG(\"Not building \" << outfile << \" - not out of date\");\n return true;\n }\n \n\n for(const auto& cmd : manifest.build_script_output().pre_build_commands)\n {\n \/\/ TODO: Run commands specified by build script (override)\n }\n\n StringList args;\n args.push_back(::helpers::path(manifest.manifest_path()).parent() \/ ::helpers::path(target.m_path));\n args.push_back(\"--crate-name\"); args.push_back(target.m_name.c_str());\n args.push_back(\"--crate-type\"); args.push_back(\"rlib\");\n args.push_back(\"-o\"); args.push_back(outfile);\n args.push_back(\"-L\"); args.push_back(m_output_dir.str().c_str());\n for(const auto& dir : manifest.build_script_output().rustc_link_search) {\n args.push_back(\"-L\"); args.push_back(dir.second.c_str());\n }\n for(const auto& lib : manifest.build_script_output().rustc_link_lib) {\n args.push_back(\"-l\"); args.push_back(lib.second.c_str());\n }\n for(const auto& cfg : manifest.build_script_output().rustc_cfg) {\n args.push_back(\"--cfg\"); args.push_back(cfg.c_str());\n }\n for(const auto& flag : manifest.build_script_output().rustc_flags) {\n args.push_back(flag.c_str());\n }\n \/\/ TODO: Environment variables (rustc_env)\n\n return this->spawn_process(args, outfile + \"_dbg.txt\");\n}\nbool Builder::build_library(const PackageManifest& manifest) const\n{\n if( manifest.build_script() != \"\" )\n {\n \/\/ Locate a build script override file\n if(this->m_build_script_overrides.is_valid())\n {\n auto override_file = this->m_build_script_overrides \/ \"build_\" + manifest.name().c_str() + \".txt\";\n \/\/ TODO: Should this test if it exists? or just assume and let it error?\n \n \/\/ > Note, override file can specify a list of commands to run.\n const_cast(manifest).load_build_script( override_file.str() );\n }\n else\n {\n \/\/ Otherwise, compile and run build script\n \/\/ - Load dependencies for the build script\n \/\/ - Build the script itself\n \/\/this->build_build_script( manifest );\n \/\/ - Run the script and put output in the right dir\n \/\/manifest.load_build_script( m_output_dir \/ \"build_\" + manifest.name().c_str() + \".txt\" );\n throw ::std::runtime_error(\"TODO: Build script for \" + manifest.name());\n }\n }\n\n return this->build_target(manifest, manifest.get_library());\n}\nbool Builder::spawn_process(const StringList& args, const ::helpers::path& logfile) const\n{\n#ifdef _WIN32\n ::std::stringstream cmdline;\n cmdline << \"mrustc.exe\";\n for (const auto& arg : args.get_vec())\n cmdline << \" \" << arg;\n auto cmdline_str = cmdline.str();\n DEBUG(\"Calling \" << cmdline_str);\n\n CreateDirectory(static_cast<::std::string>(logfile.parent()).c_str(), NULL);\n\n STARTUPINFO si = { 0 };\n si.cb = sizeof(si);\n si.dwFlags = STARTF_USESTDHANDLES;\n si.hStdInput = NULL;\n si.hStdError = GetStdHandle(STD_ERROR_HANDLE);\n {\n SECURITY_ATTRIBUTES sa = { 0 };\n sa.nLength = sizeof(sa);\n sa.bInheritHandle = TRUE;\n si.hStdOutput = CreateFile( static_cast<::std::string>(logfile).c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n DWORD tmp;\n WriteFile(si.hStdOutput, cmdline_str.data(), cmdline_str.size(), &tmp, NULL);\n WriteFile(si.hStdOutput, \"\\n\", 1, &tmp, NULL);\n }\n PROCESS_INFORMATION pi = { 0 };\n char env[] =\n \"MRUSTC_DEBUG=\"\"\\0\"\n ;\n CreateProcessA(MRUSTC_PATH, (LPSTR)cmdline_str.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);\n CloseHandle(si.hStdOutput);\n WaitForSingleObject(pi.hProcess, INFINITE);\n DWORD status = 1;\n GetExitCodeProcess(pi.hProcess, &status);\n if (status != 0)\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << status);\n return false;\n }\n#else\n\n \/\/ Create logfile output directory\n mkdir(static_cast<::std::string>(logfile.parent()).c_str(), 0755);\n\n \/\/ Create handles such that the log file is on stdout\n ::std::string logfile_str = logfile;\n pid_t pid;\n posix_spawn_file_actions_t fa;\n {\n posix_spawn_file_actions_init(&fa);\n posix_spawn_file_actions_addopen(&fa, 1, logfile_str.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0644);\n }\n\n \/\/ Generate `argv`\n auto argv = args.get_vec();\n argv.insert(argv.begin(), \"mrustc\");\n DEBUG(\"Calling \" << argv);\n argv.push_back(nullptr);\n\n \/\/ Generate `envp`\n ::std::vector envp;\n extern char **environ;\n for(auto p = environ; *p; p++)\n {\n envp.push_back(*p);\n }\n envp.push_back(nullptr);\n\n if( posix_spawn(&pid, \"..\/bin\/mrustc\", &fa, \/*attr=*\/nullptr, (char* const*)argv.data(), (char* const*)envp.data()) != 0 )\n {\n perror(\"posix_spawn\");\n DEBUG(\"Unable to spawn compiler\");\n posix_spawn_file_actions_destroy(&fa);\n return false;\n }\n posix_spawn_file_actions_destroy(&fa);\n int status = -1;\n waitpid(pid, &status, 0);\n if( status != 0 )\n {\n if( WIFEXITED(status) )\n DEBUG(\"Compiler exited with non-zero exit status \" << WEXITSTATUS(status));\n else if( WIFSIGNALED(status) )\n DEBUG(\"Compiler was terminated with signal \" << WSTOPSIG(status));\n else\n DEBUG(\"Compiler terminated for unknown reason, status=\" << status);\n return false;\n }\n#endif\n return true;\n}\n\nTimestamp Builder::get_timestamp(const ::helpers::path& path) const\n{\n#if _WIN32\n FILETIME out;\n auto handle = CreateFile(path.str().c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);\n if(handle == INVALID_HANDLE_VALUE) {\n \/\/DEBUG(\"Can't find \" << path);\n return Timestamp::infinite_past();\n }\n if( GetFileTime(handle, NULL, NULL, &out) == FALSE ) {\n \/\/DEBUG(\"Can't GetFileTime on \" << path);\n CloseHandle(handle);\n return Timestamp::infinite_past();\n }\n CloseHandle(handle);\n \/\/DEBUG(Timestamp{out} << \" \" << path);\n return Timestamp { out };\n#else\n struct stat s;\n if( stat(path.str().c_str(), &s) == 0 )\n {\n return Timestamp { s.st_mtime };\n }\n else\n {\n return Timestamp::infinite_past();\n }\n#endif\n}\n\n<|endoftext|>"} {"text":"\/*\n *\/\n#include \"manifest.h\"\n#include \"debug.h\"\n#include \n#include \n#include \/\/ stringstream\n#include \"helpers.h\" \/\/ path\n#ifdef _WIN32\n# include \n#else\n# include \n# include \n# include \n# include \n# include \n#endif\n\nstruct BuildList\n{\n struct BuildEnt {\n const PackageManifest* package;\n unsigned level;\n };\n ::std::vector m_list;\n\n void add_dependencies(const PackageManifest& p, unsigned level);\n void add_package(const PackageManifest& p, unsigned level);\n void sort_list();\n\n struct Iter {\n const BuildList& l;\n size_t i;\n\n const PackageManifest& operator*() const {\n return *this->l.m_list[this->l.m_list.size() - this->i - 1].package;\n }\n void operator++() {\n this->i++;\n }\n bool operator!=(const Iter& x) const {\n return this->i != x.i;\n }\n Iter begin() const {\n return *this;\n }\n Iter end() {\n return Iter{ this->l, this->l.m_list.size() };\n }\n };\n\n Iter iter() const {\n return Iter { *this, 0 };\n }\n};\n\nclass Builder\n{\n class StringList\n {\n ::std::vector<::std::string> m_cached;\n ::std::vector m_strings;\n public:\n StringList()\n {\n }\n\n const ::std::vector& get_vec() const\n {\n return m_strings;\n }\n\n void push_back(::std::string s)\n {\n m_cached.push_back(::std::move(s));\n m_strings.push_back(m_cached.back().c_str());\n }\n void push_back(const char* s)\n {\n m_strings.push_back(s);\n }\n };\n\npublic:\n bool build_target(const PackageManifest& manifest, const PackageTarget& target) const;\n bool build_library(const PackageManifest& manifest) const;\n\nprivate:\n bool spawn_process(const StringList& args, const ::helpers::path& logfile) const;\n};\n\nvoid MiniCargo_Build(const PackageManifest& manifest)\n{\n BuildList list;\n\n list.add_dependencies(manifest, 0);\n\n list.sort_list();\n \/\/ dedup?\n for(const auto& p : list.iter())\n {\n DEBUG(\"WILL BUILD \" << p.name() << \" from \" << p.manifest_path());\n }\n\n \/\/ Build dependencies\n Builder builder;\n for(const auto& p : list.iter())\n {\n if( ! builder.build_library(p) )\n {\n return;\n }\n }\n\n \/\/ TODO: If the manifest doesn't have a library, build the binary\n builder.build_library(manifest);\n}\n\nvoid BuildList::add_dependencies(const PackageManifest& p, unsigned level)\n{\n for (const auto& dep : p.dependencies())\n {\n if( dep.is_optional() )\n {\n continue ;\n }\n add_package(dep.get_package(), level+1);\n }\n}\nvoid BuildList::add_package(const PackageManifest& p, unsigned level)\n{\n for(auto& ent : m_list)\n {\n if(ent.package == &p)\n {\n ent.level = level;\n return ;\n }\n }\n m_list.push_back({ &p, level });\n for (const auto& dep : p.dependencies())\n {\n add_package(dep.get_package(), level+1);\n }\n}\nvoid BuildList::sort_list()\n{\n ::std::sort(m_list.begin(), m_list.end(), [](const auto& a, const auto& b){ return a.level < b.level; });\n\n for(auto it = m_list.begin(); it != m_list.end(); )\n {\n auto it2 = ::std::find_if(m_list.begin(), it, [&](const auto& x){ return x.package == it->package; });\n if( it2 != it )\n {\n it = m_list.erase(it);\n }\n else\n {\n ++it;\n }\n }\n}\n\nbool Builder::build_target(const PackageManifest& manifest, const PackageTarget& target) const\n{\n auto outdir = ::helpers::path(\"output\");\n auto outfile = outdir \/ ::format(\"lib\", target.m_name, \".hir\");\n\n \/\/ TODO: Determine if it needs re-running\n \/\/ Rerun if:\n \/\/ > `outfile` is missing\n \/\/ > mrustc\/minicargo is newer than `outfile`\n \/\/ > build script has changed\n \/\/ > any input file has changed (requires depfile from mrustc)\n\n StringList args;\n args.push_back(::helpers::path(manifest.manifest_path()).parent() \/ ::helpers::path(target.m_path));\n args.push_back(\"--crate-name\"); args.push_back(target.m_name.c_str());\n args.push_back(\"--crate-type\"); args.push_back(\"rlib\");\n args.push_back(\"-o\"); args.push_back(outfile);\n args.push_back(\"-L\"); args.push_back(outdir);\n \/\/for(const auto& dir : manifest.build_script.rustc_link_search) {\n \/\/ args.push_back(\"-L\"); args.push_back(dir.second.c_str());\n \/\/}\n \/\/for(const auto& lib : manifest.build_script.rustc_link_lib) {\n \/\/ args.push_back(\"-l\"); args.push_back(lib.second.c_str());\n \/\/}\n \/\/for(const auto& cfg : manifest.build_script.rustc_cfg) {\n \/\/ args.push_back(\"--cfg\"); args.push_back(cfg.c_str());\n \/\/}\n \/\/for(const auto& flag : manifest.build_script.rustc_flags) {\n \/\/ args.push_back(flag.c_str());\n \/\/}\n \/\/ TODO: Environment variables (rustc_env)\n\n return this->spawn_process(args, outfile + \"_dbg.txt\");\n}\nbool Builder::build_library(const PackageManifest& manifest) const\n{\n if( manifest.build_script() != \"\" )\n {\n \/\/ Locate a build script override file\n \/\/ > Note, override file can specify a list of commands to run.\n \/\/manifest.script_output = BuildScript::load( override_file );\n \/\/ Otherwise, compile and run build script\n \/\/manifest.script_output = BuildScript::load( ::helpers::path(\"output\") \/ \"build_\" + manifest.name + \".txt\" );\n \/\/ Parse build script output.\n throw ::std::runtime_error(\"TODO: Build script\");\n }\n\n return this->build_target(manifest, manifest.get_library());\n}\nbool Builder::spawn_process(const StringList& args, const ::helpers::path& logfile) const\n{\n#ifdef _WIN32\n ::std::stringstream cmdline;\n cmdline << \"mrustc.exe\";\n for (const auto& arg : args.get_vec())\n cmdline << \" \" << arg;\n auto cmdline_str = cmdline.str();\n DEBUG(\"Calling \" << cmdline_str);\n\n CreateDirectory(static_cast<::std::string>(logfile.parent()).c_str(), NULL);\n\n STARTUPINFO si = { 0 };\n si.cb = sizeof(si);\n si.dwFlags = STARTF_USESTDHANDLES;\n si.hStdInput = NULL;\n si.hStdError = GetStdHandle(STD_ERROR_HANDLE);\n {\n SECURITY_ATTRIBUTES sa = { 0 };\n sa.nLength = sizeof(sa);\n sa.bInheritHandle = TRUE;\n si.hStdOutput = CreateFile( static_cast<::std::string>(logfile).c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n DWORD tmp;\n WriteFile(si.hStdOutput, cmdline_str.data(), cmdline_str.size(), &tmp, NULL);\n WriteFile(si.hStdOutput, \"\\n\", 1, &tmp, NULL);\n }\n PROCESS_INFORMATION pi = { 0 };\n char env[] =\n \"MRUSTC_DEBUG=\"\"\\0\"\n ;\n CreateProcessA(\"x64\\\\Release\\\\mrustc.exe\", (LPSTR)cmdline_str.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);\n CloseHandle(si.hStdOutput);\n WaitForSingleObject(pi.hProcess, INFINITE);\n DWORD status = 1;\n GetExitCodeProcess(pi.hProcess, &status);\n if (status != 0)\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << status);\n return false;\n }\n#else\n\n \/\/ Create logfile output directory\n mkdir(static_cast<::std::string>(logfile.parent()).c_str(), 0755);\n\n \/\/ Create handles such that the log file is on stdout\n ::std::string logfile_str = logfile;\n pid_t pid;\n posix_spawn_file_actions_t fa;\n {\n posix_spawn_file_actions_init(&fa);\n posix_spawn_file_actions_addopen(&fa, 1, logfile_str.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0644);\n }\n\n \/\/ Generate `argv`\n auto argv = args.get_vec();\n argv.insert(argv.begin(), \"mrustc\");\n DEBUG(\"Calling \" << argv);\n argv.push_back(nullptr);\n\n \/\/ Generate `envp`\n ::std::vector envp;\n extern char **environ;\n for(auto p = environ; *p; p++)\n {\n envp.push_back(*p);\n }\n envp.push_back(nullptr);\n\n if( posix_spawn(&pid, \"..\/bin\/mrustc\", &fa, \/*attr=*\/nullptr, (char* const*)argv.data(), (char* const*)envp.data()) != 0 )\n {\n perror(\"posix_spawn\");\n DEBUG(\"Unable to spawn compiler\");\n posix_spawn_file_actions_destroy(&fa);\n return false;\n }\n posix_spawn_file_actions_destroy(&fa);\n int status = -1;\n waitpid(pid, &status, 0);\n if( WEXITSTATUS(status) != 0 )\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << WEXITSTATUS(status));\n return false;\n }\n#endif\n return true;\n}\nminicargo - Fix build ordering\/*\n *\/\n#include \"manifest.h\"\n#include \"debug.h\"\n#include \n#include \n#include \/\/ stringstream\n#include \"helpers.h\" \/\/ path\n#ifdef _WIN32\n# include \n#else\n# include \n# include \n# include \n# include \n# include \n#endif\n\nstruct BuildList\n{\n struct BuildEnt {\n const PackageManifest* package;\n unsigned level;\n };\n ::std::vector m_list;\n\n void add_dependencies(const PackageManifest& p, unsigned level);\n void add_package(const PackageManifest& p, unsigned level);\n void sort_list();\n\n struct Iter {\n const BuildList& l;\n size_t i;\n\n const PackageManifest& operator*() const {\n return *this->l.m_list[this->i].package;\n }\n void operator++() {\n this->i++;\n }\n bool operator!=(const Iter& x) const {\n return this->i != x.i;\n }\n Iter begin() const {\n return *this;\n }\n Iter end() {\n return Iter{ this->l, this->l.m_list.size() };\n }\n };\n\n Iter iter() const {\n return Iter { *this, 0 };\n }\n};\n\nclass Builder\n{\n class StringList\n {\n ::std::vector<::std::string> m_cached;\n ::std::vector m_strings;\n public:\n StringList()\n {\n }\n\n const ::std::vector& get_vec() const\n {\n return m_strings;\n }\n\n void push_back(::std::string s)\n {\n m_cached.push_back(::std::move(s));\n m_strings.push_back(m_cached.back().c_str());\n }\n void push_back(const char* s)\n {\n m_strings.push_back(s);\n }\n };\n\npublic:\n bool build_target(const PackageManifest& manifest, const PackageTarget& target) const;\n bool build_library(const PackageManifest& manifest) const;\n\nprivate:\n bool spawn_process(const StringList& args, const ::helpers::path& logfile) const;\n};\n\nvoid MiniCargo_Build(const PackageManifest& manifest)\n{\n BuildList list;\n\n list.add_dependencies(manifest, 0);\n\n list.sort_list();\n \/\/ dedup?\n for(const auto& p : list.iter())\n {\n DEBUG(\"WILL BUILD \" << p.name() << \" from \" << p.manifest_path());\n }\n\n \/\/ Build dependencies\n Builder builder;\n for(const auto& p : list.iter())\n {\n if( ! builder.build_library(p) )\n {\n return;\n }\n }\n\n \/\/ TODO: If the manifest doesn't have a library, build the binary\n builder.build_library(manifest);\n}\n\nvoid BuildList::add_dependencies(const PackageManifest& p, unsigned level)\n{\n for (const auto& dep : p.dependencies())\n {\n if( dep.is_optional() )\n {\n continue ;\n }\n add_package(dep.get_package(), level+1);\n }\n}\nvoid BuildList::add_package(const PackageManifest& p, unsigned level)\n{\n \/\/ If the package is already loaded\n for(auto& ent : m_list)\n {\n if(ent.package == &p && ent.level >= level)\n {\n \/\/ NOTE: Only skip if this package will be built before we needed (i.e. the level is greater)\n return ;\n }\n \/\/ Keep searching (might already have a higher entry)\n }\n m_list.push_back({ &p, level });\n for (const auto& dep : p.dependencies())\n {\n add_package(dep.get_package(), level+1);\n }\n}\nvoid BuildList::sort_list()\n{\n ::std::sort(m_list.begin(), m_list.end(), [](const auto& a, const auto& b){ return a.level > b.level; });\n\n \/\/ Needed to deduplicate after sorting (`add_package` doesn't fully dedup)\n for(auto it = m_list.begin(); it != m_list.end(); )\n {\n auto it2 = ::std::find_if(m_list.begin(), it, [&](const auto& x){ return x.package == it->package; });\n if( it2 != it )\n {\n DEBUG((it2 - m_list.begin()) << \": Duplicate \" << it->package->name() << \" - Already at pos \" << (it2 - m_list.begin()));\n it = m_list.erase(it);\n }\n else\n {\n DEBUG((it2 - m_list.begin()) << \": Keep \" << it->package->name() << \", level = \" << it->level);\n ++it;\n }\n }\n}\n\nbool Builder::build_target(const PackageManifest& manifest, const PackageTarget& target) const\n{\n auto outdir = ::helpers::path(\"output\");\n auto outfile = outdir \/ ::format(\"lib\", target.m_name, \".hir\");\n\n \/\/ TODO: Determine if it needs re-running\n \/\/ Rerun if:\n \/\/ > `outfile` is missing\n \/\/ > mrustc\/minicargo is newer than `outfile`\n \/\/ > build script has changed\n \/\/ > any input file has changed (requires depfile from mrustc)\n\n StringList args;\n args.push_back(::helpers::path(manifest.manifest_path()).parent() \/ ::helpers::path(target.m_path));\n args.push_back(\"--crate-name\"); args.push_back(target.m_name.c_str());\n args.push_back(\"--crate-type\"); args.push_back(\"rlib\");\n args.push_back(\"-o\"); args.push_back(outfile);\n args.push_back(\"-L\"); args.push_back(outdir);\n \/\/for(const auto& dir : manifest.build_script.rustc_link_search) {\n \/\/ args.push_back(\"-L\"); args.push_back(dir.second.c_str());\n \/\/}\n \/\/for(const auto& lib : manifest.build_script.rustc_link_lib) {\n \/\/ args.push_back(\"-l\"); args.push_back(lib.second.c_str());\n \/\/}\n \/\/for(const auto& cfg : manifest.build_script.rustc_cfg) {\n \/\/ args.push_back(\"--cfg\"); args.push_back(cfg.c_str());\n \/\/}\n \/\/for(const auto& flag : manifest.build_script.rustc_flags) {\n \/\/ args.push_back(flag.c_str());\n \/\/}\n \/\/ TODO: Environment variables (rustc_env)\n\n return this->spawn_process(args, outfile + \"_dbg.txt\");\n}\nbool Builder::build_library(const PackageManifest& manifest) const\n{\n if( manifest.build_script() != \"\" )\n {\n \/\/ Locate a build script override file\n \/\/ > Note, override file can specify a list of commands to run.\n \/\/manifest.script_output = BuildScript::load( override_file );\n \/\/ Otherwise, compile and run build script\n \/\/manifest.script_output = BuildScript::load( ::helpers::path(\"output\") \/ \"build_\" + manifest.name + \".txt\" );\n \/\/ Parse build script output.\n throw ::std::runtime_error(\"TODO: Build script for \" + manifest.name());\n }\n\n return this->build_target(manifest, manifest.get_library());\n}\nbool Builder::spawn_process(const StringList& args, const ::helpers::path& logfile) const\n{\n#ifdef _WIN32\n ::std::stringstream cmdline;\n cmdline << \"mrustc.exe\";\n for (const auto& arg : args.get_vec())\n cmdline << \" \" << arg;\n auto cmdline_str = cmdline.str();\n DEBUG(\"Calling \" << cmdline_str);\n\n CreateDirectory(static_cast<::std::string>(logfile.parent()).c_str(), NULL);\n\n STARTUPINFO si = { 0 };\n si.cb = sizeof(si);\n si.dwFlags = STARTF_USESTDHANDLES;\n si.hStdInput = NULL;\n si.hStdError = GetStdHandle(STD_ERROR_HANDLE);\n {\n SECURITY_ATTRIBUTES sa = { 0 };\n sa.nLength = sizeof(sa);\n sa.bInheritHandle = TRUE;\n si.hStdOutput = CreateFile( static_cast<::std::string>(logfile).c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n DWORD tmp;\n WriteFile(si.hStdOutput, cmdline_str.data(), cmdline_str.size(), &tmp, NULL);\n WriteFile(si.hStdOutput, \"\\n\", 1, &tmp, NULL);\n }\n PROCESS_INFORMATION pi = { 0 };\n char env[] =\n \"MRUSTC_DEBUG=\"\"\\0\"\n ;\n CreateProcessA(\"x64\\\\Release\\\\mrustc.exe\", (LPSTR)cmdline_str.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);\n CloseHandle(si.hStdOutput);\n WaitForSingleObject(pi.hProcess, INFINITE);\n DWORD status = 1;\n GetExitCodeProcess(pi.hProcess, &status);\n if (status != 0)\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << status);\n return false;\n }\n#else\n\n \/\/ Create logfile output directory\n mkdir(static_cast<::std::string>(logfile.parent()).c_str(), 0755);\n\n \/\/ Create handles such that the log file is on stdout\n ::std::string logfile_str = logfile;\n pid_t pid;\n posix_spawn_file_actions_t fa;\n {\n posix_spawn_file_actions_init(&fa);\n posix_spawn_file_actions_addopen(&fa, 1, logfile_str.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0644);\n }\n\n \/\/ Generate `argv`\n auto argv = args.get_vec();\n argv.insert(argv.begin(), \"mrustc\");\n DEBUG(\"Calling \" << argv);\n argv.push_back(nullptr);\n\n \/\/ Generate `envp`\n ::std::vector envp;\n extern char **environ;\n for(auto p = environ; *p; p++)\n {\n envp.push_back(*p);\n }\n envp.push_back(nullptr);\n\n if( posix_spawn(&pid, \"..\/bin\/mrustc\", &fa, \/*attr=*\/nullptr, (char* const*)argv.data(), (char* const*)envp.data()) != 0 )\n {\n perror(\"posix_spawn\");\n DEBUG(\"Unable to spawn compiler\");\n posix_spawn_file_actions_destroy(&fa);\n return false;\n }\n posix_spawn_file_actions_destroy(&fa);\n int status = -1;\n waitpid(pid, &status, 0);\n if( WEXITSTATUS(status) != 0 )\n {\n DEBUG(\"Compiler exited with non-zero exit status \" << WEXITSTATUS(status));\n return false;\n }\n#endif\n return true;\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/include\/usr\/initservice\/mboxRegs.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef MBOXREGS_H_\n#define MBOXREGS_H_\n\nnamespace INITSERVICE\n{\nnamespace SPLESS\n{\n const uint32_t MBOX_SCRATCH_REG1 = 0x00050038; \/\/CFAM 2838\n const uint32_t MBOX_SCRATCH_REG2 = 0x00050039; \/\/CFAM 2839\n const uint32_t MBOX_SCRATCH_REG3 = 0x0005003a; \/\/CFAM 283A\n const uint32_t MBOX_SCRATCH_REG4 = 0x0005003b; \/\/CFAM 283B\n const uint32_t MBOX_SCRATCH_REG5 = 0x0005003c; \/\/CFAM 283C\n const uint32_t MBOX_SCRATCH_REG6 = 0x0005003d; \/\/CFAM 283D\n const uint32_t MBOX_SCRATCH_REG7 = 0x0005003e; \/\/CFAM 283E\n const uint32_t MBOX_SCRATCH_REG8 = 0x0005003f; \/\/CFAM 283F\n\n enum\n {\n SCRATCH_1 = 0x0, \/\/Location in array is reg num -1\n SCRATCH_2 = 0x1,\n SCRATCH_3 = 0x2,\n SCRATCH_4 = 0x3,\n SCRATCH_5 = 0x4,\n SCRATCH_6 = 0x5,\n SCRATCH_7 = 0x6,\n SCRATCH_8 = 0x7,\n };\n\n \/\/ Mailbox Scratch Register 3\n union MboxScratch3_t\n {\n uint32_t data32;\n struct\n {\n uint32_t istepMode :1; \/\/0\n uint32_t goToRuntime :1; \/\/1\n uint32_t isMpipl :1; \/\/2\n uint32_t fspAttached :1; \/\/3\n uint32_t sbeFFDC :1; \/\/4\n uint32_t sbeInternalFFDC :1; \/\/5\n uint32_t reserved :26; \/\/6:31\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 4\n union MboxScratch4_t\n {\n uint32_t data32;\n struct\n {\n uint32_t bootFreqMult :16; \/\/0:15\n uint32_t cpFilterBypass :1; \/\/16\n uint32_t ssFilterBypass :1; \/\/17\n uint32_t ioFilterBypass :1; \/\/18\n uint32_t dpllBypass :1; \/\/19\n uint32_t nestMemXoPcieBypass :1; \/\/20\n uint32_t reserved :3; \/\/21:23\n uint32_t nestPllBucket :8; \/\/24:31\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 5\n union MboxScratch5_t\n {\n uint32_t data32;\n struct\n {\n uint32_t cacheContained :1; \/\/0\n uint32_t initAllCores :1; \/\/1\n uint32_t riskLevel :1; \/\/2\n uint32_t noBLVectors :1; \/\/3\n uint32_t mcSyncMode :1; \/\/4\n uint32_t reserved :7; \/\/5:11\n uint32_t clockPllMux :20; \/\/12:31\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 7\n union MboxScratch7_t\n {\n uint32_t data32;\n struct\n {\n uint32_t drtmPayloadAddrMb :32; \/\/0\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 8\n union MboxScratch8_t\n {\n uint32_t data32;\n struct\n {\n uint32_t validFwFunctionalEqEc :1; \/\/0\n uint32_t validSbeI2cBusSpeed :1; \/\/1\n uint32_t validFwMode :1; \/\/2\n uint32_t validBootFreq :1; \/\/3\n uint32_t validHwpControlFlags :1; \/\/4\n uint32_t validMasterSlaveChipNode :1; \/\/5\n uint32_t validDrtmPayloadAddr :1; \/\/6\n uint32_t validBytes :1; \/\/7\n uint32_t reserved :24; \/\/8:31\n } PACKED;\n };\n\n};\n};\n#endif\nClean up some mbox scratch reg documentation\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/include\/usr\/initservice\/mboxRegs.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef MBOXREGS_H_\n#define MBOXREGS_H_\n\nnamespace INITSERVICE\n{\nnamespace SPLESS\n{\n const uint32_t MBOX_SCRATCH_REG1 = 0x00050038; \/\/CFAM 2838\n const uint32_t MBOX_SCRATCH_REG2 = 0x00050039; \/\/CFAM 2839\n const uint32_t MBOX_SCRATCH_REG3 = 0x0005003a; \/\/CFAM 283A\n const uint32_t MBOX_SCRATCH_REG4 = 0x0005003b; \/\/CFAM 283B\n const uint32_t MBOX_SCRATCH_REG5 = 0x0005003c; \/\/CFAM 283C\n const uint32_t MBOX_SCRATCH_REG6 = 0x0005003d; \/\/CFAM 283D\n const uint32_t MBOX_SCRATCH_REG7 = 0x0005003e; \/\/CFAM 283E\n const uint32_t MBOX_SCRATCH_REG8 = 0x0005003f; \/\/CFAM 283F\n\n enum\n {\n SCRATCH_1 = 0x0, \/\/Location in array is reg num -1\n SCRATCH_2 = 0x1,\n SCRATCH_3 = 0x2,\n SCRATCH_4 = 0x3,\n SCRATCH_5 = 0x4,\n SCRATCH_6 = 0x5,\n SCRATCH_7 = 0x6,\n SCRATCH_8 = 0x7,\n };\n\n \/\/ Mailbox Scratch Register 1\n union MboxScratch1_t\n {\n uint32_t data32;\n struct\n {\n \/\/ bit=1 means part is NOT functional\n uint32_t eqGard :8; \/\/0:7\n uint32_t ecGard :24; \/\/8:31\n } PACKED;\n \/\/ NOTE: Used for debug tool communication during Hostboot IPL\n };\n\n \/\/ Mailbox Scratch Register 2\n union MboxScratch2_t\n {\n uint32_t data32;\n struct\n {\n uint32_t i2cRefClockDiv :16; \/\/00:15\n uint32_t ndlMeshCtl :4; \/\/16:19\n uint32_t reserved :12; \/\/20:31\n } PACKED;\n \/\/ NOTE: Used for debug tool communication during Hostboot IPL\n };\n\n \/\/ Mailbox Scratch Register 3\n union MboxScratch3_t\n {\n uint32_t data32;\n struct\n {\n uint32_t istepMode :1; \/\/0\n uint32_t goToRuntime :1; \/\/1\n uint32_t isMpipl :1; \/\/2\n uint32_t fspAttached :1; \/\/3\n uint32_t reserved1 :1; \/\/4\n uint32_t sbeInternalFFDC :1; \/\/5\n uint32_t reserved2 :26; \/\/6:31\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 4\n union MboxScratch4_t\n {\n uint32_t data32;\n struct\n {\n uint32_t bootFreqMult :16; \/\/0:15\n uint32_t cpFilterBypass :1; \/\/16\n uint32_t ssFilterBypass :1; \/\/17\n uint32_t ioFilterBypass :1; \/\/18\n uint32_t dpllBypass :1; \/\/19\n uint32_t nestMemXoPcieBypass :1; \/\/20\n uint32_t obusHalfSpeed :1; \/\/21\n uint32_t reserved :2; \/\/22:23\n uint32_t nestPllBucket :8; \/\/24:31\n } PACKED;\n \/\/ NOTE: Used for debug tooling (SPLessCmd) during Hostboot IPL\n \/\/ NOTE: Used for sbe comm during runtime\n };\n\n \/\/ Mailbox Scratch Register 5\n union MboxScratch5_t\n {\n uint32_t data32;\n struct\n {\n uint32_t cacheContained :1; \/\/0\n uint32_t initAllCores :1; \/\/1\n uint32_t riskLevel :1; \/\/2\n uint32_t noBLVectors :1; \/\/3\n uint32_t mcSyncMode :1; \/\/4\n uint32_t slowPci :1; \/\/5\n uint32_t reserved :6; \/\/6:11\n uint32_t clockPllMux :20; \/\/12:31\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 6\n union MboxScratch6_t\n {\n uint32_t data32;\n struct\n {\n uint32_t reserved1 :23; \/\/0:22\n uint32_t groupPumpMode :1; \/\/23\n uint32_t isSlave :1; \/\/24\n uint32_t reserved2 :1; \/\/25\n uint32_t groupId :3; \/\/26:28\n uint32_t chipId :3; \/\/29:31\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 7\n union MboxScratch7_t\n {\n uint32_t data32;\n struct\n {\n uint32_t drtmPayloadAddrMb :32; \/\/0\n } PACKED;\n };\n\n \/\/ Mailbox Scratch Register 8\n union MboxScratch8_t\n {\n uint32_t data32;\n struct\n {\n uint32_t validFwFunctionalEqEc :1; \/\/0\n uint32_t validSbeI2cBusSpeed :1; \/\/1\n uint32_t validFwMode :1; \/\/2\n uint32_t validBootFreq :1; \/\/3\n uint32_t validHwpControlFlags :1; \/\/4\n uint32_t validMasterSlaveChipNode :1; \/\/5\n uint32_t validDrtmPayloadAddr :1; \/\/6\n uint32_t validBytes :1; \/\/7\n uint32_t reserved :24; \/\/8:31\n } PACKED;\n };\n\n};\n};\n#endif\n<|endoftext|>"} {"text":"#include \n\n#include \"..\/bench\/util.hpp\"\n#include \n#include \n\nusing namespace mapbox::geojsonvt;\n\ntemplate \nvoid drawLine(const T points) {\n glColor4f(1, 0, 0, 1);\n glBegin(GL_LINE_STRIP);\n for (const auto& pt : points) {\n glVertex2s(pt.x, pt.y);\n }\n glEnd();\n}\n\nstruct DrawFeature {\n void operator()(const mapbox::geometry::point&) {\n }\n\n void operator()(const mapbox::geometry::line_string& points) {\n drawLine(points);\n }\n\n void operator()(const mapbox::geometry::linear_ring& points) {\n drawLine(points);\n }\n\n void operator()(const mapbox::geometry::geometry& geometry) {\n mapbox::geometry::geometry::visit(geometry, DrawFeature{});\n }\n\n template \n void operator()(const T& vector) {\n for (const auto& e : vector) {\n operator()(e);\n }\n }\n};\n\nint main() {\n if (glfwInit() == 0) {\n return -1;\n }\n\n static int width = 768;\n static int fbWidth = width;\n static int height = 768;\n static int fbHeight = height;\n\n GLFWwindow* window =\n glfwCreateWindow(width, height, \"GeoJSON VT — Drop a GeoJSON file\", nullptr, nullptr);\n if (window == nullptr) {\n glfwTerminate();\n return -1;\n }\n\n static std::unique_ptr vt;\n\n static bool dirty = true;\n static struct TileID {\n int z;\n int x;\n int y;\n } pos = { 0, 0, 0 };\n\n enum class Horizontal { Left, Right, Outside };\n enum class Vertical { Top, Bottom, Outside };\n\n static Horizontal horizontal = Horizontal::Outside;\n static Vertical vertical = Vertical::Outside;\n\n Tile* tile = nullptr;\n\n static const auto updateTile = [&] {\n const std::string name =\n std::to_string(pos.z) + \"\/\" + std::to_string(pos.x) + \"\/\" + std::to_string(pos.y);\n if (vt) {\n Timer tileTimer;\n tile = const_cast(&vt->getTile(pos.z, pos.x, pos.y));\n tileTimer(\"tile \" + name);\n glfwSetWindowTitle(window, (std::string{ \"GeoJSON VT — \" } + name).c_str());\n }\n dirty = true;\n };\n\n static const auto loadGeoJSON = [&](const std::string& filename) {\n Timer timer;\n const std::string data = loadFile(filename);\n timer(\"loadFile\");\n\n const auto features =\n mapbox::geojson::parse(data).get();\n timer(\"parse into geometry\");\n\n vt = std::make_unique(features);\n timer(\"generate tile index\");\n updateTile();\n };\n\n static const auto updateLocation = [](const Horizontal newHorizontal,\n const Vertical newVertical) {\n if (newHorizontal != horizontal || newVertical != vertical) {\n dirty = true;\n horizontal = newHorizontal;\n vertical = newVertical;\n }\n };\n\n glfwSetDropCallback(window, [](GLFWwindow*, int count, const char* name[]) {\n if (count >= 1) {\n loadGeoJSON(name[0]);\n }\n });\n\n glfwSetKeyCallback(\n window, [](GLFWwindow* w, const int key, const int, const int action, const int) {\n if (key == GLFW_KEY_Q && action == GLFW_RELEASE) {\n glfwSetWindowShouldClose(w, 1);\n }\n if ((key == GLFW_KEY_BACKSPACE || key == GLFW_KEY_ESCAPE) && action == GLFW_RELEASE) {\n \/\/ zoom out\n if (pos.z > 0) {\n pos.z--;\n pos.x \/= 2;\n pos.y \/= 2;\n updateTile();\n }\n }\n });\n\n glfwSetWindowSizeCallback(window, [](GLFWwindow*, const int w, const int h) {\n width = w;\n height = h;\n dirty = true;\n });\n\n glfwSetFramebufferSizeCallback(window, [](GLFWwindow*, const int w, const int h) {\n fbWidth = w;\n fbHeight = h;\n });\n\n glfwSetCursorPosCallback(window, [](GLFWwindow*, const double x, const double y) {\n updateLocation((x > 0 && x < width) ? (x * 2 < width ? Horizontal::Left : Horizontal::Right)\n : Horizontal::Outside,\n (y > 0 && y < height) ? (y * 2 < height ? Vertical::Top : Vertical::Bottom)\n : Vertical::Outside);\n });\n\n glfwSetCursorEnterCallback(window, [](GLFWwindow*, int entered) {\n if (entered == 0) {\n updateLocation(Horizontal::Outside, Vertical::Outside);\n }\n });\n\n glfwSetMouseButtonCallback(window, [](GLFWwindow*, int button, int action, int) {\n if (button == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {\n \/\/ zoom into a particular tile\n if (pos.z < 18 && horizontal != Horizontal::Outside && vertical != Vertical::Outside) {\n pos.z++;\n pos.x *= 2;\n pos.y *= 2;\n if (horizontal == Horizontal::Right) {\n pos.x++;\n }\n if (vertical == Vertical::Bottom) {\n pos.y++;\n }\n updateTile();\n }\n } else if (button == GLFW_MOUSE_BUTTON_2 && action == GLFW_RELEASE) {\n \/\/ zoom out\n if (pos.z > 0) {\n pos.z--;\n pos.x \/= 2;\n pos.y \/= 2;\n updateTile();\n }\n }\n });\n\n glfwGetFramebufferSize(window, &fbWidth, &fbHeight);\n\n glfwMakeContextCurrent(window);\n\n const auto drawTile = [](bool active) {\n if (active) {\n glLineWidth(2);\n glColor4f(0, 0, 1, 1);\n } else {\n glLineWidth(1);\n glColor4f(0, 1, 0, 1);\n }\n\n glBegin(GL_LINE_STRIP);\n glVertex3f(0, 0, -static_cast(active));\n glVertex3f(0, 4096, -static_cast(active));\n glVertex3f(4096, 4096, -static_cast(active));\n glVertex3f(4096, 0, -static_cast(active));\n glVertex3f(0, 0, -static_cast(active));\n glEnd();\n };\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glEnable(GL_DEPTH_TEST);\n\n loadGeoJSON(\"data\/countries.geojson\");\n\n while (glfwWindowShouldClose(window) == 0) {\n if (dirty) {\n dirty = false;\n\n if (vt) {\n glClearColor(1, 1, 1, 1);\n } else {\n glClearColor(0.8, 0.8, 0.8, 1);\n }\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glViewport(0, 0, fbWidth, fbHeight);\n\n if (tile != nullptr) {\n \/\/ main tile\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-128, 4096 + 128, 4096 + 128, -128, 10, -10);\n\n glLineWidth(1);\n\n for (const auto& feature : tile->features) {\n mapbox::geometry::geometry::visit(feature.geometry, DrawFeature{});\n }\n\n \/\/ top left\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-256, 8192 + 256, 8192 + 256, -256, 10, -10);\n drawTile(horizontal == Horizontal::Left && vertical == Vertical::Top);\n\n \/\/ top right\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-4096 - 256, 8192 + 256 - 4096, 8192 + 256, -256, 10, -10);\n drawTile(horizontal == Horizontal::Right && vertical == Vertical::Top);\n\n \/\/ bottom left\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-256, 8192 + 256, 8192 + 256 - 4096, -256 - 4096, 10, -10);\n drawTile(horizontal == Horizontal::Left && vertical == Vertical::Bottom);\n\n \/\/ bottom right\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-4096 - 256, 8192 + 256 - 4096, 8192 + 256 - 4096, -256 - 4096, 10, -10);\n drawTile(horizontal == Horizontal::Right && vertical == Vertical::Bottom);\n } else {\n }\n\n glfwSwapBuffers(window);\n }\n\n glfwWaitEvents();\n }\n\n glfwTerminate();\n return 0;\n}\nAdd missing include#include \n#include \n#include \"..\/bench\/util.hpp\"\n#include \n#include \n\nusing namespace mapbox::geojsonvt;\n\ntemplate \nvoid drawLine(const T points) {\n glColor4f(1, 0, 0, 1);\n glBegin(GL_LINE_STRIP);\n for (const auto& pt : points) {\n glVertex2s(pt.x, pt.y);\n }\n glEnd();\n}\n\nstruct DrawFeature {\n void operator()(const mapbox::geometry::point&) {\n }\n\n void operator()(const mapbox::geometry::line_string& points) {\n drawLine(points);\n }\n\n void operator()(const mapbox::geometry::linear_ring& points) {\n drawLine(points);\n }\n\n void operator()(const mapbox::geometry::geometry& geometry) {\n mapbox::geometry::geometry::visit(geometry, DrawFeature{});\n }\n\n template \n void operator()(const T& vector) {\n for (const auto& e : vector) {\n operator()(e);\n }\n }\n};\n\nint main() {\n if (glfwInit() == 0) {\n return -1;\n }\n\n static int width = 768;\n static int fbWidth = width;\n static int height = 768;\n static int fbHeight = height;\n\n GLFWwindow* window =\n glfwCreateWindow(width, height, \"GeoJSON VT — Drop a GeoJSON file\", nullptr, nullptr);\n if (window == nullptr) {\n glfwTerminate();\n return -1;\n }\n\n static std::unique_ptr vt;\n\n static bool dirty = true;\n static struct TileID {\n int z;\n int x;\n int y;\n } pos = { 0, 0, 0 };\n\n enum class Horizontal { Left, Right, Outside };\n enum class Vertical { Top, Bottom, Outside };\n\n static Horizontal horizontal = Horizontal::Outside;\n static Vertical vertical = Vertical::Outside;\n\n Tile* tile = nullptr;\n\n static const auto updateTile = [&] {\n const std::string name =\n std::to_string(pos.z) + \"\/\" + std::to_string(pos.x) + \"\/\" + std::to_string(pos.y);\n if (vt) {\n Timer tileTimer;\n tile = const_cast(&vt->getTile(pos.z, pos.x, pos.y));\n tileTimer(\"tile \" + name);\n glfwSetWindowTitle(window, (std::string{ \"GeoJSON VT — \" } + name).c_str());\n }\n dirty = true;\n };\n\n static const auto loadGeoJSON = [&](const std::string& filename) {\n Timer timer;\n const std::string data = loadFile(filename);\n timer(\"loadFile\");\n\n const auto features =\n mapbox::geojson::parse(data).get();\n timer(\"parse into geometry\");\n\n vt = std::make_unique(features);\n timer(\"generate tile index\");\n updateTile();\n };\n\n static const auto updateLocation = [](const Horizontal newHorizontal,\n const Vertical newVertical) {\n if (newHorizontal != horizontal || newVertical != vertical) {\n dirty = true;\n horizontal = newHorizontal;\n vertical = newVertical;\n }\n };\n\n glfwSetDropCallback(window, [](GLFWwindow*, int count, const char* name[]) {\n if (count >= 1) {\n loadGeoJSON(name[0]);\n }\n });\n\n glfwSetKeyCallback(\n window, [](GLFWwindow* w, const int key, const int, const int action, const int) {\n if (key == GLFW_KEY_Q && action == GLFW_RELEASE) {\n glfwSetWindowShouldClose(w, 1);\n }\n if ((key == GLFW_KEY_BACKSPACE || key == GLFW_KEY_ESCAPE) && action == GLFW_RELEASE) {\n \/\/ zoom out\n if (pos.z > 0) {\n pos.z--;\n pos.x \/= 2;\n pos.y \/= 2;\n updateTile();\n }\n }\n });\n\n glfwSetWindowSizeCallback(window, [](GLFWwindow*, const int w, const int h) {\n width = w;\n height = h;\n dirty = true;\n });\n\n glfwSetFramebufferSizeCallback(window, [](GLFWwindow*, const int w, const int h) {\n fbWidth = w;\n fbHeight = h;\n });\n\n glfwSetCursorPosCallback(window, [](GLFWwindow*, const double x, const double y) {\n updateLocation((x > 0 && x < width) ? (x * 2 < width ? Horizontal::Left : Horizontal::Right)\n : Horizontal::Outside,\n (y > 0 && y < height) ? (y * 2 < height ? Vertical::Top : Vertical::Bottom)\n : Vertical::Outside);\n });\n\n glfwSetCursorEnterCallback(window, [](GLFWwindow*, int entered) {\n if (entered == 0) {\n updateLocation(Horizontal::Outside, Vertical::Outside);\n }\n });\n\n glfwSetMouseButtonCallback(window, [](GLFWwindow*, int button, int action, int) {\n if (button == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {\n \/\/ zoom into a particular tile\n if (pos.z < 18 && horizontal != Horizontal::Outside && vertical != Vertical::Outside) {\n pos.z++;\n pos.x *= 2;\n pos.y *= 2;\n if (horizontal == Horizontal::Right) {\n pos.x++;\n }\n if (vertical == Vertical::Bottom) {\n pos.y++;\n }\n updateTile();\n }\n } else if (button == GLFW_MOUSE_BUTTON_2 && action == GLFW_RELEASE) {\n \/\/ zoom out\n if (pos.z > 0) {\n pos.z--;\n pos.x \/= 2;\n pos.y \/= 2;\n updateTile();\n }\n }\n });\n\n glfwGetFramebufferSize(window, &fbWidth, &fbHeight);\n\n glfwMakeContextCurrent(window);\n\n const auto drawTile = [](bool active) {\n if (active) {\n glLineWidth(2);\n glColor4f(0, 0, 1, 1);\n } else {\n glLineWidth(1);\n glColor4f(0, 1, 0, 1);\n }\n\n glBegin(GL_LINE_STRIP);\n glVertex3f(0, 0, -static_cast(active));\n glVertex3f(0, 4096, -static_cast(active));\n glVertex3f(4096, 4096, -static_cast(active));\n glVertex3f(4096, 0, -static_cast(active));\n glVertex3f(0, 0, -static_cast(active));\n glEnd();\n };\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glEnable(GL_DEPTH_TEST);\n\n loadGeoJSON(\"data\/countries.geojson\");\n\n while (glfwWindowShouldClose(window) == 0) {\n if (dirty) {\n dirty = false;\n\n if (vt) {\n glClearColor(1, 1, 1, 1);\n } else {\n glClearColor(0.8, 0.8, 0.8, 1);\n }\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glViewport(0, 0, fbWidth, fbHeight);\n\n if (tile != nullptr) {\n \/\/ main tile\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-128, 4096 + 128, 4096 + 128, -128, 10, -10);\n\n glLineWidth(1);\n\n for (const auto& feature : tile->features) {\n mapbox::geometry::geometry::visit(feature.geometry, DrawFeature{});\n }\n\n \/\/ top left\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-256, 8192 + 256, 8192 + 256, -256, 10, -10);\n drawTile(horizontal == Horizontal::Left && vertical == Vertical::Top);\n\n \/\/ top right\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-4096 - 256, 8192 + 256 - 4096, 8192 + 256, -256, 10, -10);\n drawTile(horizontal == Horizontal::Right && vertical == Vertical::Top);\n\n \/\/ bottom left\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-256, 8192 + 256, 8192 + 256 - 4096, -256 - 4096, 10, -10);\n drawTile(horizontal == Horizontal::Left && vertical == Vertical::Bottom);\n\n \/\/ bottom right\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-4096 - 256, 8192 + 256 - 4096, 8192 + 256 - 4096, -256 - 4096, 10, -10);\n drawTile(horizontal == Horizontal::Right && vertical == Vertical::Bottom);\n } else {\n }\n\n glfwSwapBuffers(window);\n }\n\n glfwWaitEvents();\n }\n\n glfwTerminate();\n return 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\/*\n* Covariant Mozart Utility Library: Any\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* any later version.\n*\n* This program 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 General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n*\n* Copyright (C) 2017 Michael Lee(李登淳)\n* Email: China-LDC@outlook.com\n* Github: https:\/\/github.com\/mikecovlee\n* Website: http:\/\/ldc.atd3.cn\n*\n* Version: 17.4.4\n*\/\n#include \".\/base.hpp\"\n#include \n#include \n\nnamespace std {\n\ttemplate std::string to_string(const T&)\n\t{\n\t\tthrow cov::error(\"E000D\");\n\t}\n\ttemplate<> std::string to_string(const std::string& str)\n\t{\n\t\treturn str;\n\t}\n\ttemplate<> std::string to_string(const bool& v)\n\t{\n\t\tif(v)\n\t\t\treturn \"true\";\n\t\telse\n\t\t\treturn \"false\";\n\t}\n}\n\nnamespace cov {\n\ttemplate class compare_helper {\n\t\ttemplatestruct matcher;\n\t\ttemplate static constexpr bool match(T*)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\ttemplate static constexpr bool match(matcher < T, decltype(std::declval()==std::declval()) > *)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tstatic constexpr bool value = match < _Tp > (nullptr);\n\t};\n\ttemplate struct compare_if;\n\ttemplatestruct compare_if {\n\t\tstatic bool compare(const T& a,const T& b)\n\t\t{\n\t\t\treturn a==b;\n\t\t}\n\t};\n\ttemplatestruct compare_if {\n\t\tstatic bool compare(const T& a,const T& b)\n\t\t{\n\t\t\treturn &a==&b;\n\t\t}\n\t};\n\ttemplatebool compare(const T& a,const T& b)\n\t{\n\t\treturn compare_if::value>::compare(a,b);\n\t}\n\ttemplate class hash_helper {\n\t\ttemplate::operator()) X>struct matcher;\n\t\ttemplate static constexpr bool match(T*)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\ttemplate static constexpr bool match(matcher::operator()>*)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tstatic constexpr bool value = match < _Tp > (nullptr);\n\t};\n\ttemplate struct hash_if;\n\ttemplatestruct hash_if {\n\t\tstatic std::size_t hash(const T& val)\n\t\t{\n\t\t\tstatic std::hash gen;\n\t\t\treturn gen(val);\n\t\t}\n\t};\n\ttemplatestruct hash_if {\n\t\tstatic std::size_t hash(const T& val)\n\t\t{\n\t\t\tthrow cov::error(\"E000F\");\n\t\t}\n\t};\n\ttemplatestd::size_t hash(const T& val)\n\t{\n\t\treturn hash_if::value>::hash(val);\n\t}\n\ttemplatevoid detach(T& val)\n\t{\n\t\t\/\/ Do something if you want when data is copying.\n\t}\n\tclass any final {\n\t\tclass baseHolder {\n\t\tpublic:\n\t\t\tbaseHolder() = default;\n\t\t\tvirtual ~ baseHolder() = default;\n\t\t\tvirtual const std::type_info& type() const = 0;\n\t\t\tvirtual baseHolder* duplicate() = 0;\n\t\t\tvirtual bool compare(const baseHolder *) const = 0;\n\t\t\tvirtual std::string to_string() const = 0;\n\t\t\tvirtual std::size_t hash() const = 0;\n\t\t\tvirtual void detach() = 0;\n\t\t};\n\t\ttemplate < typename T > class holder:public baseHolder {\n\t\tprotected:\n\t\t\tT mDat;\n\t\tpublic:\n\t\t\tholder() = default;\n\t\t\ttemplateholder(ArgsT&&...args):mDat(std::forward(args)...) {}\n\t\t\tvirtual ~ holder() = default;\n\t\t\tvirtual const std::type_info& type() const override\n\t\t\t{\n\t\t\t\treturn typeid(T);\n\t\t\t}\n\t\t\tvirtual baseHolder* duplicate() override\n\t\t\t{\n\t\t\t\treturn new holder(mDat);\n\t\t\t}\n\t\t\tvirtual bool compare(const baseHolder* obj) const override\n\t\t\t{\n\t\t\t\tif (obj->type()==this->type()) {\n\t\t\t\t\tconst holder* ptr=dynamic_cast*>(obj);\n\t\t\t\t\treturn ptr!=nullptr?cov::compare(mDat,ptr->data()):false;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvirtual std::string to_string() const override\n\t\t\t{\n\t\t\t\treturn std::to_string(mDat);\n\t\t\t}\n\t\t\tvirtual std::size_t hash() const override\n\t\t\t{\n\t\t\t\treturn cov::hash(mDat);\n\t\t\t}\n\t\t\tvirtual void detach() override\n\t\t\t{\n\t\t\t\tcov::detach(mDat);\n\t\t\t}\n\t\t\tT& data()\n\t\t\t{\n\t\t\t\treturn mDat;\n\t\t\t}\n\t\t\tconst T& data() const\n\t\t\t{\n\t\t\t\treturn mDat;\n\t\t\t}\n\t\t\tvoid data(const T& dat)\n\t\t\t{\n\t\t\t\tmDat = dat;\n\t\t\t}\n\t\t};\n\t\tusing size_t=unsigned long;\n\t\tstruct proxy {\n\t\t\tsize_t refcount=1;\n\t\t\tbaseHolder* data=nullptr;\n\t\t\tproxy()=default;\n\t\t\tproxy(size_t rc,baseHolder* d):refcount(rc),data(d) {}\n\t\t\t~proxy()\n\t\t\t{\n\t\t\t\tdelete data;\n\t\t\t}\n\t\t};\n\t\tproxy* mDat=nullptr;\n\t\tproxy* duplicate() const noexcept\n\t\t{\n\t\t\tif(mDat!=nullptr) {\n\t\t\t\t++mDat->refcount;\n\t\t\t}\n\t\t\treturn mDat;\n\t\t}\n\t\tvoid recycle() noexcept\n\t\t{\n\t\t\tif(mDat!=nullptr) {\n\t\t\t\t--mDat->refcount;\n\t\t\t\tif(mDat->refcount==0) {\n\t\t\t\t\tdelete mDat;\n\t\t\t\t\tmDat=nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tany(proxy* dat):mDat(dat) {}\n\tpublic:\n\t\tvoid swap(any& obj,bool raw=false) noexcept\n\t\t{\n\t\t\tif(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) {\n\t\t\t\tbaseHolder* tmp=this->mDat->data;\n\t\t\t\tthis->mDat->data=obj.mDat->data;\n\t\t\t\tobj.mDat->data=tmp;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tproxy* tmp=this->mDat;\n\t\t\t\tthis->mDat=obj.mDat;\n\t\t\t\tobj.mDat=tmp;\n\t\t\t}\n\t\t}\n\t\tvoid swap(any&& obj) noexcept\n\t\t{\n\t\t\tproxy* tmp=this->mDat;\n\t\t\tthis->mDat=obj.mDat;\n\t\t\tobj.mDat=tmp;\n\t\t}\n\t\tvoid clone() noexcept\n\t\t{\n\t\t\tif(mDat!=nullptr) {\n\t\t\t\tproxy* dat=new proxy(1,mDat->data->duplicate());\n\t\t\t\trecycle();\n\t\t\t\tmDat=dat;\n\t\t\t}\n\t\t}\n\t\tbool usable() const noexcept\n\t\t{\n\t\t\treturn mDat!=nullptr;\n\t\t}\n\t\ttemplatestatic any make(ArgsT&&...args)\n\t\t{\n\t\t\treturn any(new proxy(1,new holder(std::forward(args)...)));\n\t\t}\n\t\tany()=default;\n\t\ttemplate any(const T & dat):mDat(new proxy(1,new holder (dat))) {}\n\t\tany(const any & v):mDat(v.duplicate()) {}\n\t\tany(any&& v) noexcept\n\t\t{\n\t\t\tswap(std::forward(v));\n\t\t}\n\t\t~any()\n\t\t{\n\t\t\trecycle();\n\t\t}\n\t\tconst std::type_info& type() const\n\t\t{\n\t\t\treturn this->mDat!=nullptr?this->mDat->data->type():typeid(void);\n\t\t}\n\t\tstd::string to_string() const\n\t\t{\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\treturn \"Null\";\n\t\t\treturn this->mDat->data->to_string();\n\t\t}\n\t\tstd::size_t hash() const\n\t\t{\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\treturn cov::hash(nullptr);\n\t\t\treturn this->mDat->data->hash();\n\t\t}\n\t\tvoid detach()\n\t\t{\n\t\t\tif(this->mDat!=nullptr)\n\t\t\t\tthis->mDat->data->detach();\n\t\t}\n\t\tbool is_same(const any& obj) const\n\t\t{\n\t\t\treturn this->mDat==obj.mDat;\n\t\t}\n\t\tany& operator=(const any& var)\n\t\t{\n\t\t\tif(&var!=this) {\n\t\t\t\trecycle();\n\t\t\t\tmDat=var.duplicate();\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\tany& operator=(any&& var) noexcept\n\t\t{\n\t\t\tif(&var!=this)\n\t\t\t\tswap(std::forward(var));\n\t\t\treturn *this;\n\t\t}\n\t\tbool operator==(const any& var) const\n\t\t{\n\t\t\treturn usable()?this->mDat->data->compare(var.mDat->data):!var.usable();\n\t\t}\n\t\tbool operator!=(const any& var)const\n\t\t{\n\t\t\treturn usable()?!this->mDat->data->compare(var.mDat->data):var.usable();\n\t\t}\n\t\ttemplate T& val(bool raw=false)\n\t\t{\n\t\t\tif(typeid(T)!=this->type())\n\t\t\t\tthrow cov::error(\"E0006\");\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\tthrow cov::error(\"E0005\");\n\t\t\tif(!raw)\n\t\t\t\tclone();\n\t\t\treturn dynamic_cast*>(this->mDat->data)->data();\n\t\t}\n\t\ttemplate const T& val(bool raw=false) const\n\t\t{\n\t\t\tif(typeid(T)!=this->type())\n\t\t\t\tthrow cov::error(\"E0006\");\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\tthrow cov::error(\"E0005\");\n\t\t\treturn dynamic_cast*>(this->mDat->data)->data();\n\t\t}\n\t\ttemplate const T& const_val() const\n\t\t{\n\t\t\tif(typeid(T)!=this->type())\n\t\t\t\tthrow cov::error(\"E0006\");\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\tthrow cov::error(\"E0005\");\n\t\t\treturn dynamic_cast*>(this->mDat->data)->data();\n\t\t}\n\t\ttemplate operator const T&() const\n\t\t{\n\t\t\treturn this->const_val();\n\t\t}\n\t\tvoid assign(const any& obj,bool raw=false)\n\t\t{\n\t\t\tif(&obj!=this&&obj.mDat!=mDat) {\n\t\t\t\tif(mDat!=nullptr&&obj.mDat!=nullptr&&raw) {\n\t\t\t\t\tdelete mDat->data;\n\t\t\t\t\tmDat->data=obj.mDat->data->duplicate();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\trecycle();\n\t\t\t\t\tif(obj.mDat!=nullptr)\n\t\t\t\t\t\tmDat=new proxy(1,obj.mDat->data->duplicate());\n\t\t\t\t\telse\n\t\t\t\t\t\tmDat=nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttemplate void assign(const T& dat,bool raw=false)\n\t\t{\n\t\t\tif(raw) {\n\t\t\t\tdelete mDat->data;\n\t\t\t\tmDat->data=new holder(dat);\n\t\t\t}\n\t\t\telse {\n\t\t\t\trecycle();\n\t\t\t\tmDat=new proxy(1,new holder(dat));\n\t\t\t}\n\t\t}\n\t\ttemplate any & operator=(const T& dat)\n\t\t{\n\t\t\tassign(dat);\n\t\t\treturn *this;\n\t\t}\n\t};\n\ttemplate class any::holder:public any::holder {\n\tpublic:\n\t\tusing holder::holder;\n\t};\n\ttemplate<> class any::holder:public any::holder {\n\tpublic:\n\t\tusing holder::holder;\n\t};\n}\n\nstd::ostream& operator<<(std::ostream& out,const cov::any& val)\n{\n\tout< struct hash {\n\t\tstd::size_t operator()(const cov::any& val) const\n\t\t{\n\t\t\treturn val.hash();\n\t\t}\n\t};\n}\n更新cov::any以适应covbasic的功能#pragma once\n\/*\n* Covariant Mozart Utility Library: Any\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* any later version.\n*\n* This program 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 General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n*\n* Copyright (C) 2017 Michael Lee(李登淳)\n* Email: China-LDC@outlook.com\n* Github: https:\/\/github.com\/mikecovlee\n* Website: http:\/\/ldc.atd3.cn\n*\n* Version: 17.4.4\n*\/\n#include \".\/base.hpp\"\n#include \n#include \n\nnamespace std {\n\ttemplate std::string to_string(const T&)\n\t{\n\t\tthrow cov::error(\"E000D\");\n\t}\n\ttemplate<> std::string to_string(const std::string& str)\n\t{\n\t\treturn str;\n\t}\n\ttemplate<> std::string to_string(const bool& v)\n\t{\n\t\tif(v)\n\t\t\treturn \"true\";\n\t\telse\n\t\t\treturn \"false\";\n\t}\n}\n\nnamespace cov {\n\ttemplate class compare_helper {\n\t\ttemplatestruct matcher;\n\t\ttemplate static constexpr bool match(T*)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\ttemplate static constexpr bool match(matcher < T, decltype(std::declval()==std::declval()) > *)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tstatic constexpr bool value = match < _Tp > (nullptr);\n\t};\n\ttemplate struct compare_if;\n\ttemplatestruct compare_if {\n\t\tstatic bool compare(const T& a,const T& b)\n\t\t{\n\t\t\treturn a==b;\n\t\t}\n\t};\n\ttemplatestruct compare_if {\n\t\tstatic bool compare(const T& a,const T& b)\n\t\t{\n\t\t\treturn &a==&b;\n\t\t}\n\t};\n\ttemplatebool compare(const T& a,const T& b)\n\t{\n\t\treturn compare_if::value>::compare(a,b);\n\t}\n\ttemplate class hash_helper {\n\t\ttemplate::operator()) X>struct matcher;\n\t\ttemplate static constexpr bool match(T*)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\ttemplate static constexpr bool match(matcher::operator()>*)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tstatic constexpr bool value = match < _Tp > (nullptr);\n\t};\n\ttemplate struct hash_if;\n\ttemplatestruct hash_if {\n\t\tstatic std::size_t hash(const T& val)\n\t\t{\n\t\t\tstatic std::hash gen;\n\t\t\treturn gen(val);\n\t\t}\n\t};\n\ttemplatestruct hash_if {\n\t\tstatic std::size_t hash(const T& val)\n\t\t{\n\t\t\tthrow cov::error(\"E000F\");\n\t\t}\n\t};\n\ttemplatestd::size_t hash(const T& val)\n\t{\n\t\treturn hash_if::value>::hash(val);\n\t}\n\ttemplatevoid detach(T& val)\n\t{\n\t\t\/\/ Do something if you want when data is copying.\n\t}\n\tclass any final {\n\t\tclass baseHolder {\n\t\tpublic:\n\t\t\tbaseHolder() = default;\n\t\t\tvirtual ~ baseHolder() = default;\n\t\t\tvirtual const std::type_info& type() const = 0;\n\t\t\tvirtual baseHolder* duplicate() = 0;\n\t\t\tvirtual bool compare(const baseHolder *) const = 0;\n\t\t\tvirtual std::string to_string() const = 0;\n\t\t\tvirtual std::size_t hash() const = 0;\n\t\t\tvirtual void detach() = 0;\n\t\t};\n\t\ttemplate < typename T > class holder:public baseHolder {\n\t\tprotected:\n\t\t\tT mDat;\n\t\tpublic:\n\t\t\tholder() = default;\n\t\t\ttemplateholder(ArgsT&&...args):mDat(std::forward(args)...) {}\n\t\t\tvirtual ~ holder() = default;\n\t\t\tvirtual const std::type_info& type() const override\n\t\t\t{\n\t\t\t\treturn typeid(T);\n\t\t\t}\n\t\t\tvirtual baseHolder* duplicate() override\n\t\t\t{\n\t\t\t\treturn new holder(mDat);\n\t\t\t}\n\t\t\tvirtual bool compare(const baseHolder* obj) const override\n\t\t\t{\n\t\t\t\tif (obj->type()==this->type()) {\n\t\t\t\t\tconst holder* ptr=dynamic_cast*>(obj);\n\t\t\t\t\treturn ptr!=nullptr?cov::compare(mDat,ptr->data()):false;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvirtual std::string to_string() const override\n\t\t\t{\n\t\t\t\treturn std::to_string(mDat);\n\t\t\t}\n\t\t\tvirtual std::size_t hash() const override\n\t\t\t{\n\t\t\t\treturn cov::hash(mDat);\n\t\t\t}\n\t\t\tvirtual void detach() override\n\t\t\t{\n\t\t\t\tcov::detach(mDat);\n\t\t\t}\n\t\t\tT& data()\n\t\t\t{\n\t\t\t\treturn mDat;\n\t\t\t}\n\t\t\tconst T& data() const\n\t\t\t{\n\t\t\t\treturn mDat;\n\t\t\t}\n\t\t\tvoid data(const T& dat)\n\t\t\t{\n\t\t\t\tmDat = dat;\n\t\t\t}\n\t\t};\n\t\tusing size_t=unsigned long;\n\t\tstruct proxy {\n\t\t\tsize_t refcount=1;\n\t\t\tbaseHolder* data=nullptr;\n\t\t\tproxy()=default;\n\t\t\tproxy(size_t rc,baseHolder* d):refcount(rc),data(d) {}\n\t\t\t~proxy()\n\t\t\t{\n\t\t\t\tdelete data;\n\t\t\t}\n\t\t};\n\t\tproxy* mDat=nullptr;\n\t\tproxy* duplicate() const noexcept\n\t\t{\n\t\t\tif(mDat!=nullptr) {\n\t\t\t\t++mDat->refcount;\n\t\t\t}\n\t\t\treturn mDat;\n\t\t}\n\t\tvoid recycle() noexcept\n\t\t{\n\t\t\tif(mDat!=nullptr) {\n\t\t\t\t--mDat->refcount;\n\t\t\t\tif(mDat->refcount==0) {\n\t\t\t\t\tdelete mDat;\n\t\t\t\t\tmDat=nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tany(proxy* dat):mDat(dat) {}\n\tpublic:\n\t\tvoid swap(any& obj,bool raw=false) noexcept\n\t\t{\n\t\t\tif(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) {\n\t\t\t\tbaseHolder* tmp=this->mDat->data;\n\t\t\t\tthis->mDat->data=obj.mDat->data;\n\t\t\t\tobj.mDat->data=tmp;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tproxy* tmp=this->mDat;\n\t\t\t\tthis->mDat=obj.mDat;\n\t\t\t\tobj.mDat=tmp;\n\t\t\t}\n\t\t}\n\t\tvoid swap(any&& obj,bool raw=false) noexcept\n\t\t{\n\t\t\tif(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) {\n\t\t\t\tbaseHolder* tmp=this->mDat->data;\n\t\t\t\tthis->mDat->data=obj.mDat->data;\n\t\t\t\tobj.mDat->data=tmp;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tproxy* tmp=this->mDat;\n\t\t\t\tthis->mDat=obj.mDat;\n\t\t\t\tobj.mDat=tmp;\n\t\t\t}\n\t\t}\n\t\tvoid clone() noexcept\n\t\t{\n\t\t\tif(mDat!=nullptr) {\n\t\t\t\tproxy* dat=new proxy(1,mDat->data->duplicate());\n\t\t\t\trecycle();\n\t\t\t\tmDat=dat;\n\t\t\t}\n\t\t}\n\t\tbool usable() const noexcept\n\t\t{\n\t\t\treturn mDat!=nullptr;\n\t\t}\n\t\ttemplatestatic any make(ArgsT&&...args)\n\t\t{\n\t\t\treturn any(new proxy(1,new holder(std::forward(args)...)));\n\t\t}\n\t\tany()=default;\n\t\ttemplate any(const T & dat):mDat(new proxy(1,new holder (dat))) {}\n\t\tany(const any & v):mDat(v.duplicate()) {}\n\t\tany(any&& v) noexcept\n\t\t{\n\t\t\tswap(std::forward(v));\n\t\t}\n\t\t~any()\n\t\t{\n\t\t\trecycle();\n\t\t}\n\t\tconst std::type_info& type() const\n\t\t{\n\t\t\treturn this->mDat!=nullptr?this->mDat->data->type():typeid(void);\n\t\t}\n\t\tstd::string to_string() const\n\t\t{\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\treturn \"Null\";\n\t\t\treturn this->mDat->data->to_string();\n\t\t}\n\t\tstd::size_t hash() const\n\t\t{\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\treturn cov::hash(nullptr);\n\t\t\treturn this->mDat->data->hash();\n\t\t}\n\t\tvoid detach()\n\t\t{\n\t\t\tif(this->mDat!=nullptr)\n\t\t\t\tthis->mDat->data->detach();\n\t\t}\n\t\tbool is_same(const any& obj) const\n\t\t{\n\t\t\treturn this->mDat==obj.mDat;\n\t\t}\n\t\tany& operator=(const any& var)\n\t\t{\n\t\t\tif(&var!=this) {\n\t\t\t\trecycle();\n\t\t\t\tmDat=var.duplicate();\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\tany& operator=(any&& var) noexcept\n\t\t{\n\t\t\tif(&var!=this)\n\t\t\t\tswap(std::forward(var));\n\t\t\treturn *this;\n\t\t}\n\t\tbool operator==(const any& var) const\n\t\t{\n\t\t\treturn usable()?this->mDat->data->compare(var.mDat->data):!var.usable();\n\t\t}\n\t\tbool operator!=(const any& var)const\n\t\t{\n\t\t\treturn usable()?!this->mDat->data->compare(var.mDat->data):var.usable();\n\t\t}\n\t\ttemplate T& val(bool raw=false)\n\t\t{\n\t\t\tif(typeid(T)!=this->type())\n\t\t\t\tthrow cov::error(\"E0006\");\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\tthrow cov::error(\"E0005\");\n\t\t\tif(!raw)\n\t\t\t\tclone();\n\t\t\treturn dynamic_cast*>(this->mDat->data)->data();\n\t\t}\n\t\ttemplate const T& val(bool raw=false) const\n\t\t{\n\t\t\tif(typeid(T)!=this->type())\n\t\t\t\tthrow cov::error(\"E0006\");\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\tthrow cov::error(\"E0005\");\n\t\t\treturn dynamic_cast*>(this->mDat->data)->data();\n\t\t}\n\t\ttemplate const T& const_val() const\n\t\t{\n\t\t\tif(typeid(T)!=this->type())\n\t\t\t\tthrow cov::error(\"E0006\");\n\t\t\tif(this->mDat==nullptr)\n\t\t\t\tthrow cov::error(\"E0005\");\n\t\t\treturn dynamic_cast*>(this->mDat->data)->data();\n\t\t}\n\t\ttemplate operator const T&() const\n\t\t{\n\t\t\treturn this->const_val();\n\t\t}\n\t\tvoid assign(const any& obj,bool raw=false)\n\t\t{\n\t\t\tif(&obj!=this&&obj.mDat!=mDat) {\n\t\t\t\tif(mDat!=nullptr&&obj.mDat!=nullptr&&raw) {\n\t\t\t\t\tdelete mDat->data;\n\t\t\t\t\tmDat->data=obj.mDat->data->duplicate();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\trecycle();\n\t\t\t\t\tif(obj.mDat!=nullptr)\n\t\t\t\t\t\tmDat=new proxy(1,obj.mDat->data->duplicate());\n\t\t\t\t\telse\n\t\t\t\t\t\tmDat=nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttemplate void assign(const T& dat,bool raw=false)\n\t\t{\n\t\t\tif(raw) {\n\t\t\t\tdelete mDat->data;\n\t\t\t\tmDat->data=new holder(dat);\n\t\t\t}\n\t\t\telse {\n\t\t\t\trecycle();\n\t\t\t\tmDat=new proxy(1,new holder(dat));\n\t\t\t}\n\t\t}\n\t\ttemplate any & operator=(const T& dat)\n\t\t{\n\t\t\tassign(dat);\n\t\t\treturn *this;\n\t\t}\n\t};\n\ttemplate class any::holder:public any::holder {\n\tpublic:\n\t\tusing holder::holder;\n\t};\n\ttemplate<> class any::holder:public any::holder {\n\tpublic:\n\t\tusing holder::holder;\n\t};\n}\n\nstd::ostream& operator<<(std::ostream& out,const cov::any& val)\n{\n\tout< struct hash {\n\t\tstd::size_t operator()(const cov::any& val) const\n\t\t{\n\t\t\treturn val.hash();\n\t\t}\n\t};\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2013 Andreas Hartmetz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"localsocket.h\"\n\n#include \n#include \n#include \n#include \n#include \"sys\/uio.h\"\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/ HACK, put this somewhere else (get the value from original d-bus? or is it infinite?)\nstatic const int maxFds = 12;\n\nusing namespace std;\n\nLocalSocket::LocalSocket(const string &socketFilePath)\n : m_fd(-1)\n{\n m_supportsFileDescriptors = true;\n const int fd = socket(PF_UNIX, SOCK_STREAM, 0);\n if (fd < 0) {\n return;\n }\n \/\/ don't let forks inherit the file descriptor - that can cause confusion...\n fcntl(fd, F_SETFD, FD_CLOEXEC);\n\n struct sockaddr_un addr;\n addr.sun_family = PF_UNIX;\n bool ok = socketFilePath.length() < sizeof(addr.sun_path);\n if (ok) {\n memcpy(addr.sun_path, socketFilePath.c_str(), socketFilePath.length());\n }\n\n ok = ok && (connect(fd, (struct sockaddr *)&addr, sizeof(sa_family_t) + socketFilePath.length()) == 0);\n\n if (ok) {\n m_fd = fd;\n } else {\n ::close(fd);\n }\n}\n\nLocalSocket::LocalSocket(int fd)\n : m_fd(fd)\n{\n}\n\nLocalSocket::~LocalSocket()\n{\n close();\n}\n\nvoid LocalSocket::close()\n{\n setEventDispatcher(nullptr);\n if (m_fd >= 0) {\n ::close(m_fd);\n }\n m_fd = -1;\n}\n\nuint32 LocalSocket::write(chunk data)\n{\n if (m_fd < 0) {\n return 0; \/\/ TODO -1?\n }\n\n const uint32 initialLength = data.length;\n\n while (data.length > 0) {\n ssize_t nbytes = send(m_fd, data.ptr, data.length, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ see EAGAIN comment in read()\n if (errno == EAGAIN \/* && iov.iov_len < a.length *\/ ) {\n break;\n }\n close();\n return false;\n }\n\n data.ptr += nbytes;\n data.length -= size_t(nbytes);\n }\n\n return initialLength - data.length;\n}\n\n\/\/ TODO: consider using iovec to avoid \"copying together\" message parts before sending; iovec tricks\n\/\/ are probably not going to help for receiving, though.\nuint32 LocalSocket::writeWithFileDescriptors(chunk data, const vector &fileDescriptors)\n{\n if (m_fd < 0) {\n return 0; \/\/ TODO -1?\n }\n\n \/\/ sendmsg boilerplate\n struct msghdr send_msg;\n struct iovec iov;\n\n send_msg.msg_name = 0;\n send_msg.msg_namelen = 0;\n send_msg.msg_flags = 0;\n send_msg.msg_iov = &iov;\n send_msg.msg_iovlen = 1;\n\n iov.iov_base = data.ptr;\n iov.iov_len = data.length;\n\n \/\/ we can only send a fixed number of fds anyway due to the non-flexible size of the control message\n \/\/ receive buffer, so we set an arbitrary limit.\n const uint32 numFds = fileDescriptors.size();\n assert(fileDescriptors.size() <= maxFds); \/\/ TODO proper error\n\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n\n if (numFds) {\n \/\/ fill in a control message\n send_msg.msg_control = cmsgBuf;\n send_msg.msg_controllen = CMSG_SPACE(sizeof(int) * numFds);\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&send_msg);\n c_msg->cmsg_len = CMSG_LEN(sizeof(int) * numFds);\n c_msg->cmsg_level = SOL_SOCKET;\n c_msg->cmsg_type = SCM_RIGHTS;\n\n \/\/ set the control data to pass - this is why we don't use the simpler write()\n for (uint32 i = 0; i < numFds; i++) {\n reinterpret_cast(CMSG_DATA(c_msg))[i] = fileDescriptors[i];\n }\n } else {\n \/\/ no file descriptor to send, no control message\n send_msg.msg_control = 0;\n send_msg.msg_controllen = 0;\n }\n\n while (iov.iov_len > 0) {\n ssize_t nbytes = sendmsg(m_fd, &send_msg, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ see EAGAIN comment in read()\n if (errno == EAGAIN \/* && iov.iov_len < a.length *\/ ) {\n break;\n }\n close();\n return false;\n }\n\n iov.iov_base = static_cast(iov.iov_base) + nbytes;\n iov.iov_len -= size_t(nbytes);\n }\n\n return data.length - iov.iov_len;\n}\n\nuint32 LocalSocket::availableBytesForReading()\n{\n uint32 available = 0;\n if (ioctl(m_fd, FIONREAD, &available) < 0) {\n available = 0;\n }\n return available;\n}\n\nchunk LocalSocket::read(byte *buffer, uint32 maxSize)\n{\n chunk ret(buffer, 0);\n\n while (ret.length < maxSize) {\n ssize_t nbytes = recv(m_fd, ret.ptr + ret.length, maxSize - ret.length, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ If we were notified for reading directly by the event dispatcher, we must be able to read at\n \/\/ least one byte before getting AGAIN aka EWOULDBLOCK - *however* the event loop might notify\n \/\/ something that is very eager to read everything (like Message::notifyRead()...) by reading\n \/\/ multiple times and in that case, we may be called in an attempt to read more when there is\n \/\/ currently no more data.\n \/\/ Just return zero bytes and no error in that case.\n if (errno == EAGAIN \/* && iov.iov_len < maxSize *\/) {\n break;\n }\n close();\n return ret;\n }\n ret.length += size_t(nbytes);\n }\n\n return ret;\n}\n\nchunk LocalSocket::readWithFileDescriptors(byte *buffer, uint32 maxSize, vector *fileDescriptors)\n{\n chunk ret;\n if (maxSize <= 0) {\n return ret;\n }\n\n \/\/ recvmsg-with-control-message boilerplate\n struct msghdr recv_msg;\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n memset(cmsgBuf, 0, sizeof(cmsgBuf));\n\n recv_msg.msg_control = cmsgBuf;\n recv_msg.msg_controllen = sizeof(cmsgBuf);\n recv_msg.msg_name = 0;\n recv_msg.msg_namelen = 0;\n recv_msg.msg_flags = 0;\n\n struct iovec iov;\n recv_msg.msg_iov = &iov;\n recv_msg.msg_iovlen = 1;\n\n \/\/ end boilerplate\n\n ret.ptr = buffer;\n ret.length = 0;\n iov.iov_base = ret.ptr;\n iov.iov_len = maxSize;\n while (iov.iov_len > 0) {\n ssize_t nbytes = recvmsg(m_fd, &recv_msg, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ If we were notified for reading directly by the event dispatcher, we must be able to read at\n \/\/ least one byte before getting AGAIN aka EWOULDBLOCK - *however* the event loop might notify\n \/\/ something that is very eager to read everything (like Message::notifyRead()...) by reading\n \/\/ multiple times and in that case, we may be called in an attempt to read more when there is\n \/\/ currently no more data.\n \/\/ Just return zero bytes and no error in that case.\n if (errno == EAGAIN \/* && iov.iov_len < maxSize *\/) {\n break;\n }\n close();\n return ret;\n }\n ret.length += size_t(nbytes);\n iov.iov_base = static_cast(iov.iov_base) + nbytes;\n iov.iov_len -= size_t(nbytes);\n }\n\n \/\/ done reading \"regular data\", now read any file descriptors passed via control messages\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&recv_msg);\n if (c_msg && c_msg->cmsg_level == SOL_SOCKET && c_msg->cmsg_type == SCM_RIGHTS) {\n const int len = c_msg->cmsg_len \/ sizeof(int);\n int *cmsgData = reinterpret_cast(CMSG_DATA(c_msg));\n for (int i = 0; i < len; i++) {\n fileDescriptors->push_back(cmsgData[i]);\n }\n }\n\n return ret;\n}\n\nbool LocalSocket::isOpen()\n{\n return m_fd != -1;\n}\n\nint LocalSocket::fileDescriptor() const\n{\n return m_fd;\n}\n\nvoid LocalSocket::handleCanRead()\n{\n if (availableBytesForReading()) {\n ITransport::handleCanRead();\n } else {\n \/\/ This should really only happen in error cases! ### TODO test?\n close();\n }\n}\nLocalSocket: take null-terminator of socket path into account\/*\n Copyright (C) 2013 Andreas Hartmetz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"localsocket.h\"\n\n#include \n#include \n#include \n#include \n#include \"sys\/uio.h\"\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/ HACK, put this somewhere else (get the value from original d-bus? or is it infinite?)\nstatic const int maxFds = 12;\n\nusing namespace std;\n\nLocalSocket::LocalSocket(const string &socketFilePath)\n : m_fd(-1)\n{\n m_supportsFileDescriptors = true;\n const int fd = socket(PF_UNIX, SOCK_STREAM, 0);\n if (fd < 0) {\n return;\n }\n \/\/ don't let forks inherit the file descriptor - that can cause confusion...\n fcntl(fd, F_SETFD, FD_CLOEXEC);\n\n struct sockaddr_un addr;\n addr.sun_family = PF_UNIX;\n bool ok = socketFilePath.length() < sizeof(addr.sun_path);\n if (ok) {\n memcpy(addr.sun_path, socketFilePath.c_str(), socketFilePath.length() + 1);\n }\n\n ok = ok && (connect(fd, (struct sockaddr *)&addr,\n sizeof(sa_family_t) + socketFilePath.length() + 1) == 0);\n\n if (ok) {\n m_fd = fd;\n } else {\n ::close(fd);\n }\n}\n\nLocalSocket::LocalSocket(int fd)\n : m_fd(fd)\n{\n}\n\nLocalSocket::~LocalSocket()\n{\n close();\n}\n\nvoid LocalSocket::close()\n{\n setEventDispatcher(nullptr);\n if (m_fd >= 0) {\n ::close(m_fd);\n }\n m_fd = -1;\n}\n\nuint32 LocalSocket::write(chunk data)\n{\n if (m_fd < 0) {\n return 0; \/\/ TODO -1?\n }\n\n const uint32 initialLength = data.length;\n\n while (data.length > 0) {\n ssize_t nbytes = send(m_fd, data.ptr, data.length, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ see EAGAIN comment in read()\n if (errno == EAGAIN \/* && iov.iov_len < a.length *\/ ) {\n break;\n }\n close();\n return false;\n }\n\n data.ptr += nbytes;\n data.length -= size_t(nbytes);\n }\n\n return initialLength - data.length;\n}\n\n\/\/ TODO: consider using iovec to avoid \"copying together\" message parts before sending; iovec tricks\n\/\/ are probably not going to help for receiving, though.\nuint32 LocalSocket::writeWithFileDescriptors(chunk data, const vector &fileDescriptors)\n{\n if (m_fd < 0) {\n return 0; \/\/ TODO -1?\n }\n\n \/\/ sendmsg boilerplate\n struct msghdr send_msg;\n struct iovec iov;\n\n send_msg.msg_name = 0;\n send_msg.msg_namelen = 0;\n send_msg.msg_flags = 0;\n send_msg.msg_iov = &iov;\n send_msg.msg_iovlen = 1;\n\n iov.iov_base = data.ptr;\n iov.iov_len = data.length;\n\n \/\/ we can only send a fixed number of fds anyway due to the non-flexible size of the control message\n \/\/ receive buffer, so we set an arbitrary limit.\n const uint32 numFds = fileDescriptors.size();\n assert(fileDescriptors.size() <= maxFds); \/\/ TODO proper error\n\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n\n if (numFds) {\n \/\/ fill in a control message\n send_msg.msg_control = cmsgBuf;\n send_msg.msg_controllen = CMSG_SPACE(sizeof(int) * numFds);\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&send_msg);\n c_msg->cmsg_len = CMSG_LEN(sizeof(int) * numFds);\n c_msg->cmsg_level = SOL_SOCKET;\n c_msg->cmsg_type = SCM_RIGHTS;\n\n \/\/ set the control data to pass - this is why we don't use the simpler write()\n for (uint32 i = 0; i < numFds; i++) {\n reinterpret_cast(CMSG_DATA(c_msg))[i] = fileDescriptors[i];\n }\n } else {\n \/\/ no file descriptor to send, no control message\n send_msg.msg_control = 0;\n send_msg.msg_controllen = 0;\n }\n\n while (iov.iov_len > 0) {\n ssize_t nbytes = sendmsg(m_fd, &send_msg, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ see EAGAIN comment in read()\n if (errno == EAGAIN \/* && iov.iov_len < a.length *\/ ) {\n break;\n }\n close();\n return false;\n }\n\n iov.iov_base = static_cast(iov.iov_base) + nbytes;\n iov.iov_len -= size_t(nbytes);\n }\n\n return data.length - iov.iov_len;\n}\n\nuint32 LocalSocket::availableBytesForReading()\n{\n uint32 available = 0;\n if (ioctl(m_fd, FIONREAD, &available) < 0) {\n available = 0;\n }\n return available;\n}\n\nchunk LocalSocket::read(byte *buffer, uint32 maxSize)\n{\n chunk ret(buffer, 0);\n\n while (ret.length < maxSize) {\n ssize_t nbytes = recv(m_fd, ret.ptr + ret.length, maxSize - ret.length, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ If we were notified for reading directly by the event dispatcher, we must be able to read at\n \/\/ least one byte before getting AGAIN aka EWOULDBLOCK - *however* the event loop might notify\n \/\/ something that is very eager to read everything (like Message::notifyRead()...) by reading\n \/\/ multiple times and in that case, we may be called in an attempt to read more when there is\n \/\/ currently no more data.\n \/\/ Just return zero bytes and no error in that case.\n if (errno == EAGAIN \/* && iov.iov_len < maxSize *\/) {\n break;\n }\n close();\n return ret;\n }\n ret.length += size_t(nbytes);\n }\n\n return ret;\n}\n\nchunk LocalSocket::readWithFileDescriptors(byte *buffer, uint32 maxSize, vector *fileDescriptors)\n{\n chunk ret;\n if (maxSize <= 0) {\n return ret;\n }\n\n \/\/ recvmsg-with-control-message boilerplate\n struct msghdr recv_msg;\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n memset(cmsgBuf, 0, sizeof(cmsgBuf));\n\n recv_msg.msg_control = cmsgBuf;\n recv_msg.msg_controllen = sizeof(cmsgBuf);\n recv_msg.msg_name = 0;\n recv_msg.msg_namelen = 0;\n recv_msg.msg_flags = 0;\n\n struct iovec iov;\n recv_msg.msg_iov = &iov;\n recv_msg.msg_iovlen = 1;\n\n \/\/ end boilerplate\n\n ret.ptr = buffer;\n ret.length = 0;\n iov.iov_base = ret.ptr;\n iov.iov_len = maxSize;\n while (iov.iov_len > 0) {\n ssize_t nbytes = recvmsg(m_fd, &recv_msg, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ If we were notified for reading directly by the event dispatcher, we must be able to read at\n \/\/ least one byte before getting AGAIN aka EWOULDBLOCK - *however* the event loop might notify\n \/\/ something that is very eager to read everything (like Message::notifyRead()...) by reading\n \/\/ multiple times and in that case, we may be called in an attempt to read more when there is\n \/\/ currently no more data.\n \/\/ Just return zero bytes and no error in that case.\n if (errno == EAGAIN \/* && iov.iov_len < maxSize *\/) {\n break;\n }\n close();\n return ret;\n }\n ret.length += size_t(nbytes);\n iov.iov_base = static_cast(iov.iov_base) + nbytes;\n iov.iov_len -= size_t(nbytes);\n }\n\n \/\/ done reading \"regular data\", now read any file descriptors passed via control messages\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&recv_msg);\n if (c_msg && c_msg->cmsg_level == SOL_SOCKET && c_msg->cmsg_type == SCM_RIGHTS) {\n const int len = c_msg->cmsg_len \/ sizeof(int);\n int *cmsgData = reinterpret_cast(CMSG_DATA(c_msg));\n for (int i = 0; i < len; i++) {\n fileDescriptors->push_back(cmsgData[i]);\n }\n }\n\n return ret;\n}\n\nbool LocalSocket::isOpen()\n{\n return m_fd != -1;\n}\n\nint LocalSocket::fileDescriptor() const\n{\n return m_fd;\n}\n\nvoid LocalSocket::handleCanRead()\n{\n if (availableBytesForReading()) {\n ITransport::handleCanRead();\n } else {\n \/\/ This should really only happen in error cases! ### TODO test?\n close();\n }\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/tree:$Id$\n\/\/ Author: Rene Brun 06\/04\/96\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TNtuple \/\/\n\/\/ \/\/\n\/\/ A simple tree restricted to a list of float variables only. \/\/\n\/\/ \/\/\n\/\/ Each variable goes to a separate branch. \/\/\n\/\/ \/\/\n\/\/ A Ntuple is created via \/\/\n\/\/ TNtuple(name,title,varlist,bufsize) \/\/\n\/\/ It is filled via: \/\/\n\/\/ TNtuple::Fill(*x) or \/\/\n\/\/ TNtuple::Fill(v1,v2,v3.....) \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TNtuple.h\"\n#include \"TTree.h\"\n#include \"TBranch.h\"\n#include \"TLeaf.h\"\n#include \"TBrowser.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n\n#include \n\nClassImp(TNtuple)\n\n\/\/______________________________________________________________________________\nTNtuple::TNtuple(): TTree()\n{\n\/\/*-*-*-*-*-*Default constructor for Ntuple*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ==============================\n\n fNvar = 0;\n fArgs = 0;\n}\n\n\/\/______________________________________________________________________________\nTNtuple::TNtuple(const char *name, const char *title, const char *varlist, Int_t bufsize)\n :TTree(name,title)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*Create an Ntuple*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ================\n\/\/ The parameter varlist describes the list of the ntuple variables\n\/\/ separated by a colon:\n\/\/ example: \"x:y:z:energy\"\n\/\/ For each variable in the list a separate branch is created.\n\/\/\n\/\/ NOTE:\n\/\/ -Use TTree to create branches with variables of different data types.\n\/\/ -Use TTree when the number of branches is large (> 100). \n\/\/*-*\n\n Int_t i;\n fNvar = 0;\n fArgs = 0;\n\n\/\/ Count number of variables (separated by :)\n Int_t nch = strlen(varlist);\n if (nch == 0) return;\n char *vars = new char[nch+1];\n strcpy(vars,varlist);\n Int_t *pvars = new Int_t[nch+1];\n fNvar = 1;\n pvars[0] = 0;\n for (i=1;i=0) {\n branch->SetAddress(&fArgs[index]);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TNtuple::ResetBranchAddresses()\n{\n \/\/ Reset the branch addresses to the internal fArgs array. Use this\n \/\/ method when the addresses were changed via calls to SetBranchAddress().\n\n for (Int_t i = 0; i < fNvar; i++) {\n TBranch *branch = (TBranch*)fBranches.UncheckedAt(i);\n if (branch) branch->SetAddress(&fArgs[i]);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TNtuple::Browse(TBrowser *b)\n{\n \/\/ Browse content of the ntuple\n\n fLeaves.Browse( b );\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TNtuple::Fill()\n{\n\/\/*-*-*-*-*-*-*-*-*Fill a Ntuple with current values in fArgs*-*-*-*-*-*-*\n\/\/*-* ==========================================\n\/\/ Note that this function is protected.\n\/\/ Currently called only by TChain::Merge\n\n return TTree::Fill();\n}\n\n\/\/______________________________________________________________________________\nInt_t TNtuple::Fill(const Float_t *x)\n{\n \/\/ Fill a Ntuple with an array of floats\n\n\n \/\/ Store array x into buffer\n for (Int_t i=0;i 0) fArgs[0] = x0;\n if (fNvar > 1) fArgs[1] = x1;\n if (fNvar > 2) fArgs[2] = x2;\n if (fNvar > 3) fArgs[3] = x3;\n if (fNvar > 4) fArgs[4] = x4;\n if (fNvar > 5) fArgs[5] = x5;\n if (fNvar > 6) fArgs[6] = x6;\n if (fNvar > 7) fArgs[7] = x7;\n if (fNvar > 8) fArgs[8] = x8;\n if (fNvar > 9) fArgs[9] = x9;\n if (fNvar > 10) fArgs[10] = x10;\n if (fNvar > 11) fArgs[11] = x11;\n if (fNvar > 12) fArgs[12] = x12;\n if (fNvar > 13) fArgs[13] = x13;\n if (fNvar > 14) fArgs[14] = x14;\n\n return TTree::Fill();\n}\n\n\/\/_______________________________________________________________________\nLong64_t TNtuple::ReadFile(const char *filename, const char * \/*branchDescriptor*\/)\n{\n \/\/ Read from filename as many columns as variables in the ntuple\n \/\/ the function returns the number of rows found in the file\n \/\/ The second argument \"branchDescriptor\" is currently not used.\n \/\/ Lines in the input file starting with \"#\" are ignored.\n\n Long64_t nlines = 0;\n ifstream in;\n in.open(filename);\n while (1) {\n if ( in.peek() != '#' ) {\n for (Int_t i=0;i> fArgs[i];\n if (!in.good()) break;\n TTree::Fill();\n nlines++;\n }\n in.ignore(8192,'\\n');\n }\n in.close();\n return nlines;\n}\n\n\n\/\/_______________________________________________________________________\nvoid TNtuple::Streamer(TBuffer &b)\n{\n\/\/*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================================\n if (b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = b.ReadVersion(&R__s, &R__c);\n if (R__v > 1) {\n b.ReadClassBuffer(TNtuple::Class(), this, R__v, R__s, R__c);\n } else {\n \/\/====process old versions before automatic schema evolution\n TTree::Streamer(b);\n b >> fNvar;\n b.CheckByteCount(R__s, R__c, TNtuple::IsA());\n \/\/====end of old versions\n }\n if (fNvar <= 0) return;\n fArgs = new Float_t[fNvar];\n for (Int_t i=0;iSetAddress(&fArgs[i]);\n }\n } else {\n b.WriteClassBuffer(TNtuple::Class(),this);\n }\n}\nreplace calls to strcpy by strncpy\/\/ @(#)root\/tree:$Id$\n\/\/ Author: Rene Brun 06\/04\/96\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TNtuple \/\/\n\/\/ \/\/\n\/\/ A simple tree restricted to a list of float variables only. \/\/\n\/\/ \/\/\n\/\/ Each variable goes to a separate branch. \/\/\n\/\/ \/\/\n\/\/ A Ntuple is created via \/\/\n\/\/ TNtuple(name,title,varlist,bufsize) \/\/\n\/\/ It is filled via: \/\/\n\/\/ TNtuple::Fill(*x) or \/\/\n\/\/ TNtuple::Fill(v1,v2,v3.....) \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TNtuple.h\"\n#include \"TTree.h\"\n#include \"TBranch.h\"\n#include \"TLeaf.h\"\n#include \"TBrowser.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n\n#include \n\nClassImp(TNtuple)\n\n\/\/______________________________________________________________________________\nTNtuple::TNtuple(): TTree()\n{\n\/\/*-*-*-*-*-*Default constructor for Ntuple*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ==============================\n\n fNvar = 0;\n fArgs = 0;\n}\n\n\/\/______________________________________________________________________________\nTNtuple::TNtuple(const char *name, const char *title, const char *varlist, Int_t bufsize)\n :TTree(name,title)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*Create an Ntuple*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ================\n\/\/ The parameter varlist describes the list of the ntuple variables\n\/\/ separated by a colon:\n\/\/ example: \"x:y:z:energy\"\n\/\/ For each variable in the list a separate branch is created.\n\/\/\n\/\/ NOTE:\n\/\/ -Use TTree to create branches with variables of different data types.\n\/\/ -Use TTree when the number of branches is large (> 100). \n\/\/*-*\n\n Int_t i;\n fNvar = 0;\n fArgs = 0;\n\n\/\/ Count number of variables (separated by :)\n Int_t nch = strlen(varlist);\n if (nch == 0) return;\n char *vars = new char[nch+1];\n strncpy(vars,varlist,nch);\n Int_t *pvars = new Int_t[nch+1];\n fNvar = 1;\n pvars[0] = 0;\n for (i=1;i=0) {\n branch->SetAddress(&fArgs[index]);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TNtuple::ResetBranchAddresses()\n{\n \/\/ Reset the branch addresses to the internal fArgs array. Use this\n \/\/ method when the addresses were changed via calls to SetBranchAddress().\n\n for (Int_t i = 0; i < fNvar; i++) {\n TBranch *branch = (TBranch*)fBranches.UncheckedAt(i);\n if (branch) branch->SetAddress(&fArgs[i]);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TNtuple::Browse(TBrowser *b)\n{\n \/\/ Browse content of the ntuple\n\n fLeaves.Browse( b );\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TNtuple::Fill()\n{\n\/\/*-*-*-*-*-*-*-*-*Fill a Ntuple with current values in fArgs*-*-*-*-*-*-*\n\/\/*-* ==========================================\n\/\/ Note that this function is protected.\n\/\/ Currently called only by TChain::Merge\n\n return TTree::Fill();\n}\n\n\/\/______________________________________________________________________________\nInt_t TNtuple::Fill(const Float_t *x)\n{\n \/\/ Fill a Ntuple with an array of floats\n\n\n \/\/ Store array x into buffer\n for (Int_t i=0;i 0) fArgs[0] = x0;\n if (fNvar > 1) fArgs[1] = x1;\n if (fNvar > 2) fArgs[2] = x2;\n if (fNvar > 3) fArgs[3] = x3;\n if (fNvar > 4) fArgs[4] = x4;\n if (fNvar > 5) fArgs[5] = x5;\n if (fNvar > 6) fArgs[6] = x6;\n if (fNvar > 7) fArgs[7] = x7;\n if (fNvar > 8) fArgs[8] = x8;\n if (fNvar > 9) fArgs[9] = x9;\n if (fNvar > 10) fArgs[10] = x10;\n if (fNvar > 11) fArgs[11] = x11;\n if (fNvar > 12) fArgs[12] = x12;\n if (fNvar > 13) fArgs[13] = x13;\n if (fNvar > 14) fArgs[14] = x14;\n\n return TTree::Fill();\n}\n\n\/\/_______________________________________________________________________\nLong64_t TNtuple::ReadFile(const char *filename, const char * \/*branchDescriptor*\/)\n{\n \/\/ Read from filename as many columns as variables in the ntuple\n \/\/ the function returns the number of rows found in the file\n \/\/ The second argument \"branchDescriptor\" is currently not used.\n \/\/ Lines in the input file starting with \"#\" are ignored.\n\n Long64_t nlines = 0;\n ifstream in;\n in.open(filename);\n while (1) {\n if ( in.peek() != '#' ) {\n for (Int_t i=0;i> fArgs[i];\n if (!in.good()) break;\n TTree::Fill();\n nlines++;\n }\n in.ignore(8192,'\\n');\n }\n in.close();\n return nlines;\n}\n\n\n\/\/_______________________________________________________________________\nvoid TNtuple::Streamer(TBuffer &b)\n{\n\/\/*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================================\n if (b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = b.ReadVersion(&R__s, &R__c);\n if (R__v > 1) {\n b.ReadClassBuffer(TNtuple::Class(), this, R__v, R__s, R__c);\n } else {\n \/\/====process old versions before automatic schema evolution\n TTree::Streamer(b);\n b >> fNvar;\n b.CheckByteCount(R__s, R__c, TNtuple::IsA());\n \/\/====end of old versions\n }\n if (fNvar <= 0) return;\n fArgs = new Float_t[fNvar];\n for (Int_t i=0;iSetAddress(&fArgs[i]);\n }\n } else {\n b.WriteClassBuffer(TNtuple::Class(),this);\n }\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Build Suite.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"rulesapplicator.h\"\n\n#include \"artifact.h\"\n#include \"buildgraph.h\"\n#include \"productbuilddata.h\"\n#include \"projectbuilddata.h\"\n#include \"rulesevaluationcontext.h\"\n#include \"transformer.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace qbs {\nnamespace Internal {\n\nRulesApplicator::RulesApplicator(const ResolvedProductPtr &product,\n ArtifactsPerFileTagMap &artifactsPerFileTag, const Logger &logger)\n : m_product(product)\n , m_artifactsPerFileTag(artifactsPerFileTag)\n , m_logger(logger)\n , m_productObjectId(-1)\n{\n}\n\nvoid RulesApplicator::applyAllRules()\n{\n RulesEvaluationContext::Scope s(m_product->topLevelProject()->buildData->evaluationContext.data());\n foreach (const RuleConstPtr &rule, m_product->topSortedRules())\n applyRule(rule);\n}\n\nvoid RulesApplicator::applyRule(const RuleConstPtr &rule)\n{\n m_rule = rule;\n QScriptValue scopeValue = scope();\n setupScriptEngineForProduct(engine(), m_product, m_rule, scopeValue, this);\n Q_ASSERT_X(scope().property(\"product\").strictlyEquals(engine()->evaluate(\"product\")),\n \"BG\", \"Product object is not in current scope.\");\n m_productObjectId = scopeValue.property(QLatin1String(\"product\")).objectId();\n\n ArtifactList inputArtifacts;\n foreach (const FileTag &fileTag, m_rule->inputs)\n inputArtifacts.unite(m_artifactsPerFileTag.value(fileTag));\n if (m_rule->multiplex) { \/\/ apply the rule once for a set of inputs\n if (!inputArtifacts.isEmpty())\n doApply(inputArtifacts);\n } else { \/\/ apply the rule once for each input\n ArtifactList lst;\n foreach (Artifact * const inputArtifact, inputArtifacts) {\n setupScriptEngineForArtifact(inputArtifact);\n lst += inputArtifact;\n doApply(lst);\n lst.clear();\n }\n }\n}\n\nvoid RulesApplicator::doApply(const ArtifactList &inputArtifacts)\n{\n evalContext()->checkForCancelation();\n\n if (m_logger.debugEnabled()) {\n m_logger.qbsDebug() << \"[BG] apply rule \" << m_rule->toString() << \" \"\n << toStringList(inputArtifacts).join(\",\\n \");\n }\n\n QList > ruleArtifactArtifactMap;\n QList outputArtifacts;\n\n ArtifactList usingArtifacts;\n if (!m_rule->usings.isEmpty()) {\n const FileTags usingsFileTags = m_rule->usings;\n foreach (const ResolvedProductPtr &dep, m_product->dependencies) {\n QBS_CHECK(dep->buildData);\n ArtifactList artifactsToCheck;\n foreach (Artifact *targetArtifact, dep->buildData->targetArtifacts)\n artifactsToCheck.unite(targetArtifact->transformer->outputs);\n foreach (Artifact *artifact, artifactsToCheck) {\n if (artifact->fileTags.matches(usingsFileTags))\n usingArtifacts.insert(artifact);\n }\n }\n }\n\n m_transformer.clear();\n \/\/ create the output artifacts from the set of input artifacts\n foreach (const RuleArtifactConstPtr &ruleArtifact, m_rule->artifacts) {\n Artifact * const outputArtifact = createOutputArtifact(ruleArtifact, inputArtifacts);\n outputArtifacts << outputArtifact;\n ruleArtifactArtifactMap << qMakePair(ruleArtifact.data(), outputArtifact);\n }\n\n foreach (Artifact *outputArtifact, outputArtifacts) {\n \/\/ insert the output artifacts into the pool of artifacts\n foreach (const FileTag &fileTag, outputArtifact->fileTags)\n m_artifactsPerFileTag[fileTag].insert(outputArtifact);\n\n \/\/ connect artifacts that match the file tags in explicitlyDependsOn\n foreach (const FileTag &fileTag, m_rule->explicitlyDependsOn)\n foreach (Artifact *dependency, m_artifactsPerFileTag.value(fileTag))\n loggedConnect(outputArtifact, dependency, m_logger);\n\n \/\/ Transformer setup\n for (ArtifactList::const_iterator it = usingArtifacts.constBegin();\n it != usingArtifacts.constEnd(); ++it)\n {\n Artifact *dep = *it;\n loggedConnect(outputArtifact, dep, m_logger);\n m_transformer->inputs.insert(dep);\n }\n m_transformer->outputs.insert(outputArtifact);\n\n m_product->topLevelProject()->buildData->artifactsThatMustGetNewTransformers\n -= outputArtifact;\n }\n\n m_transformer->setupInputs(engine(), scope());\n\n \/\/ change the transformer outputs according to the bindings in Artifact\n QScriptValue scriptValue;\n for (int i = ruleArtifactArtifactMap.count(); --i >= 0;) {\n const RuleArtifact *ra = ruleArtifactArtifactMap.at(i).first;\n if (ra->bindings.isEmpty())\n continue;\n\n \/\/ expose attributes of this artifact\n Artifact *outputArtifact = ruleArtifactArtifactMap.at(i).second;\n outputArtifact->properties = outputArtifact->properties->clone();\n\n scope().setProperty(\"fileName\", engine()->toScriptValue(outputArtifact->filePath()));\n scope().setProperty(\"fileTags\",\n toScriptValue(engine(), outputArtifact->fileTags.toStringList()));\n\n QVariantMap artifactModulesCfg = outputArtifact->properties->value().value(\"modules\").toMap();\n for (int i=0; i < ra->bindings.count(); ++i) {\n const RuleArtifact::Binding &binding = ra->bindings.at(i);\n scriptValue = engine()->evaluate(binding.code);\n if (Q_UNLIKELY(scriptValue.isError())) {\n QString msg = QLatin1String(\"evaluating rule binding '%1': %2\");\n throw ErrorInfo(msg.arg(binding.name.join(QLatin1String(\".\")), scriptValue.toString()), binding.location);\n }\n setConfigProperty(artifactModulesCfg, binding.name, scriptValue.toVariant());\n }\n QVariantMap outputArtifactConfig = outputArtifact->properties->value();\n outputArtifactConfig.insert(\"modules\", artifactModulesCfg);\n outputArtifact->properties->setValue(outputArtifactConfig);\n }\n\n m_transformer->setupOutputs(engine(), scope());\n m_transformer->createCommands(m_rule->script, evalContext());\n if (Q_UNLIKELY(m_transformer->commands.isEmpty()))\n throw ErrorInfo(QString(\"There's a rule without commands: %1.\").arg(m_rule->toString()), m_rule->script->location);\n}\n\nvoid RulesApplicator::setupScriptEngineForArtifact(Artifact *artifact)\n{\n QString inFileName = artifact->fileName();\n QString inBaseName = FileInfo::baseName(artifact->filePath());\n QString inCompleteBaseName = FileInfo::completeBaseName(artifact->filePath());\n\n QString basedir;\n if (artifact->artifactType == Artifact::SourceFile) {\n QDir sourceDir(m_product->sourceDirectory);\n basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));\n } else {\n QDir buildDir(m_product->topLevelProject()->buildDirectory);\n basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));\n }\n\n \/\/ expose per file properties we want to use in an Artifact within a Rule\n QScriptValue scriptValue = engine()->newObject();\n ModuleProperties::init(scriptValue, artifact);\n scriptValue.setProperty(\"fileName\", inFileName);\n scriptValue.setProperty(\"baseName\", inBaseName);\n scriptValue.setProperty(\"completeBaseName\", inCompleteBaseName);\n scriptValue.setProperty(\"baseDir\", basedir);\n\n scope().setProperty(\"input\", scriptValue);\n Q_ASSERT_X(scriptValue.strictlyEquals(engine()->evaluate(\"input\")),\n \"BG\", \"The input object is not in current scope.\");\n}\n\nArtifact *RulesApplicator::createOutputArtifact(const RuleArtifactConstPtr &ruleArtifact,\n const ArtifactList &inputArtifacts)\n{\n QScriptValue scriptValue = engine()->evaluate(ruleArtifact->fileName);\n if (Q_UNLIKELY(scriptValue.isError() || engine()->hasUncaughtException()))\n throw ErrorInfo(\"Error in Rule.Artifact fileName: \" + scriptValue.toString());\n QString outputPath = scriptValue.toString();\n outputPath.replace(\"..\", \"dotdot\"); \/\/ don't let the output artifact \"escape\" its build dir\n outputPath = resolveOutPath(outputPath);\n\n Artifact *outputArtifact = lookupArtifact(m_product, outputPath);\n if (outputArtifact) {\n if (outputArtifact->transformer && outputArtifact->transformer != m_transformer) {\n \/\/ This can happen when applying rules after scanning for additional file tags.\n \/\/ We just regenerate the transformer.\n if (m_logger.traceEnabled()) {\n m_logger.qbsTrace() << QString::fromLocal8Bit(\"[BG] regenerating transformer \"\n \"for '%1'\").arg(relativeArtifactFileName(outputArtifact));\n }\n m_transformer = outputArtifact->transformer;\n m_transformer->inputs.unite(inputArtifacts);\n\n if (Q_UNLIKELY(m_transformer->inputs.count() > 1 && !m_rule->multiplex)) {\n QString th = \"[\" + outputArtifact->fileTags.toStringList().join(\", \") + \"]\";\n QString e = Tr::tr(\"Conflicting rules for producing %1 %2 \\n\").arg(outputArtifact->filePath(), th);\n th = \"[\" + m_rule->inputs.toStringList().join(\", \")\n + \"] -> [\" + outputArtifact->fileTags.toStringList().join(\", \") + \"]\";\n\n e += QString(\" while trying to apply: %1:%2:%3 %4\\n\")\n .arg(m_rule->script->location.fileName())\n .arg(m_rule->script->location.line())\n .arg(m_rule->script->location.column())\n .arg(th);\n\n e += QString(\" was already defined in: %1:%2:%3 %4\\n\")\n .arg(outputArtifact->transformer->rule->script->location.fileName())\n .arg(outputArtifact->transformer->rule->script->location.line())\n .arg(outputArtifact->transformer->rule->script->location.column())\n .arg(th);\n throw ErrorInfo(e);\n }\n }\n outputArtifact->fileTags += ruleArtifact->fileTags;\n } else {\n outputArtifact = new Artifact(m_product->topLevelProject());\n outputArtifact->artifactType = Artifact::Generated;\n outputArtifact->setFilePath(outputPath);\n outputArtifact->fileTags = ruleArtifact->fileTags;\n outputArtifact->alwaysUpdated = ruleArtifact->alwaysUpdated;\n insertArtifact(m_product, outputArtifact, m_logger);\n }\n\n if (outputArtifact->fileTags.isEmpty())\n outputArtifact->fileTags = m_product->fileTagsForFileName(outputArtifact->fileName());\n\n if (m_rule->multiplex)\n outputArtifact->properties = m_product->properties;\n else\n outputArtifact->properties= (*inputArtifacts.constBegin())->properties;\n\n for (int i = 0; i < m_product->artifactProperties.count(); ++i) {\n const ArtifactPropertiesConstPtr &props = m_product->artifactProperties.at(i);\n if (outputArtifact->fileTags.matches(props->fileTagsFilter())) {\n outputArtifact->properties = props->propertyMap();\n break;\n }\n }\n\n foreach (Artifact *inputArtifact, inputArtifacts) {\n QBS_CHECK(outputArtifact != inputArtifact);\n loggedConnect(outputArtifact, inputArtifact, m_logger);\n }\n\n \/\/ create transformer if not already done so\n if (!m_transformer) {\n m_transformer = Transformer::create();\n m_transformer->rule = m_rule;\n m_transformer->inputs = inputArtifacts;\n }\n outputArtifact->transformer = m_transformer;\n\n return outputArtifact;\n}\n\nQString RulesApplicator::resolveOutPath(const QString &path) const\n{\n QString buildDir = m_product->topLevelProject()->buildDirectory;\n QString result = FileInfo::resolvePath(buildDir, path);\n result = QDir::cleanPath(result);\n return result;\n}\n\nRulesEvaluationContextPtr RulesApplicator::evalContext() const\n{\n return m_product->topLevelProject()->buildData->evaluationContext;\n}\n\nScriptEngine *RulesApplicator::engine() const\n{\n return evalContext()->engine();\n}\n\nQScriptValue RulesApplicator::scope() const\n{\n return evalContext()->scope();\n}\n\nvoid RulesApplicator::onPropertyRead(const QScriptValue &object, const QString &name,\n const QScriptValue &value)\n{\n if (object.objectId() == m_productObjectId)\n engine()->addProperty(\n Property(QString(), name, value.toVariant(), Property::PropertyInProduct));\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace qbs\nassign the product's build config to rule outputs\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Build Suite.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"rulesapplicator.h\"\n\n#include \"artifact.h\"\n#include \"buildgraph.h\"\n#include \"productbuilddata.h\"\n#include \"projectbuilddata.h\"\n#include \"rulesevaluationcontext.h\"\n#include \"transformer.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace qbs {\nnamespace Internal {\n\nRulesApplicator::RulesApplicator(const ResolvedProductPtr &product,\n ArtifactsPerFileTagMap &artifactsPerFileTag, const Logger &logger)\n : m_product(product)\n , m_artifactsPerFileTag(artifactsPerFileTag)\n , m_logger(logger)\n , m_productObjectId(-1)\n{\n}\n\nvoid RulesApplicator::applyAllRules()\n{\n RulesEvaluationContext::Scope s(m_product->topLevelProject()->buildData->evaluationContext.data());\n foreach (const RuleConstPtr &rule, m_product->topSortedRules())\n applyRule(rule);\n}\n\nvoid RulesApplicator::applyRule(const RuleConstPtr &rule)\n{\n m_rule = rule;\n QScriptValue scopeValue = scope();\n setupScriptEngineForProduct(engine(), m_product, m_rule, scopeValue, this);\n Q_ASSERT_X(scope().property(\"product\").strictlyEquals(engine()->evaluate(\"product\")),\n \"BG\", \"Product object is not in current scope.\");\n m_productObjectId = scopeValue.property(QLatin1String(\"product\")).objectId();\n\n ArtifactList inputArtifacts;\n foreach (const FileTag &fileTag, m_rule->inputs)\n inputArtifacts.unite(m_artifactsPerFileTag.value(fileTag));\n if (m_rule->multiplex) { \/\/ apply the rule once for a set of inputs\n if (!inputArtifacts.isEmpty())\n doApply(inputArtifacts);\n } else { \/\/ apply the rule once for each input\n ArtifactList lst;\n foreach (Artifact * const inputArtifact, inputArtifacts) {\n setupScriptEngineForArtifact(inputArtifact);\n lst += inputArtifact;\n doApply(lst);\n lst.clear();\n }\n }\n}\n\nvoid RulesApplicator::doApply(const ArtifactList &inputArtifacts)\n{\n evalContext()->checkForCancelation();\n\n if (m_logger.debugEnabled()) {\n m_logger.qbsDebug() << \"[BG] apply rule \" << m_rule->toString() << \" \"\n << toStringList(inputArtifacts).join(\",\\n \");\n }\n\n QList > ruleArtifactArtifactMap;\n QList outputArtifacts;\n\n ArtifactList usingArtifacts;\n if (!m_rule->usings.isEmpty()) {\n const FileTags usingsFileTags = m_rule->usings;\n foreach (const ResolvedProductPtr &dep, m_product->dependencies) {\n QBS_CHECK(dep->buildData);\n ArtifactList artifactsToCheck;\n foreach (Artifact *targetArtifact, dep->buildData->targetArtifacts)\n artifactsToCheck.unite(targetArtifact->transformer->outputs);\n foreach (Artifact *artifact, artifactsToCheck) {\n if (artifact->fileTags.matches(usingsFileTags))\n usingArtifacts.insert(artifact);\n }\n }\n }\n\n m_transformer.clear();\n \/\/ create the output artifacts from the set of input artifacts\n foreach (const RuleArtifactConstPtr &ruleArtifact, m_rule->artifacts) {\n Artifact * const outputArtifact = createOutputArtifact(ruleArtifact, inputArtifacts);\n outputArtifacts << outputArtifact;\n ruleArtifactArtifactMap << qMakePair(ruleArtifact.data(), outputArtifact);\n }\n\n foreach (Artifact *outputArtifact, outputArtifacts) {\n \/\/ insert the output artifacts into the pool of artifacts\n foreach (const FileTag &fileTag, outputArtifact->fileTags)\n m_artifactsPerFileTag[fileTag].insert(outputArtifact);\n\n \/\/ connect artifacts that match the file tags in explicitlyDependsOn\n foreach (const FileTag &fileTag, m_rule->explicitlyDependsOn)\n foreach (Artifact *dependency, m_artifactsPerFileTag.value(fileTag))\n loggedConnect(outputArtifact, dependency, m_logger);\n\n \/\/ Transformer setup\n for (ArtifactList::const_iterator it = usingArtifacts.constBegin();\n it != usingArtifacts.constEnd(); ++it)\n {\n Artifact *dep = *it;\n loggedConnect(outputArtifact, dep, m_logger);\n m_transformer->inputs.insert(dep);\n }\n m_transformer->outputs.insert(outputArtifact);\n\n m_product->topLevelProject()->buildData->artifactsThatMustGetNewTransformers\n -= outputArtifact;\n }\n\n m_transformer->setupInputs(engine(), scope());\n\n \/\/ change the transformer outputs according to the bindings in Artifact\n QScriptValue scriptValue;\n for (int i = ruleArtifactArtifactMap.count(); --i >= 0;) {\n const RuleArtifact *ra = ruleArtifactArtifactMap.at(i).first;\n if (ra->bindings.isEmpty())\n continue;\n\n \/\/ expose attributes of this artifact\n Artifact *outputArtifact = ruleArtifactArtifactMap.at(i).second;\n outputArtifact->properties = outputArtifact->properties->clone();\n\n scope().setProperty(\"fileName\", engine()->toScriptValue(outputArtifact->filePath()));\n scope().setProperty(\"fileTags\",\n toScriptValue(engine(), outputArtifact->fileTags.toStringList()));\n\n QVariantMap artifactModulesCfg = outputArtifact->properties->value().value(\"modules\").toMap();\n for (int i=0; i < ra->bindings.count(); ++i) {\n const RuleArtifact::Binding &binding = ra->bindings.at(i);\n scriptValue = engine()->evaluate(binding.code);\n if (Q_UNLIKELY(scriptValue.isError())) {\n QString msg = QLatin1String(\"evaluating rule binding '%1': %2\");\n throw ErrorInfo(msg.arg(binding.name.join(QLatin1String(\".\")), scriptValue.toString()), binding.location);\n }\n setConfigProperty(artifactModulesCfg, binding.name, scriptValue.toVariant());\n }\n QVariantMap outputArtifactConfig = outputArtifact->properties->value();\n outputArtifactConfig.insert(\"modules\", artifactModulesCfg);\n outputArtifact->properties->setValue(outputArtifactConfig);\n }\n\n m_transformer->setupOutputs(engine(), scope());\n m_transformer->createCommands(m_rule->script, evalContext());\n if (Q_UNLIKELY(m_transformer->commands.isEmpty()))\n throw ErrorInfo(QString(\"There's a rule without commands: %1.\").arg(m_rule->toString()), m_rule->script->location);\n}\n\nvoid RulesApplicator::setupScriptEngineForArtifact(Artifact *artifact)\n{\n QString inFileName = artifact->fileName();\n QString inBaseName = FileInfo::baseName(artifact->filePath());\n QString inCompleteBaseName = FileInfo::completeBaseName(artifact->filePath());\n\n QString basedir;\n if (artifact->artifactType == Artifact::SourceFile) {\n QDir sourceDir(m_product->sourceDirectory);\n basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));\n } else {\n QDir buildDir(m_product->topLevelProject()->buildDirectory);\n basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));\n }\n\n \/\/ expose per file properties we want to use in an Artifact within a Rule\n QScriptValue scriptValue = engine()->newObject();\n ModuleProperties::init(scriptValue, artifact);\n scriptValue.setProperty(\"fileName\", inFileName);\n scriptValue.setProperty(\"baseName\", inBaseName);\n scriptValue.setProperty(\"completeBaseName\", inCompleteBaseName);\n scriptValue.setProperty(\"baseDir\", basedir);\n\n scope().setProperty(\"input\", scriptValue);\n Q_ASSERT_X(scriptValue.strictlyEquals(engine()->evaluate(\"input\")),\n \"BG\", \"The input object is not in current scope.\");\n}\n\nArtifact *RulesApplicator::createOutputArtifact(const RuleArtifactConstPtr &ruleArtifact,\n const ArtifactList &inputArtifacts)\n{\n QScriptValue scriptValue = engine()->evaluate(ruleArtifact->fileName);\n if (Q_UNLIKELY(scriptValue.isError() || engine()->hasUncaughtException()))\n throw ErrorInfo(\"Error in Rule.Artifact fileName: \" + scriptValue.toString());\n QString outputPath = scriptValue.toString();\n outputPath.replace(\"..\", \"dotdot\"); \/\/ don't let the output artifact \"escape\" its build dir\n outputPath = resolveOutPath(outputPath);\n\n Artifact *outputArtifact = lookupArtifact(m_product, outputPath);\n if (outputArtifact) {\n if (outputArtifact->transformer && outputArtifact->transformer != m_transformer) {\n \/\/ This can happen when applying rules after scanning for additional file tags.\n \/\/ We just regenerate the transformer.\n if (m_logger.traceEnabled()) {\n m_logger.qbsTrace() << QString::fromLocal8Bit(\"[BG] regenerating transformer \"\n \"for '%1'\").arg(relativeArtifactFileName(outputArtifact));\n }\n m_transformer = outputArtifact->transformer;\n m_transformer->inputs.unite(inputArtifacts);\n\n if (Q_UNLIKELY(m_transformer->inputs.count() > 1 && !m_rule->multiplex)) {\n QString th = \"[\" + outputArtifact->fileTags.toStringList().join(\", \") + \"]\";\n QString e = Tr::tr(\"Conflicting rules for producing %1 %2 \\n\").arg(outputArtifact->filePath(), th);\n th = \"[\" + m_rule->inputs.toStringList().join(\", \")\n + \"] -> [\" + outputArtifact->fileTags.toStringList().join(\", \") + \"]\";\n\n e += QString(\" while trying to apply: %1:%2:%3 %4\\n\")\n .arg(m_rule->script->location.fileName())\n .arg(m_rule->script->location.line())\n .arg(m_rule->script->location.column())\n .arg(th);\n\n e += QString(\" was already defined in: %1:%2:%3 %4\\n\")\n .arg(outputArtifact->transformer->rule->script->location.fileName())\n .arg(outputArtifact->transformer->rule->script->location.line())\n .arg(outputArtifact->transformer->rule->script->location.column())\n .arg(th);\n throw ErrorInfo(e);\n }\n }\n outputArtifact->fileTags += ruleArtifact->fileTags;\n } else {\n outputArtifact = new Artifact(m_product->topLevelProject());\n outputArtifact->artifactType = Artifact::Generated;\n outputArtifact->setFilePath(outputPath);\n outputArtifact->fileTags = ruleArtifact->fileTags;\n outputArtifact->alwaysUpdated = ruleArtifact->alwaysUpdated;\n outputArtifact->properties = m_product->properties;\n insertArtifact(m_product, outputArtifact, m_logger);\n }\n\n if (outputArtifact->fileTags.isEmpty())\n outputArtifact->fileTags = m_product->fileTagsForFileName(outputArtifact->fileName());\n\n for (int i = 0; i < m_product->artifactProperties.count(); ++i) {\n const ArtifactPropertiesConstPtr &props = m_product->artifactProperties.at(i);\n if (outputArtifact->fileTags.matches(props->fileTagsFilter())) {\n outputArtifact->properties = props->propertyMap();\n break;\n }\n }\n\n foreach (Artifact *inputArtifact, inputArtifacts) {\n QBS_CHECK(outputArtifact != inputArtifact);\n loggedConnect(outputArtifact, inputArtifact, m_logger);\n }\n\n \/\/ create transformer if not already done so\n if (!m_transformer) {\n m_transformer = Transformer::create();\n m_transformer->rule = m_rule;\n m_transformer->inputs = inputArtifacts;\n }\n outputArtifact->transformer = m_transformer;\n\n return outputArtifact;\n}\n\nQString RulesApplicator::resolveOutPath(const QString &path) const\n{\n QString buildDir = m_product->topLevelProject()->buildDirectory;\n QString result = FileInfo::resolvePath(buildDir, path);\n result = QDir::cleanPath(result);\n return result;\n}\n\nRulesEvaluationContextPtr RulesApplicator::evalContext() const\n{\n return m_product->topLevelProject()->buildData->evaluationContext;\n}\n\nScriptEngine *RulesApplicator::engine() const\n{\n return evalContext()->engine();\n}\n\nQScriptValue RulesApplicator::scope() const\n{\n return evalContext()->scope();\n}\n\nvoid RulesApplicator::onPropertyRead(const QScriptValue &object, const QString &name,\n const QScriptValue &value)\n{\n if (object.objectId() == m_productObjectId)\n engine()->addProperty(\n Property(QString(), name, value.toVariant(), Property::PropertyInProduct));\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace qbs\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"wrapper_tutorial_06.h\"\n\nusing namespace tiramisu;\n\n\/**\n * Test reductions.\n *\n * We want to represent the following program\n *\n * result = 0\n * for (int i = 0; i < N; i++)\n * result = result + input[i];\n *\n * This program computes the sum of all the elements in the\n * buffer input[].\n *\n * In order to implement this program, we create the following two\n * computations\n * {result[0] }: 0\n * {result[i]: 0result_scalar[0]}\n * {input[i]->input_buffer[i]}\n *\n * This means that each computation result[i] is stored\n * in the scalar \"result_scalar[0]\" and that each computation\n * input[i] is retrieved from input_buffer[i].\n *\n *\/\n\nvoid generate_function(std::string name, int size, int val0)\n{\n tiramisu::global::set_default_tiramisu_options();\n global::set_loop_iterator_type(p_int32);\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n\n\n\n tiramisu::function function0(name);\n tiramisu::constant N(\"N\", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0);\n tiramisu::var i = tiramisu::var(\"i\");\n tiramisu::computation input(\"[N]->{input[i]}\", tiramisu::expr(), false, p_uint8, &function0);\n tiramisu::computation result(\"[N]->{result[0]}\", tiramisu::expr(input(0)), true, p_uint8, &function0);\n result.add_definitions(\"[N]->{result[i]: 1<=i{input[i]->input_buffer[i]}\");\n result.set_access(\"[N]->{result[i]->result_scalar[0]}\");\n result.get_update(1).set_access(\"[N]->{result[i]->result_scalar[0]}\");\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n\n\n\n function0.set_arguments({&input_buffer, &result_scalar});\n function0.gen_time_space_domain();\n function0.gen_isl_ast();\n function0.gen_halide_stmt();\n function0.gen_c_code();\n function0.gen_halide_obj(\"build\/generated_fct_tutorial_06.o\");\n}\n\nint main(int argc, char **argv)\n{\n generate_function(\"tiramisu_generated_code\", SIZE1, 0);\n\n return 0;\n}\nUpdate tutorial_06.cpp#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"wrapper_tutorial_06.h\"\n\nusing namespace tiramisu;\n\n\/**\n * Test reductions.\n *\n * We want to represent the following program\n *\n * result = 0\n * for (int i = 0; i < N; i++)\n * result = result + input[i];\n *\n * This program computes the sum of all the elements in the\n * buffer input[].\n *\n * In order to implement this program, we create the following two\n * computations\n * {result[0] }: 0\n * {result[i]: 0result_scalar[0]}\n * {input[i]->input_buffer[i]}\n *\n * This means that each computation result[i] is stored\n * in the scalar \"result_scalar[0]\" and that each computation\n * input[i] is retrieved from input_buffer[i].\n *\n *\/\n\nvoid generate_function(std::string name, int size, int val0)\n{\n tiramisu::global::set_default_tiramisu_options();\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n\n\n\n tiramisu::function function0(name);\n tiramisu::constant N(\"N\", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0);\n tiramisu::var i = tiramisu::var(\"i\");\n tiramisu::computation input(\"[N]->{input[i]}\", tiramisu::expr(), false, p_uint8, &function0);\n tiramisu::computation result(\"[N]->{result[0]}\", tiramisu::expr(input(0)), true, p_uint8, &function0);\n result.add_definitions(\"[N]->{result[i]: 1<=i{input[i]->input_buffer[i]}\");\n result.set_access(\"[N]->{result[i]->result_scalar[0]}\");\n result.get_update(1).set_access(\"[N]->{result[i]->result_scalar[0]}\");\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n\n\n\n function0.set_arguments({&input_buffer, &result_scalar});\n function0.gen_time_space_domain();\n function0.gen_isl_ast();\n function0.gen_halide_stmt();\n function0.gen_c_code();\n function0.gen_halide_obj(\"build\/generated_fct_tutorial_06.o\");\n}\n\nint main(int argc, char **argv)\n{\n generate_function(\"tiramisu_generated_code\", SIZE1, 0);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ KMail Account\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"kmacctmgr.h\"\n#include \"kmacctfolder.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmfiltermgr.h\"\n#include \"kmsender.h\"\n#include \"kmbroadcaststatus.h\"\n\n\/\/----------------------\n#include \"kmaccount.moc\"\n\n\/\/-----------------------------------------------------------------------------\nKMPrecommand::KMPrecommand(const QString &precommand, QObject *parent)\n : QObject(parent)\n{\n mPrecommand = precommand;\n KMBroadcastStatus::instance()->setStatusMsg(\n i18n(\"Executing precommand %1\").arg(precommand ));\n\n mPrecommandProcess << precommand;\n\n connect(&mPrecommandProcess, SIGNAL(processExited(KProcess *)),\n SLOT(precommandExited(KProcess *)));\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMPrecommand::~KMPrecommand()\n{\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool KMPrecommand::start()\n{\n bool ok = mPrecommandProcess.start( KProcess::NotifyOnExit );\n if (!ok) KMessageBox::error(0, i18n(\"Couldn't execute precommand '%1'.\")\n .arg(mPrecommand));\n return ok;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMPrecommand::precommandExited(KProcess *p)\n{\n int exitCode = p->normalExit() ? p->exitStatus() : -1;\n if (exitCode)\n KMessageBox::error(0, i18n(\"The precommand exited with code %1:\\n%2\")\n .arg(exitCode).arg(strerror(exitCode)));\n emit finished(!exitCode);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount::KMAccount(KMAcctMgr* aOwner, const QString& aName)\n{\n assert(aOwner != NULL);\n\n mOwner = aOwner;\n mName = aName;\n mFolder = NULL;\n mTimer = NULL;\n mInterval = 0;\n mExclude = false;\n mCheckingMail = FALSE;\n mPrecommandSuccess = TRUE;\n connect(&mReceiptTimer,SIGNAL(timeout()),SLOT(sendReceipts()));\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount::~KMAccount()\n{\n if (!kernel->shuttingDown() && mFolder) mFolder->removeAccount(this);\n if (mTimer) deinstallTimer();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setName(const QString& aName)\n{\n mName = (aName.isEmpty()) ? i18n(\"Unnamed\") : aName;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::clearPasswd()\n{\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setFolder(KMFolder* aFolder)\n{\n if(!aFolder)\n {\n kdDebug(5006) << \"KMAccount::setFolder() : aFolder == NULL\" << endl;\n mFolder = NULL;\n return;\n }\n mFolder = (KMAcctFolder*)aFolder;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::readConfig(KConfig& config)\n{\n KMAcctFolder* folder;\n QString folderName;\n\n mFolder = NULL;\n mName = config.readEntry(\"Name\", i18n(\"Unnamed\"));\n folderName = config.readEntry(\"Folder\", \"\");\n setCheckInterval(config.readNumEntry(\"check-interval\", 0));\n setCheckExclude(config.readBoolEntry(\"check-exclude\", false));\n setPrecommand(config.readEntry(\"precommand\"));\n\n if (!folderName.isEmpty())\n {\n folder = (KMAcctFolder*)kernel->folderMgr()->findIdString(folderName);\n if (folder)\n {\n mFolder = folder;\n mFolder->addAccount(this);\n }\n else kdDebug(5006) << \"Cannot find folder `\" << folderName << \"' for account `\" << mName << \"'.\" << endl;\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::writeConfig(KConfig& config)\n{\n config.writeEntry(\"Type\", type());\n config.writeEntry(\"Name\", mName);\n config.writeEntry(\"Folder\", mFolder ? mFolder->idString() : QString::null);\n config.writeEntry(\"check-interval\", mInterval);\n config.writeEntry(\"check-exclude\", mExclude);\n config.writeEntry(\"precommand\", mPrecommand);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::sendReceipt(KMMessage* aMsg)\n{\n KConfig* cfg = kapp->config();\n bool sendReceipts;\n\n KConfigGroupSaver saver(cfg, \"General\");\n\n sendReceipts = cfg->readBoolEntry(\"send-receipts\", false);\n if (!sendReceipts) return;\n\n KMMessage *newMsg = aMsg->createDeliveryReceipt();\n if (newMsg) {\n mReceipts.append(newMsg);\n mReceiptTimer.start(0,true);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool KMAccount::processNewMsg(KMMessage* aMsg)\n{\n int rc, processResult;\n\n assert(aMsg != NULL);\n\n \/\/ checks whether we should send delivery receipts\n \/\/ and sends them.\n sendReceipt(aMsg);\n\n \/\/ Set status of new messages that are marked as old to read, otherwise\n \/\/ the user won't see which messages newly arrived.\n if (aMsg->status()==KMMsgStatusOld)\n aMsg->setStatus(KMMsgStatusUnread); \/\/ -sanders\n \/\/ aMsg->setStatus(KMMsgStatusRead);\n else aMsg->setStatus(KMMsgStatusNew);\n\n \/\/ 0==message moved; 1==processing ok, no move; 2==critical error, abort!\n processResult = kernel->filterMgr()->process(aMsg,KMFilterMgr::Inbound);\n if (processResult == 2) {\n perror(\"Critical error: Unable to collect mail (out of space?)\");\n KMessageBox::information(0,(i18n(\"Critical error: \"\n \"Unable to collect mail (out of space?)\")));\n return false;\n }\n else if (processResult == 1)\n {\n kernel->filterMgr()->tempOpenFolder(mFolder);\n rc = mFolder->addMsg(aMsg);\n if (rc) {\n perror(\"failed to add message\");\n KMessageBox::information(0, i18n(\"Failed to add message:\\n\") +\n\t\t\t QString(strerror(rc)));\n return false;\n }\n else return true;\n }\n \/\/ What now - are we owner or not?\n return true; \/\/Everything's fine - message has been added by filter }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setCheckInterval(int aInterval)\n{\n if (aInterval <= 0)\n {\n mInterval = 0;\n deinstallTimer();\n }\n else\n {\n mInterval = aInterval;\n installTimer();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setCheckExclude(bool aExclude)\n{\n mExclude = aExclude;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::installTimer()\n{\n if (mInterval <= 0) return;\n if(!mTimer)\n {\n mTimer = new QTimer();\n connect(mTimer,SIGNAL(timeout()),SLOT(mailCheck()));\n }\n else\n {\n mTimer->stop();\n }\n mTimer->start(mInterval*60000);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::deinstallTimer()\n{\n if(mTimer) {\n delete mTimer;\n mTimer = NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KMAccount::runPrecommand(const QString &precommand)\n{\n \/\/ Run the pre command if there is one\n if ( precommand.isEmpty() )\n return true;\n\n KMPrecommand precommandProcess(precommand, this);\n\n KMBroadcastStatus::instance()->setStatusMsg(\n i18n(\"Executing precommand %1\").arg(precommand ));\n\n connect(&precommandProcess, SIGNAL(finished(bool)),\n SLOT(precommandExited(bool)));\n\n kdDebug(5006) << \"Running precommand \" << precommand << endl;\n if (!precommandProcess.start()) return false;\n\n kapp->enter_loop();\n\n return mPrecommandSuccess;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::precommandExited(bool success)\n{\n mPrecommandSuccess = success;\n kapp->exit_loop();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::mailCheck()\n{\n if (mCheckingMail) return;\n mCheckingMail = TRUE;\n kernel->acctMgr()->singleCheckMail(this,false);\n mCheckingMail = FALSE;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::sendReceipts()\n{\n \/\/ re-entrant\n QValueList receipts;\n QValueList::Iterator it;\n for(it = mReceipts.begin(); it != mReceipts.end(); ++it)\n receipts.append(*it);\n mReceipts.clear();\n\n for(it = receipts.begin(); it != receipts.end(); ++it)\n kernel->msgSender()->send(*it); \/\/might process events\n}\n\n\/\/-----------------------------------------------------------------------------\nQString KMAccount::encryptStr(const QString &aStr)\n{\n QString result;\n for (uint i = 0; i < aStr.length(); i++)\n result += (aStr[i].unicode() < 0x20) ? aStr[i] :\n QChar(0x1001F - aStr[i].unicode());\n return result;\n}\nUse const init list instead of an arry of mFoo = aFoo in the ctor\/\/ KMail Account\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"kmacctmgr.h\"\n#include \"kmacctfolder.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmfiltermgr.h\"\n#include \"kmsender.h\"\n#include \"kmbroadcaststatus.h\"\n\n\/\/----------------------\n#include \"kmaccount.moc\"\n\n\/\/-----------------------------------------------------------------------------\nKMPrecommand::KMPrecommand(const QString &precommand, QObject *parent)\n : QObject(parent), mPrecommand(precommand)\n{\n KMBroadcastStatus::instance()->setStatusMsg(\n i18n(\"Executing precommand %1\").arg(precommand ));\n\n mPrecommandProcess << precommand;\n\n connect(&mPrecommandProcess, SIGNAL(processExited(KProcess *)),\n SLOT(precommandExited(KProcess *)));\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMPrecommand::~KMPrecommand()\n{\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool KMPrecommand::start()\n{\n bool ok = mPrecommandProcess.start( KProcess::NotifyOnExit );\n if (!ok) KMessageBox::error(0, i18n(\"Couldn't execute precommand '%1'.\")\n .arg(mPrecommand));\n return ok;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMPrecommand::precommandExited(KProcess *p)\n{\n int exitCode = p->normalExit() ? p->exitStatus() : -1;\n if (exitCode)\n KMessageBox::error(0, i18n(\"The precommand exited with code %1:\\n%2\")\n .arg(exitCode).arg(strerror(exitCode)));\n emit finished(!exitCode);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount::KMAccount(KMAcctMgr* aOwner, const QString& aName)\n : mName(aName),\n mOwner(aOwner),\n mFolder(0),\n mTimer(0),\n mInterval(0),\n mExclude(false),\n mCheckingMail(false),\n mPrecommandSuccess(true)\n{\n assert(aOwner != NULL);\n\n connect(&mReceiptTimer,SIGNAL(timeout()),SLOT(sendReceipts()));\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount::~KMAccount()\n{\n if (!kernel->shuttingDown() && mFolder) mFolder->removeAccount(this);\n if (mTimer) deinstallTimer();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setName(const QString& aName)\n{\n mName = (aName.isEmpty()) ? i18n(\"Unnamed\") : aName;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::clearPasswd()\n{\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setFolder(KMFolder* aFolder)\n{\n if(!aFolder)\n {\n kdDebug(5006) << \"KMAccount::setFolder() : aFolder == NULL\" << endl;\n mFolder = NULL;\n return;\n }\n mFolder = (KMAcctFolder*)aFolder;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::readConfig(KConfig& config)\n{\n KMAcctFolder* folder;\n QString folderName;\n\n mFolder = NULL;\n mName = config.readEntry(\"Name\", i18n(\"Unnamed\"));\n folderName = config.readEntry(\"Folder\", \"\");\n setCheckInterval(config.readNumEntry(\"check-interval\", 0));\n setCheckExclude(config.readBoolEntry(\"check-exclude\", false));\n setPrecommand(config.readEntry(\"precommand\"));\n\n if (!folderName.isEmpty())\n {\n folder = (KMAcctFolder*)kernel->folderMgr()->findIdString(folderName);\n if (folder)\n {\n mFolder = folder;\n mFolder->addAccount(this);\n }\n else kdDebug(5006) << \"Cannot find folder `\" << folderName << \"' for account `\" << mName << \"'.\" << endl;\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::writeConfig(KConfig& config)\n{\n config.writeEntry(\"Type\", type());\n config.writeEntry(\"Name\", mName);\n config.writeEntry(\"Folder\", mFolder ? mFolder->idString() : QString::null);\n config.writeEntry(\"check-interval\", mInterval);\n config.writeEntry(\"check-exclude\", mExclude);\n config.writeEntry(\"precommand\", mPrecommand);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::sendReceipt(KMMessage* aMsg)\n{\n KConfig* cfg = kapp->config();\n bool sendReceipts;\n\n KConfigGroupSaver saver(cfg, \"General\");\n\n sendReceipts = cfg->readBoolEntry(\"send-receipts\", false);\n if (!sendReceipts) return;\n\n KMMessage *newMsg = aMsg->createDeliveryReceipt();\n if (newMsg) {\n mReceipts.append(newMsg);\n mReceiptTimer.start(0,true);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool KMAccount::processNewMsg(KMMessage* aMsg)\n{\n int rc, processResult;\n\n assert(aMsg != NULL);\n\n \/\/ checks whether we should send delivery receipts\n \/\/ and sends them.\n sendReceipt(aMsg);\n\n \/\/ Set status of new messages that are marked as old to read, otherwise\n \/\/ the user won't see which messages newly arrived.\n if (aMsg->status()==KMMsgStatusOld)\n aMsg->setStatus(KMMsgStatusUnread); \/\/ -sanders\n \/\/ aMsg->setStatus(KMMsgStatusRead);\n else aMsg->setStatus(KMMsgStatusNew);\n\n \/\/ 0==message moved; 1==processing ok, no move; 2==critical error, abort!\n processResult = kernel->filterMgr()->process(aMsg,KMFilterMgr::Inbound);\n if (processResult == 2) {\n perror(\"Critical error: Unable to collect mail (out of space?)\");\n KMessageBox::information(0,(i18n(\"Critical error: \"\n \"Unable to collect mail (out of space?)\")));\n return false;\n }\n else if (processResult == 1)\n {\n kernel->filterMgr()->tempOpenFolder(mFolder);\n rc = mFolder->addMsg(aMsg);\n if (rc) {\n perror(\"failed to add message\");\n KMessageBox::information(0, i18n(\"Failed to add message:\\n\") +\n\t\t\t QString(strerror(rc)));\n return false;\n }\n else return true;\n }\n \/\/ What now - are we owner or not?\n return true; \/\/Everything's fine - message has been added by filter }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setCheckInterval(int aInterval)\n{\n if (aInterval <= 0)\n {\n mInterval = 0;\n deinstallTimer();\n }\n else\n {\n mInterval = aInterval;\n installTimer();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::setCheckExclude(bool aExclude)\n{\n mExclude = aExclude;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::installTimer()\n{\n if (mInterval <= 0) return;\n if(!mTimer)\n {\n mTimer = new QTimer();\n connect(mTimer,SIGNAL(timeout()),SLOT(mailCheck()));\n }\n else\n {\n mTimer->stop();\n }\n mTimer->start(mInterval*60000);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::deinstallTimer()\n{\n if(mTimer) {\n delete mTimer;\n mTimer = NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KMAccount::runPrecommand(const QString &precommand)\n{\n \/\/ Run the pre command if there is one\n if ( precommand.isEmpty() )\n return true;\n\n KMPrecommand precommandProcess(precommand, this);\n\n KMBroadcastStatus::instance()->setStatusMsg(\n i18n(\"Executing precommand %1\").arg(precommand ));\n\n connect(&precommandProcess, SIGNAL(finished(bool)),\n SLOT(precommandExited(bool)));\n\n kdDebug(5006) << \"Running precommand \" << precommand << endl;\n if (!precommandProcess.start()) return false;\n\n kapp->enter_loop();\n\n return mPrecommandSuccess;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::precommandExited(bool success)\n{\n mPrecommandSuccess = success;\n kapp->exit_loop();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::mailCheck()\n{\n if (mCheckingMail) return;\n mCheckingMail = TRUE;\n kernel->acctMgr()->singleCheckMail(this,false);\n mCheckingMail = FALSE;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAccount::sendReceipts()\n{\n \/\/ re-entrant\n QValueList receipts;\n QValueList::Iterator it;\n for(it = mReceipts.begin(); it != mReceipts.end(); ++it)\n receipts.append(*it);\n mReceipts.clear();\n\n for(it = receipts.begin(); it != receipts.end(); ++it)\n kernel->msgSender()->send(*it); \/\/might process events\n}\n\n\/\/-----------------------------------------------------------------------------\nQString KMAccount::encryptStr(const QString &aStr)\n{\n QString result;\n for (uint i = 0; i < aStr.length(); i++)\n result += (aStr[i].unicode() < 0x20) ? aStr[i] :\n QChar(0x1001F - aStr[i].unicode());\n return result;\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/container_iterator.hpp\"\n#include \"base\/disjoint_sets.hpp\"\n#include \"ksp_plugin\/frames.hpp\"\n#include \"ksp_plugin\/identification.hpp\"\n#include \"ksp_plugin\/part_subsets.hpp\"\n#include \"ksp_plugin\/pile_up.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"serialization\/ksp_plugin.pb.h\"\n\nnamespace principia {\nnamespace ksp_plugin {\nnamespace internal_part {\n\nusing base::IteratorOn;\nusing base::not_null;\nusing base::Subset;\nusing geometry::Position;\nusing geometry::Vector;\nusing geometry::Velocity;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing quantities::Force;\nusing quantities::Mass;\n\n\/\/ Represents a KSP part.\nclass Part final {\n public:\n Part(PartId part_id,\n std::string const& name,\n Mass const& mass,\n DegreesOfFreedom const& degrees_of_freedom,\n std::function deletion_callback);\n\n \/\/ Calls the deletion callback passed at construction, if any. This part must\n \/\/ not be piled up.\n ~Part();\n\n PartId part_id() const;\n\n \/\/ Sets or returns the mass. Event though a part is massless in the sense\n \/\/ that it doesn't exert gravity, it has a mass used to determine its\n \/\/ intrinsic acceleration.\n void set_mass(Mass const& mass);\n Mass const& mass() const;\n\n \/\/ Clears, increments or returns the intrinsic force exerted on the part by\n \/\/ its engines (or a tractor beam).\n \/\/ TODO(phl): Keep track of the point where the force is applied.\n void clear_intrinsic_force();\n void increment_intrinsic_force(\n Vector const& intrinsic_force);\n Vector const& intrinsic_force() const;\n\n \/\/ Sets or returns the degrees of freedom of the part.\n void set_degrees_of_freedom(\n DegreesOfFreedom const& degrees_of_freedom);\n DegreesOfFreedom const& degrees_of_freedom() const;\n\n \/\/ This temporarily holds the trajectory followed by the part during the call\n \/\/ to |PileUp::AdvanceTime| for the containing |PileUp|. It read and cleared\n \/\/ by |Part::AdvanceTime| for the containing |Part|.\n DiscreteTrajectory& tail();\n DiscreteTrajectory const& tail() const;\n\n \/\/ True if and only if the last point of the tail is authoritative, i.e.,\n \/\/ corresponds to a point in the psychohistory of the enclosing Part.\n bool tail_is_authoritative() const;\n void set_tail_is_authoritative(bool tail_is_authoritative);\n\n \/\/ Requires |!is_piled_up()|.\n void set_containing_pile_up(IteratorOn> pile_up);\n\n \/\/ An iterator to the containing |PileUp|, if any. Do not |Erase| this\n \/\/ iterator, use |clear_pile_up| instead, which will take care of letting all\n \/\/ parts know that their |PileUp| is gone.\n std::experimental::optional>>\n containing_pile_up() const;\n\n \/\/ Whether this part is in a |PileUp|. Equivalent to |containing_pile_up()|.\n bool is_piled_up() const;\n\n \/\/ If this part is in a |PileUp|, erases that |PileUp|. After this call, all\n \/\/ parts in that |PileUp| are no longer piled up.\n void clear_pile_up();\n\n void WriteToMessage(not_null message) const;\n static not_null> ReadFromMessage(\n serialization::Part const& message,\n std::function deletion_callback);\n void FillContainingPileUpFromMessage(\n serialization::Part const& message,\n not_null*> const pile_ups);\n\n \/\/ Returns \"part name (part ID)\".\n std::string ShortDebugString() const;\n\n private:\n PartId const part_id_;\n std::string const name_;\n Mass mass_;\n Vector intrinsic_force_;\n\n std::experimental::optional>>\n containing_pile_up_;\n\n DegreesOfFreedom degrees_of_freedom_;\n not_null>> tail_;\n bool tail_is_authoritative_ = false;\n\n \/\/ TODO(egg): we may want to keep track of the moment of inertia, angular\n \/\/ momentum, etc.\n\n \/\/ We will use union-find algorithms on |Part|s.\n not_null::Node>> const subset_node_;\n friend class Subset::Node;\n\n \/\/ Called in the destructor.\n std::function deletion_callback_;\n};\n\nstd::ostream& operator<<(std::ostream& out, Part const& part);\n\n} \/\/ namespace internal_part\n\nusing internal_part::Part;\n\n} \/\/ namespace ksp_plugin\n\nnamespace base {\n\ntemplate<>\ninline not_null::Node*>\nSubset::Node::Get(ksp_plugin::Part& element) {\n return element.subset_node_.get();\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\nwrong comment is wrong\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/container_iterator.hpp\"\n#include \"base\/disjoint_sets.hpp\"\n#include \"ksp_plugin\/frames.hpp\"\n#include \"ksp_plugin\/identification.hpp\"\n#include \"ksp_plugin\/part_subsets.hpp\"\n#include \"ksp_plugin\/pile_up.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"serialization\/ksp_plugin.pb.h\"\n\nnamespace principia {\nnamespace ksp_plugin {\nnamespace internal_part {\n\nusing base::IteratorOn;\nusing base::not_null;\nusing base::Subset;\nusing geometry::Position;\nusing geometry::Vector;\nusing geometry::Velocity;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing quantities::Force;\nusing quantities::Mass;\n\n\/\/ Represents a KSP part.\nclass Part final {\n public:\n Part(PartId part_id,\n std::string const& name,\n Mass const& mass,\n DegreesOfFreedom const& degrees_of_freedom,\n std::function deletion_callback);\n\n \/\/ Calls the deletion callback passed at construction, if any. This part must\n \/\/ not be piled up.\n ~Part();\n\n PartId part_id() const;\n\n \/\/ Sets or returns the mass. Event though a part is massless in the sense\n \/\/ that it doesn't exert gravity, it has a mass used to determine its\n \/\/ intrinsic acceleration.\n void set_mass(Mass const& mass);\n Mass const& mass() const;\n\n \/\/ Clears, increments or returns the intrinsic force exerted on the part by\n \/\/ its engines (or a tractor beam).\n \/\/ TODO(phl): Keep track of the point where the force is applied.\n void clear_intrinsic_force();\n void increment_intrinsic_force(\n Vector const& intrinsic_force);\n Vector const& intrinsic_force() const;\n\n \/\/ Sets or returns the degrees of freedom of the part.\n void set_degrees_of_freedom(\n DegreesOfFreedom const& degrees_of_freedom);\n DegreesOfFreedom const& degrees_of_freedom() const;\n\n \/\/ This temporarily holds the trajectory followed by the part during the call\n \/\/ to |PileUp::AdvanceTime| for the containing |PileUp|. It is read and\n \/\/ cleared by |Vessel::AdvanceTime| for the containing |Vessel|.\n DiscreteTrajectory& tail();\n DiscreteTrajectory const& tail() const;\n\n \/\/ True if and only if the last point of the tail is authoritative, i.e.,\n \/\/ corresponds to a point in the psychohistory of the enclosing Part.\n bool tail_is_authoritative() const;\n void set_tail_is_authoritative(bool tail_is_authoritative);\n\n \/\/ Requires |!is_piled_up()|.\n void set_containing_pile_up(IteratorOn> pile_up);\n\n \/\/ An iterator to the containing |PileUp|, if any. Do not |Erase| this\n \/\/ iterator, use |clear_pile_up| instead, which will take care of letting all\n \/\/ parts know that their |PileUp| is gone.\n std::experimental::optional>>\n containing_pile_up() const;\n\n \/\/ Whether this part is in a |PileUp|. Equivalent to |containing_pile_up()|.\n bool is_piled_up() const;\n\n \/\/ If this part is in a |PileUp|, erases that |PileUp|. After this call, all\n \/\/ parts in that |PileUp| are no longer piled up.\n void clear_pile_up();\n\n void WriteToMessage(not_null message) const;\n static not_null> ReadFromMessage(\n serialization::Part const& message,\n std::function deletion_callback);\n void FillContainingPileUpFromMessage(\n serialization::Part const& message,\n not_null*> const pile_ups);\n\n \/\/ Returns \"part name (part ID)\".\n std::string ShortDebugString() const;\n\n private:\n PartId const part_id_;\n std::string const name_;\n Mass mass_;\n Vector intrinsic_force_;\n\n std::experimental::optional>>\n containing_pile_up_;\n\n DegreesOfFreedom degrees_of_freedom_;\n not_null>> tail_;\n bool tail_is_authoritative_ = false;\n\n \/\/ TODO(egg): we may want to keep track of the moment of inertia, angular\n \/\/ momentum, etc.\n\n \/\/ We will use union-find algorithms on |Part|s.\n not_null::Node>> const subset_node_;\n friend class Subset::Node;\n\n \/\/ Called in the destructor.\n std::function deletion_callback_;\n};\n\nstd::ostream& operator<<(std::ostream& out, Part const& part);\n\n} \/\/ namespace internal_part\n\nusing internal_part::Part;\n\n} \/\/ namespace ksp_plugin\n\nnamespace base {\n\ntemplate<>\ninline not_null::Node*>\nSubset::Node::Get(ksp_plugin::Part& element) {\n return element.subset_node_.get();\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\/*\n This file is part of ksync.\n\n Copyright (c) 2001 Cornelius Schumacher \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ksync.h\"\n#include \"ksync.moc\"\n#include \"ksyncview.h\"\n#include \n\n#define ID_STATUS_MSG 1\n\nKSync::KSync(QWidget* , const char* name):KMainWindow(0, name)\n{\n config=kapp->config();\n\n initStatusBar();\n initActions();\n initView();\n\t\n readOptions();\n\n \/\/ disable actions at startup\n fileSave->setEnabled(false);\n fileSaveAs->setEnabled(false);\n filePrint->setEnabled(false);\n editCut->setEnabled(false);\n editCopy->setEnabled(false);\n editPaste->setEnabled(false);\n setAutoSaveSettings();\n}\n\nvoid KSync::initActions()\n{\n fileNewWindow = new KAction(i18n(\"New &Window\"), 0, 0, this, SLOT(slotFileNewWindow()), actionCollection(),\"file_new_window\");\n fileNew = KStdAction::openNew(this, SLOT(slotFileNew()), actionCollection());\n fileOpen = KStdAction::open(this, SLOT(slotFileOpen()), actionCollection());\n fileOpenRecent = KStdAction::openRecent(this, SLOT(slotFileOpenRecent(const KURL&)), actionCollection());\n fileSave = KStdAction::save(this, SLOT(slotFileSave()), actionCollection());\n fileSaveAs = KStdAction::saveAs(this, SLOT(slotFileSaveAs()), actionCollection());\n fileClose = KStdAction::close(this, SLOT(slotFileClose()), actionCollection());\n filePrint = KStdAction::print(this, SLOT(slotFilePrint()), actionCollection());\n fileQuit = KStdAction::quit(this, SLOT(slotFileQuit()), actionCollection());\n editCut = KStdAction::cut(this, SLOT(slotEditCut()), actionCollection());\n editCopy = KStdAction::copy(this, SLOT(slotEditCopy()), actionCollection());\n editPaste = KStdAction::paste(this, SLOT(slotEditPaste()), actionCollection());\n createStandardStatusBarAction();\n setStandardToolBarMenuEnabled(true);\n \n fileNewWindow->setStatusText(i18n(\"Opens a new application window\"));\n fileNew->setStatusText(i18n(\"Creates a new document\"));\n fileOpen->setStatusText(i18n(\"Opens an existing document\"));\n fileOpenRecent->setStatusText(i18n(\"Opens a recently used file\"));\n fileSave->setStatusText(i18n(\"Saves the actual document\"));\n fileSaveAs->setStatusText(i18n(\"Saves the actual document as...\"));\n fileClose->setStatusText(i18n(\"Closes the actual document\"));\n filePrint ->setStatusText(i18n(\"Prints out the actual document\"));\n fileQuit->setStatusText(i18n(\"Quits the application\"));\n editCut->setStatusText(i18n(\"Cuts the selected section and puts it to the clipboard\"));\n editCopy->setStatusText(i18n(\"Copies the selected section to the clipboard\"));\n editPaste->setStatusText(i18n(\"Pastes the clipboard contents to actual position\"));\n\n \/\/ use the absolute path to your ksyncui.rc file for testing purpose in createGUI();\n createGUI();\n\n}\n\n\nvoid KSync::initStatusBar()\n{\n statusBar()->insertItem(i18n(\"Ready.\"), ID_STATUS_MSG);\n}\n\nvoid KSync::initView()\n{\n mView = new KSyncView(this);\n setCentralWidget(mView);\t\n\/\/ setCaption(doc->URL().fileName(),false);\n}\n\nvoid KSync::openDocumentFile(const KURL& url)\n{\n slotStatusMsg(i18n(\"Opening file...\"));\n\n\/\/ doc->openDocument( url);\n fileOpenRecent->addURL( url );\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\n\nvoid KSync::saveOptions()\n{\t\n config->setGroup(\"General Options\");\n fileOpenRecent->saveEntries(config,\"Recent Files\");\n\n mView->writeConfig(config);\n}\n\n\nvoid KSync::readOptions()\n{\n config->setGroup(\"General Options\");\n\n \/\/ initialize the recent file list\n fileOpenRecent->loadEntries(config,\"Recent Files\");\n mView->readConfig(config);\n}\n\nvoid KSync::saveProperties(KConfig *)\n{\n#if 0\n if(doc->URL().fileName()!=i18n(\"Untitled\") && !doc->isModified())\n {\n \/\/ saving to tempfile not necessary\n\n }\n else\n {\n KURL url=doc->URL();\t\n _cfg->writePathEntry(\"filename\", url.url());\n _cfg->writeEntry(\"modified\", doc->isModified());\n QString tempname = kapp->tempSaveName(url.url());\n QString tempurl= KURL::encode_string(tempname);\n KURL _url(tempurl);\n doc->saveDocument(_url);\n }\n#endif\n}\n\n\nvoid KSync::readProperties(KConfig *)\n{\n#if 0\n QString filename = _cfg->readPathEntry(\"filename\");\n KURL url(filename);\n bool modified = _cfg->readBoolEntry(\"modified\", false);\n if(modified)\n {\n bool canRecover;\n QString tempname = kapp->checkRecoverFile(filename, canRecover);\n KURL _url(tempname);\n \t\n if(canRecover)\n {\n doc->openDocument(_url);\n doc->setModified();\n setCaption(_url.fileName(),true);\n QFile::remove(tempname);\n }\n }\n else\n {\n if(!filename.isEmpty())\n {\n doc->openDocument(url);\n setCaption(url.fileName(),false);\n }\n }\n#endif\n}\n\nbool KSync::queryClose()\n{\n\/\/ return doc->saveModified();\n return true;\n}\n\nbool KSync::queryExit()\n{\n saveOptions();\n return true;\n}\n\nvoid KSync::slotFileNewWindow()\n{\n slotStatusMsg(i18n(\"Opening a new application window...\"));\n\t\n KSync *new_window= new KSync();\n new_window->show();\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileNew()\n{\n slotStatusMsg(i18n(\"Creating new document...\"));\n\n#if 0\n if(!doc->saveModified())\n {\n \/\/ here saving wasn't successful\n\n }\n else\n {\t\n doc->newDocument();\t\t\n setCaption(doc->URL().fileName(), false);\n }\n#endif\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileOpen()\n{\n slotStatusMsg(i18n(\"Opening file...\"));\n\n#if 0\t\n if(!doc->saveModified())\n {\n \/\/ here saving wasn't successful\n\n }\n else\n {\t\n KURL url=KFileDialog::getOpenURL(QString::null,\n i18n(\"*|All Files\"), this, i18n(\"Open File\"));\n if(!url.isEmpty())\n {\n doc->openDocument(url);\n setCaption(url.fileName(), false);\n fileOpenRecent->addURL( url );\n }\n }\n#endif\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileOpenRecent(const KURL&)\n{\n slotStatusMsg(i18n(\"Opening file...\"));\n\n#if 0\t\n if(!doc->saveModified())\n {\n \/\/ here saving wasn't successful\n }\n else\n {\n doc->openDocument(url);\n setCaption(url.fileName(), false);\n }\n#endif\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileSave()\n{\n slotStatusMsg(i18n(\"Saving file...\"));\n\t\n\/\/ doc->saveDocument(doc->URL());\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileSaveAs()\n{\n slotStatusMsg(i18n(\"Saving file with a new filename...\"));\n\n KURL url=KFileDialog::getSaveURL(QDir::currentDirPath(),\n i18n(\"*|All Files\"), this, i18n(\"Save As\"));\n if(!url.isEmpty())\n {\n\/\/ doc->saveDocument(url);\n fileOpenRecent->addURL(url);\n\/\/ setCaption(url.fileName(),doc->isModified());\n }\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileClose()\n{\n slotStatusMsg(i18n(\"Closing file...\"));\n\t\n close();\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFilePrint()\n{\n slotStatusMsg(i18n(\"Printing...\"));\n\n QPrinter printer;\n if (printer.setup(this))\n {\n mView->print(&printer);\n }\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileQuit()\n{\n slotStatusMsg(i18n(\"Exiting...\"));\n saveOptions();\n \/\/ close the first window, the list makes the next one the first again.\n \/\/ This ensures that queryClose() is called on each window to ask for closing\n KMainWindow* w;\n if(memberList)\n {\n for(w=memberList->first(); w!=0; w=memberList->first())\n {\n \/\/ only close the window if the closeEvent is accepted. If the user presses Cancel on the saveModified() dialog,\n \/\/ the window and the application stay open.\n if(!w->close())\n\tbreak;\n }\n }\t\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotEditCut()\n{\n slotStatusMsg(i18n(\"Cutting selection...\"));\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotEditCopy()\n{\n slotStatusMsg(i18n(\"Copying selection to clipboard...\"));\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotEditPaste()\n{\n slotStatusMsg(i18n(\"Inserting clipboard contents...\"));\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotStatusMsg(const QString &text)\n{\n statusBar()->clear();\n statusBar()->changeItem(text, ID_STATUS_MSG);\n}\n\nKDE_NO_COMPAT compile fixes\/*\n This file is part of ksync.\n\n Copyright (c) 2001 Cornelius Schumacher \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ksync.h\"\n#include \"ksync.moc\"\n#include \"ksyncview.h\"\n#include \n\n#define ID_STATUS_MSG 1\n\nKSync::KSync(QWidget* , const char* name):KMainWindow(0, name)\n{\n config=kapp->config();\n\n initStatusBar();\n initActions();\n initView();\n\t\n readOptions();\n\n \/\/ disable actions at startup\n fileSave->setEnabled(false);\n fileSaveAs->setEnabled(false);\n filePrint->setEnabled(false);\n editCut->setEnabled(false);\n editCopy->setEnabled(false);\n editPaste->setEnabled(false);\n setAutoSaveSettings();\n}\n\nvoid KSync::initActions()\n{\n fileNewWindow = new KAction(i18n(\"New &Window\"), 0, 0, this, SLOT(slotFileNewWindow()), actionCollection(),\"file_new_window\");\n fileNew = KStdAction::openNew(this, SLOT(slotFileNew()), actionCollection());\n fileOpen = KStdAction::open(this, SLOT(slotFileOpen()), actionCollection());\n fileOpenRecent = KStdAction::openRecent(this, SLOT(slotFileOpenRecent(const KURL&)), actionCollection());\n fileSave = KStdAction::save(this, SLOT(slotFileSave()), actionCollection());\n fileSaveAs = KStdAction::saveAs(this, SLOT(slotFileSaveAs()), actionCollection());\n fileClose = KStdAction::close(this, SLOT(slotFileClose()), actionCollection());\n filePrint = KStdAction::print(this, SLOT(slotFilePrint()), actionCollection());\n fileQuit = KStdAction::quit(this, SLOT(slotFileQuit()), actionCollection());\n editCut = KStdAction::cut(this, SLOT(slotEditCut()), actionCollection());\n editCopy = KStdAction::copy(this, SLOT(slotEditCopy()), actionCollection());\n editPaste = KStdAction::paste(this, SLOT(slotEditPaste()), actionCollection());\n createStandardStatusBarAction();\n setStandardToolBarMenuEnabled(true);\n \n fileNewWindow->setToolTip(i18n(\"Opens a new application window\"));\n fileNew->setToolTip(i18n(\"Creates a new document\"));\n fileOpen->setToolTip(i18n(\"Opens an existing document\"));\n fileOpenRecent->setToolTip(i18n(\"Opens a recently used file\"));\n fileSave->setToolTip(i18n(\"Saves the actual document\"));\n fileSaveAs->setToolTip(i18n(\"Saves the actual document as...\"));\n fileClose->setToolTip(i18n(\"Closes the actual document\"));\n filePrint ->setToolTip(i18n(\"Prints out the actual document\"));\n fileQuit->setToolTip(i18n(\"Quits the application\"));\n editCut->setToolTip(i18n(\"Cuts the selected section and puts it to the clipboard\"));\n editCopy->setToolTip(i18n(\"Copies the selected section to the clipboard\"));\n editPaste->setToolTip(i18n(\"Pastes the clipboard contents to actual position\"));\n\n \/\/ use the absolute path to your ksyncui.rc file for testing purpose in createGUI();\n createGUI();\n\n}\n\n\nvoid KSync::initStatusBar()\n{\n statusBar()->insertItem(i18n(\"Ready.\"), ID_STATUS_MSG);\n}\n\nvoid KSync::initView()\n{\n mView = new KSyncView(this);\n setCentralWidget(mView);\t\n\/\/ setCaption(doc->URL().fileName(),false);\n}\n\nvoid KSync::openDocumentFile(const KURL& url)\n{\n slotStatusMsg(i18n(\"Opening file...\"));\n\n\/\/ doc->openDocument( url);\n fileOpenRecent->addURL( url );\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\n\nvoid KSync::saveOptions()\n{\t\n config->setGroup(\"General Options\");\n fileOpenRecent->saveEntries(config,\"Recent Files\");\n\n mView->writeConfig(config);\n}\n\n\nvoid KSync::readOptions()\n{\n config->setGroup(\"General Options\");\n\n \/\/ initialize the recent file list\n fileOpenRecent->loadEntries(config,\"Recent Files\");\n mView->readConfig(config);\n}\n\nvoid KSync::saveProperties(KConfig *)\n{\n#if 0\n if(doc->URL().fileName()!=i18n(\"Untitled\") && !doc->isModified())\n {\n \/\/ saving to tempfile not necessary\n\n }\n else\n {\n KURL url=doc->URL();\t\n _cfg->writePathEntry(\"filename\", url.url());\n _cfg->writeEntry(\"modified\", doc->isModified());\n QString tempname = kapp->tempSaveName(url.url());\n QString tempurl= KURL::encode_string(tempname);\n KURL _url(tempurl);\n doc->saveDocument(_url);\n }\n#endif\n}\n\n\nvoid KSync::readProperties(KConfig *)\n{\n#if 0\n QString filename = _cfg->readPathEntry(\"filename\");\n KURL url(filename);\n bool modified = _cfg->readBoolEntry(\"modified\", false);\n if(modified)\n {\n bool canRecover;\n QString tempname = kapp->checkRecoverFile(filename, canRecover);\n KURL _url(tempname);\n \t\n if(canRecover)\n {\n doc->openDocument(_url);\n doc->setModified();\n setCaption(_url.fileName(),true);\n QFile::remove(tempname);\n }\n }\n else\n {\n if(!filename.isEmpty())\n {\n doc->openDocument(url);\n setCaption(url.fileName(),false);\n }\n }\n#endif\n}\n\nbool KSync::queryClose()\n{\n\/\/ return doc->saveModified();\n return true;\n}\n\nbool KSync::queryExit()\n{\n saveOptions();\n return true;\n}\n\nvoid KSync::slotFileNewWindow()\n{\n slotStatusMsg(i18n(\"Opening a new application window...\"));\n\t\n KSync *new_window= new KSync();\n new_window->show();\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileNew()\n{\n slotStatusMsg(i18n(\"Creating new document...\"));\n\n#if 0\n if(!doc->saveModified())\n {\n \/\/ here saving wasn't successful\n\n }\n else\n {\t\n doc->newDocument();\t\t\n setCaption(doc->URL().fileName(), false);\n }\n#endif\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileOpen()\n{\n slotStatusMsg(i18n(\"Opening file...\"));\n\n#if 0\t\n if(!doc->saveModified())\n {\n \/\/ here saving wasn't successful\n\n }\n else\n {\t\n KURL url=KFileDialog::getOpenURL(QString::null,\n i18n(\"*|All Files\"), this, i18n(\"Open File\"));\n if(!url.isEmpty())\n {\n doc->openDocument(url);\n setCaption(url.fileName(), false);\n fileOpenRecent->addURL( url );\n }\n }\n#endif\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileOpenRecent(const KURL&)\n{\n slotStatusMsg(i18n(\"Opening file...\"));\n\n#if 0\t\n if(!doc->saveModified())\n {\n \/\/ here saving wasn't successful\n }\n else\n {\n doc->openDocument(url);\n setCaption(url.fileName(), false);\n }\n#endif\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileSave()\n{\n slotStatusMsg(i18n(\"Saving file...\"));\n\t\n\/\/ doc->saveDocument(doc->URL());\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileSaveAs()\n{\n slotStatusMsg(i18n(\"Saving file with a new filename...\"));\n\n KURL url=KFileDialog::getSaveURL(QDir::currentDirPath(),\n i18n(\"*|All Files\"), this, i18n(\"Save As\"));\n if(!url.isEmpty())\n {\n\/\/ doc->saveDocument(url);\n fileOpenRecent->addURL(url);\n\/\/ setCaption(url.fileName(),doc->isModified());\n }\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileClose()\n{\n slotStatusMsg(i18n(\"Closing file...\"));\n\t\n close();\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFilePrint()\n{\n slotStatusMsg(i18n(\"Printing...\"));\n\n QPrinter printer;\n if (printer.setup(this))\n {\n mView->print(&printer);\n }\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotFileQuit()\n{\n slotStatusMsg(i18n(\"Exiting...\"));\n saveOptions();\n \/\/ close the first window, the list makes the next one the first again.\n \/\/ This ensures that queryClose() is called on each window to ask for closing\n KMainWindow* w;\n if(memberList)\n {\n for(w=memberList->first(); w!=0; w=memberList->first())\n {\n \/\/ only close the window if the closeEvent is accepted. If the user presses Cancel on the saveModified() dialog,\n \/\/ the window and the application stay open.\n if(!w->close())\n\tbreak;\n }\n }\t\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotEditCut()\n{\n slotStatusMsg(i18n(\"Cutting selection...\"));\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotEditCopy()\n{\n slotStatusMsg(i18n(\"Copying selection to clipboard...\"));\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotEditPaste()\n{\n slotStatusMsg(i18n(\"Inserting clipboard contents...\"));\n\n slotStatusMsg(i18n(\"Ready.\"));\n}\n\nvoid KSync::slotStatusMsg(const QString &text)\n{\n statusBar()->clear();\n statusBar()->changeItem(text, ID_STATUS_MSG);\n}\n\n<|endoftext|>"} {"text":"#include \"include\/AgentFactor.h\"\n\nusing namespace std;\n\nnamespace bwi_actexec {\n\n AgentFactory::AgentFactory(Agent* ag) {\n\n }\n}\nRestructure for class agent implementation - compile error forward decl?<|endoftext|>"} {"text":"\/\/ FRAGMENT(includes)\n#include \n#include \n\nusing namespace seqan;\n\n\/\/ FRAGMENT(open_file)\nint main (int argc, char const * argv[])\n{\n\tMultiSeqFile multiSeqFile;\n\tif (argc < 2 || !open(multiSeqFile.concat, argv[1], OPEN_RDONLY))\n\t\treturn 1;\n\n\/\/ FRAGMENT(guess_and_split)\n\tAutoSeqFormat format;\n\tguessFormat(multiSeqFile.concat, format);\n\tsplit(multiSeqFile, format);\n\n\/\/ FRAGMENT(read_sequences)\n\tunsigned seqCount = length(multiSeqFile);\n\tStringSet > seqs;\n\tStringSet seqIDs;\n\n\treserve(seqs, seqCount, Exact());\n\treserve(seqIDs, seqCount, Exact());\n\n\tString seq;\n\tCharString qual;\n\tCharString id;\n\n\tfor(unsigned i = 0; i < seqCount; ++i)\n\t{\n\t\tassignSeq(seq, multiSeqFile[i], format); \/\/ read sequence\n\t\tassignQual(qual, multiSeqFile[i], format); \/\/ read ascii quality values\n\t\tassignSeqId(id, multiSeqFile[i], format); \/\/ read sequence id\n\n\t\t\/\/ convert ascii to values from 0..62\n\t\t\/\/ store dna and quality together in Dna5Q\n\t\tfor (unsigned j = 0; j < length(qual) && j < length(seq); ++j)\n\t\t\tassignQualityValue(seq[j], (int)(ordValue(qual[j]) - 33));\n\n\t\t\/\/ we use reserve and append, as assign is not supported\n\t\t\/\/ by StringSet<..., Owner > >\n\t\tappendValue(seqs, seq, Generous());\n\t\tappendValue(ids, id, Generous());\n\t}\n\n\/\/ FRAGMENT(output)\n\tfor (unsigned i = 0; i < seqCount && i < 10; ++i)\n\t{\n\t\tstd::cout << '>' << ids[i] << std::endl;\n\t\tstd::cout << seqs[i] << std::endl;\n\t}\n\n\treturn 0;\n}\n\nfixed frags\/\/ FRAGMENT(includes)\n#define SEQAN_PROFILE\n#include \n#include \n\nusing namespace seqan;\n\n\/\/ FRAGMENT(open_file)\nint main (int argc, char const * argv[])\n{\n\tSEQAN_PROTIMESTART(loadTime);\n\n\tMultiSeqFile multiSeqFile;\n\tif (argc < 2 || !open(multiSeqFile.concat, argv[1], OPEN_RDONLY))\n\t\treturn 1;\n\n\/\/ FRAGMENT(guess_and_split)\n\tAutoSeqFormat format;\n\tguessFormat(multiSeqFile.concat, format);\n\tsplit(multiSeqFile, format);\n\n\/\/ FRAGMENT(reserve)\n\tunsigned seqCount = length(multiSeqFile);\n\tStringSet > seqs;\n\tStringSet seqIDs;\n\n\treserve(seqs, seqCount, Exact());\n\treserve(seqIDs, seqCount, Exact());\n\n\/\/ FRAGMENT(read_sequences)\n\tString seq;\n\tCharString qual;\n\tCharString id;\n\n\tfor(unsigned i = 0; i < seqCount; ++i)\n\t{\n\t\tassignSeq(seq, multiSeqFile[i], format); \/\/ read sequence\n\t\tassignQual(qual, multiSeqFile[i], format); \/\/ read ascii quality values\n\t\tassignSeqId(id, multiSeqFile[i], format); \/\/ read sequence id\n\n\t\t\/\/ convert ascii to values from 0..62\n\t\t\/\/ store dna and quality together in Dna5Q\n\t\tfor (unsigned j = 0; j < length(qual) && j < length(seq); ++j)\n\t\t\tassignQualityValue(seq[j], (int)(ordValue(qual[j]) - 33));\n\n\t\t\/\/ we use reserve and append, as assign is not supported\n\t\t\/\/ by StringSet<..., Owner > >\n\t\tappendValue(seqs, seq, Generous());\n\t\tappendValue(seqIDs, id, Generous());\n\t}\n\n\/\/ FRAGMENT(output)\n\tstd::cout << \"Loading \" << seqCount << \" sequences took \" << SEQAN_PROTIMEDIFF(loadTime);\n\tstd::cout << \" seconds.\" << std::endl << std::endl;\n\tfor (unsigned i = 0; i < seqCount && i < 10; ++i)\n\t{\n\t\tstd::cout << '>' << seqIDs[i] << std::endl;\n\t\tstd::cout << seqs[i] << std::endl;\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/**\n * @file\n * @brief Implements the particle generator\n * @remark Based on code from John Idarraga\n * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"GeneratorActionG4.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core\/config\/exceptions.h\"\n#include \"core\/utils\/log.h\"\n#include \"tools\/geant4.h\"\n\nusing namespace allpix;\n\nGeneratorActionG4::GeneratorActionG4(const Configuration& config)\n : particle_source_(std::make_unique()) {\n\n if(config.get(\"source_type\") == \"macro\") {\n\n LOG(INFO) << \"Using user macro for particle source.\";\n\n \/\/ Get the UI commander\n G4UImanager* UI = G4UImanager::GetUIpointer();\n\n \/\/ Execute the user's macro\n std::ifstream file(config.getPath(\"file_name\", true));\n std::string line;\n while(std::getline(file, line)) {\n \/\/ Check for the \"\/gps\/\" pattern in the line:\n if(!line.empty()) {\n if(line.substr(0, 5) == \"\/gps\/\" || line.at(0) == '#') {\n UI->ApplyCommand(line);\n } else {\n LOG(WARNING) << \"Ignoring Geant4 macro command: \\\"\" + line + \"\\\" - not related to particle source.\";\n }\n }\n }\n\n } else {\n\n \/\/ Set verbosity of source to off\n particle_source_->SetVerbosity(0);\n\n \/\/ Get source specific parameters\n auto single_source = particle_source_->GetCurrentSource();\n\n \/\/ Find Geant4 particle\n auto pdg_table = G4ParticleTable::GetParticleTable();\n auto particle_type = config.get(\"particle_type\", \"\");\n std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);\n auto particle_code = config.get(\"particle_code\", 0);\n G4ParticleDefinition* particle = nullptr;\n\n if(!particle_type.empty() && particle_code != 0) {\n if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) {\n LOG(WARNING) << \"particle_type and particle_code given. Continuing because they match.\";\n particle = pdg_table->FindParticle(particle_code);\n if(particle == nullptr) {\n throw InvalidValueError(config, \"particle_code\", \"particle code does not exist.\");\n }\n } else {\n throw InvalidValueError(\n config, \"particle_type\", \"Given particle_type does not match particle_code. Please remove one of them.\");\n }\n } else if(particle_type.empty() && particle_code == 0) {\n throw InvalidValueError(config, \"particle_code\", \"Please set particle_code or particle_type.\");\n } else if(particle_code != 0) {\n particle = pdg_table->FindParticle(particle_code);\n if(particle == nullptr) {\n throw InvalidValueError(config, \"particle_code\", \"particle code does not exist.\");\n }\n } else {\n particle = pdg_table->FindParticle(particle_type);\n if(particle == nullptr) {\n throw InvalidValueError(config, \"particle_type\", \"particle type does not exist.\");\n }\n }\n\n LOG(DEBUG) << \"Using particle \" << particle->GetParticleName() << \" (ID \" << particle->GetPDGEncoding() << \").\";\n\n \/\/ Set global parameters of the source\n single_source->SetNumberOfParticles(1);\n single_source->SetParticleDefinition(particle);\n \/\/ Set the primary track's start time in for the current event to zero:\n single_source->SetParticleTime(0.0);\n\n \/\/ Set energy parameters\n single_source->GetEneDist()->SetEnergyDisType(\"Gauss\");\n single_source->GetEneDist()->SetMonoEnergy(config.get(\"source_energy\"));\n single_source->GetEneDist()->SetBeamSigmaInE(config.get(\"source_energy_spread\", 0.));\n\n \/\/ Set the centre coordinate of the source\n single_source->GetPosDist()->SetCentreCoords(config.get(\"source_position\"));\n\n \/\/ Set other position and direction parameters according to shape\n if(config.get(\"source_type\") == \"beam\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Beam\");\n single_source->GetPosDist()->SetBeamSigmaInR(config.get(\"source_beam_size\", 0));\n\n \/\/ Set angle distribution parameters\n single_source->GetAngDist()->SetAngDistType(\"beam2d\");\n single_source->GetAngDist()->DefineAngRefAxes(\"angref1\", G4ThreeVector(-1., 0, 0));\n G4TwoVector divergence = config.get(\"source_beam_divergence\", G4TwoVector(0., 0.));\n single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x());\n single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y());\n G4ThreeVector direction = config.get(\"source_beam_direction\");\n if(fabs(direction.mag() - 1.0) > std::numeric_limits::epsilon()) {\n LOG(WARNING) << \"Momentum direction is not a unit vector: magnitude is ignored\";\n }\n single_source->GetAngDist()->SetParticleMomentumDirection(direction);\n\n } else if(config.get(\"source_type\") == \"sphere\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Volume\");\n single_source->GetPosDist()->SetPosDisShape(\"Sphere\");\n\n \/\/ Set angle distribution parameters\n single_source->GetPosDist()->SetRadius(config.get(\"source_sphere_radius\"));\n single_source->GetAngDist()->SetAngDistType(\"focused\");\n single_source->GetAngDist()->SetFocusPoint(G4ThreeVector(0, 0, 0));\n\n } else if(config.get(\"source_type\") == \"square\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Plane\");\n single_source->GetPosDist()->SetPosDisShape(\"Square\");\n single_source->GetPosDist()->SetHalfX(config.get(\"source_square_side\") \/ 2);\n single_source->GetPosDist()->SetHalfY(config.get(\"source_square_side\") \/ 2);\n\n \/\/ Set angle distribution parameters\n single_source->GetAngDist()->SetAngDistType(\"iso\");\n single_source->GetAngDist()->SetMaxTheta(config.get(\"source_square_angle\", 1.571));\n\n } else {\n\n throw InvalidValueError(config, \"source_type\", \"The source type is not valid.\");\n }\n }\n}\n\n\/**\n * Called automatically for every event\n *\/\nvoid GeneratorActionG4::GeneratePrimaries(G4Event* event) {\n particle_source_->GeneratePrimaryVertex(event);\n}\nAdded a point source.\/**\n * @file\n * @brief Implements the particle generator\n * @remark Based on code from John Idarraga\n * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"GeneratorActionG4.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core\/config\/exceptions.h\"\n#include \"core\/utils\/log.h\"\n#include \"tools\/geant4.h\"\n\nusing namespace allpix;\n\nGeneratorActionG4::GeneratorActionG4(const Configuration& config)\n : particle_source_(std::make_unique()) {\n\n if(config.get(\"source_type\") == \"macro\") {\n\n LOG(INFO) << \"Using user macro for particle source.\";\n\n \/\/ Get the UI commander\n G4UImanager* UI = G4UImanager::GetUIpointer();\n\n \/\/ Execute the user's macro\n std::ifstream file(config.getPath(\"file_name\", true));\n std::string line;\n while(std::getline(file, line)) {\n \/\/ Check for the \"\/gps\/\" pattern in the line:\n if(!line.empty()) {\n if(line.substr(0, 5) == \"\/gps\/\" || line.at(0) == '#') {\n UI->ApplyCommand(line);\n } else {\n LOG(WARNING) << \"Ignoring Geant4 macro command: \\\"\" + line + \"\\\" - not related to particle source.\";\n }\n }\n }\n\n } else {\n\n \/\/ Set verbosity of source to off\n particle_source_->SetVerbosity(0);\n\n \/\/ Get source specific parameters\n auto single_source = particle_source_->GetCurrentSource();\n\n \/\/ Find Geant4 particle\n auto pdg_table = G4ParticleTable::GetParticleTable();\n auto particle_type = config.get(\"particle_type\", \"\");\n std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);\n auto particle_code = config.get(\"particle_code\", 0);\n G4ParticleDefinition* particle = nullptr;\n\n if(!particle_type.empty() && particle_code != 0) {\n if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) {\n LOG(WARNING) << \"particle_type and particle_code given. Continuing because they match.\";\n particle = pdg_table->FindParticle(particle_code);\n if(particle == nullptr) {\n throw InvalidValueError(config, \"particle_code\", \"particle code does not exist.\");\n }\n } else {\n throw InvalidValueError(\n config, \"particle_type\", \"Given particle_type does not match particle_code. Please remove one of them.\");\n }\n } else if(particle_type.empty() && particle_code == 0) {\n throw InvalidValueError(config, \"particle_code\", \"Please set particle_code or particle_type.\");\n } else if(particle_code != 0) {\n particle = pdg_table->FindParticle(particle_code);\n if(particle == nullptr) {\n throw InvalidValueError(config, \"particle_code\", \"particle code does not exist.\");\n }\n } else {\n particle = pdg_table->FindParticle(particle_type);\n if(particle == nullptr) {\n throw InvalidValueError(config, \"particle_type\", \"particle type does not exist.\");\n }\n }\n\n LOG(DEBUG) << \"Using particle \" << particle->GetParticleName() << \" (ID \" << particle->GetPDGEncoding() << \").\";\n\n \/\/ Set global parameters of the source\n single_source->SetNumberOfParticles(1);\n single_source->SetParticleDefinition(particle);\n \/\/ Set the primary track's start time in for the current event to zero:\n single_source->SetParticleTime(0.0);\n\n \/\/ Set energy parameters\n single_source->GetEneDist()->SetEnergyDisType(\"Gauss\");\n single_source->GetEneDist()->SetMonoEnergy(config.get(\"source_energy\"));\n single_source->GetEneDist()->SetBeamSigmaInE(config.get(\"source_energy_spread\", 0.));\n\n \/\/ Set the centre coordinate of the source\n single_source->GetPosDist()->SetCentreCoords(config.get(\"source_position\"));\n\n \/\/ Set other position and direction parameters according to shape\n if(config.get(\"source_type\") == \"beam\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Beam\");\n single_source->GetPosDist()->SetBeamSigmaInR(config.get(\"source_beam_size\", 0));\n\n \/\/ Set angle distribution parameters\n single_source->GetAngDist()->SetAngDistType(\"beam2d\");\n single_source->GetAngDist()->DefineAngRefAxes(\"angref1\", G4ThreeVector(-1., 0, 0));\n G4TwoVector divergence = config.get(\"source_beam_divergence\", G4TwoVector(0., 0.));\n single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x());\n single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y());\n G4ThreeVector direction = config.get(\"source_beam_direction\");\n if(fabs(direction.mag() - 1.0) > std::numeric_limits::epsilon()) {\n LOG(WARNING) << \"Momentum direction is not a unit vector: magnitude is ignored\";\n }\n single_source->GetAngDist()->SetParticleMomentumDirection(direction);\n\n } else if(config.get(\"source_type\") == \"sphere\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Volume\");\n single_source->GetPosDist()->SetPosDisShape(\"Sphere\");\n\n \/\/ Set angle distribution parameters\n single_source->GetPosDist()->SetRadius(config.get(\"source_sphere_radius\"));\n single_source->GetAngDist()->SetAngDistType(\"focused\");\n single_source->GetAngDist()->SetFocusPoint(G4ThreeVector(0, 0, 0));\n\n } else if(config.get(\"source_type\") == \"square\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Plane\");\n single_source->GetPosDist()->SetPosDisShape(\"Square\");\n single_source->GetPosDist()->SetHalfX(config.get(\"source_square_side\") \/ 2);\n single_source->GetPosDist()->SetHalfY(config.get(\"source_square_side\") \/ 2);\n\n \/\/ Set angle distribution parameters\n single_source->GetAngDist()->SetAngDistType(\"iso\");\n single_source->GetAngDist()->SetMaxTheta(config.get(\"source_square_angle\", ROOT::Math::Pi() \/ 2));\n\n } else if(config.get(\"source_type\") == \"point\") {\n\n \/\/ Set position parameters\n single_source->GetPosDist()->SetPosDisType(\"Point\");\n\n \/\/ Set angle distribution parameters\n single_source->GetAngDist()->SetAngDistType(\"iso\");\n\n } else {\n\n throw InvalidValueError(config, \"source_type\", \"The source type is not valid.\");\n }\n }\n}\n\n\/**\n * Called automatically for every event\n *\/\nvoid GeneratorActionG4::GeneratePrimaries(G4Event* event) {\n particle_source_->GeneratePrimaryVertex(event);\n}\n<|endoftext|>"} {"text":"\/**\n * Appcelerator Kroll - licensed under the Apache Public License 2\n * see LICENSE in the root folder for details on the license.\n * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.\n *\/\n#include \n#include \"php_module.h\"\n#include \n\n#ifdef ZTS\nvoid ***tsrm_ls;\n#endif\n\nnamespace kroll\n{\n\tKROLL_MODULE(PHPModule, STRING(MODULE_NAME), STRING(MODULE_VERSION));\n\tstatic Logger* logger = Logger::Get(\"PHPModule\");\n\tconst static std::string phpSuffix(\"module.php\");\n\tstatic bool buffering = false;\n\n\tPHPModule* PHPModule::instance_ = NULL;\n\tstd::ostringstream PHPModule::buffer;\n\tstd::string PHPModule::mimeType(\"text\/html\");\n\n\tstatic int UnbufferedWrite(const char *, unsigned int TSRMLS_DC);\n\tstatic void SetIniDefault(HashTable*, const char*, const char*);\n\tstatic void IniDefaults(HashTable*);\n\tstatic void LogMessage(char*);\n\tstatic int HeaderHandler(sapi_header_struct*, sapi_header_op_enum, \n\t\tsapi_headers_struct* TSRMLS_DC);\n\n\tvoid PHPModule::Initialize()\n\t{\n\t\tPHPModule::instance_ = this;\n\t\tint argc = 1;\n\t\tchar *argv[2] = { \"php_kroll\", NULL };\n\n\t\tphp_embed_module.ub_write = UnbufferedWrite;\n\t\tphp_embed_module.log_message = LogMessage;\n\t\tphp_embed_module.ini_defaults = IniDefaults;\n\t\tphp_embed_module.header_handler = HeaderHandler;\n\t\tphp_embed_init(argc, argv PTSRMLS_CC);\n\n\t\tPHPUtils::InitializePHPKrollClasses();\n\t\tthis->InitializeBinding();\n\t\thost->AddModuleProvider(this);\n\n\t\tstd::string resourcesPath(host->GetApplication()->GetResourcesPath());\n\t\tzend_alter_ini_entry(\"include_path\", sizeof(\"include_path\"),\n\t\t\t(char*) resourcesPath.c_str(), resourcesPath.size() - 1,\n\t\t\tZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);\n\t}\n\n\t\/*static*\/\n\tvoid PHPModule::SetBuffering(bool newBuffering)\n\t{\n\t\tif (buffering)\n\t\t{\n\t\t\tbuffer.str(\"\");\n\t\t}\n\t\tbuffering = newBuffering;\n\t}\n\n\tvoid PHPModule::Stop()\n\t{\n\t\tPHPModule::instance_ = NULL;\n\n\t\tSharedKObject global = this->host->GetGlobalObject();\n\t\tScript::GetInstance()->RemoveScriptEvaluator(this->binding);\n\t\tglobal->Set(\"PHP\", Value::Undefined);\n\t\tthis->binding->Set(\"evaluate\", Value::Undefined);\n\t\tthis->binding = 0;\n\t\tPHPModule::instance_ = 0;\n\n\t\tphp_embed_shutdown(TSRMLS_C);\n\t}\n\n\tvoid PHPModule::InitializeBinding()\n\t{\n\t\tPHPModule::mimeType = SG(default_mimetype);\n\n\t\tSharedKObject global = this->host->GetGlobalObject();\n\t\tthis->binding = new PHPEvaluator();\n\t\tglobal->Set(\"PHP\", Value::NewObject(this->binding));\n\t\tScript::GetInstance()->AddScriptEvaluator(this->binding);\n\n\t\tzval *titaniumValue = PHPUtils::ToPHPValue(Value::NewObject(global));\n\t\tZEND_SET_SYMBOL(&EG(symbol_table), PRODUCT_NAME, titaniumValue);\n\t}\n\n\n\tbool PHPModule::IsModule(std::string& path)\n\t{\n\t\treturn (path.substr(path.length()-phpSuffix.length()) == phpSuffix);\n\t}\n\n\tModule* PHPModule::CreateModule(std::string& path)\n\t{\n\t\tzend_first_try\n\t\t{\n\t\t\tstd::string includeScript = \"include '\" + path + \"';\";\n\t\t\tif (SUCCESS != zend_eval_string((char *) includeScript.c_str(),\n\t\t\t\tNULL, (char *) path.c_str() TSRMLS_CC))\n\t\t\t\tlogger->Error(\"Error evaluating module at path: %s\", path.c_str());\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tlogger->Error(\"Error evaluating module at path: %s\", path.c_str());\n\t\t}\n\t\tzend_end_try();\n\n\t\tPoco::Path p(path);\n\t\tstd::string name(p.getBaseName());\n\t\tstd::string moduledir(p.makeParent().toString());\n\t\tlogger->Info(\"Loading PHP module name=%s path=%s\", name.c_str(), path.c_str());\n\n\t\treturn new PHPModuleInstance(host, path, moduledir, name);\n\t}\n\n\tstatic int UnbufferedWrite(const char *str, unsigned int length TSRMLS_DC)\n\t{\n\t\tstd::string string(str, length);\n\t\tstd::ostringstream& buffer = PHPModule::GetBuffer();\n\n\t\t\/\/ This shouldn't need to be thread safe right?\n\t\tif (buffering)\n\t\t{\n\t\t\tbuffer << string;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger->Info(string.c_str());\n\t\t}\n\t\treturn length;\n\t}\n\n\tstatic void SetIniDefault(HashTable* config, const char* name, const char* value)\n\t{\n\t\t\/\/ Forgive me Martin, borrowed from php_cli.c line 409\n\t\t\/\/ Thou are forgiven.\n\t\tzval tmp;\n\t\tZ_SET_REFCOUNT(tmp, 0);\n\t\tZ_UNSET_ISREF(tmp);\n\t\tZVAL_STRINGL(&tmp, zend_strndup(value, sizeof(value)-1), sizeof(value)-1, 0);\n\t\tzend_hash_update(config, name, sizeof(name), &tmp, sizeof(zval), NULL);\n\t}\n\n\tstatic void IniDefaults(HashTable* configuration)\n\t{\n\t\tSetIniDefault(configuration, \"display_errors\", \"1\");\n\t}\n\n\tstatic void LogMessage(char* message)\n\t{\n\t\tlogger->Debug(message);\n\t}\n\n\tstatic int HeaderHandler(sapi_header_struct* sapiHeader,\n\t\tsapi_header_op_enum op, sapi_headers_struct* sapiHeaders TSRMLS_DC)\n\t{\n\t\tif (sapiHeaders && sapiHeaders->mimetype)\n\t\t{\n\t\t\tstd::string& mimeType = PHPModule::GetMimeType();\n\t\t\tmimeType = sapiHeaders->mimetype;\n\t\t}\n\t\treturn op;\n\t}\n}\nFix off-by-one size error in PHP modules initialization.\/**\n * Appcelerator Kroll - licensed under the Apache Public License 2\n * see LICENSE in the root folder for details on the license.\n * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.\n *\/\n#include \n#include \"php_module.h\"\n#include \n\n#ifdef ZTS\nvoid ***tsrm_ls;\n#endif\n\nnamespace kroll\n{\n\tKROLL_MODULE(PHPModule, STRING(MODULE_NAME), STRING(MODULE_VERSION));\n\tstatic Logger* logger = Logger::Get(\"PHPModule\");\n\tconst static std::string phpSuffix(\"module.php\");\n\tstatic bool buffering = false;\n\n\tPHPModule* PHPModule::instance_ = NULL;\n\tstd::ostringstream PHPModule::buffer;\n\tstd::string PHPModule::mimeType(\"text\/html\");\n\n\tstatic int UnbufferedWrite(const char *, unsigned int TSRMLS_DC);\n\tstatic void SetIniDefault(HashTable*, const char*, const char*);\n\tstatic void IniDefaults(HashTable*);\n\tstatic void LogMessage(char*);\n\tstatic int HeaderHandler(sapi_header_struct*, sapi_header_op_enum, \n\t\tsapi_headers_struct* TSRMLS_DC);\n\n\tvoid PHPModule::Initialize()\n\t{\n\t\tPHPModule::instance_ = this;\n\t\tint argc = 1;\n\t\tchar *argv[2] = { \"php_kroll\", NULL };\n\n\t\tphp_embed_module.ub_write = UnbufferedWrite;\n\t\tphp_embed_module.log_message = LogMessage;\n\t\tphp_embed_module.ini_defaults = IniDefaults;\n\t\tphp_embed_module.header_handler = HeaderHandler;\n\t\tphp_embed_init(argc, argv PTSRMLS_CC);\n\n\t\tPHPUtils::InitializePHPKrollClasses();\n\t\tthis->InitializeBinding();\n\t\thost->AddModuleProvider(this);\n\n\t\tstd::string resourcesPath(host->GetApplication()->GetResourcesPath());\n\t\tzend_alter_ini_entry(\"include_path\", sizeof(\"include_path\"),\n\t\t\t(char*) resourcesPath.c_str(), resourcesPath.size(),\n\t\t\tZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);\n\t}\n\n\t\/*static*\/\n\tvoid PHPModule::SetBuffering(bool newBuffering)\n\t{\n\t\tif (buffering)\n\t\t{\n\t\t\tbuffer.str(\"\");\n\t\t}\n\t\tbuffering = newBuffering;\n\t}\n\n\tvoid PHPModule::Stop()\n\t{\n\t\tPHPModule::instance_ = NULL;\n\n\t\tSharedKObject global = this->host->GetGlobalObject();\n\t\tScript::GetInstance()->RemoveScriptEvaluator(this->binding);\n\t\tglobal->Set(\"PHP\", Value::Undefined);\n\t\tthis->binding->Set(\"evaluate\", Value::Undefined);\n\t\tthis->binding = 0;\n\t\tPHPModule::instance_ = 0;\n\n\t\tphp_embed_shutdown(TSRMLS_C);\n\t}\n\n\tvoid PHPModule::InitializeBinding()\n\t{\n\t\tPHPModule::mimeType = SG(default_mimetype);\n\n\t\tSharedKObject global = this->host->GetGlobalObject();\n\t\tthis->binding = new PHPEvaluator();\n\t\tglobal->Set(\"PHP\", Value::NewObject(this->binding));\n\t\tScript::GetInstance()->AddScriptEvaluator(this->binding);\n\n\t\tzval *titaniumValue = PHPUtils::ToPHPValue(Value::NewObject(global));\n\t\tZEND_SET_SYMBOL(&EG(symbol_table), PRODUCT_NAME, titaniumValue);\n\t}\n\n\n\tbool PHPModule::IsModule(std::string& path)\n\t{\n\t\treturn (path.substr(path.length()-phpSuffix.length()) == phpSuffix);\n\t}\n\n\tModule* PHPModule::CreateModule(std::string& path)\n\t{\n\t\tzend_first_try\n\t\t{\n\t\t\tstd::string includeScript = \"include '\" + path + \"';\";\n\t\t\tif (SUCCESS != zend_eval_string((char *) includeScript.c_str(),\n\t\t\t\tNULL, (char *) path.c_str() TSRMLS_CC))\n\t\t\t\tlogger->Error(\"Error evaluating module at path: %s\", path.c_str());\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tlogger->Error(\"Error evaluating module at path: %s\", path.c_str());\n\t\t}\n\t\tzend_end_try();\n\n\t\tPoco::Path p(path);\n\t\tstd::string name(p.getBaseName());\n\t\tstd::string moduledir(p.makeParent().toString());\n\t\tlogger->Info(\"Loading PHP module name=%s path=%s\", name.c_str(), path.c_str());\n\n\t\treturn new PHPModuleInstance(host, path, moduledir, name);\n\t}\n\n\tstatic int UnbufferedWrite(const char *str, unsigned int length TSRMLS_DC)\n\t{\n\t\tstd::string string(str, length);\n\t\tstd::ostringstream& buffer = PHPModule::GetBuffer();\n\n\t\t\/\/ This shouldn't need to be thread safe right?\n\t\tif (buffering)\n\t\t{\n\t\t\tbuffer << string;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger->Info(string.c_str());\n\t\t}\n\t\treturn length;\n\t}\n\n\tstatic void SetIniDefault(HashTable* config, const char* name, const char* value)\n\t{\n\t\t\/\/ Forgive me Martin, borrowed from php_cli.c line 409\n\t\t\/\/ Thou are forgiven.\n\t\tzval tmp;\n\t\tZ_SET_REFCOUNT(tmp, 0);\n\t\tZ_UNSET_ISREF(tmp);\n\t\tZVAL_STRINGL(&tmp, zend_strndup(value, sizeof(value)-1), sizeof(value)-1, 0);\n\t\tzend_hash_update(config, name, sizeof(name), &tmp, sizeof(zval), NULL);\n\t}\n\n\tstatic void IniDefaults(HashTable* configuration)\n\t{\n\t\tSetIniDefault(configuration, \"display_errors\", \"1\");\n\t}\n\n\tstatic void LogMessage(char* message)\n\t{\n\t\tlogger->Debug(message);\n\t}\n\n\tstatic int HeaderHandler(sapi_header_struct* sapiHeader,\n\t\tsapi_header_op_enum op, sapi_headers_struct* sapiHeaders TSRMLS_DC)\n\t{\n\t\tif (sapiHeaders && sapiHeaders->mimetype)\n\t\t{\n\t\t\tstd::string& mimeType = PHPModule::GetMimeType();\n\t\t\tmimeType = sapiHeaders->mimetype;\n\t\t}\n\t\treturn op;\n\t}\n}\n<|endoftext|>"} {"text":"\/* Copyright 2016 kunming.xie\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 \"gtest\/gtest.h\"\n#include \"base\/string16.h\"\n\n\nTEST(char16, empty)\n{\n}\ndelete unused test case<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"TestPool.hxx\"\n#include \"GrowingBuffer.hxx\"\n#include \"direct.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"fb_pool.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/WritableBuffer.hxx\"\n\n#include \n\n#include \n#include \n\nstruct Context final : IstreamHandler {\n struct pool *pool;\n bool got_data = false, eof = false, abort = false, closed = false;\n IstreamPointer abort_istream;\n\n explicit Context(struct pool &_pool)\n :pool(&_pool), abort_istream(nullptr) {}\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() noexcept override;\n void OnError(std::exception_ptr ep) noexcept override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nContext::OnData(gcc_unused const void *data, size_t length)\n{\n got_data = true;\n\n if (abort_istream.IsDefined()) {\n closed = true;\n abort_istream.ClearAndClose();\n pool_unref(pool);\n return 0;\n }\n\n return length;\n}\n\nvoid\nContext::OnEof() noexcept\n{\n eof = true;\n\n pool_unref(pool);\n}\n\nvoid\nContext::OnError(std::exception_ptr) noexcept\n{\n abort = true;\n\n pool_unref(pool);\n}\n\n\/*\n * utils\n *\n *\/\n\nstatic void\nistream_read_expect(Context *ctx, IstreamPointer &istream)\n{\n ASSERT_FALSE(ctx->eof);\n\n ctx->got_data = false;\n\n istream.Read();\n ASSERT_TRUE(ctx->eof || ctx->got_data);\n}\n\nstatic void\nrun_istream_ctx(Context *ctx, struct pool *pool, Istream *_istream)\n{\n gcc_unused off_t a1 = _istream->GetAvailable(false);\n gcc_unused off_t a2 = _istream->GetAvailable(true);\n\n IstreamPointer istream(*_istream, *ctx);\n\n#ifndef NO_GOT_DATA_ASSERT\n while (!ctx->eof)\n istream_read_expect(ctx, istream);\n#else\n for (int i = 0; i < 1000 && !ctx->eof; ++i)\n istream->Read();\n#endif\n\n if (!ctx->eof && !ctx->abort)\n istream.Close();\n\n if (!ctx->eof) {\n pool_trash(pool);\n pool_unref(pool);\n }\n\n pool_commit();\n}\n\nstatic void\nrun_istream(struct pool *pool, Istream *istream)\n{\n Context ctx(*pool);\n run_istream_ctx(&ctx, pool, istream);\n}\n\nstatic Istream *\ncreate_test(struct pool *pool)\n{\n GrowingBuffer gb;\n gb.Write(\"foo\");\n return istream_gb_new(*pool, std::move(gb)).Steal();\n}\n\nstatic Istream *\ncreate_empty(struct pool *pool)\n{\n GrowingBuffer gb;\n return istream_gb_new(*pool, std::move(gb)).Steal();\n}\n\nstatic bool\nEquals(WritableBuffer a, const char *b)\n{\n return a.size == strlen(b) && memcmp(a.data, b, a.size) == 0;\n}\n\n\n\/*\n * tests\n *\n *\/\n\n\/** normal run *\/\nTEST(GrowingBufferTest, Normal)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n auto *istream = create_test(pool);\n run_istream(&pool.Steal(), istream);\n}\n\n\/** empty input *\/\nTEST(GrowingBufferTest, Empty)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n auto *istream = create_empty(pool);\n run_istream(&pool.Steal(), istream);\n}\n\n\/** first buffer is too small, empty *\/\nTEST(GrowingBufferTest, FirstEmpty)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n GrowingBuffer buffer;\n\n buffer.Write(\"0123456789abcdefg\");\n\n ASSERT_EQ(buffer.GetSize(), 17);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"0123456789abcdefg\"));\n\n GrowingBufferReader reader(std::move(buffer));\n auto x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 17);\n\n reader.Consume(x.size);\n}\n\n\/** test growing_buffer_reader_skip() *\/\nTEST(GrowingBufferTest, Skip)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n GrowingBuffer buffer;\n\n buffer.Write(\"0123\");\n buffer.Write(\"4567\");\n buffer.Write(\"89ab\");\n buffer.Write(\"cdef\");\n\n ASSERT_EQ(buffer.GetSize(), 16);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"0123456789abcdef\"));\n\n constexpr size_t buffer_size = 8192 - 2 * sizeof(void*) - 2 * sizeof(size_t);\n\n static char zero[buffer_size * 2];\n buffer.Write(zero, sizeof(zero));\n ASSERT_EQ(buffer.GetSize(), 16 + buffer_size * 2);\n\n GrowingBufferReader reader(std::move(buffer));\n reader.Skip(buffer_size - 2);\n\n auto x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 2);\n reader.Consume(1);\n\n reader.Skip(5);\n\n x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, buffer_size - 4);\n reader.Consume(4);\n\n x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, buffer_size - 8);\n\n reader.Skip(buffer_size);\n\n x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 8);\n\n reader.Skip(8);\n\n x = reader.Read();\n ASSERT_TRUE(x.IsNull());\n}\n\n\/** test reading the head while appending to the tail *\/\nTEST(GrowingBufferTest, ConcurrentRW)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n GrowingBuffer buffer;\n\n buffer.Write(\"0123\");\n buffer.Write(\"4567\");\n buffer.Write(\"89ab\");\n\n ASSERT_EQ(buffer.GetSize(), 12);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"0123456789ab\"));\n\n buffer.Skip(12);\n ASSERT_TRUE(buffer.IsEmpty());\n ASSERT_EQ(buffer.GetSize(), 0);\n\n buffer.Write(\"cdef\");\n\n ASSERT_FALSE(buffer.IsEmpty());\n ASSERT_EQ(buffer.GetSize(),4);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"cdef\"));\n\n auto x = buffer.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 4);\n}\n\n\/** abort without handler *\/\nTEST(GrowingBufferTest, AbortWithoutHandler)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n auto *istream = create_test(pool);\n istream->CloseUnused();\n}\n\n\/** abort with handler *\/\nTEST(GrowingBufferTest, AbortWithHandler)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n Context ctx(pool.Steal());\n\n Istream *istream = create_test(ctx.pool);\n istream->SetHandler(ctx);\n\n istream->Close();\n pool_unref(ctx.pool);\n\n ASSERT_FALSE(ctx.abort);\n}\n\n\/** abort in handler *\/\nTEST(GrowingBufferTest, AbortInHandler)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n Context ctx(pool.Steal());\n\n ctx.abort_istream.Set(*create_test(ctx.pool), ctx);\n\n while (!ctx.eof && !ctx.abort && !ctx.closed)\n istream_read_expect(&ctx, ctx.abort_istream);\n\n ASSERT_FALSE(ctx.abort_istream.IsDefined());\n ASSERT_FALSE(ctx.abort);\n ASSERT_TRUE(ctx.closed);\n}\ntest\/t_growing_buffer: use class UnusedIstreamPtr\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"TestPool.hxx\"\n#include \"GrowingBuffer.hxx\"\n#include \"direct.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"fb_pool.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/WritableBuffer.hxx\"\n\n#include \n\n#include \n#include \n\nstruct Context final : IstreamHandler {\n struct pool *pool;\n bool got_data = false, eof = false, abort = false, closed = false;\n IstreamPointer abort_istream;\n\n explicit Context(struct pool &_pool)\n :pool(&_pool), abort_istream(nullptr) {}\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() noexcept override;\n void OnError(std::exception_ptr ep) noexcept override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nContext::OnData(gcc_unused const void *data, size_t length)\n{\n got_data = true;\n\n if (abort_istream.IsDefined()) {\n closed = true;\n abort_istream.ClearAndClose();\n pool_unref(pool);\n return 0;\n }\n\n return length;\n}\n\nvoid\nContext::OnEof() noexcept\n{\n eof = true;\n\n pool_unref(pool);\n}\n\nvoid\nContext::OnError(std::exception_ptr) noexcept\n{\n abort = true;\n\n pool_unref(pool);\n}\n\n\/*\n * utils\n *\n *\/\n\nstatic void\nistream_read_expect(Context *ctx, IstreamPointer &istream)\n{\n ASSERT_FALSE(ctx->eof);\n\n ctx->got_data = false;\n\n istream.Read();\n ASSERT_TRUE(ctx->eof || ctx->got_data);\n}\n\nstatic void\nrun_istream_ctx(Context *ctx, struct pool *pool, UnusedIstreamPtr _istream)\n{\n gcc_unused off_t a1 = _istream.GetAvailable(false);\n gcc_unused off_t a2 = _istream.GetAvailable(true);\n\n IstreamPointer istream(std::move(_istream), *ctx);\n\n#ifndef NO_GOT_DATA_ASSERT\n while (!ctx->eof)\n istream_read_expect(ctx, istream);\n#else\n for (int i = 0; i < 1000 && !ctx->eof; ++i)\n istream->Read();\n#endif\n\n if (!ctx->eof && !ctx->abort)\n istream.Close();\n\n if (!ctx->eof) {\n pool_trash(pool);\n pool_unref(pool);\n }\n\n pool_commit();\n}\n\nstatic void\nrun_istream(struct pool *pool, UnusedIstreamPtr istream)\n{\n Context ctx(*pool);\n run_istream_ctx(&ctx, pool, std::move(istream));\n}\n\nstatic UnusedIstreamPtr\ncreate_test(struct pool *pool)\n{\n GrowingBuffer gb;\n gb.Write(\"foo\");\n return istream_gb_new(*pool, std::move(gb));\n}\n\nstatic UnusedIstreamPtr\ncreate_empty(struct pool *pool)\n{\n GrowingBuffer gb;\n return istream_gb_new(*pool, std::move(gb));\n}\n\nstatic bool\nEquals(WritableBuffer a, const char *b)\n{\n return a.size == strlen(b) && memcmp(a.data, b, a.size) == 0;\n}\n\n\n\/*\n * tests\n *\n *\/\n\n\/** normal run *\/\nTEST(GrowingBufferTest, Normal)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n run_istream(&pool.Steal(), create_test(pool));\n}\n\n\/** empty input *\/\nTEST(GrowingBufferTest, Empty)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n run_istream(&pool.Steal(), create_empty(pool));\n}\n\n\/** first buffer is too small, empty *\/\nTEST(GrowingBufferTest, FirstEmpty)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n GrowingBuffer buffer;\n\n buffer.Write(\"0123456789abcdefg\");\n\n ASSERT_EQ(buffer.GetSize(), 17);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"0123456789abcdefg\"));\n\n GrowingBufferReader reader(std::move(buffer));\n auto x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 17);\n\n reader.Consume(x.size);\n}\n\n\/** test growing_buffer_reader_skip() *\/\nTEST(GrowingBufferTest, Skip)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n GrowingBuffer buffer;\n\n buffer.Write(\"0123\");\n buffer.Write(\"4567\");\n buffer.Write(\"89ab\");\n buffer.Write(\"cdef\");\n\n ASSERT_EQ(buffer.GetSize(), 16);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"0123456789abcdef\"));\n\n constexpr size_t buffer_size = 8192 - 2 * sizeof(void*) - 2 * sizeof(size_t);\n\n static char zero[buffer_size * 2];\n buffer.Write(zero, sizeof(zero));\n ASSERT_EQ(buffer.GetSize(), 16 + buffer_size * 2);\n\n GrowingBufferReader reader(std::move(buffer));\n reader.Skip(buffer_size - 2);\n\n auto x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 2);\n reader.Consume(1);\n\n reader.Skip(5);\n\n x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, buffer_size - 4);\n reader.Consume(4);\n\n x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, buffer_size - 8);\n\n reader.Skip(buffer_size);\n\n x = reader.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 8);\n\n reader.Skip(8);\n\n x = reader.Read();\n ASSERT_TRUE(x.IsNull());\n}\n\n\/** test reading the head while appending to the tail *\/\nTEST(GrowingBufferTest, ConcurrentRW)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n GrowingBuffer buffer;\n\n buffer.Write(\"0123\");\n buffer.Write(\"4567\");\n buffer.Write(\"89ab\");\n\n ASSERT_EQ(buffer.GetSize(), 12);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"0123456789ab\"));\n\n buffer.Skip(12);\n ASSERT_TRUE(buffer.IsEmpty());\n ASSERT_EQ(buffer.GetSize(), 0);\n\n buffer.Write(\"cdef\");\n\n ASSERT_FALSE(buffer.IsEmpty());\n ASSERT_EQ(buffer.GetSize(),4);\n ASSERT_TRUE(Equals(buffer.Dup(pool), \"cdef\"));\n\n auto x = buffer.Read();\n ASSERT_FALSE(x.IsNull());\n ASSERT_EQ(x.size, 4);\n}\n\n\/** abort without handler *\/\nTEST(GrowingBufferTest, AbortWithoutHandler)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n\n auto istream = create_test(pool);\n istream.Clear();\n}\n\n\/** abort with handler *\/\nTEST(GrowingBufferTest, AbortWithHandler)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n Context ctx(pool.Steal());\n\n Istream *istream = create_test(ctx.pool).Steal();\n istream->SetHandler(ctx);\n\n istream->Close();\n pool_unref(ctx.pool);\n\n ASSERT_FALSE(ctx.abort);\n}\n\n\/** abort in handler *\/\nTEST(GrowingBufferTest, AbortInHandler)\n{\n const ScopeFbPoolInit fb_pool_init;\n TestPool pool;\n Context ctx(pool.Steal());\n\n ctx.abort_istream.Set(create_test(ctx.pool), ctx);\n\n while (!ctx.eof && !ctx.abort && !ctx.closed)\n istream_read_expect(&ctx, ctx.abort_istream);\n\n ASSERT_FALSE(ctx.abort_istream.IsDefined());\n ASSERT_FALSE(ctx.abort);\n ASSERT_TRUE(ctx.closed);\n}\n<|endoftext|>"} {"text":"#include \"RootPool.hxx\"\n#include \"growing_buffer.hxx\"\n#include \"direct.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"event\/Base.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include \n\n#include \n\nstruct Context final : IstreamHandler {\n struct pool *pool;\n bool got_data = false, eof = false, abort = false, closed = false;\n Istream *abort_istream = nullptr;\n\n explicit Context(struct pool &_pool):pool(&_pool) {}\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() override;\n void OnError(GError *error) override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nContext::OnData(gcc_unused const void *data, size_t length)\n{\n got_data = true;\n\n if (abort_istream != nullptr) {\n closed = true;\n istream_free(&abort_istream);\n pool_unref(pool);\n return 0;\n }\n\n return length;\n}\n\nvoid\nContext::OnEof()\n{\n eof = true;\n\n pool_unref(pool);\n}\n\nvoid\nContext::OnError(GError *error)\n{\n g_error_free(error);\n\n abort = true;\n\n pool_unref(pool);\n}\n\n\/*\n * utils\n *\n *\/\n\nstatic int\nistream_read_event(Istream *istream)\n{\n istream->Read();\n return event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK);\n}\n\nstatic void\nistream_read_expect(Context *ctx, Istream *istream)\n{\n int ret;\n\n assert(!ctx->eof);\n\n ctx->got_data = false;\n\n ret = istream_read_event(istream);\n assert(ctx->eof || ctx->got_data || ret == 0);\n\n \/* give istream_later another chance to breathe *\/\n event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK);\n}\n\nstatic void\nrun_istream_ctx(Context *ctx, struct pool *pool, Istream *istream)\n{\n gcc_unused off_t a1 = istream->GetAvailable(false);\n gcc_unused off_t a2 = istream->GetAvailable(true);\n\n istream->SetHandler(*ctx);\n\n#ifndef NO_GOT_DATA_ASSERT\n while (!ctx->eof)\n istream_read_expect(ctx, istream);\n#else\n for (int i = 0; i < 1000 && !ctx->eof; ++i)\n istream_read_event(istream);\n#endif\n\n if (!ctx->eof) {\n pool_trash(pool);\n pool_unref(pool);\n }\n\n pool_commit();\n}\n\nstatic void\nrun_istream(struct pool *pool, Istream *istream)\n{\n Context ctx(*pool);\n run_istream_ctx(&ctx, pool, istream);\n}\n\nstatic Istream *\ncreate_test(struct pool *pool)\n{\n GrowingBuffer *gb = growing_buffer_new(pool, 64);\n growing_buffer_write_string(gb, \"foo\");\n return istream_gb_new(*pool, *gb);\n}\n\nstatic Istream *\ncreate_empty(struct pool *pool)\n{\n GrowingBuffer *gb = growing_buffer_new(pool, 64);\n return istream_gb_new(*pool, *gb);\n}\n\n\n\/*\n * tests\n *\n *\/\n\n\/** normal run *\/\nstatic void\ntest_normal(struct pool *pool)\n{\n Istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 8192);\n istream = create_test(pool);\n\n run_istream(pool, istream);\n}\n\n\/** empty input *\/\nstatic void\ntest_empty(struct pool *pool)\n{\n Istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 8192);\n istream = create_empty(pool);\n\n run_istream(pool, istream);\n}\n\n\/** first buffer is too small, empty *\/\nstatic void\ntest_first_empty(struct pool *pool)\n{\n pool = pool_new_linear(pool, \"test\", 8192);\n GrowingBuffer *buffer = growing_buffer_new(pool, 16);\n GrowingBufferReader reader(*buffer);\n\n growing_buffer_write_string(buffer, \"0123456789abcdefg\");\n\n auto x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 17);\n\n reader.Consume(x.size);\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** test growing_buffer_reader_skip() *\/\nstatic void\ntest_skip(struct pool *pool)\n{\n pool = pool_new_linear(pool, \"test\", 8192);\n GrowingBuffer *buffer = growing_buffer_new(pool, 3);\n GrowingBufferReader reader(*buffer);\n\n growing_buffer_write_string(buffer, \"0123\");\n growing_buffer_write_string(buffer, \"4567\");\n growing_buffer_write_string(buffer, \"89ab\");\n growing_buffer_write_string(buffer, \"cdef\");\n\n reader.Skip(6);\n\n auto x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 2);\n reader.Consume(1);\n\n reader.Skip(5);\n\n x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 4);\n reader.Consume(4);\n\n x = reader.Read();\n assert(x.IsNull());\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** test reading the head while appending to the tail *\/\nstatic void\ntest_concurrent_rw(struct pool *pool)\n{\n pool = pool_new_linear(pool, \"test\", 8192);\n GrowingBuffer *buffer = growing_buffer_new(pool, 3);\n GrowingBufferReader reader(*buffer);\n\n growing_buffer_write_string(buffer, \"0123\");\n growing_buffer_write_string(buffer, \"4567\");\n growing_buffer_write_string(buffer, \"89ab\");\n assert(reader.Available() == 12);\n\n reader.Skip(12);\n assert(reader.IsEOF());\n assert(reader.Available() == 0);\n\n growing_buffer_write_string(buffer, \"cdef\");\n reader.Update();\n\n assert(!reader.IsEOF());\n assert(reader.Available() == 4);\n\n auto x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 4);\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** abort without handler *\/\nstatic void\ntest_abort_without_handler(struct pool *pool)\n{\n Istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 8192);\n\n istream = create_test(pool);\n istream->CloseUnused();\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** abort with handler *\/\nstatic void\ntest_abort_with_handler(struct pool *pool)\n{\n Context ctx(*pool);\n Istream *istream;\n\n ctx.pool = pool_new_linear(pool, \"test\", 8192);\n\n istream = create_test(ctx.pool);\n istream->SetHandler(ctx);\n\n istream_free(&istream);\n pool_unref(ctx.pool);\n\n assert(!ctx.abort);\n\n pool_commit();\n}\n\n\/** abort in handler *\/\nstatic void\ntest_abort_in_handler(struct pool *pool)\n{\n Context ctx(*pool_new_linear(pool, \"test\", 8192));\n\n ctx.abort_istream = create_test(ctx.pool);\n ctx.abort_istream->SetHandler(ctx);\n\n while (!ctx.eof && !ctx.abort && !ctx.closed) {\n istream_read_expect(&ctx, ctx.abort_istream);\n event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK);\n }\n\n assert(ctx.abort_istream == nullptr);\n assert(!ctx.abort);\n assert(ctx.closed);\n\n pool_commit();\n}\n\n\/*\n * main\n *\n *\/\n\n\nint main(int argc, char **argv) {\n (void)argc;\n (void)argv;\n\n direct_global_init();\n EventBase event_base;\n\n \/* run test suite *\/\n\n test_normal(RootPool());\n test_empty(RootPool());\n test_first_empty(RootPool());\n test_skip(RootPool());\n test_concurrent_rw(RootPool());\n test_abort_without_handler(RootPool());\n test_abort_with_handler(RootPool());\n test_abort_in_handler(RootPool());\n}\ntest\/t_growing_buffer: use class IstreamPointer#include \"RootPool.hxx\"\n#include \"growing_buffer.hxx\"\n#include \"direct.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"event\/Base.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include \n\n#include \n\nstruct Context final : IstreamHandler {\n struct pool *pool;\n bool got_data = false, eof = false, abort = false, closed = false;\n IstreamPointer abort_istream;\n\n explicit Context(struct pool &_pool)\n :pool(&_pool), abort_istream(nullptr) {}\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() override;\n void OnError(GError *error) override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nContext::OnData(gcc_unused const void *data, size_t length)\n{\n got_data = true;\n\n if (abort_istream.IsDefined()) {\n closed = true;\n abort_istream.ClearAndClose();\n pool_unref(pool);\n return 0;\n }\n\n return length;\n}\n\nvoid\nContext::OnEof()\n{\n eof = true;\n\n pool_unref(pool);\n}\n\nvoid\nContext::OnError(GError *error)\n{\n g_error_free(error);\n\n abort = true;\n\n pool_unref(pool);\n}\n\n\/*\n * utils\n *\n *\/\n\nstatic int\nistream_read_event(IstreamPointer &istream)\n{\n istream.Read();\n return event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK);\n}\n\nstatic void\nistream_read_expect(Context *ctx, IstreamPointer &istream)\n{\n int ret;\n\n assert(!ctx->eof);\n\n ctx->got_data = false;\n\n ret = istream_read_event(istream);\n assert(ctx->eof || ctx->got_data || ret == 0);\n\n \/* give istream_later another chance to breathe *\/\n event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK);\n}\n\nstatic void\nrun_istream_ctx(Context *ctx, struct pool *pool, Istream *_istream)\n{\n gcc_unused off_t a1 = _istream->GetAvailable(false);\n gcc_unused off_t a2 = _istream->GetAvailable(true);\n\n IstreamPointer istream(*_istream, *ctx);\n\n#ifndef NO_GOT_DATA_ASSERT\n while (!ctx->eof)\n istream_read_expect(ctx, istream);\n#else\n for (int i = 0; i < 1000 && !ctx->eof; ++i)\n istream_read_event(istream);\n#endif\n\n if (!ctx->eof) {\n pool_trash(pool);\n pool_unref(pool);\n }\n\n pool_commit();\n}\n\nstatic void\nrun_istream(struct pool *pool, Istream *istream)\n{\n Context ctx(*pool);\n run_istream_ctx(&ctx, pool, istream);\n}\n\nstatic Istream *\ncreate_test(struct pool *pool)\n{\n GrowingBuffer *gb = growing_buffer_new(pool, 64);\n growing_buffer_write_string(gb, \"foo\");\n return istream_gb_new(*pool, *gb);\n}\n\nstatic Istream *\ncreate_empty(struct pool *pool)\n{\n GrowingBuffer *gb = growing_buffer_new(pool, 64);\n return istream_gb_new(*pool, *gb);\n}\n\n\n\/*\n * tests\n *\n *\/\n\n\/** normal run *\/\nstatic void\ntest_normal(struct pool *pool)\n{\n Istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 8192);\n istream = create_test(pool);\n\n run_istream(pool, istream);\n}\n\n\/** empty input *\/\nstatic void\ntest_empty(struct pool *pool)\n{\n Istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 8192);\n istream = create_empty(pool);\n\n run_istream(pool, istream);\n}\n\n\/** first buffer is too small, empty *\/\nstatic void\ntest_first_empty(struct pool *pool)\n{\n pool = pool_new_linear(pool, \"test\", 8192);\n GrowingBuffer *buffer = growing_buffer_new(pool, 16);\n GrowingBufferReader reader(*buffer);\n\n growing_buffer_write_string(buffer, \"0123456789abcdefg\");\n\n auto x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 17);\n\n reader.Consume(x.size);\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** test growing_buffer_reader_skip() *\/\nstatic void\ntest_skip(struct pool *pool)\n{\n pool = pool_new_linear(pool, \"test\", 8192);\n GrowingBuffer *buffer = growing_buffer_new(pool, 3);\n GrowingBufferReader reader(*buffer);\n\n growing_buffer_write_string(buffer, \"0123\");\n growing_buffer_write_string(buffer, \"4567\");\n growing_buffer_write_string(buffer, \"89ab\");\n growing_buffer_write_string(buffer, \"cdef\");\n\n reader.Skip(6);\n\n auto x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 2);\n reader.Consume(1);\n\n reader.Skip(5);\n\n x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 4);\n reader.Consume(4);\n\n x = reader.Read();\n assert(x.IsNull());\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** test reading the head while appending to the tail *\/\nstatic void\ntest_concurrent_rw(struct pool *pool)\n{\n pool = pool_new_linear(pool, \"test\", 8192);\n GrowingBuffer *buffer = growing_buffer_new(pool, 3);\n GrowingBufferReader reader(*buffer);\n\n growing_buffer_write_string(buffer, \"0123\");\n growing_buffer_write_string(buffer, \"4567\");\n growing_buffer_write_string(buffer, \"89ab\");\n assert(reader.Available() == 12);\n\n reader.Skip(12);\n assert(reader.IsEOF());\n assert(reader.Available() == 0);\n\n growing_buffer_write_string(buffer, \"cdef\");\n reader.Update();\n\n assert(!reader.IsEOF());\n assert(reader.Available() == 4);\n\n auto x = reader.Read();\n assert(!x.IsNull());\n assert(x.size == 4);\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** abort without handler *\/\nstatic void\ntest_abort_without_handler(struct pool *pool)\n{\n Istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 8192);\n\n istream = create_test(pool);\n istream->CloseUnused();\n\n pool_trash(pool);\n pool_unref(pool);\n pool_commit();\n}\n\n\/** abort with handler *\/\nstatic void\ntest_abort_with_handler(struct pool *pool)\n{\n Context ctx(*pool);\n Istream *istream;\n\n ctx.pool = pool_new_linear(pool, \"test\", 8192);\n\n istream = create_test(ctx.pool);\n istream->SetHandler(ctx);\n\n istream_free(&istream);\n pool_unref(ctx.pool);\n\n assert(!ctx.abort);\n\n pool_commit();\n}\n\n\/** abort in handler *\/\nstatic void\ntest_abort_in_handler(struct pool *pool)\n{\n Context ctx(*pool_new_linear(pool, \"test\", 8192));\n\n ctx.abort_istream.Set(*create_test(ctx.pool), ctx);\n\n while (!ctx.eof && !ctx.abort && !ctx.closed) {\n istream_read_expect(&ctx, ctx.abort_istream);\n event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK);\n }\n\n assert(!ctx.abort_istream.IsDefined());\n assert(!ctx.abort);\n assert(ctx.closed);\n\n pool_commit();\n}\n\n\/*\n * main\n *\n *\/\n\n\nint main(int argc, char **argv) {\n (void)argc;\n (void)argv;\n\n direct_global_init();\n EventBase event_base;\n\n \/* run test suite *\/\n\n test_normal(RootPool());\n test_empty(RootPool());\n test_first_empty(RootPool());\n test_skip(RootPool());\n test_concurrent_rw(RootPool());\n test_abort_without_handler(RootPool());\n test_abort_with_handler(RootPool());\n test_abort_in_handler(RootPool());\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"profileinformation.h\"\n\n#include \"devicesupport\/desktopdevice.h\"\n#include \"devicesupport\/devicemanager.h\"\n#include \"projectexplorerconstants.h\"\n#include \"profile.h\"\n#include \"profileinformationconfigwidget.h\"\n#include \"toolchain.h\"\n#include \"toolchainmanager.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace ProjectExplorer {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ SysRootInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char SYSROOT_INFORMATION[] = \"PE.Profile.SysRoot\";\n\nSysRootProfileInformation::SysRootProfileInformation()\n{\n setObjectName(QLatin1String(\"SysRootInformation\"));\n}\n\nCore::Id SysRootProfileInformation::dataId() const\n{\n static const Core::Id id(SYSROOT_INFORMATION);\n return id;\n}\n\nunsigned int SysRootProfileInformation::priority() const\n{\n return 32000;\n}\n\nQVariant SysRootProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p)\n return QString();\n}\n\nQList SysRootProfileInformation::validate(Profile *p) const\n{\n QList result;\n const Utils::FileName dir = SysRootProfileInformation::sysRoot(p);\n if (!dir.toFileInfo().isDir() && SysRootProfileInformation::hasSysRoot(p))\n result << Task(Task::Error, QObject::tr(\"Sys Root \\\"%1\\\" is not a directory.\").arg(dir.toUserOutput()),\n Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));\n return result;\n}\n\nProfileConfigWidget *SysRootProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::SysRootInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList SysRootProfileInformation::toUserOutput(Profile *p) const\n{\n return ItemList() << qMakePair(tr(\"Sys Root\"), sysRoot(p).toUserOutput());\n}\n\nbool SysRootProfileInformation::hasSysRoot(const Profile *p)\n{\n return !p->value(Core::Id(SYSROOT_INFORMATION)).isNull();\n}\n\nUtils::FileName SysRootProfileInformation::sysRoot(const Profile *p)\n{\n if (!p)\n return Utils::FileName();\n return Utils::FileName::fromString(p->value(Core::Id(SYSROOT_INFORMATION)).toString());\n}\n\nvoid SysRootProfileInformation::setSysRoot(Profile *p, const Utils::FileName &v)\n{\n p->setValue(Core::Id(SYSROOT_INFORMATION), v.toString());\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ToolChainInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char TOOLCHAIN_INFORMATION[] = \"PE.Profile.ToolChain\";\n\nToolChainProfileInformation::ToolChainProfileInformation()\n{\n setObjectName(QLatin1String(\"ToolChainInformation\"));\n connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),\n this, SIGNAL(validationNeeded()));\n connect(ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),\n this, SIGNAL(validationNeeded()));\n}\n\nCore::Id ToolChainProfileInformation::dataId() const\n{\n static const Core::Id id(TOOLCHAIN_INFORMATION);\n return id;\n}\n\nunsigned int ToolChainProfileInformation::priority() const\n{\n return 30000;\n}\n\nQVariant ToolChainProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p);\n QList tcList = ToolChainManager::instance()->toolChains();\n if (tcList.isEmpty())\n return QString();\n\n ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi();\n\n foreach (ToolChain *tc, tcList) {\n if (tc->targetAbi() == abi)\n return tc->id();\n }\n\n return tcList.at(0)->id();\n}\n\nQList ToolChainProfileInformation::validate(Profile *p) const\n{\n QList result;\n if (!toolChain(p)) {\n setToolChain(p, 0); \/\/ make sure to clear out no longer known tool chains\n result << Task(Task::Error, QObject::tr(\"No tool chain set up.\"),\n Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));\n }\n return result;\n}\n\nProfileConfigWidget *ToolChainProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::ToolChainInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList ToolChainProfileInformation::toUserOutput(Profile *p) const\n{\n ToolChain *tc = toolChain(p);\n return ItemList() << qMakePair(tr(\"Tool chain\"), tc ? tc->displayName() : tr(\"None\"));\n}\n\nvoid ToolChainProfileInformation::addToEnvironment(const Profile *p, Utils::Environment &env) const\n{\n ToolChain *tc = toolChain(p);\n if (tc)\n tc->addToEnvironment(env);\n}\n\nToolChain *ToolChainProfileInformation::toolChain(const Profile *p)\n{\n if (!p)\n return 0;\n const QString id = p->value(Core::Id(TOOLCHAIN_INFORMATION)).toString();\n return ToolChainManager::instance()->findToolChain(id);\n}\n\nvoid ToolChainProfileInformation::setToolChain(Profile *p, ToolChain *tc)\n{\n p->setValue(Core::Id(TOOLCHAIN_INFORMATION), tc ? tc->id() : QString());\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceTypeInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char DEVICETYPE_INFORMATION[] = \"PE.Profile.DeviceType\";\n\nDeviceTypeProfileInformation::DeviceTypeProfileInformation()\n{\n setObjectName(QLatin1String(\"DeviceTypeInformation\"));\n}\n\nCore::Id DeviceTypeProfileInformation::dataId() const\n{\n static const Core::Id id(DEVICETYPE_INFORMATION);\n return id;\n}\n\nunsigned int DeviceTypeProfileInformation::priority() const\n{\n return 33000;\n}\n\nQVariant DeviceTypeProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p);\n return QByteArray(Constants::DESKTOP_DEVICE_TYPE);\n}\n\nQList DeviceTypeProfileInformation::validate(Profile *p) const\n{\n IDevice::ConstPtr dev = DeviceProfileInformation::device(p);\n QList result;\n if (!dev.isNull() && dev->type() != DeviceTypeProfileInformation::deviceTypeId(p))\n result.append(Task(Task::Error, QObject::tr(\"Device does not match device type.\"),\n Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));\n return result;\n}\n\nProfileConfigWidget *DeviceTypeProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::DeviceTypeInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList DeviceTypeProfileInformation::toUserOutput(Profile *p) const\n{\n Core::Id type = deviceTypeId(p);\n QString typeDisplayName = tr(\"Unknown device type\");\n if (type.isValid()) {\n QList factories\n = ExtensionSystem::PluginManager::instance()->getObjects();\n foreach (IDeviceFactory *factory, factories) {\n if (factory->availableCreationIds().contains(type)) {\n typeDisplayName = factory->displayNameForId(type);\n break;\n }\n }\n }\n return ItemList() << qMakePair(tr(\"Device type\"), typeDisplayName);\n}\n\nconst Core::Id DeviceTypeProfileInformation::deviceTypeId(const Profile *p)\n{\n if (!p)\n return Core::Id();\n return Core::Id(p->value(Core::Id(DEVICETYPE_INFORMATION)).toByteArray().constData());\n}\n\nvoid DeviceTypeProfileInformation::setDeviceTypeId(Profile *p, Core::Id type)\n{\n p->setValue(Core::Id(DEVICETYPE_INFORMATION), type.name());\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char DEVICE_INFORMATION[] = \"PE.Profile.Device\";\n\nDeviceProfileInformation::DeviceProfileInformation()\n{\n setObjectName(QLatin1String(\"DeviceInformation\"));\n connect(DeviceManager::instance(), SIGNAL(deviceRemoved(Core::Id)),\n this, SIGNAL(validationNeeded()));\n connect(DeviceManager::instance(), SIGNAL(deviceUpdated(Core::Id)),\n this, SIGNAL(validationNeeded()));\n}\n\nCore::Id DeviceProfileInformation::dataId() const\n{\n static const Core::Id id(DEVICE_INFORMATION);\n return id;\n}\n\nunsigned int DeviceProfileInformation::priority() const\n{\n return 32000;\n}\n\nQVariant DeviceProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p);\n return QByteArray(Constants::DESKTOP_DEVICE_ID);\n}\n\nQList DeviceProfileInformation::validate(Profile *p) const\n{\n Q_UNUSED(p);\n QList result;\n return result;\n}\n\nProfileConfigWidget *DeviceProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::DeviceInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList DeviceProfileInformation::toUserOutput(Profile *p) const\n{\n IDevice::ConstPtr dev = device(p);\n return ItemList() << qMakePair(tr(\"Device\"), dev.isNull() ? tr(\"Unconfigured\") : dev->displayName());\n}\n\nIDevice::ConstPtr DeviceProfileInformation::device(const Profile *p)\n{\n DeviceManager *dm = DeviceManager::instance();\n return dm ? dm->find(deviceId(p)) : IDevice::ConstPtr();\n}\n\nCore::Id DeviceProfileInformation::deviceId(const Profile *p)\n{\n if (p) {\n QByteArray idname = p->value(Core::Id(DEVICE_INFORMATION)).toByteArray();\n return idname.isEmpty() ? IDevice::invalidId() : Core::Id(idname.constData());\n }\n return IDevice::invalidId();\n}\n\nvoid DeviceProfileInformation::setDevice(Profile *p, IDevice::ConstPtr dev)\n{\n setDeviceId(p, dev ? dev->id() : IDevice::invalidId());\n}\n\nvoid DeviceProfileInformation::setDeviceId(Profile *p, const Core::Id id)\n{\n p->setValue(Core::Id(DEVICE_INFORMATION), id.name());\n}\n\n} \/\/ namespace ProjectExplorer\nSysRoot: Do not treat \"\" as invalid sysroot\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"profileinformation.h\"\n\n#include \"devicesupport\/desktopdevice.h\"\n#include \"devicesupport\/devicemanager.h\"\n#include \"projectexplorerconstants.h\"\n#include \"profile.h\"\n#include \"profileinformationconfigwidget.h\"\n#include \"toolchain.h\"\n#include \"toolchainmanager.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace ProjectExplorer {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ SysRootInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char SYSROOT_INFORMATION[] = \"PE.Profile.SysRoot\";\n\nSysRootProfileInformation::SysRootProfileInformation()\n{\n setObjectName(QLatin1String(\"SysRootInformation\"));\n}\n\nCore::Id SysRootProfileInformation::dataId() const\n{\n static const Core::Id id(SYSROOT_INFORMATION);\n return id;\n}\n\nunsigned int SysRootProfileInformation::priority() const\n{\n return 32000;\n}\n\nQVariant SysRootProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p)\n return QString();\n}\n\nQList SysRootProfileInformation::validate(Profile *p) const\n{\n QList result;\n const Utils::FileName dir = SysRootProfileInformation::sysRoot(p);\n if (!dir.toFileInfo().isDir() && SysRootProfileInformation::hasSysRoot(p))\n result << Task(Task::Error, QObject::tr(\"Sys Root \\\"%1\\\" is not a directory.\").arg(dir.toUserOutput()),\n Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));\n return result;\n}\n\nProfileConfigWidget *SysRootProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::SysRootInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList SysRootProfileInformation::toUserOutput(Profile *p) const\n{\n return ItemList() << qMakePair(tr(\"Sys Root\"), sysRoot(p).toUserOutput());\n}\n\nbool SysRootProfileInformation::hasSysRoot(const Profile *p)\n{\n return !p->value(Core::Id(SYSROOT_INFORMATION)).toString().isEmpty();\n}\n\nUtils::FileName SysRootProfileInformation::sysRoot(const Profile *p)\n{\n if (!p)\n return Utils::FileName();\n return Utils::FileName::fromString(p->value(Core::Id(SYSROOT_INFORMATION)).toString());\n}\n\nvoid SysRootProfileInformation::setSysRoot(Profile *p, const Utils::FileName &v)\n{\n p->setValue(Core::Id(SYSROOT_INFORMATION), v.toString());\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ToolChainInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char TOOLCHAIN_INFORMATION[] = \"PE.Profile.ToolChain\";\n\nToolChainProfileInformation::ToolChainProfileInformation()\n{\n setObjectName(QLatin1String(\"ToolChainInformation\"));\n connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),\n this, SIGNAL(validationNeeded()));\n connect(ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),\n this, SIGNAL(validationNeeded()));\n}\n\nCore::Id ToolChainProfileInformation::dataId() const\n{\n static const Core::Id id(TOOLCHAIN_INFORMATION);\n return id;\n}\n\nunsigned int ToolChainProfileInformation::priority() const\n{\n return 30000;\n}\n\nQVariant ToolChainProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p);\n QList tcList = ToolChainManager::instance()->toolChains();\n if (tcList.isEmpty())\n return QString();\n\n ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi();\n\n foreach (ToolChain *tc, tcList) {\n if (tc->targetAbi() == abi)\n return tc->id();\n }\n\n return tcList.at(0)->id();\n}\n\nQList ToolChainProfileInformation::validate(Profile *p) const\n{\n QList result;\n if (!toolChain(p)) {\n setToolChain(p, 0); \/\/ make sure to clear out no longer known tool chains\n result << Task(Task::Error, QObject::tr(\"No tool chain set up.\"),\n Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));\n }\n return result;\n}\n\nProfileConfigWidget *ToolChainProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::ToolChainInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList ToolChainProfileInformation::toUserOutput(Profile *p) const\n{\n ToolChain *tc = toolChain(p);\n return ItemList() << qMakePair(tr(\"Tool chain\"), tc ? tc->displayName() : tr(\"None\"));\n}\n\nvoid ToolChainProfileInformation::addToEnvironment(const Profile *p, Utils::Environment &env) const\n{\n ToolChain *tc = toolChain(p);\n if (tc)\n tc->addToEnvironment(env);\n}\n\nToolChain *ToolChainProfileInformation::toolChain(const Profile *p)\n{\n if (!p)\n return 0;\n const QString id = p->value(Core::Id(TOOLCHAIN_INFORMATION)).toString();\n return ToolChainManager::instance()->findToolChain(id);\n}\n\nvoid ToolChainProfileInformation::setToolChain(Profile *p, ToolChain *tc)\n{\n p->setValue(Core::Id(TOOLCHAIN_INFORMATION), tc ? tc->id() : QString());\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceTypeInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char DEVICETYPE_INFORMATION[] = \"PE.Profile.DeviceType\";\n\nDeviceTypeProfileInformation::DeviceTypeProfileInformation()\n{\n setObjectName(QLatin1String(\"DeviceTypeInformation\"));\n}\n\nCore::Id DeviceTypeProfileInformation::dataId() const\n{\n static const Core::Id id(DEVICETYPE_INFORMATION);\n return id;\n}\n\nunsigned int DeviceTypeProfileInformation::priority() const\n{\n return 33000;\n}\n\nQVariant DeviceTypeProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p);\n return QByteArray(Constants::DESKTOP_DEVICE_TYPE);\n}\n\nQList DeviceTypeProfileInformation::validate(Profile *p) const\n{\n IDevice::ConstPtr dev = DeviceProfileInformation::device(p);\n QList result;\n if (!dev.isNull() && dev->type() != DeviceTypeProfileInformation::deviceTypeId(p))\n result.append(Task(Task::Error, QObject::tr(\"Device does not match device type.\"),\n Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));\n return result;\n}\n\nProfileConfigWidget *DeviceTypeProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::DeviceTypeInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList DeviceTypeProfileInformation::toUserOutput(Profile *p) const\n{\n Core::Id type = deviceTypeId(p);\n QString typeDisplayName = tr(\"Unknown device type\");\n if (type.isValid()) {\n QList factories\n = ExtensionSystem::PluginManager::instance()->getObjects();\n foreach (IDeviceFactory *factory, factories) {\n if (factory->availableCreationIds().contains(type)) {\n typeDisplayName = factory->displayNameForId(type);\n break;\n }\n }\n }\n return ItemList() << qMakePair(tr(\"Device type\"), typeDisplayName);\n}\n\nconst Core::Id DeviceTypeProfileInformation::deviceTypeId(const Profile *p)\n{\n if (!p)\n return Core::Id();\n return Core::Id(p->value(Core::Id(DEVICETYPE_INFORMATION)).toByteArray().constData());\n}\n\nvoid DeviceTypeProfileInformation::setDeviceTypeId(Profile *p, Core::Id type)\n{\n p->setValue(Core::Id(DEVICETYPE_INFORMATION), type.name());\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceInformation:\n\/\/ --------------------------------------------------------------------------\n\nstatic const char DEVICE_INFORMATION[] = \"PE.Profile.Device\";\n\nDeviceProfileInformation::DeviceProfileInformation()\n{\n setObjectName(QLatin1String(\"DeviceInformation\"));\n connect(DeviceManager::instance(), SIGNAL(deviceRemoved(Core::Id)),\n this, SIGNAL(validationNeeded()));\n connect(DeviceManager::instance(), SIGNAL(deviceUpdated(Core::Id)),\n this, SIGNAL(validationNeeded()));\n}\n\nCore::Id DeviceProfileInformation::dataId() const\n{\n static const Core::Id id(DEVICE_INFORMATION);\n return id;\n}\n\nunsigned int DeviceProfileInformation::priority() const\n{\n return 32000;\n}\n\nQVariant DeviceProfileInformation::defaultValue(Profile *p) const\n{\n Q_UNUSED(p);\n return QByteArray(Constants::DESKTOP_DEVICE_ID);\n}\n\nQList DeviceProfileInformation::validate(Profile *p) const\n{\n Q_UNUSED(p);\n QList result;\n return result;\n}\n\nProfileConfigWidget *DeviceProfileInformation::createConfigWidget(Profile *p) const\n{\n Q_ASSERT(p);\n return new Internal::DeviceInformationConfigWidget(p);\n}\n\nProfileInformation::ItemList DeviceProfileInformation::toUserOutput(Profile *p) const\n{\n IDevice::ConstPtr dev = device(p);\n return ItemList() << qMakePair(tr(\"Device\"), dev.isNull() ? tr(\"Unconfigured\") : dev->displayName());\n}\n\nIDevice::ConstPtr DeviceProfileInformation::device(const Profile *p)\n{\n DeviceManager *dm = DeviceManager::instance();\n return dm ? dm->find(deviceId(p)) : IDevice::ConstPtr();\n}\n\nCore::Id DeviceProfileInformation::deviceId(const Profile *p)\n{\n if (p) {\n QByteArray idname = p->value(Core::Id(DEVICE_INFORMATION)).toByteArray();\n return idname.isEmpty() ? IDevice::invalidId() : Core::Id(idname.constData());\n }\n return IDevice::invalidId();\n}\n\nvoid DeviceProfileInformation::setDevice(Profile *p, IDevice::ConstPtr dev)\n{\n setDeviceId(p, dev ? dev->id() : IDevice::invalidId());\n}\n\nvoid DeviceProfileInformation::setDeviceId(Profile *p, const Core::Id id)\n{\n p->setValue(Core::Id(DEVICE_INFORMATION), id.name());\n}\n\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlprojectplugin.h\"\n#include \"qmlprojectmanager.h\"\n#include \"qmlprojectimportwizard.h\"\n#include \"qmlprojectapplicationwizard.h\"\n#include \"qmlstandaloneappwizard.h\"\n#include \"qmlprojectconstants.h\"\n#include \"qmlproject.h\"\n#include \"qmlprojectrunconfigurationfactory.h\"\n#include \"qmlprojectruncontrol.h\"\n#include \"fileformat\/qmlprojectfileformat.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\nnamespace QmlProjectManager {\nnamespace Internal {\n\nQmlProjectPlugin::QmlProjectPlugin()\n{ }\n\nQmlProjectPlugin::~QmlProjectPlugin()\n{\n}\n\nbool QmlProjectPlugin::initialize(const QStringList &, QString *errorMessage)\n{\n using namespace Core;\n\n ICore *core = ICore::instance();\n Core::MimeDatabase *mimeDB = core->mimeDatabase();\n\n const QLatin1String mimetypesXml(\":qmlproject\/QmlProject.mimetypes.xml\");\n\n if (! mimeDB->addMimeTypes(mimetypesXml, errorMessage))\n return false;\n\n Manager *manager = new Manager;\n\n addAutoReleasedObject(manager);\n addAutoReleasedObject(new Internal::QmlProjectRunConfigurationFactory);\n addAutoReleasedObject(new Internal::QmlRunControlFactory);\n addAutoReleasedObject(new QmlStandaloneAppWizard(QmlStandaloneAppWizard::NewQmlFile));\n addAutoReleasedObject(new QmlStandaloneAppWizard(QmlStandaloneAppWizard::ImportQmlFile));\n addAutoReleasedObject(new QmlProjectApplicationWizard);\n addAutoReleasedObject(new QmlProjectImportWizard);\n\n QmlProjectFileFormat::registerDeclarativeTypes();\n\n Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();\n iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(\":\/qmlproject\/images\/qmlproject.png\")), \"qmlproject\");\n return true;\n}\n\nvoid QmlProjectPlugin::extensionsInitialized()\n{\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmlProjectManager\n\nQ_EXPORT_PLUGIN(QmlProjectManager::Internal::QmlProjectPlugin)\nFix of a (harmless) typo\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlprojectplugin.h\"\n#include \"qmlprojectmanager.h\"\n#include \"qmlprojectimportwizard.h\"\n#include \"qmlprojectapplicationwizard.h\"\n#include \"qmlstandaloneappwizard.h\"\n#include \"qmlprojectconstants.h\"\n#include \"qmlproject.h\"\n#include \"qmlprojectrunconfigurationfactory.h\"\n#include \"qmlprojectruncontrol.h\"\n#include \"fileformat\/qmlprojectfileformat.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\nnamespace QmlProjectManager {\nnamespace Internal {\n\nQmlProjectPlugin::QmlProjectPlugin()\n{ }\n\nQmlProjectPlugin::~QmlProjectPlugin()\n{\n}\n\nbool QmlProjectPlugin::initialize(const QStringList &, QString *errorMessage)\n{\n using namespace Core;\n\n ICore *core = ICore::instance();\n Core::MimeDatabase *mimeDB = core->mimeDatabase();\n\n const QLatin1String mimetypesXml(\":\/qmlproject\/QmlProject.mimetypes.xml\");\n\n if (! mimeDB->addMimeTypes(mimetypesXml, errorMessage))\n return false;\n\n Manager *manager = new Manager;\n\n addAutoReleasedObject(manager);\n addAutoReleasedObject(new Internal::QmlProjectRunConfigurationFactory);\n addAutoReleasedObject(new Internal::QmlRunControlFactory);\n addAutoReleasedObject(new QmlStandaloneAppWizard(QmlStandaloneAppWizard::NewQmlFile));\n addAutoReleasedObject(new QmlStandaloneAppWizard(QmlStandaloneAppWizard::ImportQmlFile));\n addAutoReleasedObject(new QmlProjectApplicationWizard);\n addAutoReleasedObject(new QmlProjectImportWizard);\n\n QmlProjectFileFormat::registerDeclarativeTypes();\n\n Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();\n iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(\":\/qmlproject\/images\/qmlproject.png\")), \"qmlproject\");\n return true;\n}\n\nvoid QmlProjectPlugin::extensionsInitialized()\n{\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmlProjectManager\n\nQ_EXPORT_PLUGIN(QmlProjectManager::Internal::QmlProjectPlugin)\n<|endoftext|>"} {"text":"\/\/ -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-\n\n#include \"RobotDevastation.hpp\"\n\nbool rd::RobotDevastation::configure(yarp::os::ResourceFinder &rf)\n{\n \/\/-- Show help\n \/\/printf(\"--------------------------------------------------------------\\n\");\n if (rf.check(\"help\")) {\n printf(\"RobotDevastation options:\\n\");\n printf(\"\\t--help (this help)\\t--from [file.ini]\\t--context [path]\\n\");\n printf(\"\\t--id integer\\n\");\n printf(\"\\t--name string\\n\");\n printf(\"\\t--team integer\\n\");\n printf(\"\\t--robot string\\n\");\n \/\/ Do not exit: let last layer exit so we get help from the complete chain.\n }\n printf(\"RobotDevastation using no additional special options.\\n\");\n\n \/\/-- Get player data\n \/\/-----------------------------------------------------------------------------\n rdRoot = ::getenv (\"RD_ROOT\");\n if (rdRoot!=NULL)\n {\n RD_INFO(\"The RD_ROOT is: %s\\n\",rdRoot);\n }\n else\n {\n RD_WARNING(\"No RD_ROOT environment variable!\\n\");\n rdRoot=\"..\/..\"; \/\/-- Allow to run from build\/bin\n }\n\n if( ! rf.check(\"id\") )\n {\n RD_ERROR(\"No id!\\n\");\n return false;\n }\n RD_INFO(\"id: %d\\n\",rf.find(\"id\").asInt());\n\n if( ! rf.check(\"name\") )\n {\n RD_ERROR(\"No name!\\n\");\n return false;\n }\n RD_INFO(\"name: %s\\n\",rf.find(\"name\").asString().c_str());\n\n if( ! rf.check(\"team\") )\n {\n RD_ERROR(\"No team!\\n\");\n return false;\n }\n RD_INFO(\"team: %d\\n\",rf.find(\"team\").asInt());\n\n if( ! rf.check(\"robot\") )\n {\n RD_ERROR(\"No robot!\\n\");\n return false;\n }\n RD_INFO(\"robot: %s\\n\",rf.find(\"robot\").asString().c_str());\n\n \/\/-- Init mentalMap\n mentalMap = RdMentalMap::getMentalMap();\n mentalMap->configure( rf.find(\"id\").asInt() );\n\n std::vector< RdPlayer > players;\n players.push_back( RdPlayer(rf.find(\"id\").asInt(),std::string(rf.find(\"name\").asString()),100,100,rf.find(\"team\").asInt(),0) );\n mentalMap->updatePlayers(players);\n\n mentalMap->addWeapon(RdWeapon(\"Default gun\", 10, 5));\n\n \/\/-- Init input manager\n inputManager = RdInputManager::getInputManager();\n inputManager->addInputEventListener(this);\n if (!inputManager->start() )\n {\n RD_ERROR(\"Could not init inputManager!\\n\");\n return false;\n }\n\n \/\/-- Init sound\n if( ! initSound() )\n return false;\n\n audioManager->playMusic(\"bso\", -1);\n\n \/\/-- Init robot\n if( rf.find(\"robot\").asString() == \"rd1\")\n robotManager = new RdRd1RobotManager(rf.find(\"id\").asInt());\n else if( rf.find(\"robot\").asString() == \"ecro\")\n robotManager = new RdEcroRobotManager(rf.find(\"id\").asInt());\n else {\n RD_ERROR(\"Unknown robot type \\\"%s\\\"!\\n\", rf.find(\"robot\").asString().c_str());\n return false;\n }\n if( ! robotManager->connect() ) {\n RD_ERROR(\"Could not connect to robot id \\\"%d\\\" type \\\"%s\\\"!\\n\",rf.find(\"id\").asInt(),rf.find(\"robot\").asString().c_str());\n RD_ERROR(\"Use syntax: robotDevastation --id %d --robot %s\\n\",rf.find(\"id\").asInt(),rf.find(\"robot\").asString().c_str());\n return false;\n }\n\n \/\/-- Init network manager\n networkManager = RdYarpNetworkManager::getNetworkManager();\n networkManager->addNetworkEventListener(mentalMap);\n mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager);\n networkManager->login(mentalMap->getMyself());\n\n \/\/-- Init image manager\n RdYarpImageManager::RegisterManager();\n imageManager = RdImageManager::getImageManager(RdYarpImageManager::id);\n \/\/-- Add the image processing listener to the image manager\n imageManager->addImageEventListener(&processorImageEventListener);\n \/\/-- Configure the camera port\n std::ostringstream remoteCameraPortName; \/\/-- Default looks like \"\/0\/rd1\/img:o\"\n remoteCameraPortName << \"\/\";\n remoteCameraPortName << rf.find(\"id\").asInt();\n remoteCameraPortName << \"\/\";\n remoteCameraPortName << rf.find(\"robot\").asString();\n remoteCameraPortName << \"\/img:o\";\n imageManager->configure(\"remote_img_port\", remoteCameraPortName.str() );\n std::ostringstream localCameraPortName; \/\/-- Default should look like \"\/0\/robot\/img:i\"\n localCameraPortName << \"\/\";\n localCameraPortName << rf.find(\"id\").asInt();\n localCameraPortName << \"\/robot\/img:i\";\n imageManager->configure(\"local_img_port\", localCameraPortName.str() ); \/\/-- Name given by me\n if( ! imageManager->start() )\n return false;\n\n \/\/-- Init output thread\n rateThreadOutput.setRdRoot(rdRoot);\n rateThreadOutput.init(rf);\n\n return true;\n}\n\nbool rd::RobotDevastation::onKeyUp(rd::RdKey k)\n{\nif (k.isPrintable() )\n {\n RD_SUCCESS( \"Key \\\"%c\\\" was pressed!\\n\", k.getChar() );\n\n if ( k.getChar() == 'w')\n {\n robotManager->stopMovement();\n }\n else if ( k.getChar() == 'a')\n {\n robotManager->stopMovement();\n }\n else if ( k.getChar() == 's')\n {\n robotManager->stopMovement();\n }\n else if ( k.getChar() == 'd')\n {\n robotManager->stopMovement();\n }\n }\n\treturn true;\n}\n\nbool rd::RobotDevastation::onKeyDown(rd::RdKey k)\n{\n if ( k.isControlKey() )\n {\n RD_SUCCESS( \"Control key with code %d pressed!\\n\", k.getValue() );\n\n if ( k.getValue() == RdKey::KEY_SPACE)\n {\n \/\/-- Do things to shoot\n mentalMap->shoot();\n RD_SUCCESS(\"Shoot!\\n\");\n }\n else if ( k.getValue() == RdKey::KEY_ESCAPE)\n {\n RD_SUCCESS(\"Exit!\\n\");\n this->interruptModule();\n }\n }\n else if (k.isPrintable() )\n {\n RD_SUCCESS( \"Key \\\"%c\\\" was pressed!\\n\", k.getChar() );\n\n if ( k.getChar() == 'r')\n {\n RD_SUCCESS(\"Reload!\\n\");\n mentalMap->reload();\n }\n else if ( k.getChar() == 'q')\n {\n RD_SUCCESS(\"Exit!\\n\");\n this->interruptModule();\n }\n else if ( k.getChar() == 'w')\n {\n robotManager->moveForward();\n }\n else if ( k.getChar() == 'a')\n {\n robotManager->turnLeft();\n }\n else if ( k.getChar() == 'd')\n {\n robotManager->turnRight();\n }\n else if ( k.getChar() == 's')\n {\n robotManager->moveBackwards();\n }\n }\n\treturn true;\n}\n\ndouble rd::RobotDevastation::getPeriod()\n{\n return 2.0; \/\/ Fixed, in seconds, the slow thread that calls updateModule below\n}\n\nbool rd::RobotDevastation::updateModule()\n{\n printf(\"===robotDevastation===\\n\");\n printf(\"Number of players: %zd\\n\",mentalMap->getPlayers().size());\n for(size_t i=0;igetPlayers().size();i++)\n {\n printf(\"----------------------\\n%s\\n\",mentalMap->getPlayers().at(i).str().c_str());\n }\n \/\/printf(\"======================\\n\");\n return true;\n}\n\nbool rd::RobotDevastation::initSound()\n{\n std::string rdRootStr(rdRoot);\n\n audioManager = RdAudioManager::getAudioManager();\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/RobotDevastationBSO.mp3\", \"bso\", 0) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/01_milshot.wav\", \"shoot\", 1) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/15_explosion.wav\", \"explosion\", 1) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/03_clip.wav\", \"noAmmo\", 1) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/04_milaction.wav\", \"reload\", 1) )\n return false;\n\n return true;\n}\n\nbool rd::RobotDevastation::interruptModule()\n{\n RD_INFO(\"Closing program...\\n\");\n\n rateThreadOutput.stop();\n\n \/\/-- Detach listeners to avoid segmentation faults\n inputManager->removeInputEventListeners();\n networkManager->removeNetworkEventListeners();\n mentalMap->removeMentalMapEventListeners();\n imageManager->removeImageEventListeners();\n\n \/\/-- Closing input manager:\n RdInputManager::destroyInputManager();\n inputManager = NULL;\n\n \/\/-- Closing network system\n networkManager->logout(mentalMap->getMyself());\n RdYarpNetworkManager::destroyNetworkManager();\n networkManager = NULL;\n\n \/\/-- Closing audio system:\n RdAudioManager::destroyAudioManager();\n audioManager = NULL;\n\n \/\/-- Closing mental map:\n RdMentalMap::destroyMentalMap();\n mentalMap = NULL;\n\n \/\/-- Close img related ports:\n imageManager->stop();\n RdImageManager::destroyImageManager();\n imageManager = NULL;\n\n robotManager->disconnect();\n\n return true;\n}\n\nadd noMusic option (does not cancel out fx)\/\/ -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-\n\n#include \"RobotDevastation.hpp\"\n\nbool rd::RobotDevastation::configure(yarp::os::ResourceFinder &rf)\n{\n \/\/-- Show help\n \/\/printf(\"--------------------------------------------------------------\\n\");\n if (rf.check(\"help\")) {\n printf(\"RobotDevastation options:\\n\");\n printf(\"\\t--help (this help)\\t--from [file.ini]\\t--context [path]\\n\");\n printf(\"\\t--id integer\\n\");\n printf(\"\\t--name string\\n\");\n printf(\"\\t--team integer\\n\");\n printf(\"\\t--robot string\\n\");\n \/\/ Do not exit: let last layer exit so we get help from the complete chain.\n }\n printf(\"RobotDevastation using no additional special options.\\n\");\n\n \/\/-- Get player data\n \/\/-----------------------------------------------------------------------------\n rdRoot = ::getenv (\"RD_ROOT\");\n if (rdRoot!=NULL)\n {\n RD_INFO(\"The RD_ROOT is: %s\\n\",rdRoot);\n }\n else\n {\n RD_WARNING(\"No RD_ROOT environment variable!\\n\");\n rdRoot=\"..\/..\"; \/\/-- Allow to run from build\/bin\n }\n\n if( ! rf.check(\"id\") )\n {\n RD_ERROR(\"No id!\\n\");\n return false;\n }\n RD_INFO(\"id: %d\\n\",rf.find(\"id\").asInt());\n\n if( ! rf.check(\"name\") )\n {\n RD_ERROR(\"No name!\\n\");\n return false;\n }\n RD_INFO(\"name: %s\\n\",rf.find(\"name\").asString().c_str());\n\n if( ! rf.check(\"team\") )\n {\n RD_ERROR(\"No team!\\n\");\n return false;\n }\n RD_INFO(\"team: %d\\n\",rf.find(\"team\").asInt());\n\n if( ! rf.check(\"robot\") )\n {\n RD_ERROR(\"No robot!\\n\");\n return false;\n }\n RD_INFO(\"robot: %s\\n\",rf.find(\"robot\").asString().c_str());\n\n \/\/-- Init mentalMap\n mentalMap = RdMentalMap::getMentalMap();\n mentalMap->configure( rf.find(\"id\").asInt() );\n\n std::vector< RdPlayer > players;\n players.push_back( RdPlayer(rf.find(\"id\").asInt(),std::string(rf.find(\"name\").asString()),100,100,rf.find(\"team\").asInt(),0) );\n mentalMap->updatePlayers(players);\n\n mentalMap->addWeapon(RdWeapon(\"Default gun\", 10, 5));\n\n \/\/-- Init input manager\n inputManager = RdInputManager::getInputManager();\n inputManager->addInputEventListener(this);\n if (!inputManager->start() )\n {\n RD_ERROR(\"Could not init inputManager!\\n\");\n return false;\n }\n\n \/\/-- Init sound\n if( ! initSound() )\n return false;\n\n if( ! rf.check(\"noMusic\") )\n audioManager->playMusic(\"bso\", -1);\n\n \/\/-- Init robot\n if( rf.find(\"robot\").asString() == \"rd1\")\n robotManager = new RdRd1RobotManager(rf.find(\"id\").asInt());\n else if( rf.find(\"robot\").asString() == \"ecro\")\n robotManager = new RdEcroRobotManager(rf.find(\"id\").asInt());\n else {\n RD_ERROR(\"Unknown robot type \\\"%s\\\"!\\n\", rf.find(\"robot\").asString().c_str());\n return false;\n }\n if( ! robotManager->connect() ) {\n RD_ERROR(\"Could not connect to robot id \\\"%d\\\" type \\\"%s\\\"!\\n\",rf.find(\"id\").asInt(),rf.find(\"robot\").asString().c_str());\n RD_ERROR(\"Use syntax: robotDevastation --id %d --robot %s\\n\",rf.find(\"id\").asInt(),rf.find(\"robot\").asString().c_str());\n return false;\n }\n\n \/\/-- Init network manager\n networkManager = RdYarpNetworkManager::getNetworkManager();\n networkManager->addNetworkEventListener(mentalMap);\n mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager);\n networkManager->login(mentalMap->getMyself());\n\n \/\/-- Init image manager\n RdYarpImageManager::RegisterManager();\n imageManager = RdImageManager::getImageManager(RdYarpImageManager::id);\n \/\/-- Add the image processing listener to the image manager\n imageManager->addImageEventListener(&processorImageEventListener);\n \/\/-- Configure the camera port\n std::ostringstream remoteCameraPortName; \/\/-- Default looks like \"\/0\/rd1\/img:o\"\n remoteCameraPortName << \"\/\";\n remoteCameraPortName << rf.find(\"id\").asInt();\n remoteCameraPortName << \"\/\";\n remoteCameraPortName << rf.find(\"robot\").asString();\n remoteCameraPortName << \"\/img:o\";\n imageManager->configure(\"remote_img_port\", remoteCameraPortName.str() );\n std::ostringstream localCameraPortName; \/\/-- Default should look like \"\/0\/robot\/img:i\"\n localCameraPortName << \"\/\";\n localCameraPortName << rf.find(\"id\").asInt();\n localCameraPortName << \"\/robot\/img:i\";\n imageManager->configure(\"local_img_port\", localCameraPortName.str() ); \/\/-- Name given by me\n if( ! imageManager->start() )\n return false;\n\n \/\/-- Init output thread\n rateThreadOutput.setRdRoot(rdRoot);\n rateThreadOutput.init(rf);\n\n return true;\n}\n\nbool rd::RobotDevastation::onKeyUp(rd::RdKey k)\n{\nif (k.isPrintable() )\n {\n RD_SUCCESS( \"Key \\\"%c\\\" was pressed!\\n\", k.getChar() );\n\n if ( k.getChar() == 'w')\n {\n robotManager->stopMovement();\n }\n else if ( k.getChar() == 'a')\n {\n robotManager->stopMovement();\n }\n else if ( k.getChar() == 's')\n {\n robotManager->stopMovement();\n }\n else if ( k.getChar() == 'd')\n {\n robotManager->stopMovement();\n }\n }\n\treturn true;\n}\n\nbool rd::RobotDevastation::onKeyDown(rd::RdKey k)\n{\n if ( k.isControlKey() )\n {\n RD_SUCCESS( \"Control key with code %d pressed!\\n\", k.getValue() );\n\n if ( k.getValue() == RdKey::KEY_SPACE)\n {\n \/\/-- Do things to shoot\n mentalMap->shoot();\n RD_SUCCESS(\"Shoot!\\n\");\n }\n else if ( k.getValue() == RdKey::KEY_ESCAPE)\n {\n RD_SUCCESS(\"Exit!\\n\");\n this->interruptModule();\n }\n }\n else if (k.isPrintable() )\n {\n RD_SUCCESS( \"Key \\\"%c\\\" was pressed!\\n\", k.getChar() );\n\n if ( k.getChar() == 'r')\n {\n RD_SUCCESS(\"Reload!\\n\");\n mentalMap->reload();\n }\n else if ( k.getChar() == 'q')\n {\n RD_SUCCESS(\"Exit!\\n\");\n this->interruptModule();\n }\n else if ( k.getChar() == 'w')\n {\n robotManager->moveForward();\n }\n else if ( k.getChar() == 'a')\n {\n robotManager->turnLeft();\n }\n else if ( k.getChar() == 'd')\n {\n robotManager->turnRight();\n }\n else if ( k.getChar() == 's')\n {\n robotManager->moveBackwards();\n }\n }\n\treturn true;\n}\n\ndouble rd::RobotDevastation::getPeriod()\n{\n return 2.0; \/\/ Fixed, in seconds, the slow thread that calls updateModule below\n}\n\nbool rd::RobotDevastation::updateModule()\n{\n printf(\"===robotDevastation===\\n\");\n printf(\"Number of players: %zd\\n\",mentalMap->getPlayers().size());\n for(size_t i=0;igetPlayers().size();i++)\n {\n printf(\"----------------------\\n%s\\n\",mentalMap->getPlayers().at(i).str().c_str());\n }\n \/\/printf(\"======================\\n\");\n return true;\n}\n\nbool rd::RobotDevastation::initSound()\n{\n std::string rdRootStr(rdRoot);\n\n audioManager = RdAudioManager::getAudioManager();\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/RobotDevastationBSO.mp3\", \"bso\", 0) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/01_milshot.wav\", \"shoot\", 1) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/15_explosion.wav\", \"explosion\", 1) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/03_clip.wav\", \"noAmmo\", 1) )\n return false;\n\n if ( ! audioManager->load(rdRootStr+\"\/share\/sounds\/04_milaction.wav\", \"reload\", 1) )\n return false;\n\n return true;\n}\n\nbool rd::RobotDevastation::interruptModule()\n{\n RD_INFO(\"Closing program...\\n\");\n\n rateThreadOutput.stop();\n\n \/\/-- Detach listeners to avoid segmentation faults\n inputManager->removeInputEventListeners();\n networkManager->removeNetworkEventListeners();\n mentalMap->removeMentalMapEventListeners();\n imageManager->removeImageEventListeners();\n\n \/\/-- Closing input manager:\n RdInputManager::destroyInputManager();\n inputManager = NULL;\n\n \/\/-- Closing network system\n networkManager->logout(mentalMap->getMyself());\n RdYarpNetworkManager::destroyNetworkManager();\n networkManager = NULL;\n\n \/\/-- Closing audio system:\n RdAudioManager::destroyAudioManager();\n audioManager = NULL;\n\n \/\/-- Closing mental map:\n RdMentalMap::destroyMentalMap();\n mentalMap = NULL;\n\n \/\/-- Close img related ports:\n imageManager->stop();\n RdImageManager::destroyImageManager();\n imageManager = NULL;\n\n robotManager->disconnect();\n\n return true;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::string random_str(size_t length)\n{\n auto randchar = []() -> char\n {\n const char charset[] =\n \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n const size_t max_index = (sizeof(charset) - 1);\n return charset[ rand() % max_index ];\n };\n std::string str(length,0);\n std::generate_n( str.begin(), length, randchar );\n return str;\n}\n\nCommunityFundCreatePaymentRequestDialog::CommunityFundCreatePaymentRequestDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::CommunityFundCreatePaymentRequestDialog),\n model(0)\n{\n ui->setupUi(this);\n\n connect(ui->pushButtonClose, SIGNAL(clicked()), this, SLOT(reject()));\n connect(ui->pushButtonSubmitPaymentRequest, SIGNAL(clicked()), SLOT(click_pushButtonSubmitPaymentRequest()));\n}\n\nvoid CommunityFundCreatePaymentRequestDialog::setModel(WalletModel *model)\n{\n this->model = model;\n}\n\nbool CommunityFundCreatePaymentRequestDialog::validate()\n{\n bool isValid = true;\n\n \/\/ Proposal hash;\n if(!isActiveProposal(uint256S(ui->lineEditProposalHash->text().toStdString())))\n {\n isValid = false;\n ui->lineEditProposalHash->setValid(false);\n }\n\n \/\/ Amount\n if(!ui->lineEditRequestedAmount->validate())\n {\n isValid = false;\n ui->lineEditRequestedAmount->setValid(false);\n }\n\n \/\/ Description\n size_t desc_size = ui->plainTextEditDescription->toPlainText().toStdString().length();\n if(desc_size >= 1024 || desc_size == 0)\n {\n isValid = false;\n ui->plainTextEditDescription->setValid(false);\n }\n else\n {\n ui->plainTextEditDescription->setValid(true);\n }\n\n return isValid;\n}\n\nvoid CommunityFundCreatePaymentRequestDialog::click_pushButtonSubmitPaymentRequest()\n{\n\n if(this->validate())\n {\n LOCK2(cs_main, pwalletMain->cs_wallet);\n\n \/\/ Get Proposal\n CFund::CProposal proposal;\n if(!pcoinsTip->GetProposal(uint256S(ui->lineEditProposalHash->text().toStdString()), proposal)) {\n QMessageBox msgBox(this);\n std::string str = \"Proposal could not be found with that hash\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Proposal not found\");\n msgBox.exec();\n return;\n }\n if(proposal.fState != CFund::ACCEPTED) {\n QMessageBox msgBox(this);\n std::string str = \"Proposals need to have been accepted to create a Payment Request for them\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Proposal not accepted\");\n msgBox.exec();\n return;\n }\n\n \/\/ Get Address\n CNavCoinAddress address(proposal.Address);\n if(!address.IsValid()) {\n QMessageBox msgBox(this);\n std::string str = \"The address of the Proposal is not valid\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Address not valid\");\n msgBox.exec();\n return;\n }\n\n \/\/ Get KeyID\n CKeyID keyID;\n if (!address.GetKeyID(keyID)) {\n QMessageBox msgBox(this);\n std::string str = \"The address does not refer to a key\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Address not valid\");\n msgBox.exec();\n return;\n }\n\n \/\/ Ensure wallet is unlocked\n WalletModel::UnlockContext ctx(model->requestUnlock());\n if(!ctx.isValid())\n {\n \/\/ Unlock wallet was cancelled\n return;\n }\n\n \/\/ Get Key\n CKey key;\n if (!pwalletMain->GetKey(keyID, key)) {\n QMessageBox msgBox(this);\n std::string str = \"You are not the owner of the Proposal\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Not the owner\");\n msgBox.exec();\n return;\n }\n\n \/\/ Get fields from form\n CAmount nReqAmount = ui->lineEditRequestedAmount->value();\n std::string id = ui->plainTextEditDescription->toPlainText().toStdString();\n std::string sRandom = random_str(16);\n\n \/\/ Construct Secret\n std::string Secret = sRandom + \"I kindly ask to withdraw \" +\n std::to_string(nReqAmount) + \"NAV from the proposal \" +\n proposal.hash.ToString() + \". Payment request id: \" + id;\n\n CHashWriter ss(SER_GETHASH, 0);\n ss << strMessageMagic;\n ss << Secret;\n\n \/\/ Attempt to sign\n vector vchSig;\n if (!key.SignCompact(ss.GetHash(), vchSig)) {\n QMessageBox msgBox(this);\n std::string str = \"Failed to sign\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Sign Failed\");\n msgBox.exec();\n return;\n }\n\n \/\/ Create Signature\n std::string Signature = EncodeBase64(&vchSig[0], vchSig.size());\n\n \/\/ Validate requested amount\n if (nReqAmount <= 0 || nReqAmount > proposal.GetAvailable(*pcoinsTip, true)) {\n QMessageBox msgBox(this);\n std::string str = \"Cannot create a Payment Request for the requested amount\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Invalid Amount\");\n msgBox.exec();\n return;\n }\n\n \/\/ Create wtx\n CWalletTx wtx;\n bool fSubtractFeeFromAmount = false;\n\n UniValue strDZeel(UniValue::VOBJ);\n\n strDZeel.pushKV(\"h\",ui->lineEditProposalHash->text().toStdString());\n strDZeel.pushKV(\"n\",nReqAmount);\n strDZeel.pushKV(\"s\",Signature);\n strDZeel.pushKV(\"r\",sRandom);\n strDZeel.pushKV(\"i\",id);\n strDZeel.pushKV(\"v\",IsReducedCFundQuorumEnabled(chainActive.Tip(), Params().GetConsensus()) ? CFund::CPaymentRequest::CURRENT_VERSION : 2);\n\n wtx.strDZeel = strDZeel.write();\n wtx.nCustomVersion = CTransaction::PAYMENT_REQUEST_VERSION;\n\n \/\/ Validate wtx\n if(wtx.strDZeel.length() > 1024) {\n QMessageBox msgBox(this);\n std::string str = \"Description too long\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Invalid String\");\n msgBox.exec();\n return;\n }\n\n \/\/ Check balance\n CAmount curBalance = pwalletMain->GetBalance();\n if (curBalance <= 10000) {\n QMessageBox msgBox(this);\n string fee = std::to_string(10000 \/ COIN);\n std::string str = \"You require at least \" + fee + \" NAV mature and available to create a payment request\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Insufficient NAV\");\n msgBox.exec();\n return;\n }\n\n \/\/ Create partial proposal object with all nessesary display fields from input and create confirmation dialog\n {\n \/\/ Create confirmation dialog\n CFund::CPaymentRequest* preq = new CFund::CPaymentRequest();\n preq->nAmount = ui->lineEditRequestedAmount->value();\n preq->proposalhash = proposal.hash;\n preq->strDZeel = ui->plainTextEditDescription->toPlainText().toStdString();\n\n SendCommunityFundDialog dlg(this, preq, 10);\n if(dlg.exec()== QDialog::Rejected) {\n \/\/ User Declined to make the prequest\n return;\n }\n else {\n \/\/ User accepted making the prequest\n \/\/ Parse NavCoin address\n CScript CFContributionScript;\n CScript scriptPubKey = GetScriptForDestination(address.Get());\n CFund::SetScriptForCommunityFundContribution(scriptPubKey);\n\n \/\/ Create and send the transaction\n CReserveKey reservekey(pwalletMain);\n CAmount nFeeRequired;\n std::string strError;\n vector vecSend;\n int nChangePosRet = -1;\n CAmount nValue = 1000;\n CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount, \"\"};\n vecSend.push_back(recipient);\n\n bool created_prequest = true;\n\n if (!pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, nullptr, true, \"\")) {\n if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance()) {\n created_prequest = false;\n }\n }\n if (!pwalletMain->CommitTransaction(wtx, reservekey)) {\n created_prequest = false;\n }\n\n \/\/ If the proposal was successfully made, confirm to the user it was made\n if (created_prequest) {\n \/\/ Display success UI\n CommunityFundSuccessDialog dlg(wtx.GetHash(), this, preq);\n dlg.exec();\n QDialog::accept();\n return;\n }\n else {\n \/\/ Display something went wrong UI\n QMessageBox msgBox(this);\n std::string str = \"Payment Request creation failed\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Error\");\n msgBox.exec();\n return;\n }\n }\n }\n }\n else\n {\n QMessageBox msgBox(this);\n QString str = tr(\"Please enter a valid:\\n\");\n if(!isActiveProposal(uint256S(ui->lineEditProposalHash->text().toStdString())))\n str += QString(tr(\"- Proposal Hash\\n\"));\n if(!ui->lineEditRequestedAmount->validate())\n str += QString(tr(\"- Requested Amount\\n\"));\n if(ui->plainTextEditDescription->toPlainText() == QString(\"\") || ui->plainTextEditDescription->toPlainText().size() <= 0)\n str += QString(tr(\"- Description\\n\"));\n\n msgBox.setText(str);\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.exec();\n return;\n }\n}\n\nbool CommunityFundCreatePaymentRequestDialog::isActiveProposal(uint256 hash)\n{\n std::vector vec;\n CProposalMap mapProposals;\n\n if(pcoinsTip->GetAllProposals(mapProposals))\n {\n for (CProposalMap::iterator it = mapProposals.begin(); it != mapProposals.end(); it++)\n {\n CFund::CProposal proposal;\n if (!pcoinsTip->GetProposal(it->first, proposal))\n continue;\n vec.push_back(proposal);\n }\n\n if(std::find_if(vec.begin(), vec.end(), [&hash](CFund::CProposal& obj) {return obj.hash == hash;}) == vec.end())\n {\n return false;\n }\n }\n\n return true;\n}\n\nCommunityFundCreatePaymentRequestDialog::~CommunityFundCreatePaymentRequestDialog()\n{\n delete ui;\n}\nAdded clearer error messages for the nRequest amount validation (#609)#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::string random_str(size_t length)\n{\n auto randchar = []() -> char\n {\n const char charset[] =\n \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n const size_t max_index = (sizeof(charset) - 1);\n return charset[ rand() % max_index ];\n };\n std::string str(length,0);\n std::generate_n( str.begin(), length, randchar );\n return str;\n}\n\nCommunityFundCreatePaymentRequestDialog::CommunityFundCreatePaymentRequestDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::CommunityFundCreatePaymentRequestDialog),\n model(0)\n{\n ui->setupUi(this);\n\n connect(ui->pushButtonClose, SIGNAL(clicked()), this, SLOT(reject()));\n connect(ui->pushButtonSubmitPaymentRequest, SIGNAL(clicked()), SLOT(click_pushButtonSubmitPaymentRequest()));\n}\n\nvoid CommunityFundCreatePaymentRequestDialog::setModel(WalletModel *model)\n{\n this->model = model;\n}\n\nbool CommunityFundCreatePaymentRequestDialog::validate()\n{\n bool isValid = true;\n\n \/\/ Proposal hash;\n if(!isActiveProposal(uint256S(ui->lineEditProposalHash->text().toStdString())))\n {\n isValid = false;\n ui->lineEditProposalHash->setValid(false);\n }\n\n \/\/ Amount\n if(!ui->lineEditRequestedAmount->validate())\n {\n isValid = false;\n ui->lineEditRequestedAmount->setValid(false);\n }\n\n \/\/ Description\n size_t desc_size = ui->plainTextEditDescription->toPlainText().toStdString().length();\n if(desc_size >= 1024 || desc_size == 0)\n {\n isValid = false;\n ui->plainTextEditDescription->setValid(false);\n }\n else\n {\n ui->plainTextEditDescription->setValid(true);\n }\n\n return isValid;\n}\n\nvoid CommunityFundCreatePaymentRequestDialog::click_pushButtonSubmitPaymentRequest()\n{\n\n if(this->validate())\n {\n LOCK2(cs_main, pwalletMain->cs_wallet);\n\n \/\/ Get Proposal\n CFund::CProposal proposal;\n if(!pcoinsTip->GetProposal(uint256S(ui->lineEditProposalHash->text().toStdString()), proposal)) {\n QMessageBox msgBox(this);\n std::string str = \"Proposal could not be found with that hash\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Proposal not found\");\n msgBox.exec();\n return;\n }\n if(proposal.fState != CFund::ACCEPTED) {\n QMessageBox msgBox(this);\n std::string str = \"Proposals need to have been accepted to create a Payment Request for them\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Proposal not accepted\");\n msgBox.exec();\n return;\n }\n\n \/\/ Get Address\n CNavCoinAddress address(proposal.Address);\n if(!address.IsValid()) {\n QMessageBox msgBox(this);\n std::string str = \"The address of the Proposal is not valid\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Address not valid\");\n msgBox.exec();\n return;\n }\n\n \/\/ Get KeyID\n CKeyID keyID;\n if (!address.GetKeyID(keyID)) {\n QMessageBox msgBox(this);\n std::string str = \"The address does not refer to a key\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Address not valid\");\n msgBox.exec();\n return;\n }\n\n \/\/ Ensure wallet is unlocked\n WalletModel::UnlockContext ctx(model->requestUnlock());\n if(!ctx.isValid())\n {\n \/\/ Unlock wallet was cancelled\n return;\n }\n\n \/\/ Get Key\n CKey key;\n if (!pwalletMain->GetKey(keyID, key)) {\n QMessageBox msgBox(this);\n std::string str = \"You are not the owner of the Proposal\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Not the owner\");\n msgBox.exec();\n return;\n }\n\n \/\/ Get fields from form\n CAmount nReqAmount = ui->lineEditRequestedAmount->value();\n std::string id = ui->plainTextEditDescription->toPlainText().toStdString();\n std::string sRandom = random_str(16);\n\n \/\/ Construct Secret\n std::string Secret = sRandom + \"I kindly ask to withdraw \" +\n std::to_string(nReqAmount) + \"NAV from the proposal \" +\n proposal.hash.ToString() + \". Payment request id: \" + id;\n\n CHashWriter ss(SER_GETHASH, 0);\n ss << strMessageMagic;\n ss << Secret;\n\n \/\/ Attempt to sign\n vector vchSig;\n if (!key.SignCompact(ss.GetHash(), vchSig)) {\n QMessageBox msgBox(this);\n std::string str = \"Failed to sign\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Sign Failed\");\n msgBox.exec();\n return;\n }\n\n \/\/ Create Signature\n std::string Signature = EncodeBase64(&vchSig[0], vchSig.size());\n\n \/\/ Validate requested amount\n if (nReqAmount <= 0 || nReqAmount > proposal.GetAvailable(*pcoinsTip, true)) {\n QMessageBox msgBox(this);\n QString str = tr(\"Requested amount must be greater than 0 NAV (Zero)\\n\");\n if (nReqAmount > proposal.GetAvailable(*pcoinsTip, true)) {\n str = tr(\"Requested amount %1 is more than avaible coins in the proposal (%2)\\n\")\n .arg(\n NavCoinUnits::formatWithUnit(NavCoinUnits::NAV, nReqAmount),\n NavCoinUnits::formatWithUnit(NavCoinUnits::NAV, proposal.GetAvailable(*pcoinsTip, true))\n );\n }\n msgBox.setText(str);\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(tr(\"Invalid Amount\"));\n msgBox.exec();\n return;\n }\n\n \/\/ Create wtx\n CWalletTx wtx;\n bool fSubtractFeeFromAmount = false;\n\n UniValue strDZeel(UniValue::VOBJ);\n\n strDZeel.pushKV(\"h\",ui->lineEditProposalHash->text().toStdString());\n strDZeel.pushKV(\"n\",nReqAmount);\n strDZeel.pushKV(\"s\",Signature);\n strDZeel.pushKV(\"r\",sRandom);\n strDZeel.pushKV(\"i\",id);\n strDZeel.pushKV(\"v\",IsReducedCFundQuorumEnabled(chainActive.Tip(), Params().GetConsensus()) ? CFund::CPaymentRequest::CURRENT_VERSION : 2);\n\n wtx.strDZeel = strDZeel.write();\n wtx.nCustomVersion = CTransaction::PAYMENT_REQUEST_VERSION;\n\n \/\/ Validate wtx\n if(wtx.strDZeel.length() > 1024) {\n QMessageBox msgBox(this);\n std::string str = \"Description too long\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Invalid String\");\n msgBox.exec();\n return;\n }\n\n \/\/ Check balance\n CAmount curBalance = pwalletMain->GetBalance();\n if (curBalance <= 10000) {\n QMessageBox msgBox(this);\n string fee = std::to_string(10000 \/ COIN);\n std::string str = \"You require at least \" + fee + \" NAV mature and available to create a payment request\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Insufficient NAV\");\n msgBox.exec();\n return;\n }\n\n \/\/ Create partial proposal object with all nessesary display fields from input and create confirmation dialog\n {\n \/\/ Create confirmation dialog\n CFund::CPaymentRequest* preq = new CFund::CPaymentRequest();\n preq->nAmount = ui->lineEditRequestedAmount->value();\n preq->proposalhash = proposal.hash;\n preq->strDZeel = ui->plainTextEditDescription->toPlainText().toStdString();\n\n SendCommunityFundDialog dlg(this, preq, 10);\n if(dlg.exec()== QDialog::Rejected) {\n \/\/ User Declined to make the prequest\n return;\n }\n else {\n \/\/ User accepted making the prequest\n \/\/ Parse NavCoin address\n CScript CFContributionScript;\n CScript scriptPubKey = GetScriptForDestination(address.Get());\n CFund::SetScriptForCommunityFundContribution(scriptPubKey);\n\n \/\/ Create and send the transaction\n CReserveKey reservekey(pwalletMain);\n CAmount nFeeRequired;\n std::string strError;\n vector vecSend;\n int nChangePosRet = -1;\n CAmount nValue = 1000;\n CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount, \"\"};\n vecSend.push_back(recipient);\n\n bool created_prequest = true;\n\n if (!pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, nullptr, true, \"\")) {\n if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance()) {\n created_prequest = false;\n }\n }\n if (!pwalletMain->CommitTransaction(wtx, reservekey)) {\n created_prequest = false;\n }\n\n \/\/ If the proposal was successfully made, confirm to the user it was made\n if (created_prequest) {\n \/\/ Display success UI\n CommunityFundSuccessDialog dlg(wtx.GetHash(), this, preq);\n dlg.exec();\n QDialog::accept();\n return;\n }\n else {\n \/\/ Display something went wrong UI\n QMessageBox msgBox(this);\n std::string str = \"Payment Request creation failed\\n\";\n msgBox.setText(tr(str.c_str()));\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.setWindowTitle(\"Error\");\n msgBox.exec();\n return;\n }\n }\n }\n }\n else\n {\n QMessageBox msgBox(this);\n QString str = tr(\"Please enter a valid:\\n\");\n if(!isActiveProposal(uint256S(ui->lineEditProposalHash->text().toStdString())))\n str += QString(tr(\"- Proposal Hash\\n\"));\n if(!ui->lineEditRequestedAmount->validate())\n str += QString(tr(\"- Requested Amount\\n\"));\n if(ui->plainTextEditDescription->toPlainText() == QString(\"\") || ui->plainTextEditDescription->toPlainText().size() <= 0)\n str += QString(tr(\"- Description\\n\"));\n\n msgBox.setText(str);\n msgBox.addButton(tr(\"Ok\"), QMessageBox::AcceptRole);\n msgBox.setIcon(QMessageBox::Warning);\n msgBox.exec();\n return;\n }\n}\n\nbool CommunityFundCreatePaymentRequestDialog::isActiveProposal(uint256 hash)\n{\n std::vector vec;\n CProposalMap mapProposals;\n\n if(pcoinsTip->GetAllProposals(mapProposals))\n {\n for (CProposalMap::iterator it = mapProposals.begin(); it != mapProposals.end(); it++)\n {\n CFund::CProposal proposal;\n if (!pcoinsTip->GetProposal(it->first, proposal))\n continue;\n vec.push_back(proposal);\n }\n\n if(std::find_if(vec.begin(), vec.end(), [&hash](CFund::CProposal& obj) {return obj.hash == hash;}) == vec.end())\n {\n return false;\n }\n }\n\n return true;\n}\n\nCommunityFundCreatePaymentRequestDialog::~CommunityFundCreatePaymentRequestDialog()\n{\n delete ui;\n}\n<|endoftext|>"} {"text":"#include \"Mailer.h\"\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"..\/Interface\/Database.h\"\r\n#include \"database.h\"\r\n#include \"..\/urlplugin\/IUrlFactory.h\"\r\n#include \"ClientMain.h\"\r\n#include \r\n\r\nIMutex* Mailer::mutex = NULL;\r\nICondition* Mailer::cond = NULL;\r\nbool Mailer::queue_limit = false;\r\nbool Mailer::queued_mail = false;\r\nextern IUrlFactory *url_fak;\r\n\r\nbool Mailer::sendMail(const std::string & send_to, const std::string & subject, const std::string & message)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tif (queue_limit)\r\n\t\treturn false;\r\n\r\n\tlock.relock(NULL);\r\n\r\n\tIDatabase* db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);\r\n\tDBScopedSynchronous db_synchronous(db);\r\n\tIQuery* q = db->Prepare(\"INSERT INTO mail_queue (send_to, subject, message) VALUES (?,?,?)\", false);\r\n\tq->Bind(send_to);\r\n\tq->Bind(subject);\r\n\tq->Bind(message);\r\n\tbool b = q->Write();\r\n\r\n\tif (b)\r\n\t{\r\n\t\tlock.relock(mutex);\r\n\t\tcond->notify_all();\r\n\t\tqueued_mail = true;\r\n\t}\r\n\r\n\tdb->destroyQuery(q);\r\n\r\n\treturn b;\r\n}\r\n\r\nvoid Mailer::init()\r\n{\r\n\tmutex = Server->createMutex();\r\n\tcond = Server->createCondition();\r\n\tServer->createThread(new Mailer, \"mail queue\");\r\n}\r\n\r\nvoid Mailer::operator()()\r\n{\r\n\tif (url_fak == NULL)\r\n\t\treturn;\r\n\r\n\tbool has_mail_server;\r\n\t{\r\n\t\tMailServer mail_server = ClientMain::getMailServerSettings();\r\n\t\thas_mail_server = !mail_server.servername.empty();\r\n\t}\r\n\r\n\tif (!has_mail_server)\r\n\t{\r\n\t\tqueue_limit = true;\r\n\t}\r\n\r\n\tIDatabase* db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);\r\n\tIQuery* q_get_mail = db->Prepare(\"SELECT id, send_to, subject, message, next_try, retry_count FROM mail_queue WHERE next_try IS NULL or next_try>=?\");\r\n\tIQuery* q_set_retry = db->Prepare(\"UPDATE mail_queue SET next_try=?, retry_count=? WHERE id=?\");\r\n\tIQuery* q_remove_mail = db->Prepare(\"DELETE FROM mail_queue WHERE id=?\");\r\n\r\n\tdb->Write(\"UPDATE mail_queue SET next_try=NULL\");\r\n\r\n\twhile (true)\r\n\t{\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\tif (!queued_mail)\r\n\t\t\t{\r\n\t\t\t\tcond->wait(&lock, 5 * 60 * 1000);\r\n\t\t\t\tqueued_mail = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tq_get_mail->Bind(Server->getTimeMS());\r\n\t\tdb_results res = q_get_mail->Read();\r\n\t\tq_get_mail->Reset();\r\n\r\n\t\tif (res.size() > 1000)\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\tqueue_limit = true;\r\n\t\t}\r\n\t\telse if (queue_limit\r\n\t\t\t&& has_mail_server)\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\tqueue_limit = false;\r\n\t\t}\r\n\r\n\t\tMailServer mail_server;\n\n\t\tif (!res.empty() || !has_mail_server)\n\t\t{\n\t\t\tmail_server = ClientMain::getMailServerSettings();\n\t\t}\n\n\t\tif (mail_server.servername.empty())\n\t\t{\n\t\t\thas_mail_server = false;\n\t\t\tcontinue;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\thas_mail_server = true;\r\n\t\t}\r\n\r\n\t\tfor (size_t i = 0; i < res.size(); ++i)\r\n\t\t{\r\n\t\t\tstd::vector addrs;\n\t\t\tTokenize(res[i][\"send_to\"], addrs, \";,\");\r\n\r\n\t\t\tstd::string errmsg;\r\n\t\t\tif (!url_fak->sendMail(mail_server, addrs, res[i][\"subject\"], res[i][\"message\"], &errmsg))\r\n\t\t\t{\r\n\t\t\t\tint n = watoi(res[i][\"retry_count\"]);\r\n\t\t\t\tunsigned int waittime = (std::min)(static_cast(1000.*pow(2., static_cast(n))), (unsigned int)30 * 60 * 1000); \/\/30min\r\n\t\t\t\tif (n>20)\r\n\t\t\t\t{\r\n\t\t\t\t\twaittime = (unsigned int)30 * 60 * 1000;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tServer->Log(\"Error sending mail to \\\"\" + res[i][\"send_to\"] + \"\\\". \" + errmsg + \". Retrying in \" + PrettyPrintTime(waittime), LL_WARNING);\r\n\r\n\t\t\t\tq_set_retry->Bind(Server->getTimeMS()+waittime);\r\n\t\t\t\tq_set_retry->Bind(n + 1);\r\n\t\t\t\tq_set_retry->Bind(res[i][\"id\"]);\r\n\t\t\t\tq_set_retry->Write();\r\n\t\t\t\tq_set_retry->Reset();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tq_remove_mail->Bind(res[i][\"id\"]);\r\n\t\t\t\tq_remove_mail->Write();\r\n\t\t\t\tq_remove_mail->Reset();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\nReset queued_mail#include \"Mailer.h\"\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"..\/Interface\/Database.h\"\r\n#include \"database.h\"\r\n#include \"..\/urlplugin\/IUrlFactory.h\"\r\n#include \"ClientMain.h\"\r\n#include \r\n\r\nIMutex* Mailer::mutex = NULL;\r\nICondition* Mailer::cond = NULL;\r\nbool Mailer::queue_limit = false;\r\nbool Mailer::queued_mail = false;\r\nextern IUrlFactory *url_fak;\r\n\r\nbool Mailer::sendMail(const std::string & send_to, const std::string & subject, const std::string & message)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tif (queue_limit)\r\n\t\treturn false;\r\n\r\n\tlock.relock(NULL);\r\n\r\n\tIDatabase* db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);\r\n\tDBScopedSynchronous db_synchronous(db);\r\n\tIQuery* q = db->Prepare(\"INSERT INTO mail_queue (send_to, subject, message) VALUES (?,?,?)\", false);\r\n\tq->Bind(send_to);\r\n\tq->Bind(subject);\r\n\tq->Bind(message);\r\n\tbool b = q->Write();\r\n\r\n\tif (b)\r\n\t{\r\n\t\tlock.relock(mutex);\r\n\t\tcond->notify_all();\r\n\t\tqueued_mail = true;\r\n\t}\r\n\r\n\tdb->destroyQuery(q);\r\n\r\n\treturn b;\r\n}\r\n\r\nvoid Mailer::init()\r\n{\r\n\tmutex = Server->createMutex();\r\n\tcond = Server->createCondition();\r\n\tServer->createThread(new Mailer, \"mail queue\");\r\n}\r\n\r\nvoid Mailer::operator()()\r\n{\r\n\tif (url_fak == NULL)\r\n\t\treturn;\r\n\r\n\tbool has_mail_server;\r\n\t{\r\n\t\tMailServer mail_server = ClientMain::getMailServerSettings();\r\n\t\thas_mail_server = !mail_server.servername.empty();\r\n\t}\r\n\r\n\tif (!has_mail_server)\r\n\t{\r\n\t\tqueue_limit = true;\r\n\t}\r\n\r\n\tIDatabase* db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);\r\n\tIQuery* q_get_mail = db->Prepare(\"SELECT id, send_to, subject, message, next_try, retry_count FROM mail_queue WHERE next_try IS NULL or next_try>=?\");\r\n\tIQuery* q_set_retry = db->Prepare(\"UPDATE mail_queue SET next_try=?, retry_count=? WHERE id=?\");\r\n\tIQuery* q_remove_mail = db->Prepare(\"DELETE FROM mail_queue WHERE id=?\");\r\n\r\n\tdb->Write(\"UPDATE mail_queue SET next_try=NULL\");\r\n\r\n\twhile (true)\r\n\t{\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\tif (!queued_mail)\r\n\t\t\t{\r\n\t\t\t\tcond->wait(&lock, 5 * 60 * 1000);\r\n\t\t\t}\r\n\t\t\tqueued_mail = false;\r\n\t\t}\r\n\r\n\t\tq_get_mail->Bind(Server->getTimeMS());\r\n\t\tdb_results res = q_get_mail->Read();\r\n\t\tq_get_mail->Reset();\r\n\r\n\t\tif (res.size() > 1000)\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\tqueue_limit = true;\r\n\t\t}\r\n\t\telse if (queue_limit\r\n\t\t\t&& has_mail_server)\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\tqueue_limit = false;\r\n\t\t}\r\n\r\n\t\tMailServer mail_server;\n\n\t\tif (!res.empty() || !has_mail_server)\n\t\t{\n\t\t\tmail_server = ClientMain::getMailServerSettings();\n\t\t}\n\n\t\tif (mail_server.servername.empty())\n\t\t{\n\t\t\thas_mail_server = false;\n\t\t\tcontinue;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\thas_mail_server = true;\r\n\t\t}\r\n\r\n\t\tfor (size_t i = 0; i < res.size(); ++i)\r\n\t\t{\r\n\t\t\tstd::vector addrs;\n\t\t\tTokenize(res[i][\"send_to\"], addrs, \";,\");\r\n\r\n\t\t\tstd::string errmsg;\r\n\t\t\tif (!url_fak->sendMail(mail_server, addrs, res[i][\"subject\"], res[i][\"message\"], &errmsg))\r\n\t\t\t{\r\n\t\t\t\tint n = watoi(res[i][\"retry_count\"]);\r\n\t\t\t\tunsigned int waittime = (std::min)(static_cast(1000.*pow(2., static_cast(n))), (unsigned int)30 * 60 * 1000); \/\/30min\r\n\t\t\t\tif (n>20)\r\n\t\t\t\t{\r\n\t\t\t\t\twaittime = (unsigned int)30 * 60 * 1000;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tServer->Log(\"Error sending mail to \\\"\" + res[i][\"send_to\"] + \"\\\". \" + errmsg + \". Retrying in \" + PrettyPrintTime(waittime), LL_WARNING);\r\n\r\n\t\t\t\tq_set_retry->Bind(Server->getTimeMS()+waittime);\r\n\t\t\t\tq_set_retry->Bind(n + 1);\r\n\t\t\t\tq_set_retry->Bind(res[i][\"id\"]);\r\n\t\t\t\tq_set_retry->Write();\r\n\t\t\t\tq_set_retry->Reset();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tq_remove_mail->Bind(res[i][\"id\"]);\r\n\t\t\t\tq_remove_mail->Write();\r\n\t\t\t\tq_remove_mail->Reset();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2008 Bertjan Broeksema \n Copyright (c) 2008 Volker Krause \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"singlefileresourcebase.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Akonadi;\n\nSingleFileResourceBase::SingleFileResourceBase( const QString & id ) :\n ResourceBase( id )\n{\n connect( &mDirtyTimer, SIGNAL(timeout()), SLOT(writeFile()) );\n mDirtyTimer.setSingleShot( true );\n\n connect( this, SIGNAL(reloadConfiguration()), SLOT(reloadFile()) );\n QTimer::singleShot( 0, this, SLOT(readFile()) );\n\n changeRecorder()->itemFetchScope().fetchFullPayload();\n changeRecorder()->fetchCollection( true );\n\n connect( KDirWatch::self(), SIGNAL(dirty(QString)), SLOT(fileChanged(QString)) );\n}\n\nvoid SingleFileResourceBase::setSupportedMimetypes(const QStringList & mimeTypes, const QString &icon)\n{\n mSupportedMimetypes = mimeTypes;\n mCollectionIcon = icon;\n}\n\nvoid SingleFileResourceBase::collectionChanged(const Akonadi::Collection & collection)\n{\n QString newName = collection.name();\n if ( collection.hasAttribute() ) {\n CollectionDisplayAttribute *attr = collection.attribute();\n if ( !attr->displayName().isEmpty() )\n newName = attr->displayName();\n }\n\n if ( newName != name() )\n setName( newName );\n}\n\nvoid SingleFileResourceBase::reloadFile()\n{\n \/\/ if we have something loaded already, make sure we write that back in case the settings changed\n if ( !mCurrentUrl.isEmpty() )\n writeFile();\n readFile();\n}\n\nvoid SingleFileResourceBase::fileChanged(const QString & fileName)\n{\n if ( fileName != mCurrentUrl.path() )\n return;\n\n \/\/ handle conflicts\n if ( mDirtyTimer.isActive() && !mCurrentUrl.isEmpty() ) {\n const KUrl prevUrl = mCurrentUrl;\n int i = 0;\n QString lostFoundFileName;\n do {\n lostFoundFileName = KStandardDirs::locateLocal( \"data\", identifier() + QDir::separator()\n + prevUrl.fileName() + \"-\" + QString::number( ++i ) );\n } while ( KStandardDirs::exists( lostFoundFileName ) );\n mCurrentUrl = KUrl( lostFoundFileName );\n writeFile();\n emit warning( i18n( \"The file '%1' was changed on disk while there were still pending changes in Akonadi. \"\n \"To avoid dataloss, a backup of the internal changes has been created at '%2'.\",\n prevUrl.prettyUrl(), mCurrentUrl.prettyUrl() ) );\n mCurrentUrl = prevUrl;\n }\n\n readFile();\n synchronize();\n}\n\n#include \"singlefileresourcebase.moc\"\nDo a sync after reloading the file, so that the contacts and events show up directly after running the migrator.\/*\n Copyright (c) 2008 Bertjan Broeksema \n Copyright (c) 2008 Volker Krause \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"singlefileresourcebase.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Akonadi;\n\nSingleFileResourceBase::SingleFileResourceBase( const QString & id ) :\n ResourceBase( id )\n{\n connect( &mDirtyTimer, SIGNAL(timeout()), SLOT(writeFile()) );\n mDirtyTimer.setSingleShot( true );\n\n connect( this, SIGNAL(reloadConfiguration()), SLOT(reloadFile()) );\n QTimer::singleShot( 0, this, SLOT(readFile()) );\n\n changeRecorder()->itemFetchScope().fetchFullPayload();\n changeRecorder()->fetchCollection( true );\n\n connect( KDirWatch::self(), SIGNAL(dirty(QString)), SLOT(fileChanged(QString)) );\n}\n\nvoid SingleFileResourceBase::setSupportedMimetypes(const QStringList & mimeTypes, const QString &icon)\n{\n mSupportedMimetypes = mimeTypes;\n mCollectionIcon = icon;\n}\n\nvoid SingleFileResourceBase::collectionChanged(const Akonadi::Collection & collection)\n{\n QString newName = collection.name();\n if ( collection.hasAttribute() ) {\n CollectionDisplayAttribute *attr = collection.attribute();\n if ( !attr->displayName().isEmpty() )\n newName = attr->displayName();\n }\n\n if ( newName != name() )\n setName( newName );\n}\n\nvoid SingleFileResourceBase::reloadFile()\n{\n \/\/ if we have something loaded already, make sure we write that back in case the settings changed\n if ( !mCurrentUrl.isEmpty() )\n writeFile();\n readFile();\n synchronize();\n}\n\nvoid SingleFileResourceBase::fileChanged(const QString & fileName)\n{\n if ( fileName != mCurrentUrl.path() )\n return;\n\n \/\/ handle conflicts\n if ( mDirtyTimer.isActive() && !mCurrentUrl.isEmpty() ) {\n const KUrl prevUrl = mCurrentUrl;\n int i = 0;\n QString lostFoundFileName;\n do {\n lostFoundFileName = KStandardDirs::locateLocal( \"data\", identifier() + QDir::separator()\n + prevUrl.fileName() + \"-\" + QString::number( ++i ) );\n } while ( KStandardDirs::exists( lostFoundFileName ) );\n mCurrentUrl = KUrl( lostFoundFileName );\n writeFile();\n emit warning( i18n( \"The file '%1' was changed on disk while there were still pending changes in Akonadi. \"\n \"To avoid dataloss, a backup of the internal changes has been created at '%2'.\",\n prevUrl.prettyUrl(), mCurrentUrl.prettyUrl() ) );\n mCurrentUrl = prevUrl;\n }\n\n readFile();\n synchronize();\n}\n\n#include \"singlefileresourcebase.moc\"\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 Paulo Marques (pjp.marques@gmail.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of \n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all \n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN \n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/* Information about the P9813 protocol obtained from:\n * http:\/\/www.seeedstudio.com\/wiki\/index.php?title=Twig_-_Chainable_RGB_LED\n *\n * HSB to RGB routine adapted from:\n * http:\/\/mjijackson.com\/2008\/02\/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n *\/\n\n\n\/\/ --------------------------------------------------------------------------------------\n\n#include \"ChainableLED.h\"\n\n\/\/ Forward declaration\nfloat hue2rgb(float p, float q, float t);\n\n\/\/ --------------------------------------------------------------------------------------\n\nChainableLED::ChainableLED(byte clk_pin, byte data_pin, byte number_of_leds) :\n _clk_pin(clk_pin), _data_pin(data_pin), _num_leds(number_of_leds)\n{\n _led_state = (byte*) calloc(_num_leds*3, sizeof(byte));\n}\n\nChainableLED::~ChainableLED()\n{\n free(_led_state);\n}\n\n\/\/ --------------------------------------------------------------------------------------\n\nvoid ChainableLED::init()\n{\n pinMode(_clk_pin, OUTPUT);\n pinMode(_data_pin, OUTPUT);\n\n for (byte i=0; i<_num_leds; i++)\n setColorRGB(i, 0, 0, 0);\n}\n\nvoid ChainableLED::clk(void)\n{\n digitalWrite(_clk_pin, LOW);\n delayMicroseconds(_CLK_PULSE_DELAY); \n digitalWrite(_clk_pin, HIGH);\n delayMicroseconds(_CLK_PULSE_DELAY); \n}\n\nvoid ChainableLED::sendByte(byte b)\n{\n \/\/ Send one bit at a time, starting with the MSB\n for (byte i=0; i<8; i++)\n {\n \/\/ If MSB is 1, write one and clock it, else write 0 and clock\n if ((b & 0x80) != 0)\n digitalWrite(_data_pin, HIGH);\n else\n digitalWrite(_data_pin, LOW);\n clk();\n\n \/\/ Advance to the next bit to send\n b <<= 1;\n }\n}\n \nvoid ChainableLED::sendColor(byte red, byte green, byte blue)\n{\n \/\/ Start by sending a byte with the format \"1 1 \/B7 \/B6 \/G7 \/G6 \/R7 \/R6\"\n byte prefix = 0b11000000;\n if ((blue & 0x80) == 0) prefix|= 0b00100000;\n if ((blue & 0x40) == 0) prefix|= 0b00010000; \n if ((green & 0x80) == 0) prefix|= 0b00001000;\n if ((green & 0x40) == 0) prefix|= 0b00000100;\n if ((red & 0x80) == 0) prefix|= 0b00000010;\n if ((red & 0x40) == 0) prefix|= 0b00000001;\n sendByte(prefix);\n \n \/\/ Now must send the 3 colors\n sendByte(blue);\n sendByte(green);\n sendByte(red);\n}\n\nvoid ChainableLED::setColorRGB(byte led, byte red, byte green, byte blue)\n{\n \/\/ Send data frame prefix (32x \"0\")\n sendByte(0x00);\n sendByte(0x00);\n sendByte(0x00);\n sendByte(0x00);\n \n \/\/ Send color data for each one of the leds\n for (byte i=0; i<_num_leds; i++)\n {\n if (i == led)\n {\n _led_state[i*3 + _CL_RED] = red;\n _led_state[i*3 + _CL_GREEN] = green;\n _led_state[i*3 + _CL_BLUE] = blue;\n }\n \n sendColor(_led_state[i*3 + _CL_RED], \n _led_state[i*3 + _CL_GREEN], \n _led_state[i*3 + _CL_BLUE]);\n }\n\n \/\/ Terminate data frame (32x \"0\")\n sendByte(0x00);\n sendByte(0x00);\n sendByte(0x00);\n sendByte(0x00);\n}\n\nvoid ChainableLED::setColorHSB(byte led, float hue, float saturation, float brightness)\n{\n float r, g, b;\n \n constrain(hue, 0.0, 1.0);\n constrain(saturation, 0.0, 1.0);\n constrain(brightness, 0.0, 1.0);\n\n if(saturation == 0.0)\n {\n r = g = b = brightness;\n }\n else\n {\n float q = brightness < 0.5 ? \n brightness * (1.0 + saturation) : brightness + saturation - brightness * saturation;\n float p = 2.0 * brightness - q;\n r = hue2rgb(p, q, hue + 1.0\/3.0);\n g = hue2rgb(p, q, hue);\n b = hue2rgb(p, q, hue - 1.0\/3.0);\n }\n\n setColorRGB(led, (byte)(255.0*r), (byte)(255.0*g), (byte)(255.0*b));\n}\n\n\/\/ --------------------------------------------------------------------------------------\n\nfloat hue2rgb(float p, float q, float t)\n{\n if (t < 0.0) \n t += 1.0;\n if(t > 1.0) \n t -= 1.0;\n if(t < 1.0\/6.0) \n return p + (q - p) * 6.0 * t;\n if(t < 1.0\/2.0) \n return q;\n if(t < 2.0\/3.0) \n return p + (q - p) * (2.0\/3.0 - t) * 6.0;\n\n return p;\n}\nDelete ChainableLED.cpp<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Umur Gedik on 5\/4\/16.\n\/\/\n\n#include \n#ifdef _MSC_VER\n#include \n#endif\n#include \n#include \n#include \n#include \"ConfigParser.h\"\n#include \"parsers\/EntryTypeParser.h\"\n#include \"parsers\/EntryMessageParser.h\"\n\nSupConfig ConfigParser::Parse(const fs::path &path)\n{\n std::ifstream fs{path.string()};\n\n pt::ptree tree;\n pt::read_json(fs, tree);\n\n SupConfig config;\n\n auto issue_type_tree = tree.get_child_optional(\"issueType\");\n if (issue_type_tree) {\n ParseEntryTypeParserOptions(*issue_type_tree, config.entry_type_parser_options);\n }\n\n auto body_tree = tree.get_child_optional(\"body\");\n if (body_tree) {\n ParseMessageParserOptions(*body_tree, config.message_parser_options);\n }\n\n config.issue_id_regex = tree.get(\"issueIdRegex\", \"#(\\\\d+)\");\n config.entry_template = tree.get(\"template\", \"[$issueId] $body\");\n config.omit_newlines = tree.get(\"omitNewlinesInBody\", false);\n config.filter_regex = tree.get(\"filter\", \".*\");\n config.tag_filter = tree.get(\"tagFilter\", \"v*\");\n config.file_path = tree.get(\"file\", \"CHANGELOG.md\");\n config.group_by_issue_type = tree.get(\"groupByIssueType\", true);\n\n return config;\n}\n\nvoid ConfigParser::ParseEntryTypeParserOptions(const pt::ptree &tree, EntryTypeParserOptions &options)\n{\n auto regex = tree.get_optional(\"regex\");\n if (regex) {\n options.regex = *regex;\n options.regex_based = true;\n }\n\n auto line_number = tree.get_optional(\"lineNumber\");\n if (line_number) {\n options.line_number = *line_number;\n options.line_based = true;\n options.regex_based = false;\n }\n\n auto searchAt = tree.get_optional(\"searchAt\");\n if (regex && searchAt) {\n options.line_number = *searchAt;\n options.line_based = false;\n options.regex_based = true;\n }\n}\n\nvoid ConfigParser::ParseMessageParserOptions(const boost::property_tree::ptree &pt, EntryMessageParserOptions &options)\n{\n auto line_number = pt.get_optional(\"lineNumber\");\n if (line_number) {\n options.line_number = *line_number;\n options.regex_based = false;\n options.one_line = true;\n return;\n }\n\n auto regex = pt.get_optional(\"regex\");\n if (regex) {\n options.regex = *regex;\n options.regex_based = true;\n return;\n }\n\n auto start_from = pt.get_optional(\"startingAt\");\n if (start_from) {\n options.from_line = *start_from;\n }\n\n auto delimiter = pt.get_optional(\"endOfBody\");\n if (delimiter) {\n options.delimiter = *delimiter;\n options.until_delimiter = true;\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfix: regex should override delimiter for body parser\/\/\n\/\/ Created by Umur Gedik on 5\/4\/16.\n\/\/\n\n#include \n#ifdef _MSC_VER\n#include \n#endif\n#include \n#include \n#include \n#include \"ConfigParser.h\"\n#include \"parsers\/EntryTypeParser.h\"\n#include \"parsers\/EntryMessageParser.h\"\n\nSupConfig ConfigParser::Parse(const fs::path &path)\n{\n std::ifstream fs{path.string()};\n\n pt::ptree tree;\n pt::read_json(fs, tree);\n\n SupConfig config;\n\n auto issue_type_tree = tree.get_child_optional(\"issueType\");\n if (issue_type_tree) {\n ParseEntryTypeParserOptions(*issue_type_tree, config.entry_type_parser_options);\n }\n\n auto body_tree = tree.get_child_optional(\"body\");\n if (body_tree) {\n ParseMessageParserOptions(*body_tree, config.message_parser_options);\n }\n\n config.issue_id_regex = tree.get(\"issueIdRegex\", \"#(\\\\d+)\");\n config.entry_template = tree.get(\"template\", \"[$issueId] $body\");\n config.omit_newlines = tree.get(\"omitNewlinesInBody\", false);\n config.filter_regex = tree.get(\"filter\", \".*\");\n config.tag_filter = tree.get(\"tagFilter\", \"v*\");\n config.file_path = tree.get(\"file\", \"CHANGELOG.md\");\n config.group_by_issue_type = tree.get(\"groupByIssueType\", true);\n\n return config;\n}\n\nvoid ConfigParser::ParseEntryTypeParserOptions(const pt::ptree &tree, EntryTypeParserOptions &options)\n{\n auto regex = tree.get_optional(\"regex\");\n if (regex) {\n options.regex = *regex;\n options.regex_based = true;\n }\n\n auto line_number = tree.get_optional(\"lineNumber\");\n if (line_number) {\n options.line_number = *line_number;\n options.line_based = true;\n options.regex_based = false;\n }\n\n auto searchAt = tree.get_optional(\"searchAt\");\n if (regex && searchAt) {\n options.line_number = *searchAt;\n options.line_based = false;\n options.regex_based = true;\n }\n}\n\nvoid ConfigParser::ParseMessageParserOptions(const boost::property_tree::ptree &pt, EntryMessageParserOptions &options)\n{\n auto line_number = pt.get_optional(\"lineNumber\");\n if (line_number) {\n options.line_number = *line_number;\n options.regex_based = false;\n options.one_line = true;\n options.until_delimiter = false;\n return;\n }\n\n auto regex = pt.get_optional(\"regex\");\n if (regex) {\n options.regex = *regex;\n options.regex_based = true;\n options.until_delimiter = false;\n return;\n }\n\n auto start_from = pt.get_optional(\"startingAt\");\n if (start_from) {\n options.from_line = *start_from;\n }\n\n auto delimiter = pt.get_optional(\"endOfBody\");\n if (delimiter) {\n options.delimiter = *delimiter;\n options.until_delimiter = true;\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 Google 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\n#include \"lpc_aspeed.hpp\"\n\n#include \"mapper_errors.hpp\"\n#include \"window_hw_interface.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ipmi_flash\n{\n\nconst std::string LpcMapperAspeed::lpcControlPath = \"\/dev\/aspeed-lpc-ctrl\";\n\nstd::unique_ptr\n LpcMapperAspeed::createAspeedMapper(std::uint32_t regionAddress,\n std::size_t regionSize)\n{\n \/* NOTE: considered using a joint factory to create one or the other, for\n * now, separate factories.\n *\/\n return std::make_unique(regionAddress, regionSize);\n}\n\nvoid LpcMapperAspeed::close()\n{\n if (mappedRegion)\n {\n sys->munmap(mappedRegion, regionSize);\n mappedRegion = nullptr;\n }\n\n if (mappedFd != -1)\n {\n sys->close(mappedFd);\n mappedFd = -1;\n }\n}\n\nWindowMapResult LpcMapperAspeed::mapWindow(std::uint32_t address,\n std::uint32_t length)\n{\n WindowMapResult result = {};\n static const std::uint32_t MASK_64K = 0xFFFFU;\n const std::uint32_t offset = address & MASK_64K;\n\n if (offset + length > regionSize)\n {\n std::fprintf(stderr,\n \"requested window size %\" PRIu32 \", offset %#\" PRIx32\n \" is too large for mem region\"\n \" of size %zu\\n\",\n length, offset, regionSize);\n\n result.response = EFBIG;\n result.windowSize = regionSize - offset;\n return result;\n }\n\n struct aspeed_lpc_ctrl_mapping map = {\n .window_type = ASPEED_LPC_CTRL_WINDOW_MEMORY,\n .window_id = 0,\n .flags = 0,\n .addr = address & ~MASK_64K,\n .offset = 0,\n .size = __ALIGN_KERNEL_MASK(offset + length, MASK_64K),\n };\n\n std::fprintf(stderr,\n \"requesting Aspeed LPC window at %#\" PRIx32 \" of size %\" PRIu32\n \"\\n\",\n map.addr, map.size);\n\n const auto lpcControlFd = sys->open(lpcControlPath.c_str(), O_RDWR);\n if (lpcControlFd == -1)\n {\n std::fprintf(stderr,\n \"cannot open Aspeed LPC kernel control dev \\\"%s\\\"\\n\",\n lpcControlPath.c_str());\n\n result.response = EINVAL;\n return result;\n }\n\n if (sys->ioctl(lpcControlFd, ASPEED_LPC_CTRL_IOCTL_MAP, &map) == -1)\n {\n std::fprintf(stderr, \"Failed to ioctl Aspeed LPC map with error %s\\n\",\n std::strerror(errno));\n sys->close(lpcControlFd);\n\n result.response = EINVAL;\n return result;\n }\n\n sys->close(lpcControlFd);\n\n result.response = 0;\n result.windowOffset = offset;\n result.windowSize = length;\n return result;\n}\n\nMemorySet LpcMapperAspeed::open()\n{\n if (mapRegion())\n {\n MemorySet output;\n output.mappedFd = mappedFd;\n output.mapped = mappedRegion;\n return output;\n }\n\n throw MapperException(\"Unable to memory-map region\");\n}\n\nbool LpcMapperAspeed::mapRegion()\n{\n \/* Open the file to map. *\/\n mappedFd = sys->open(lpcControlPath.c_str(), O_RDONLY | O_SYNC);\n\n \/* TODO: The offset to use is the address we use for the map - the base\n * address of the memory region we reserved in the device-tree.\n *\/\n mappedRegion = reinterpret_cast(\n sys->mmap(0, regionSize, PROT_READ, MAP_SHARED, mappedFd, 0));\n\n if (mappedRegion == MAP_FAILED)\n {\n sys->close(mappedFd);\n mappedFd = -1;\n std::fprintf(stderr, \"Mmap failure: '%s'\\n\", std::strerror(errno));\n return false;\n }\n\n \/* TOOD: There is no close() method here, to close mappedFd, or mappedRegion\n * -- therefore, a good next step will be to evaluate whether or not the\n * other pieces should go here...\n *\/\n return true;\n}\n\n} \/\/ namespace ipmi_flash\nbmc: lpc aspeed: add missing file open failure check\/*\n * Copyright 2018 Google 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\n#include \"lpc_aspeed.hpp\"\n\n#include \"mapper_errors.hpp\"\n#include \"window_hw_interface.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ipmi_flash\n{\n\nconst std::string LpcMapperAspeed::lpcControlPath = \"\/dev\/aspeed-lpc-ctrl\";\n\nstd::unique_ptr\n LpcMapperAspeed::createAspeedMapper(std::uint32_t regionAddress,\n std::size_t regionSize)\n{\n \/* NOTE: considered using a joint factory to create one or the other, for\n * now, separate factories.\n *\/\n return std::make_unique(regionAddress, regionSize);\n}\n\nvoid LpcMapperAspeed::close()\n{\n if (mappedRegion)\n {\n sys->munmap(mappedRegion, regionSize);\n mappedRegion = nullptr;\n }\n\n if (mappedFd != -1)\n {\n sys->close(mappedFd);\n mappedFd = -1;\n }\n}\n\nWindowMapResult LpcMapperAspeed::mapWindow(std::uint32_t address,\n std::uint32_t length)\n{\n WindowMapResult result = {};\n static const std::uint32_t MASK_64K = 0xFFFFU;\n const std::uint32_t offset = address & MASK_64K;\n\n if (offset + length > regionSize)\n {\n std::fprintf(stderr,\n \"requested window size %\" PRIu32 \", offset %#\" PRIx32\n \" is too large for mem region\"\n \" of size %zu\\n\",\n length, offset, regionSize);\n\n result.response = EFBIG;\n result.windowSize = regionSize - offset;\n return result;\n }\n\n struct aspeed_lpc_ctrl_mapping map = {\n .window_type = ASPEED_LPC_CTRL_WINDOW_MEMORY,\n .window_id = 0,\n .flags = 0,\n .addr = address & ~MASK_64K,\n .offset = 0,\n .size = __ALIGN_KERNEL_MASK(offset + length, MASK_64K),\n };\n\n std::fprintf(stderr,\n \"requesting Aspeed LPC window at %#\" PRIx32 \" of size %\" PRIu32\n \"\\n\",\n map.addr, map.size);\n\n const auto lpcControlFd = sys->open(lpcControlPath.c_str(), O_RDWR);\n if (lpcControlFd == -1)\n {\n std::fprintf(stderr,\n \"cannot open Aspeed LPC kernel control dev \\\"%s\\\"\\n\",\n lpcControlPath.c_str());\n\n result.response = EINVAL;\n return result;\n }\n\n if (sys->ioctl(lpcControlFd, ASPEED_LPC_CTRL_IOCTL_MAP, &map) == -1)\n {\n std::fprintf(stderr, \"Failed to ioctl Aspeed LPC map with error %s\\n\",\n std::strerror(errno));\n sys->close(lpcControlFd);\n\n result.response = EINVAL;\n return result;\n }\n\n sys->close(lpcControlFd);\n\n result.response = 0;\n result.windowOffset = offset;\n result.windowSize = length;\n return result;\n}\n\nMemorySet LpcMapperAspeed::open()\n{\n if (mapRegion())\n {\n MemorySet output;\n output.mappedFd = mappedFd;\n output.mapped = mappedRegion;\n return output;\n }\n\n throw MapperException(\"Unable to memory-map region\");\n}\n\nbool LpcMapperAspeed::mapRegion()\n{\n \/* Open the file to map. *\/\n mappedFd = sys->open(lpcControlPath.c_str(), O_RDONLY | O_SYNC);\n if (mappedFd == -1)\n {\n std::fprintf(stderr, \"ipmiflash: unable to open %s\\n\",\n lpcControlPath.c_str());\n return false;\n }\n\n mappedRegion = reinterpret_cast(\n sys->mmap(0, regionSize, PROT_READ, MAP_SHARED, mappedFd, 0));\n\n if (mappedRegion == MAP_FAILED)\n {\n sys->close(mappedFd);\n mappedFd = -1;\n std::fprintf(stderr, \"Mmap failure: '%s'\\n\", std::strerror(errno));\n return false;\n }\n\n \/* TOOD: There is no close() method here, to close mappedFd, or mappedRegion\n * -- therefore, a good next step will be to evaluate whether or not the\n * other pieces should go here...\n *\/\n return true;\n}\n\n} \/\/ namespace ipmi_flash\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"watchman\/root\/Root.h\"\n\nusing namespace watchman;\n\nstatic json_ref config_get_ignore_vcs(Root* root) {\n json_ref ignores = root->config.get(\"ignore_vcs\");\n if (ignores && !ignores.isArray()) {\n return nullptr;\n }\n\n if (!ignores) {\n \/\/ default to a well-known set of vcs's\n ignores = json_array(\n {typed_string_to_json(\".git\"),\n typed_string_to_json(\".svn\"),\n typed_string_to_json(\".hg\")});\n }\n return ignores;\n}\n\nvoid Root::applyIgnoreVCSConfiguration() {\n auto ignores = config_get_ignore_vcs(this);\n if (!ignores) {\n throw std::runtime_error(\"ignore_vcs must be an array of strings\");\n }\n\n for (auto& jignore : ignores.array()) {\n if (!jignore.isString()) {\n throw std::runtime_error(\"ignore_vcs must be an array of strings\");\n }\n\n auto fullname = w_string::pathCat({root_path, json_to_w_string(jignore)});\n\n \/\/ if we are completely ignoring this dir, we have nothing more to\n \/\/ do here\n if (ignore.isIgnoreDir(fullname)) {\n continue;\n }\n\n ignore.add(fullname, true);\n\n \/\/ Since we do not have a watcher just yet, we can't test if the watcher\n \/\/ will have WATCHER_HAS_SPLIT_WATCH, thus, rely on whether only the root\n \/\/ is present in the cookies dirs.\n auto cookieDirs = cookies.cookieDirs();\n if (cookieDirs.size() == 1 && cookieDirs.count(root_path) == 1) {\n \/\/ While we're at it, see if we can find out where to put our\n \/\/ query cookie information\n try {\n auto info = getFileInformation(fullname.c_str(), case_sensitive);\n if (info.isDir()) {\n \/\/ root\/{.hg,.git,.svn}\n cookies.setCookieDir(fullname);\n }\n } catch (...) {\n \/\/ Don't care\n }\n }\n }\n}\n\n\/* vim:ts=2:sw=2:et:\n *\/\nremove an invariant conditional\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"watchman\/Logging.h\"\n#include \"watchman\/root\/Root.h\"\n\nusing namespace watchman;\n\nstatic json_ref config_get_ignore_vcs(Root* root) {\n json_ref ignores = root->config.get(\"ignore_vcs\");\n if (ignores && !ignores.isArray()) {\n return nullptr;\n }\n\n if (!ignores) {\n \/\/ default to a well-known set of vcs's\n ignores = json_array(\n {typed_string_to_json(\".git\"),\n typed_string_to_json(\".svn\"),\n typed_string_to_json(\".hg\")});\n }\n return ignores;\n}\n\nvoid Root::applyIgnoreVCSConfiguration() {\n auto cookieDirs = cookies.cookieDirs();\n w_check(\n cookieDirs.size() == 1 && cookieDirs.count(root_path) == 1,\n fmt::format(\n \"cookie was already initialized with {}: {}\\n\",\n cookieDirs.size(),\n *cookieDirs.begin()));\n\n bool default_cookie = true;\n\n auto ignores = config_get_ignore_vcs(this);\n if (!ignores) {\n throw std::runtime_error(\"ignore_vcs must be an array of strings\");\n }\n\n for (auto& jignore : ignores.array()) {\n if (!jignore.isString()) {\n throw std::runtime_error(\"ignore_vcs must be an array of strings\");\n }\n\n auto fullname = w_string::pathCat({root_path, json_to_w_string(jignore)});\n\n \/\/ if we are completely ignoring this dir, we have nothing more to\n \/\/ do here\n if (ignore.isIgnoreDir(fullname)) {\n continue;\n }\n\n ignore.add(fullname, true);\n\n if (default_cookie) {\n \/\/ While we're at it, see if we can find out where to put our\n \/\/ query cookie information\n try {\n auto info = getFileInformation(fullname.c_str(), case_sensitive);\n if (info.isDir()) {\n \/\/ root\/{.hg,.git,.svn}\n cookies.setCookieDir(fullname);\n default_cookie = false;\n }\n } catch (...) {\n \/\/ Don't care\n }\n }\n }\n}\n\n\/* vim:ts=2:sw=2:et:\n *\/\n<|endoftext|>"} {"text":"#ifndef ALGORITHM_HPP\n# define ALGORUTHM_HPP\n# pragma once\n\n#include \n\n#include \n\n#include \n\n#include \"meta.hpp\"\n\nnamespace generic\n{\n\n\/\/ min, max\ntemplate \nconstexpr inline T const& max(T const& a, T const& b) noexcept\n{\n return a > b ? a : b;\n}\n\ntemplate \nconstexpr inline T const& min(T const& a, T const& b) noexcept\n{\n return a < b ? a : b;\n}\n\ntemplate \nconstexpr inline typename ::std::enable_if<\n bool(sizeof...(A)) &&\n all_of<\n ::std::is_same<\n typename ::std::decay::type,\n typename ::std::decay::type\n >...\n >{},\n T\n>::type\nmax(T const& a, T const& b, A&& ...args) noexcept\n{\n return a > b ?\n max(a, ::std::forward(args)...) :\n max(b, ::std::forward(args)...);\n}\n\ntemplate \nconstexpr inline typename ::std::enable_if<\n bool(sizeof...(A)) &&\n all_of<\n ::std::is_same<\n typename ::std::decay::type,\n typename ::std::decay::type\n >...\n >{},\n T\n>::type\nmin(T const& a, T const& b, A&& ...args) noexcept\n{\n return a < b ?\n min(a, ::std::forward(args)...) :\n min(b, ::std::forward(args)...);\n}\n\ntemplate \nconstexpr inline typename ::std::enable_if<\n bool(sizeof...(A)) &&\n all_of<\n ::std::is_same<\n typename ::std::decay::type>::type,\n typename ::std::decay::type\n >...\n >{},\n ::std::pair<\n typename ::std::decay::type>::type,\n typename ::std::decay::type>::type\n >\n>::type\nminmax(A&& ...args) noexcept\n{\n return {\n min(::std::forward(args)...),\n max(::std::forward(args)...)\n };\n}\n\n}\n\n#endif \/\/ ALGORITHM_HPP\nsome fixes#ifndef GENERIC_ALGORITHM_HPP\n# define GENERIC_ALGORITHM_HPP\n# pragma once\n\n#include \n\n#include \n\n#include \n\n#include \"meta.hpp\"\n\nnamespace generic\n{\n\n\/\/ min, max\ntemplate \nconstexpr inline T const& max(T const& a, T const& b) noexcept\n{\n return a > b ? a : b;\n}\n\ntemplate \nconstexpr inline T const& min(T const& a, T const& b) noexcept\n{\n return a < b ? a : b;\n}\n\ntemplate \nconstexpr inline typename ::std::enable_if<\n bool(sizeof...(A)) &&\n all_of<\n ::std::is_same<\n typename ::std::decay::type,\n typename ::std::decay::type\n >...\n >{},\n T\n>::type\nmax(T const& a, T const& b, A&& ...args) noexcept\n{\n return a > b ?\n max(a, ::std::forward(args)...) :\n max(b, ::std::forward(args)...);\n}\n\ntemplate \nconstexpr inline typename ::std::enable_if<\n bool(sizeof...(A)) &&\n all_of<\n ::std::is_same<\n typename ::std::decay::type,\n typename ::std::decay::type\n >...\n >{},\n T\n>::type\nmin(T const& a, T const& b, A&& ...args) noexcept\n{\n return a < b ?\n min(a, ::std::forward(args)...) :\n min(b, ::std::forward(args)...);\n}\n\ntemplate \nconstexpr inline typename ::std::enable_if<\n bool(sizeof...(A)) &&\n all_of<\n ::std::is_same<\n typename ::std::decay::type>::type,\n typename ::std::decay::type\n >...\n >{},\n ::std::pair<\n typename ::std::decay::type>::type,\n typename ::std::decay::type>::type\n >\n>::type\nminmax(A&& ...args) noexcept\n{\n return {\n min(::std::forward(args)...),\n max(::std::forward(args)...)\n };\n}\n\n}\n\n#endif \/\/ GENERIC_ALGORITHM_HPP\n<|endoftext|>"} {"text":"#ifndef KISSFFT_CLASS_HH\n#include \n#include \n\nnamespace kissfft_utils {\n\ntemplate \nstruct traits\n{\n typedef T_scalar scalar_type;\n typedef std::complex cpx_type;\n void fill_twiddles( std::complex * dst ,int nfft,bool inverse)\n {\n T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) \/ nfft;\n for (int i=0;i(0,i*phinc) );\n }\n\n void prepare(\n std::vector< std::complex > & dst,\n int nfft,bool inverse, \n std::vector & stageRadix, \n std::vector & stageRemainder )\n {\n _twiddles.resize(nfft);\n fill_twiddles( &_twiddles[0],nfft,inverse);\n dst = _twiddles;\n\n \/\/factorize\n \/\/start factoring out 4's, then 2's, then 3,5,7,9,...\n int n= nfft;\n int p=4;\n do {\n while (n % p) {\n switch (p) {\n case 4: p = 2; break;\n case 2: p = 3; break;\n default: p += 2; break;\n }\n if (p*p>n)\n p=n;\/\/ no more factors\n }\n n \/= p;\n stageRadix.push_back(p);\n stageRemainder.push_back(n);\n }while(n>1);\n }\n std::vector _twiddles;\n\n\n const cpx_type twiddle(int i) { return _twiddles[i]; }\n};\n\n}\n\ntemplate \n >\nclass kissfft\n{\n public:\n typedef T_traits traits_type;\n typedef typename traits_type::scalar_type scalar_type;\n typedef typename traits_type::cpx_type cpx_type;\n\n kissfft(int nfft,bool inverse,const traits_type & traits=traits_type() ) \n :_nfft(nfft),_inverse(inverse),_traits(traits)\n {\n _traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder);\n }\n\n void transform(const cpx_type * src , cpx_type * dst)\n {\n kf_work(0, dst, src, 1,1);\n }\n\n private:\n void kf_work( int stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride)\n {\n int p = _stageRadix[stage];\n int m = _stageRemainder[stage];\n cpx_type * Fout_beg = Fout;\n cpx_type * Fout_end = Fout + p*m;\n\n if (m==1) {\n do{\n *Fout = *f;\n f += fstride*in_stride;\n }while(++Fout != Fout_end );\n }else{\n do{\n \/\/ recursive call:\n \/\/ DFT of size m*p performed by doing\n \/\/ p instances of smaller DFTs of size m, \n \/\/ each one takes a decimated version of the input\n kf_work(stage+1, Fout , f, fstride*p,in_stride);\n f += fstride*in_stride;\n }while( (Fout += m) != Fout_end );\n }\n\n Fout=Fout_beg;\n\n \/\/ recombine the p smaller DFTs \n switch (p) {\n case 2: kf_bfly2(Fout,fstride,m); break;\n case 3: kf_bfly3(Fout,fstride,m); break;\n case 4: kf_bfly4(Fout,fstride,m); break;\n case 5: kf_bfly5(Fout,fstride,m); break;\n default: kf_bfly_generic(Fout,fstride,m,p); break;\n }\n }\n\n \/\/ these were #define macros in the original kiss_fft\n void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;}\n void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;}\n void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;}\n void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;}\n void C_FIXDIV( cpx_type & ,int ) {} \/\/ NO-OP for float types\n scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;}\n scalar_type HALF_OF( const scalar_type & a) { return a*.5;}\n void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;}\n\n void kf_bfly2( cpx_type * Fout, const size_t fstride, int m)\n {\n for (int k=0;kreal() - HALF_OF(scratch[3].real() ) , Fout->imag() - HALF_OF(scratch[3].imag() ) );\n\n C_MULBYSCALAR( scratch[0] , epi3.imag() );\n\n C_ADDTO(*Fout,scratch[3]);\n\n Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() );\n\n C_ADDTO( Fout[m] , cpx_type( -scratch[0].imag(),scratch[0].real() ) );\n ++Fout;\n }while(--k);\n }\n\n void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m)\n {\n cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;\n size_t u;\n cpx_type scratch[13];\n cpx_type * twiddles = &_twiddles[0];\n cpx_type *tw;\n cpx_type ya,yb;\n ya = twiddles[fstride*m];\n yb = twiddles[fstride*2*m];\n\n Fout0=Fout;\n Fout1=Fout0+m;\n Fout2=Fout0+2*m;\n Fout3=Fout0+3*m;\n Fout4=Fout0+4*m;\n\n tw=twiddles;\n for ( u=0; u=Norig) twidx-=Norig;\n C_MUL(t,scratchbuf[q] , twiddles[twidx] );\n C_ADDTO( Fout[ k ] ,t);\n }\n k += m;\n }\n }\n }\n\n int _nfft;\n bool _inverse;\n std::vector _twiddles;\n std::vector _stageRadix;\n std::vector _stageRemainder;\n traits_type _traits;\n};\n#endif\nguard against multiple inclusion#ifndef KISSFFT_CLASS_HH\n#define KISSFFT_CLASS_HH\n#include \n#include \n\nnamespace kissfft_utils {\n\ntemplate \nstruct traits\n{\n typedef T_scalar scalar_type;\n typedef std::complex cpx_type;\n void fill_twiddles( std::complex * dst ,int nfft,bool inverse)\n {\n T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) \/ nfft;\n for (int i=0;i(0,i*phinc) );\n }\n\n void prepare(\n std::vector< std::complex > & dst,\n int nfft,bool inverse, \n std::vector & stageRadix, \n std::vector & stageRemainder )\n {\n _twiddles.resize(nfft);\n fill_twiddles( &_twiddles[0],nfft,inverse);\n dst = _twiddles;\n\n \/\/factorize\n \/\/start factoring out 4's, then 2's, then 3,5,7,9,...\n int n= nfft;\n int p=4;\n do {\n while (n % p) {\n switch (p) {\n case 4: p = 2; break;\n case 2: p = 3; break;\n default: p += 2; break;\n }\n if (p*p>n)\n p=n;\/\/ no more factors\n }\n n \/= p;\n stageRadix.push_back(p);\n stageRemainder.push_back(n);\n }while(n>1);\n }\n std::vector _twiddles;\n\n\n const cpx_type twiddle(int i) { return _twiddles[i]; }\n};\n\n}\n\ntemplate \n >\nclass kissfft\n{\n public:\n typedef T_traits traits_type;\n typedef typename traits_type::scalar_type scalar_type;\n typedef typename traits_type::cpx_type cpx_type;\n\n kissfft(int nfft,bool inverse,const traits_type & traits=traits_type() ) \n :_nfft(nfft),_inverse(inverse),_traits(traits)\n {\n _traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder);\n }\n\n void transform(const cpx_type * src , cpx_type * dst)\n {\n kf_work(0, dst, src, 1,1);\n }\n\n private:\n void kf_work( int stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride)\n {\n int p = _stageRadix[stage];\n int m = _stageRemainder[stage];\n cpx_type * Fout_beg = Fout;\n cpx_type * Fout_end = Fout + p*m;\n\n if (m==1) {\n do{\n *Fout = *f;\n f += fstride*in_stride;\n }while(++Fout != Fout_end );\n }else{\n do{\n \/\/ recursive call:\n \/\/ DFT of size m*p performed by doing\n \/\/ p instances of smaller DFTs of size m, \n \/\/ each one takes a decimated version of the input\n kf_work(stage+1, Fout , f, fstride*p,in_stride);\n f += fstride*in_stride;\n }while( (Fout += m) != Fout_end );\n }\n\n Fout=Fout_beg;\n\n \/\/ recombine the p smaller DFTs \n switch (p) {\n case 2: kf_bfly2(Fout,fstride,m); break;\n case 3: kf_bfly3(Fout,fstride,m); break;\n case 4: kf_bfly4(Fout,fstride,m); break;\n case 5: kf_bfly5(Fout,fstride,m); break;\n default: kf_bfly_generic(Fout,fstride,m,p); break;\n }\n }\n\n \/\/ these were #define macros in the original kiss_fft\n void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;}\n void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;}\n void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;}\n void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;}\n void C_FIXDIV( cpx_type & ,int ) {} \/\/ NO-OP for float types\n scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;}\n scalar_type HALF_OF( const scalar_type & a) { return a*.5;}\n void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;}\n\n void kf_bfly2( cpx_type * Fout, const size_t fstride, int m)\n {\n for (int k=0;kreal() - HALF_OF(scratch[3].real() ) , Fout->imag() - HALF_OF(scratch[3].imag() ) );\n\n C_MULBYSCALAR( scratch[0] , epi3.imag() );\n\n C_ADDTO(*Fout,scratch[3]);\n\n Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() );\n\n C_ADDTO( Fout[m] , cpx_type( -scratch[0].imag(),scratch[0].real() ) );\n ++Fout;\n }while(--k);\n }\n\n void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m)\n {\n cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;\n size_t u;\n cpx_type scratch[13];\n cpx_type * twiddles = &_twiddles[0];\n cpx_type *tw;\n cpx_type ya,yb;\n ya = twiddles[fstride*m];\n yb = twiddles[fstride*2*m];\n\n Fout0=Fout;\n Fout1=Fout0+m;\n Fout2=Fout0+2*m;\n Fout3=Fout0+3*m;\n Fout4=Fout0+4*m;\n\n tw=twiddles;\n for ( u=0; u=Norig) twidx-=Norig;\n C_MUL(t,scratchbuf[q] , twiddles[twidx] );\n C_ADDTO( Fout[ k ] ,t);\n }\n k += m;\n }\n }\n }\n\n int _nfft;\n bool _inverse;\n std::vector _twiddles;\n std::vector _stageRadix;\n std::vector _stageRemainder;\n traits_type _traits;\n};\n#endif\n<|endoftext|>"} {"text":"\/*\n * libMaia - maiaObject.cpp\n * Copyright (c) 2003 Frerich Raabe and\n * Ian Reinhart Geiser \n * Copyright (c) 2007 Sebastian Wiedenroth \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"maiaObject.h\"\n\nMaiaObject::MaiaObject(QObject* parent) : QObject(parent){\n\tQDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);\n}\n\nQDomElement MaiaObject::toXml(QVariant arg) {\n\t\n\t\/\/dummy document\n\tQDomDocument doc;\n\t\/\/value element, we need this in each case\n\tQDomElement tagValue = doc.createElement(\"value\");\n\n\tswitch(arg.type()) {\n\tcase QVariant::String: {\n\n\t\tQDomElement tagString = doc.createElement(\"string\"); \n\t\tQDomText textString = doc.createTextNode(arg.toString());\n\t\t\n\t\ttagValue.appendChild(tagString);\n\t\ttagString.appendChild(textString);\n\n\t\treturn tagValue;\n\n\t} case QVariant::Int: {\n\n\t\tQDomElement tagInt = doc.createElement(\"int\"); \n\t\tQDomText textInt = doc.createTextNode(QString::number(arg.toInt()));\n\t\t\n\t\ttagValue.appendChild(tagInt);\n\t\ttagInt.appendChild(textInt);\n\n\t\treturn tagValue;\n\n\t} case QVariant::Double: {\n\n\t\tQDomElement tagDouble = doc.createElement(\"double\"); \n\t\tQDomText textDouble = doc.createTextNode(QString::number(arg.toDouble()));\n\t\t\n\t\ttagValue.appendChild(tagDouble);\n\t\ttagDouble.appendChild(textDouble);\n\n\t\treturn tagValue;\n\n\t} case QVariant::Bool: {\n\t\n\t\tQString textValue = arg.toBool() ? \"true\" : \"false\";\n\n\t\tQDomElement tag = doc.createElement(\"boolean\"); \n\t\tQDomText text = doc.createTextNode(textValue);\n\t\t\n\t\ttagValue.appendChild(tag);\n\t\ttag.appendChild(text);\n\n\t\treturn tagValue;\n\n\t} case QVariant::ByteArray: {\n\n\t\tQString textValue = arg.toByteArray().toBase64();\n\n\t\tQDomElement tag = doc.createElement(\"base64\"); \n\t\tQDomText text = doc.createTextNode(textValue);\n\t\t\n\t\ttagValue.appendChild(tag);\n\t\ttag.appendChild(text);\n\n\t\treturn tagValue;\n\n\t} case QVariant::DateTime: {\n\t\n\t\tQString textValue = arg.toDateTime().toString(\"yyyyMMddThh:mm:ss\");\n\n\t\tQDomElement tag = doc.createElement(\"datetime.iso8601\"); \n\t\tQDomText text = doc.createTextNode(textValue);\n\t\t\n\t\ttagValue.appendChild(tag);\n\t\ttag.appendChild(text);\n\n\t\treturn tagValue;\n\n\t} case QVariant::List: {\n\n\t\tQDomElement tagArray = doc.createElement(\"array\");\n\t\tQDomElement tagData = doc.createElement(\"data\");\n\t\ttagArray.appendChild(tagData);\n\t\ttagValue.appendChild(tagArray);\n\n\t\tconst QList args = arg.toList();\n\t\tfor(int i = 0; i < args.size(); ++i) {\n\t\t\ttagData.appendChild(toXml(args.at(i)));\n\t\t}\n\t\n\t\treturn tagValue;\n\n\t} case QVariant::Map: {\n\n\t\tQDomElement tagStruct = doc.createElement(\"struct\");\n\t\tQDomElement member;\n\t\tQDomElement name;\n\n\t\ttagValue.appendChild(tagStruct);\n\n\t\tQMap map = arg.toMap();\n\t\tQMapIterator i(map);\n\t\twhile(i.hasNext()) {\n\t\t\ti.next();\n\n\t\t\tmember = doc.createElement(\"member\");\n\t\t\tname = doc.createElement(\"name\");\n\n\t\t\t\/\/ (key) -> name -> member -> struct\n\t\t\ttagStruct.appendChild(member);\n\t\t\tmember.appendChild(name);\n\t\t\tname.appendChild(doc.createTextNode(i.key()));\n\n\t\t\t\/\/ add variables by recursion\n\t\t\tmember.appendChild(toXml(i.value()));\n\t\t}\n\n\t\treturn tagValue;\n\n\t} default:\n\t\tqDebug() << \"Failed to marshal unknown variant type: \" << arg.type() << endl;\n\t}\n\treturn QDomElement(); \/\/QString::null;\n}\n\nQVariant MaiaObject::fromXml(const QDomElement &elem) {\n\tif(elem.tagName().toLower() != \"value\") {\n\t\treturn QVariant();\n\t}\n\t\n\tconst QDomElement typeElement = elem.firstChild().toElement();\t\n\tconst QString typeName = typeElement.tagName().toLower();\n\n\tif(typeName == \"string\")\n\t\treturn QVariant(typeElement.text());\n\telse if(typeName == \"i4\" || typeName == \"int\")\n\t\treturn QVariant(typeElement.text().toInt());\n\telse if(typeName == \"double\")\n\t\treturn QVariant(typeElement.text().toDouble());\n\telse if (typeName == \"boolean\") {\n\t\tif(typeElement.text().toLower() == \"true\" || typeElement.text() == \"1\")\n\t\t\treturn QVariant(true);\n\t\telse\n\t\t\treturn QVariant(false);\n\t} else if(typeName == \"base64\")\n\t\treturn QVariant(QByteArray::fromBase64( typeElement.text().toLatin1()));\n\telse if(typeName == \"datetime\" || typeName == \"datetime.iso8601\")\n\t\treturn QVariant(QDateTime::fromString(typeElement.text(), \"yyyyMMddThh:mm:ss\"));\n\telse if ( typeName == \"array\" ) {\n\t\tQList values;\n\t\tQDomNode valueNode = typeElement.firstChild().firstChild();\n\t\twhile(!valueNode.isNull()) {\n\t\t\tvalues << fromXml(valueNode.toElement());\n\t\t\tvalueNode = valueNode.nextSibling();\n\t\t}\n\t\treturn QVariant(values);\n\t}\n\telse if ( typeName == \"struct\" ) {\n\t\tQMap map;\n\t\tQDomNode memberNode = typeElement.firstChild();\n\t\twhile(!memberNode.isNull())\t{\n\t\t\tconst QString key = memberNode.toElement().elementsByTagName(\"name\").item(0).toElement().text();\n\t\t\tconst QVariant data = fromXml(memberNode.toElement().elementsByTagName(\"value\").item(0).toElement());\n\t\t\tmap[key] = data;\n\t\t\tmemberNode = memberNode.nextSibling();\n\t\t}\n\t\treturn QVariant(map);\n\t} else {\n\t\tqDebug() << \"Cannot demarshal unknown type \" << typeElement.tagName().toLower();\n\t}\n\treturn QVariant();\n}\n\n\nQString MaiaObject::prepareCall(QString method, QList args) {\n\t\n\n\tQDomDocument doc;\n\n\tQDomProcessingInstruction header = doc.createProcessingInstruction( \"xml\", QString(\"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"\" ));\n\tdoc.appendChild(header);\n\t\n\tQDomElement methodCall = doc.createElement(\"methodCall\");\n\tQDomElement methodName = doc.createElement(\"methodName\");\n\tQDomElement params = doc.createElement(\"params\");\n\tQDomElement param;\n\n\tdoc.appendChild(methodCall);\n\tmethodCall.appendChild(methodName);\n\tmethodName.appendChild(doc.createTextNode(method));\n\n\tmethodCall.appendChild(params);\n\n\tfor(int i = 0; i < args.size(); ++i) {\n\t\tparam = doc.createElement(\"param\");\n\t\tparam.appendChild(toXml(args.at(i)));\n\t\tparams.appendChild(param);\n\t}\n\n\treturn doc.toString();\n}\n\nQString MaiaObject::prepareResponse(QVariant arg) {\n\n\tQDomDocument doc;\n\n\tQDomProcessingInstruction header = doc.createProcessingInstruction( \"xml\", QString(\"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"\" )); \n\tdoc.appendChild(header);\n\t\n\tQDomElement methodResponse = doc.createElement(\"methodResponse\");\n\tQDomElement params = doc.createElement(\"params\");\n\tQDomElement param;\n\n\tdoc.appendChild(methodResponse);\n\n\tmethodResponse.appendChild(params);\n\n\tif(!arg.isNull()) {\n\t\tparam = doc.createElement(\"param\");\n\t\tparam.appendChild(toXml(arg));\n\t\tparams.appendChild(param);\n\t}\n\treturn doc.toString();\n}\n\nvoid MaiaObject::parseResponse(QString response, QNetworkReply* reply) {\n\tQDomDocument doc;\n\tQVariant arg;\n\tQString errorMsg;\n\tint errorLine;\n\tint errorColumn;\n\tif(!doc.setContent(response, &errorMsg, &errorLine, &errorColumn)) {\n\t\temit fault(-32700, QString(\"parse error: response not well formed at line %1: %2\").arg(errorLine).arg(errorMsg), reply);\n\t\tdelete this;\n\t\treturn;\n\t}\n\tif(doc.documentElement().firstChild().toElement().tagName().toLower() == \"params\") {\n\t\tQDomNode paramNode = doc.documentElement().firstChild().firstChild();\n\t\tif(!paramNode.isNull()) {\n\t\t\targ = fromXml( paramNode.firstChild().toElement() );\n\t\t}\n\t\temit aresponse(arg, reply);\n\t} else if(doc.documentElement().firstChild().toElement().tagName().toLower() == \"fault\") {\n\t\tconst QVariant errorVariant = fromXml(doc.documentElement().firstChild().firstChild().toElement());\n\t\temit fault(errorVariant.toMap() [ \"faultCode\" ].toInt(),\n\t\t errorVariant.toMap() [ \"faultString\" ].toString(),\n\t\t reply);\n\t} else {\n\t\temit fault(-32600,\n\t\t tr(\"parse error: invalid xml-rpc. not conforming to spec.\"),\n\t\t reply);\n\t}\n\tdelete this;\n\treturn;\n}\n\ncompatibility with ws-xmlrpc (untested) - thanks to Martin Scheffler\/*\n * libMaia - maiaObject.cpp\n * Copyright (c) 2003 Frerich Raabe and\n * Ian Reinhart Geiser \n * Copyright (c) 2007 Sebastian Wiedenroth \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"maiaObject.h\"\n\nMaiaObject::MaiaObject(QObject* parent) : QObject(parent){\n\tQDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);\n}\n\nQDomElement MaiaObject::toXml(QVariant arg) {\n\t\n\t\/\/dummy document\n\tQDomDocument doc;\n\t\/\/value element, we need this in each case\n\tQDomElement tagValue = doc.createElement(\"value\");\n\n\tswitch(arg.type()) {\n\tcase QVariant::String: {\n\n\t\tQDomElement tagString = doc.createElement(\"string\"); \n\t\tQDomText textString = doc.createTextNode(arg.toString());\n\t\t\n\t\ttagValue.appendChild(tagString);\n\t\ttagString.appendChild(textString);\n\n\t\treturn tagValue;\n\n\t} case QVariant::Int: {\n\n\t\tQDomElement tagInt = doc.createElement(\"int\"); \n\t\tQDomText textInt = doc.createTextNode(QString::number(arg.toInt()));\n\t\t\n\t\ttagValue.appendChild(tagInt);\n\t\ttagInt.appendChild(textInt);\n\n\t\treturn tagValue;\n\n\t} case QVariant::Double: {\n\n\t\tQDomElement tagDouble = doc.createElement(\"double\"); \n\t\tQDomText textDouble = doc.createTextNode(QString::number(arg.toDouble()));\n\t\t\n\t\ttagValue.appendChild(tagDouble);\n\t\ttagDouble.appendChild(textDouble);\n\n\t\treturn tagValue;\n\n\t} case QVariant::Bool: {\n\t\n\t\tQString textValue = arg.toBool() ? \"true\" : \"false\";\n\n\t\tQDomElement tag = doc.createElement(\"boolean\"); \n\t\tQDomText text = doc.createTextNode(textValue);\n\t\t\n\t\ttagValue.appendChild(tag);\n\t\ttag.appendChild(text);\n\n\t\treturn tagValue;\n\n\t} case QVariant::ByteArray: {\n\n\t\tQString textValue = arg.toByteArray().toBase64();\n\n\t\tQDomElement tag = doc.createElement(\"base64\"); \n\t\tQDomText text = doc.createTextNode(textValue);\n\t\t\n\t\ttagValue.appendChild(tag);\n\t\ttag.appendChild(text);\n\n\t\treturn tagValue;\n\n\t} case QVariant::DateTime: {\n\t\n\t\tQString textValue = arg.toDateTime().toString(\"yyyyMMddThh:mm:ss\");\n\n\t\tQDomElement tag = doc.createElement(\"datetime.iso8601\"); \n\t\tQDomText text = doc.createTextNode(textValue);\n\t\t\n\t\ttagValue.appendChild(tag);\n\t\ttag.appendChild(text);\n\n\t\treturn tagValue;\n\n\t} case QVariant::List: {\n\n\t\tQDomElement tagArray = doc.createElement(\"array\");\n\t\tQDomElement tagData = doc.createElement(\"data\");\n\t\ttagArray.appendChild(tagData);\n\t\ttagValue.appendChild(tagArray);\n\n\t\tconst QList args = arg.toList();\n\t\tfor(int i = 0; i < args.size(); ++i) {\n\t\t\ttagData.appendChild(toXml(args.at(i)));\n\t\t}\n\t\n\t\treturn tagValue;\n\n\t} case QVariant::Map: {\n\n\t\tQDomElement tagStruct = doc.createElement(\"struct\");\n\t\tQDomElement member;\n\t\tQDomElement name;\n\n\t\ttagValue.appendChild(tagStruct);\n\n\t\tQMap map = arg.toMap();\n\t\tQMapIterator i(map);\n\t\twhile(i.hasNext()) {\n\t\t\ti.next();\n\n\t\t\tmember = doc.createElement(\"member\");\n\t\t\tname = doc.createElement(\"name\");\n\n\t\t\t\/\/ (key) -> name -> member -> struct\n\t\t\ttagStruct.appendChild(member);\n\t\t\tmember.appendChild(name);\n\t\t\tname.appendChild(doc.createTextNode(i.key()));\n\n\t\t\t\/\/ add variables by recursion\n\t\t\tmember.appendChild(toXml(i.value()));\n\t\t}\n\n\t\treturn tagValue;\n\n\t} default:\n\t\tqDebug() << \"Failed to marshal unknown variant type: \" << arg.type() << endl;\n\t}\n\treturn QDomElement(); \/\/QString::null;\n}\n\nQVariant MaiaObject::fromXml(const QDomElement &elem) {\n\tif(elem.tagName().toLower() != \"value\") {\n\t\treturn QVariant();\n\t}\n\t\n\t\/\/ If no type is indicated, the type is string.\n\tif(!elem.firstChild().isElement()) {\n\t\treturn QVariant(elem.text());\n\t}\n\t\n\tconst QDomElement typeElement = elem.firstChild().toElement();\t\n\tconst QString typeName = typeElement.tagName().toLower();\n\n\tif(typeName == \"string\")\n\t\treturn QVariant(typeElement.text());\n\telse if(typeName == \"i4\" || typeName == \"int\")\n\t\treturn QVariant(typeElement.text().toInt());\n\telse if(typeName == \"double\")\n\t\treturn QVariant(typeElement.text().toDouble());\n\telse if (typeName == \"boolean\") {\n\t\tif(typeElement.text().toLower() == \"true\" || typeElement.text() == \"1\")\n\t\t\treturn QVariant(true);\n\t\telse\n\t\t\treturn QVariant(false);\n\t} else if(typeName == \"base64\")\n\t\treturn QVariant(QByteArray::fromBase64( typeElement.text().toLatin1()));\n\telse if(typeName == \"datetime\" || typeName == \"datetime.iso8601\")\n\t\treturn QVariant(QDateTime::fromString(typeElement.text(), \"yyyyMMddThh:mm:ss\"));\n\telse if ( typeName == \"array\" ) {\n\t\tQList values;\n\t\tQDomNode valueNode = typeElement.firstChild().firstChild();\n\t\twhile(!valueNode.isNull()) {\n\t\t\tvalues << fromXml(valueNode.toElement());\n\t\t\tvalueNode = valueNode.nextSibling();\n\t\t}\n\t\treturn QVariant(values);\n\t}\n\telse if ( typeName == \"struct\" ) {\n\t\tQMap map;\n\t\tQDomNode memberNode = typeElement.firstChild();\n\t\twhile(!memberNode.isNull())\t{\n\t\t\tconst QString key = memberNode.toElement().elementsByTagName(\"name\").item(0).toElement().text();\n\t\t\tconst QVariant data = fromXml(memberNode.toElement().elementsByTagName(\"value\").item(0).toElement());\n\t\t\tmap[key] = data;\n\t\t\tmemberNode = memberNode.nextSibling();\n\t\t}\n\t\treturn QVariant(map);\n\t} else {\n\t\tqDebug() << \"Cannot demarshal unknown type \" << typeElement.tagName().toLower();\n\t}\n\treturn QVariant();\n}\n\n\nQString MaiaObject::prepareCall(QString method, QList args) {\n\t\n\n\tQDomDocument doc;\n\n\tQDomProcessingInstruction header = doc.createProcessingInstruction( \"xml\", QString(\"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"\" ));\n\tdoc.appendChild(header);\n\t\n\tQDomElement methodCall = doc.createElement(\"methodCall\");\n\tQDomElement methodName = doc.createElement(\"methodName\");\n\tQDomElement params = doc.createElement(\"params\");\n\tQDomElement param;\n\n\tdoc.appendChild(methodCall);\n\tmethodCall.appendChild(methodName);\n\tmethodName.appendChild(doc.createTextNode(method));\n\n\tmethodCall.appendChild(params);\n\n\tfor(int i = 0; i < args.size(); ++i) {\n\t\tparam = doc.createElement(\"param\");\n\t\tparam.appendChild(toXml(args.at(i)));\n\t\tparams.appendChild(param);\n\t}\n\n\treturn doc.toString();\n}\n\nQString MaiaObject::prepareResponse(QVariant arg) {\n\n\tQDomDocument doc;\n\n\tQDomProcessingInstruction header = doc.createProcessingInstruction( \"xml\", QString(\"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"\" )); \n\tdoc.appendChild(header);\n\t\n\tQDomElement methodResponse = doc.createElement(\"methodResponse\");\n\tQDomElement params = doc.createElement(\"params\");\n\tQDomElement param;\n\n\tdoc.appendChild(methodResponse);\n\n\tmethodResponse.appendChild(params);\n\n\tif(!arg.isNull()) {\n\t\tparam = doc.createElement(\"param\");\n\t\tparam.appendChild(toXml(arg));\n\t\tparams.appendChild(param);\n\t}\n\treturn doc.toString();\n}\n\nvoid MaiaObject::parseResponse(QString response, QNetworkReply* reply) {\n\tQDomDocument doc;\n\tQVariant arg;\n\tQString errorMsg;\n\tint errorLine;\n\tint errorColumn;\n\tif(!doc.setContent(response, &errorMsg, &errorLine, &errorColumn)) {\n\t\temit fault(-32700, QString(\"parse error: response not well formed at line %1: %2\").arg(errorLine).arg(errorMsg), reply);\n\t\tdelete this;\n\t\treturn;\n\t}\n\tif(doc.documentElement().firstChild().toElement().tagName().toLower() == \"params\") {\n\t\tQDomNode paramNode = doc.documentElement().firstChild().firstChild();\n\t\tif(!paramNode.isNull()) {\n\t\t\targ = fromXml( paramNode.firstChild().toElement() );\n\t\t}\n\t\temit aresponse(arg, reply);\n\t} else if(doc.documentElement().firstChild().toElement().tagName().toLower() == \"fault\") {\n\t\tconst QVariant errorVariant = fromXml(doc.documentElement().firstChild().firstChild().toElement());\n\t\temit fault(errorVariant.toMap() [ \"faultCode\" ].toInt(),\n\t\t errorVariant.toMap() [ \"faultString\" ].toString(),\n\t\t reply);\n\t} else {\n\t\temit fault(-32600,\n\t\t tr(\"parse error: invalid xml-rpc. not conforming to spec.\"),\n\t\t reply);\n\t}\n\tdelete this;\n\treturn;\n}\n\n<|endoftext|>"} {"text":"#include \"thrusttest\/testframework.h\"\n#include \"thrusttest\/exceptions.h\"\n\n#include \n#include \n#include \n#include \n\nvoid UnitTestDriver::register_test(UnitTest *test)\n{\n UnitTestDriver::s_driver()._test_list.push_back(test);\n}\n\nUnitTest::UnitTest(const char * _name) : name(_name)\n{\n UnitTestDriver::s_driver().register_test(this);\n}\n\nbool UnitTestDriver::run_tests(const std::vector &tests_to_run, const bool verbose)\n{\n bool any_failed = false;\n\n std::cout << \"Running \" << tests_to_run.size() << \" unit tests.\" << std::endl;\n\n std::vector< std::pair > test_failures;\n std::vector< std::pair > test_known_failures;\n std::vector< std::pair > test_errors;\n std::vector< UnitTest * > test_exceptions;\n \n cudaError_t error = cudaGetLastError();\n if(error){\n std::cerr << \"[ERROR] CUDA Error detected before running tests: [\";\n std::cerr << std::string(cudaGetErrorString(error));\n std::cerr << \"]\" << std::endl;\n exit(EXIT_FAILURE);\n } \n\n\n for(size_t i = 0; i < tests_to_run.size(); i++){\n UnitTest * test = tests_to_run[i];\n\n if (verbose)\n std::cout << \"Running \" << test->name << \"\\r\" << std::flush;\n\n try {\n test->run();\n if (verbose)\n std::cout << \"[PASS] \";\n else\n std::cout << \".\";\n } \n catch (thrusttest::UnitTestFailure& f){\n any_failed = true;\n if (verbose)\n std::cout << \"[FAILURE] \";\n else\n std::cout << \"F\";\n test_failures.push_back(std::make_pair(test,f));\n }\n catch (thrusttest::UnitTestKnownFailure& f){\n if (verbose)\n std::cout << \"[KNOWN FAILURE] \";\n else\n std::cout << \"K\";\n test_known_failures.push_back(std::make_pair(test,f));\n } \n catch (thrusttest::UnitTestError& e){\n any_failed = true;\n if (verbose)\n std::cout << \"[ERROR] \";\n else\n std::cout << \"E\";\n test_errors.push_back(std::make_pair(test,e));\n } \n catch (...){\n any_failed = true;\n if (verbose)\n std::cout << \"[UNKNOWN EXCEPTION] \" << std::endl;\n else\n std::cout << \"U\";\n test_exceptions.push_back(test);\n }\n \n if (verbose)\n std::cout << \" \" << test->name << std::endl;\n \n error = cudaGetLastError();\n if(error){\n std::cerr << \"\\t[ERROR] CUDA Error detected after running \" << test->name << \": [\";\n std::cerr << std::string(cudaGetErrorString(error));\n std::cerr << \"]\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::cout.flush();\n }\n std::cout << std::endl;\n\n std::string hline = \"================================================================\";\n\n for(size_t i = 0; i < test_failures.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"FAILURE: \" << test_failures[i].first->name << std::endl;\n std::cout << test_failures[i].second << std::endl;\n }\n for(size_t i = 0; i < test_known_failures.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"KNOWN FAILURE: \" << test_known_failures[i].first->name << std::endl;\n std::cout << test_known_failures[i].second << std::endl;\n }\n for(size_t i = 0; i < test_errors.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"ERROR: \" << test_errors[i].first->name << std::endl;\n std::cout << test_errors[i].second << std::endl;\n }\n for(size_t i = 0; i < test_exceptions.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"UNKNOWN EXCEPTION: \" << test_exceptions[i]->name << std::endl;\n }\n\n std::cout << hline << std::endl;\n\n std::cout << \"Totals: \";\n std::cout << test_failures.size() << \" failures, \";\n std::cout << test_known_failures.size() << \" known failures, \";\n std::cout << test_errors.size() << \" errors and \";\n std::cout << test_exceptions.size() << \" unknown exceptions.\" << std::endl;\n\n return any_failed;\n}\n\n\n\/\/ for sorting UnitTests by name\nstruct UnitTest_name_cmp\n{\n bool operator()(const UnitTest * a, const UnitTest * b) const {\n return a->name < b->name;\n }\n\n};\n\nbool UnitTestDriver::run_all_tests(const bool verbose)\n{\n std::vector tests_to_run(_test_list);\n\n \/\/ sort tests by name for deterministic results\n std::sort(tests_to_run.begin(), tests_to_run.end(), UnitTest_name_cmp());\n\n return run_tests(tests_to_run, verbose);\n}\n\nbool \nUnitTestDriver::run_tests(const std::vector &tests, const bool verbose)\n{\n int i, j;\n std::vector tests_to_run;\n\n for (j=0; j < tests.size(); j++) {\n\n bool found = false;\n for (i = 0; !found && i < _test_list.size(); i++)\n if (tests[j] == _test_list[i]->name) {\n\n tests_to_run.push_back(_test_list[i]);\n found = true;\n }\n\n if (!found) {\n printf(\"[WARNING] UnitTestDriver::run_tests - test %s not found\\n\", tests[j].c_str());\n }\n }\n\n return run_tests(tests_to_run, verbose);\n}\n\nUnitTestDriver &\nUnitTestDriver::s_driver()\n{\n static UnitTestDriver s_instance;\n return s_instance;\n}\n\n\n\nCorrectly return the status of unit tests in testframework.cpp.#include \"thrusttest\/testframework.h\"\n#include \"thrusttest\/exceptions.h\"\n\n#include \n#include \n#include \n#include \n\nvoid UnitTestDriver::register_test(UnitTest *test)\n{\n UnitTestDriver::s_driver()._test_list.push_back(test);\n}\n\nUnitTest::UnitTest(const char * _name) : name(_name)\n{\n UnitTestDriver::s_driver().register_test(this);\n}\n\nbool UnitTestDriver::run_tests(const std::vector &tests_to_run, const bool verbose)\n{\n bool all_passed = true;\n\n std::cout << \"Running \" << tests_to_run.size() << \" unit tests.\" << std::endl;\n\n std::vector< std::pair > test_failures;\n std::vector< std::pair > test_known_failures;\n std::vector< std::pair > test_errors;\n std::vector< UnitTest * > test_exceptions;\n \n cudaError_t error = cudaGetLastError();\n if(error){\n std::cerr << \"[ERROR] CUDA Error detected before running tests: [\";\n std::cerr << std::string(cudaGetErrorString(error));\n std::cerr << \"]\" << std::endl;\n exit(EXIT_FAILURE);\n } \n\n\n for(size_t i = 0; i < tests_to_run.size(); i++){\n UnitTest * test = tests_to_run[i];\n\n if (verbose)\n std::cout << \"Running \" << test->name << \"\\r\" << std::flush;\n\n try {\n test->run();\n if (verbose)\n std::cout << \"[PASS] \";\n else\n std::cout << \".\";\n } \n catch (thrusttest::UnitTestFailure& f){\n all_passed = false;\n if (verbose)\n std::cout << \"[FAILURE] \";\n else\n std::cout << \"F\";\n test_failures.push_back(std::make_pair(test,f));\n }\n catch (thrusttest::UnitTestKnownFailure& f){\n if (verbose)\n std::cout << \"[KNOWN FAILURE] \";\n else\n std::cout << \"K\";\n test_known_failures.push_back(std::make_pair(test,f));\n } \n catch (thrusttest::UnitTestError& e){\n all_passed = false;\n if (verbose)\n std::cout << \"[ERROR] \";\n else\n std::cout << \"E\";\n test_errors.push_back(std::make_pair(test,e));\n } \n catch (...){\n all_passed = false;\n if (verbose)\n std::cout << \"[UNKNOWN EXCEPTION] \" << std::endl;\n else\n std::cout << \"U\";\n test_exceptions.push_back(test);\n }\n \n if (verbose)\n std::cout << \" \" << test->name << std::endl;\n \n error = cudaGetLastError();\n if(error){\n std::cerr << \"\\t[ERROR] CUDA Error detected after running \" << test->name << \": [\";\n std::cerr << std::string(cudaGetErrorString(error));\n std::cerr << \"]\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::cout.flush();\n }\n std::cout << std::endl;\n\n std::string hline = \"================================================================\";\n\n for(size_t i = 0; i < test_failures.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"FAILURE: \" << test_failures[i].first->name << std::endl;\n std::cout << test_failures[i].second << std::endl;\n }\n for(size_t i = 0; i < test_known_failures.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"KNOWN FAILURE: \" << test_known_failures[i].first->name << std::endl;\n std::cout << test_known_failures[i].second << std::endl;\n }\n for(size_t i = 0; i < test_errors.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"ERROR: \" << test_errors[i].first->name << std::endl;\n std::cout << test_errors[i].second << std::endl;\n }\n for(size_t i = 0; i < test_exceptions.size(); i++){\n std::cout << hline << std::endl;\n std::cout << \"UNKNOWN EXCEPTION: \" << test_exceptions[i]->name << std::endl;\n }\n\n std::cout << hline << std::endl;\n\n std::cout << \"Totals: \";\n std::cout << test_failures.size() << \" failures, \";\n std::cout << test_known_failures.size() << \" known failures, \";\n std::cout << test_errors.size() << \" errors and \";\n std::cout << test_exceptions.size() << \" unknown exceptions.\" << std::endl;\n\n return all_passed;\n}\n\n\n\/\/ for sorting UnitTests by name\nstruct UnitTest_name_cmp\n{\n bool operator()(const UnitTest * a, const UnitTest * b) const {\n return a->name < b->name;\n }\n\n};\n\nbool UnitTestDriver::run_all_tests(const bool verbose)\n{\n std::vector tests_to_run(_test_list);\n\n \/\/ sort tests by name for deterministic results\n std::sort(tests_to_run.begin(), tests_to_run.end(), UnitTest_name_cmp());\n\n return run_tests(tests_to_run, verbose);\n}\n\nbool \nUnitTestDriver::run_tests(const std::vector &tests, const bool verbose)\n{\n int i, j;\n std::vector tests_to_run;\n\n for (j=0; j < tests.size(); j++) {\n\n bool found = false;\n for (i = 0; !found && i < _test_list.size(); i++)\n if (tests[j] == _test_list[i]->name) {\n\n tests_to_run.push_back(_test_list[i]);\n found = true;\n }\n\n if (!found) {\n printf(\"[WARNING] UnitTestDriver::run_tests - test %s not found\\n\", tests[j].c_str());\n }\n }\n\n return run_tests(tests_to_run, verbose);\n}\n\nUnitTestDriver &\nUnitTestDriver::s_driver()\n{\n static UnitTestDriver s_instance;\n return s_instance;\n}\n\n\n\n<|endoftext|>"} {"text":"#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"logic\/blinkcore.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n core(new BlinkCore(this)),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n auto availableTypes = core->availableSelectorTypes();\r\n ui->anime_selectorFormat->addItems(availableTypes);\r\n ui->manga_selectorFormat->addItems(availableTypes);\r\n core->setAnimeOutFormat(availableTypes.at(0));\r\n core->setMangaOutFormat(availableTypes.at(0));\r\n connect(core, &BlinkCore::animelistTotal,\r\n [this](int i) { ui->anime_progress->setMaximum(qMax(i, 1)); });\r\n connect(core, &BlinkCore::animelistProcessed,\r\n ui->anime_progress, &QProgressBar::setValue);\r\n connect(core, &BlinkCore::mangalistTotal,\r\n [this](int i) { ui->manga_progress->setMaximum(qMax(i, 1)); });\r\n connect(core, &BlinkCore::mangalistProcessed,\r\n ui->manga_progress, &QProgressBar::setValue);\r\n\r\n connect(core, &BlinkCore::finished,\r\n this, &MainWindow::onBlinkFinished);\r\n connect(core, &BlinkCore::error,\r\n this, &MainWindow::onBlinkError);\r\n\r\n connect(ui->usernameEdit, &QLineEdit::textChanged,\r\n core, &BlinkCore::setUsername);\r\n connect(ui->usernameEdit, &QLineEdit::textChanged, this, &MainWindow::purgeProgress);\r\n connect(ui->anime_group, &QGroupBox::toggled, core, &BlinkCore::processAnimelist);\r\n connect(ui->manga_group, &QGroupBox::toggled, core, &BlinkCore::processMangalist);\r\n connect(ui->anime_path, &QLineEdit::textChanged, core, &BlinkCore::setAnimeOutPath);\r\n connect(ui->manga_path, &QLineEdit::textChanged, core, &BlinkCore::setMangaOutPath);\r\n connect(ui->anime_selectorFormat, &QComboBox::currentTextChanged, core, &BlinkCore::setAnimeOutFormat);\r\n connect(ui->manga_selectorFormat, &QComboBox::currentTextChanged, core, &BlinkCore::setMangaOutFormat);\r\n connect(ui->anime_browseButton, &QPushButton::clicked, [this]{writePath(ui->anime_path);});\r\n connect(ui->manga_browseButton, &QPushButton::clicked, [this]{writePath(ui->manga_path);});\r\n connect(ui->blinkButton, &QPushButton::clicked, this, &MainWindow::onBlinkButtonPressed);\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete core;\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::changeEvent(QEvent *e)\r\n{\r\n QMainWindow::changeEvent(e);\r\n switch (e->type()) {\r\n case QEvent::LanguageChange:\r\n ui->retranslateUi(this);\r\n break;\r\n default:\r\n break;\r\n }\r\n}\r\n\r\nvoid MainWindow::writePath(QLineEdit *le)\r\n{\r\n QString path\r\n = QFileDialog::getSaveFileName(this, tr(\"Save covers file as\"),\r\n QString(),\r\n tr(\"Cascading style sheet files (*.css)\"\r\n \";;All files (*.*)\"));\r\n if (!path.isEmpty()) le->setText(path);\r\n}\r\n\r\nvoid MainWindow::onBlinkButtonPressed()\r\n{\r\n if (ui->anime_path->text() == ui->manga_path->text()) {\r\n QMessageBox::warning(this, tr(\"Warning\"),\r\n tr(\"You cannot save both cover files into one\"));\r\n return;\r\n }\r\n if (ui->anime_group->isChecked() && ui->anime_path->text().isEmpty()) {\r\n QMessageBox::warning(this, tr(\"Warning\"),\r\n tr(\"You must specify a path to save anime list covers\"));\r\n return;\r\n }\r\n if (ui->manga_group->isChecked() && ui->manga_path->text().isEmpty()) {\r\n QMessageBox::warning(this, tr(\"Warning\"),\r\n tr(\"You must specify a path to save manga list covers\"));\r\n return;\r\n }\r\n enableControls(false);\r\n core->startProcessing();\r\n}\r\n\r\nvoid MainWindow::enableControls(bool enable)\r\n{\r\n ui->anime_group->setEnabled(enable);\r\n ui->manga_group->setEnabled(enable);\r\n ui->usernameEdit->setEnabled(enable);\r\n ui->blinkButton->setEnabled(enable);\r\n}\r\n\r\nvoid MainWindow::purgeProgress()\r\n{\r\n ui->anime_progress->setValue(0);\r\n ui->anime_progress->setMaximum(1);\r\n ui->manga_progress->setValue(0);\r\n ui->manga_progress->setMaximum(1);\r\n}\r\n\r\nvoid MainWindow::onBlinkFinished()\r\n{\r\n \/\/ this is a workaround because MAL can report incorrect quantities\r\n \/\/ so I just quickly change the values to indicate correct ones\r\n ui->anime_progress->setMaximum(qMax(1,ui->anime_progress->value()));\r\n ui->manga_progress->setMaximum(qMax(1,ui->manga_progress->value()));\r\n QMessageBox::information(this, tr(\"Info\"),\r\n tr(\"Saving completed\"));\r\n enableControls(true);\r\n}\r\n\r\nvoid MainWindow::onBlinkError(QString msg)\r\n{\r\n enableControls(true);\r\n QMessageBox::critical(this, tr(\"Error\"),\r\n tr(\"An error occured during operation:\/n%1\").arg(msg));\r\n}\r\nFixed issue when path is the same but one of groups is disabled#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"logic\/blinkcore.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n core(new BlinkCore(this)),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n auto availableTypes = core->availableSelectorTypes();\r\n ui->anime_selectorFormat->addItems(availableTypes);\r\n ui->manga_selectorFormat->addItems(availableTypes);\r\n core->setAnimeOutFormat(availableTypes.at(0));\r\n core->setMangaOutFormat(availableTypes.at(0));\r\n connect(core, &BlinkCore::animelistTotal,\r\n [this](int i) { ui->anime_progress->setMaximum(qMax(i, 1)); });\r\n connect(core, &BlinkCore::animelistProcessed,\r\n ui->anime_progress, &QProgressBar::setValue);\r\n connect(core, &BlinkCore::mangalistTotal,\r\n [this](int i) { ui->manga_progress->setMaximum(qMax(i, 1)); });\r\n connect(core, &BlinkCore::mangalistProcessed,\r\n ui->manga_progress, &QProgressBar::setValue);\r\n\r\n connect(core, &BlinkCore::finished,\r\n this, &MainWindow::onBlinkFinished);\r\n connect(core, &BlinkCore::error,\r\n this, &MainWindow::onBlinkError);\r\n\r\n connect(ui->usernameEdit, &QLineEdit::textChanged,\r\n core, &BlinkCore::setUsername);\r\n connect(ui->usernameEdit, &QLineEdit::textChanged, this, &MainWindow::purgeProgress);\r\n connect(ui->anime_group, &QGroupBox::toggled, core, &BlinkCore::processAnimelist);\r\n connect(ui->manga_group, &QGroupBox::toggled, core, &BlinkCore::processMangalist);\r\n connect(ui->anime_path, &QLineEdit::textChanged, core, &BlinkCore::setAnimeOutPath);\r\n connect(ui->manga_path, &QLineEdit::textChanged, core, &BlinkCore::setMangaOutPath);\r\n connect(ui->anime_selectorFormat, &QComboBox::currentTextChanged, core, &BlinkCore::setAnimeOutFormat);\r\n connect(ui->manga_selectorFormat, &QComboBox::currentTextChanged, core, &BlinkCore::setMangaOutFormat);\r\n connect(ui->anime_browseButton, &QPushButton::clicked, [this]{writePath(ui->anime_path);});\r\n connect(ui->manga_browseButton, &QPushButton::clicked, [this]{writePath(ui->manga_path);});\r\n connect(ui->blinkButton, &QPushButton::clicked, this, &MainWindow::onBlinkButtonPressed);\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete core;\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::changeEvent(QEvent *e)\r\n{\r\n QMainWindow::changeEvent(e);\r\n switch (e->type()) {\r\n case QEvent::LanguageChange:\r\n ui->retranslateUi(this);\r\n break;\r\n default:\r\n break;\r\n }\r\n}\r\n\r\nvoid MainWindow::writePath(QLineEdit *le)\r\n{\r\n QString path\r\n = QFileDialog::getSaveFileName(this, tr(\"Save covers file as\"),\r\n QString(),\r\n tr(\"Cascading style sheet files (*.css)\"\r\n \";;All files (*.*)\"));\r\n if (!path.isEmpty()) le->setText(path);\r\n}\r\n\r\nvoid MainWindow::onBlinkButtonPressed()\r\n{\r\n if (ui->anime_group->isChecked() && ui->manga_group->isChecked()\r\n && ui->anime_path->text() == ui->manga_path->text()) {\r\n QMessageBox::warning(this, tr(\"Warning\"),\r\n tr(\"You cannot save both cover files into one\"));\r\n return;\r\n }\r\n if (ui->anime_group->isChecked() && ui->anime_path->text().isEmpty()) {\r\n QMessageBox::warning(this, tr(\"Warning\"),\r\n tr(\"You must specify a path to save anime list covers\"));\r\n return;\r\n }\r\n if (ui->manga_group->isChecked() && ui->manga_path->text().isEmpty()) {\r\n QMessageBox::warning(this, tr(\"Warning\"),\r\n tr(\"You must specify a path to save manga list covers\"));\r\n return;\r\n }\r\n enableControls(false);\r\n core->startProcessing();\r\n}\r\n\r\nvoid MainWindow::enableControls(bool enable)\r\n{\r\n ui->anime_group->setEnabled(enable);\r\n ui->manga_group->setEnabled(enable);\r\n ui->usernameEdit->setEnabled(enable);\r\n ui->blinkButton->setEnabled(enable);\r\n}\r\n\r\nvoid MainWindow::purgeProgress()\r\n{\r\n ui->anime_progress->setValue(0);\r\n ui->anime_progress->setMaximum(1);\r\n ui->manga_progress->setValue(0);\r\n ui->manga_progress->setMaximum(1);\r\n}\r\n\r\nvoid MainWindow::onBlinkFinished()\r\n{\r\n \/\/ this is a workaround because MAL can report incorrect quantities\r\n \/\/ so I just quickly change the values to indicate correct ones\r\n ui->anime_progress->setMaximum(qMax(1,ui->anime_progress->value()));\r\n ui->manga_progress->setMaximum(qMax(1,ui->manga_progress->value()));\r\n QMessageBox::information(this, tr(\"Info\"),\r\n tr(\"Saving completed\"));\r\n enableControls(true);\r\n}\r\n\r\nvoid MainWindow::onBlinkError(QString msg)\r\n{\r\n enableControls(true);\r\n QMessageBox::critical(this, tr(\"Error\"),\r\n tr(\"An error occured during operation:\/n%1\").arg(msg));\r\n}\r\n<|endoftext|>"} {"text":"\/*\r\n * Copyright 2013 IoriAYANE\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"tweetdialog.h\"\r\n#include \"settingsdialog.h\"\r\n#include \"cookiejar.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \r\n\r\n#define URL_KANCOLLE \"http:\/\/www.dmm.com\/netgame\/social\/-\/gadgets\/=\/app_id=854854\/\"\r\n#define FLASH_POS_SEARCH_START_Y 40 \/\/Flashの位置を探すときにY方向の開始座標(つまりDMMのヘッダを飛ばす)\r\n#define KANCOLLE_WIDTH 800\r\n#define KANCOLLE_HEIGHT 480\r\n\r\n#define SETTING_FILE_NAME \"settings.ini\"\r\n#define SETTING_FILE_FORMAT QSettings::IniFormat\r\n\r\n#define STATUS_BAR_MSG_TIME 5000\r\n\r\nclass MainWindow::Private\r\n{\r\npublic:\r\n Private(MainWindow *parent);\r\n ~Private();\r\n\r\nprivate:\r\n MainWindow *q;\r\n\r\npublic:\r\n Ui::MainWindow ui;\r\n QSettings settings; \/\/設定管理\r\n \/\/設定保存データ\r\n QString savePath; \/\/保存パス\r\n QPoint flashPos; \/\/座標\r\n\r\n \/\/一時データ\r\n QPoint scroolPos; \/\/スクロール量\r\n bool finishCalibrated; \/\/キャリブレーション済み\r\n};\r\n\r\nMainWindow::Private::Private(MainWindow *parent)\r\n : q(parent)\r\n , settings(SETTING_FILE_NAME, SETTING_FILE_FORMAT)\r\n , savePath(settings.value(\"path\", \"\").toString())\r\n , flashPos(settings.value(\"flashPos\", QPoint(0, 0)).toPoint())\r\n , finishCalibrated(settings.value(\"finishCalibrated\", false).toBool())\r\n{\r\n ui.setupUi(q);\r\n ui.webView->page()->networkAccessManager()->setCookieJar(new CookieJar(q));\r\n connect(ui.capture, &QAction::triggered, q, &MainWindow::captureGame);\r\n connect(ui.reload, &QAction::triggered, ui.webView, &QWebView::reload);\r\n connect(ui.exit, &QAction::triggered, q, &MainWindow::close);\r\n connect(ui.adjust, &QAction::triggered, q, &MainWindow::calibration);\r\n\r\n \/\/設定ダイアログ表示\r\n connect(ui.preferences, &QAction::triggered, [this]() {\r\n SettingsDialog dlg(q);\r\n dlg.setSavePath(savePath);\r\n if (dlg.exec()) {\r\n \/\/設定更新\r\n savePath = dlg.savePath();\r\n }\r\n });\r\n\r\n \/\/アバウト\r\n connect(ui.about, &QAction::triggered, [this]() {\r\n QMessageBox::about(q, MainWindow::tr(\"Kan Memo\"), MainWindow::tr(\"Kan Memo -KanMusu Memory-\\n\\nCopyright 2013 IoriAYANE\"));\r\n });\r\n\r\n connect(ui.webView, &QWebView::loadStarted, [this](){\r\n ui.progressBar->show();\r\n });\r\n \/\/WebViewの読込み完了\r\n connect(ui.webView, &QWebView::loadFinished, [this](bool ok) {\r\n if (ok) {\r\n ui.statusBar->showMessage(MainWindow::tr(\"complete\"), STATUS_BAR_MSG_TIME);\r\n } else {\r\n ui.statusBar->showMessage(MainWindow::tr(\"error\"), STATUS_BAR_MSG_TIME);\r\n }\r\n ui.progressBar->hide();\r\n });\r\n\r\n \/\/WebViewの読込み状態\r\n connect(ui.webView, &QWebView::loadProgress, ui.progressBar, &QProgressBar::setValue);\r\n\r\n connect(ui.webView->page(), SIGNAL(scrollRequested(int,int,QRect)), q, SLOT(scrollRequested(int,int,QRect)));\r\n}\r\n\r\nMainWindow::Private::~Private()\r\n{\r\n \/\/設定保存\r\n settings.setValue(\"path\", savePath);\r\n settings.setValue(\"flashPos\", flashPos);\r\n settings.setValue(\"finishCalibrated\", finishCalibrated);\r\n}\r\n\r\nMainWindow::MainWindow(QWidget *parent)\r\n : QMainWindow(parent)\r\n , d(new Private(this))\r\n{\r\n if(d->savePath.length() == 0){\r\n \/\/設定を促す\r\n QMessageBox::information(this\r\n , tr(\"Kan Memo\")\r\n , tr(\"Please select a folder to save the image of KanMusu.\"));\r\n d->savePath = SettingsDialog::selectSavePath(this, QDir::homePath());\r\n }\r\n\r\n \/\/設定\r\n QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);\r\n QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true);\r\n \/\/艦これ読込み\r\n d->ui.webView->load(QUrl(URL_KANCOLLE));\r\n\r\n connect(this, &MainWindow::destroyed, [this]() {delete d;});\r\n}\r\n\r\n\/\/思い出を残す\r\nvoid MainWindow::captureGame()\r\n{\r\n qDebug() << \"captureGame\";\r\n\r\n if(!d->finishCalibrated){\r\n \/\/キャリブレーションされてないので確認して実行\r\n calibration();\r\n }\r\n\r\n \/\/キャリブレーションしてなければ実行しない\r\n if(!d->finishCalibrated){\r\n d->ui.statusBar->showMessage(QString(tr(\"cancel\")), STATUS_BAR_MSG_TIME);\r\n return;\r\n }\r\n\r\n int x = d->flashPos.x() + d->scroolPos.x();\/\/ int((d->ui.webView->size().width()-16) \/ 2) - int(800 \/ 2);\r\n int y = d->flashPos.y() + d->scroolPos.y();\r\n QImage img(d->ui.webView->size(), QImage::Format_ARGB32);\r\n QImage img2(KANCOLLE_WIDTH, KANCOLLE_HEIGHT, QImage::Format_ARGB32);\r\n QPainter painter(&img);\r\n QPainter painter2(&img2);\r\n \/\/全体を描画\r\n d->ui.webView->page()->view()->render(&painter);\r\n \/\/2つ目へ必要な分だけコピー\r\n painter2.drawImage(QPoint(0,0), img, QRect(x, y, KANCOLLE_WIDTH, KANCOLLE_HEIGHT));\r\n QDate date(QDate::currentDate());\r\n QTime time(QTime::currentTime());\r\n QString path = d->savePath + \"\/kanmusu\";\r\n path.append(QString(\"_%1-%2-%3_%4-%5-%6-%7\")\r\n .arg(date.year()).arg(date.month()).arg(date.day())\r\n .arg(time.hour()).arg(time.minute()).arg(time.second()).arg(time.msec())\r\n );\r\n path.append(\".png\");\r\n \/\/ path.append(\".jpg\");\r\n qDebug() << \"path:\" << path;\r\n\r\n \/\/保存する\r\n if(img2.save(path)){\r\n d->ui.statusBar->showMessage(tr(\"saving to %1...\").arg(path), STATUS_BAR_MSG_TIME);\r\n\r\n\r\n \/\/つぶやくダイアログ\r\n TweetDialog dlg(this);\r\n dlg.setImagePath(path);\r\n dlg.setToken(d->settings.value(\"token\", \"\").toString());\r\n dlg.setTokenSecret(d->settings.value(\"tokenSecret\", \"\").toString());\r\n dlg.user_id(d->settings.value(\"user_id\", \"\").toString());\r\n dlg.screen_name(d->settings.value(\"screen_name\", \"\").toString());\r\n dlg.exec();\r\n d->settings.setValue(\"token\", dlg.token());\r\n d->settings.setValue(\"tokenSecret\", dlg.tokenSecret());\r\n d->settings.setValue(\"user_id\", dlg.user_id());\r\n d->settings.setValue(\"screen_name\", dlg.screen_name());\r\n \/\/ d->settings.sync();\r\n\r\n }else{\r\n d->ui.statusBar->showMessage(tr(\"failed\"), STATUS_BAR_MSG_TIME);\r\n }\r\n\r\n}\r\n\/\/キャリブレーション\r\nvoid MainWindow::calibration()\r\n{\r\n qDebug() << \"calibration\";\r\n\r\n\/\/ QMessageBox::information(this\r\n\/\/ , tr(\"Information\")\r\n\/\/ , tr(\"Calibrate Kankore position.\"));\r\n QMessageBox msgdlg(this);\r\n msgdlg.setWindowTitle(tr(\"Information\"));\r\n msgdlg.setText(tr(\"Search Kankore position.\\nPlease be performed in the state that it seems the whole of KanColle.\"));\r\n msgdlg.setStandardButtons(QMessageBox::Yes);\r\n msgdlg.addButton(\"No\", QMessageBox::RejectRole);\r\n msgdlg.exec();\r\n qDebug() << \"calib:\" << msgdlg.result();\r\n if(msgdlg.result() != QMessageBox::Yes)\r\n return;\r\n\r\n int set_count = 0;\r\n QImage img(d->ui.webView->size(), QImage::Format_ARGB32);\r\n QPainter painter(&img);\r\n int w = d->ui.webView->size().width();\r\n int h = d->ui.webView->size().height();\r\n QRgb rgb;\r\n\r\n \/\/全体を描画\r\n d->ui.webView->page()->view()->render(&painter);\r\n\r\n \/\/横方向にはじっこを調べる\r\n for(int i=0; i<(w\/2); i++){\r\n rgb = img.pixel(i, h\/2);\r\n if(qGray(rgb) < 250){\r\n qDebug() << \"found X:\" << i << \",\" << (h\/2) << \"\/\" << qGray(rgb)\r\n << \"\/\" << qRed(rgb) << \",\" << qGreen(rgb) << \",\" << qBlue(rgb);\r\n d->flashPos.setX(i);\r\n set_count++;\r\n break;\r\n }\r\n }\r\n \/\/縦方向に端っこを調べる\r\n \/\/ for(int i=h-1; i>=(h\/2); i--){\r\n \/\/ rgb = img.pixel(w\/2, i);\r\n \/\/ if(qGray(rgb) < 250){\r\n \/\/ qDebug() << \"found Y:\" << (w\/2) << \",\" << (i-KANKORE_HEIGHT) << \"\/\" << qGray(rgb)\r\n \/\/ << \"\/\" << qRed(rgb) << \",\" << qGreen(rgb) << \",\" << qBlue(rgb);\r\n \/\/ d->flashPos.setY(i - KANKORE_HEIGHT + 1 - d->scroolPos.y());\r\n \/\/ set_count++;\r\n \/\/ break;\r\n \/\/ }\r\n \/\/ }\r\n for(int i=FLASH_POS_SEARCH_START_Y; iflashPos.setY(i - d->scroolPos.y());\r\n set_count++;\r\n break;\r\n }\r\n }\r\n \/\/キャリブレーション済み\r\n if(set_count == 2){\r\n d->ui.statusBar->showMessage(tr(\"calibration succeded\"), STATUS_BAR_MSG_TIME);\r\n d->finishCalibrated = true;\r\n }else{\r\n d->ui.statusBar->showMessage(tr(\"calibration failed\"), STATUS_BAR_MSG_TIME);\r\n d->finishCalibrated = false;\r\n }\r\n}\r\n\r\n\/\/スクロール状態\r\nvoid MainWindow::scrollRequested(int dx, int dy, const QRect &rectToScroll)\r\n{\r\n Q_UNUSED(dx)\r\n Q_UNUSED(rectToScroll)\r\n \/\/ qDebug() << \"scroll:\" << dx << \",\" << dy << \"\/\" << rectToScroll;\r\n d->scroolPos.setY(d->scroolPos.y() + dy);\r\n \/\/ if(d->scroolPos.y() < 0)\r\n \/\/ d->scroolPos.setY(0);\r\n\r\n qDebug() << \"scroll:\" << d->scroolPos.y();\r\n}\r\ncleanup taking screen shot code\/*\r\n * Copyright 2013 IoriAYANE\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"tweetdialog.h\"\r\n#include \"settingsdialog.h\"\r\n#include \"cookiejar.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \r\n\r\n#define URL_KANCOLLE \"http:\/\/www.dmm.com\/netgame\/social\/-\/gadgets\/=\/app_id=854854\/\"\r\n#define FLASH_POS_SEARCH_START_Y 40 \/\/Flashの位置を探すときにY方向の開始座標(つまりDMMのヘッダを飛ばす)\r\n#define KANCOLLE_WIDTH 800\r\n#define KANCOLLE_HEIGHT 480\r\n\r\n#define SETTING_FILE_NAME \"settings.ini\"\r\n#define SETTING_FILE_FORMAT QSettings::IniFormat\r\n\r\n#define STATUS_BAR_MSG_TIME 5000\r\n\r\nclass MainWindow::Private\r\n{\r\npublic:\r\n Private(MainWindow *parent);\r\n ~Private();\r\n\r\nprivate:\r\n MainWindow *q;\r\n\r\npublic:\r\n Ui::MainWindow ui;\r\n QSettings settings; \/\/設定管理\r\n \/\/設定保存データ\r\n QString savePath; \/\/保存パス\r\n QPoint flashPos; \/\/座標\r\n\r\n \/\/一時データ\r\n QPoint scroolPos; \/\/スクロール量\r\n bool finishCalibrated; \/\/キャリブレーション済み\r\n};\r\n\r\nMainWindow::Private::Private(MainWindow *parent)\r\n : q(parent)\r\n , settings(SETTING_FILE_NAME, SETTING_FILE_FORMAT)\r\n , savePath(settings.value(\"path\", \"\").toString())\r\n , flashPos(settings.value(\"flashPos\", QPoint(0, 0)).toPoint())\r\n , finishCalibrated(settings.value(\"finishCalibrated\", false).toBool())\r\n{\r\n ui.setupUi(q);\r\n ui.webView->page()->networkAccessManager()->setCookieJar(new CookieJar(q));\r\n connect(ui.capture, &QAction::triggered, q, &MainWindow::captureGame);\r\n connect(ui.reload, &QAction::triggered, ui.webView, &QWebView::reload);\r\n connect(ui.exit, &QAction::triggered, q, &MainWindow::close);\r\n connect(ui.adjust, &QAction::triggered, q, &MainWindow::calibration);\r\n\r\n \/\/設定ダイアログ表示\r\n connect(ui.preferences, &QAction::triggered, [this]() {\r\n SettingsDialog dlg(q);\r\n dlg.setSavePath(savePath);\r\n if (dlg.exec()) {\r\n \/\/設定更新\r\n savePath = dlg.savePath();\r\n }\r\n });\r\n\r\n \/\/アバウト\r\n connect(ui.about, &QAction::triggered, [this]() {\r\n QMessageBox::about(q, MainWindow::tr(\"Kan Memo\"), MainWindow::tr(\"Kan Memo -KanMusu Memory-\\n\\nCopyright 2013 IoriAYANE\"));\r\n });\r\n\r\n connect(ui.webView, &QWebView::loadStarted, [this](){\r\n ui.progressBar->show();\r\n });\r\n \/\/WebViewの読込み完了\r\n connect(ui.webView, &QWebView::loadFinished, [this](bool ok) {\r\n if (ok) {\r\n ui.statusBar->showMessage(MainWindow::tr(\"complete\"), STATUS_BAR_MSG_TIME);\r\n } else {\r\n ui.statusBar->showMessage(MainWindow::tr(\"error\"), STATUS_BAR_MSG_TIME);\r\n }\r\n ui.progressBar->hide();\r\n });\r\n\r\n \/\/WebViewの読込み状態\r\n connect(ui.webView, &QWebView::loadProgress, ui.progressBar, &QProgressBar::setValue);\r\n\r\n connect(ui.webView->page(), SIGNAL(scrollRequested(int,int,QRect)), q, SLOT(scrollRequested(int,int,QRect)));\r\n}\r\n\r\nMainWindow::Private::~Private()\r\n{\r\n \/\/設定保存\r\n settings.setValue(\"path\", savePath);\r\n settings.setValue(\"flashPos\", flashPos);\r\n settings.setValue(\"finishCalibrated\", finishCalibrated);\r\n}\r\n\r\nMainWindow::MainWindow(QWidget *parent)\r\n : QMainWindow(parent)\r\n , d(new Private(this))\r\n{\r\n if(d->savePath.length() == 0){\r\n \/\/設定を促す\r\n QMessageBox::information(this\r\n , tr(\"Kan Memo\")\r\n , tr(\"Please select a folder to save the image of KanMusu.\"));\r\n d->savePath = SettingsDialog::selectSavePath(this, QDir::homePath());\r\n }\r\n\r\n \/\/設定\r\n QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);\r\n QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true);\r\n \/\/艦これ読込み\r\n d->ui.webView->load(QUrl(URL_KANCOLLE));\r\n\r\n connect(this, &MainWindow::destroyed, [this]() {delete d;});\r\n}\r\n\r\n\/\/思い出を残す\r\nvoid MainWindow::captureGame()\r\n{\r\n qDebug() << \"captureGame\";\r\n\r\n if(!d->finishCalibrated){\r\n \/\/キャリブレーションされてないので確認して実行\r\n calibration();\r\n }\r\n\r\n \/\/キャリブレーションしてなければ実行しない\r\n if(!d->finishCalibrated){\r\n d->ui.statusBar->showMessage(QString(tr(\"cancel\")), STATUS_BAR_MSG_TIME);\r\n return;\r\n }\r\n\r\n int x = d->flashPos.x() + d->scroolPos.x();\/\/ int((d->ui.webView->size().width()-16) \/ 2) - int(800 \/ 2);\r\n int y = d->flashPos.y() + d->scroolPos.y();\r\n\r\n QImage img(KANCOLLE_WIDTH, KANCOLLE_HEIGHT, QImage::Format_ARGB32);\r\n QPainter painter(&img);\r\n \/\/全体を描画\r\n d->ui.webView->page()->view()->render(&painter, QPoint(0,0), QRegion(x, y, KANCOLLE_WIDTH, KANCOLLE_HEIGHT));\r\n\r\n QString path = QStringLiteral(\"%1\/kanmusu_%2.png\").arg(d->savePath).arg(QDateTime::currentDateTime().toString(QStringLiteral(\"yyyy-MM-dd_hh-mm-ss-zzz\")));\r\n qDebug() << \"path:\" << path;\r\n\r\n \/\/保存する\r\n d->ui.statusBar->showMessage(tr(\"saving to %1...\").arg(path), STATUS_BAR_MSG_TIME);\r\n if(img.save(path)){\r\n \/\/つぶやくダイアログ\r\n TweetDialog dlg(this);\r\n dlg.setImagePath(path);\r\n dlg.setToken(d->settings.value(\"token\", \"\").toString());\r\n dlg.setTokenSecret(d->settings.value(\"tokenSecret\", \"\").toString());\r\n dlg.user_id(d->settings.value(\"user_id\", \"\").toString());\r\n dlg.screen_name(d->settings.value(\"screen_name\", \"\").toString());\r\n dlg.exec();\r\n d->settings.setValue(\"token\", dlg.token());\r\n d->settings.setValue(\"tokenSecret\", dlg.tokenSecret());\r\n d->settings.setValue(\"user_id\", dlg.user_id());\r\n d->settings.setValue(\"screen_name\", dlg.screen_name());\r\n \/\/ d->settings.sync();\r\n\r\n }else{\r\n d->ui.statusBar->showMessage(tr(\"failed\"), STATUS_BAR_MSG_TIME);\r\n }\r\n\r\n}\r\n\/\/キャリブレーション\r\nvoid MainWindow::calibration()\r\n{\r\n qDebug() << \"calibration\";\r\n\r\n\/\/ QMessageBox::information(this\r\n\/\/ , tr(\"Information\")\r\n\/\/ , tr(\"Calibrate Kankore position.\"));\r\n QMessageBox msgdlg(this);\r\n msgdlg.setWindowTitle(tr(\"Information\"));\r\n msgdlg.setText(tr(\"Search Kankore position.\\nPlease be performed in the state that it seems the whole of KanColle.\"));\r\n msgdlg.setStandardButtons(QMessageBox::Yes);\r\n msgdlg.addButton(\"No\", QMessageBox::RejectRole);\r\n msgdlg.exec();\r\n qDebug() << \"calib:\" << msgdlg.result();\r\n if(msgdlg.result() != QMessageBox::Yes)\r\n return;\r\n\r\n int set_count = 0;\r\n QImage img(d->ui.webView->size(), QImage::Format_ARGB32);\r\n QPainter painter(&img);\r\n int w = d->ui.webView->size().width();\r\n int h = d->ui.webView->size().height();\r\n QRgb rgb;\r\n\r\n \/\/全体を描画\r\n d->ui.webView->page()->view()->render(&painter);\r\n\r\n \/\/横方向にはじっこを調べる\r\n for(int i=0; i<(w\/2); i++){\r\n rgb = img.pixel(i, h\/2);\r\n if(qGray(rgb) < 250){\r\n qDebug() << \"found X:\" << i << \",\" << (h\/2) << \"\/\" << qGray(rgb)\r\n << \"\/\" << qRed(rgb) << \",\" << qGreen(rgb) << \",\" << qBlue(rgb);\r\n d->flashPos.setX(i);\r\n set_count++;\r\n break;\r\n }\r\n }\r\n \/\/縦方向に端っこを調べる\r\n \/\/ for(int i=h-1; i>=(h\/2); i--){\r\n \/\/ rgb = img.pixel(w\/2, i);\r\n \/\/ if(qGray(rgb) < 250){\r\n \/\/ qDebug() << \"found Y:\" << (w\/2) << \",\" << (i-KANKORE_HEIGHT) << \"\/\" << qGray(rgb)\r\n \/\/ << \"\/\" << qRed(rgb) << \",\" << qGreen(rgb) << \",\" << qBlue(rgb);\r\n \/\/ d->flashPos.setY(i - KANKORE_HEIGHT + 1 - d->scroolPos.y());\r\n \/\/ set_count++;\r\n \/\/ break;\r\n \/\/ }\r\n \/\/ }\r\n for(int i=FLASH_POS_SEARCH_START_Y; iflashPos.setY(i - d->scroolPos.y());\r\n set_count++;\r\n break;\r\n }\r\n }\r\n \/\/キャリブレーション済み\r\n if(set_count == 2){\r\n d->ui.statusBar->showMessage(tr(\"calibration succeded\"), STATUS_BAR_MSG_TIME);\r\n d->finishCalibrated = true;\r\n }else{\r\n d->ui.statusBar->showMessage(tr(\"calibration failed\"), STATUS_BAR_MSG_TIME);\r\n d->finishCalibrated = false;\r\n }\r\n}\r\n\r\n\/\/スクロール状態\r\nvoid MainWindow::scrollRequested(int dx, int dy, const QRect &rectToScroll)\r\n{\r\n Q_UNUSED(dx)\r\n Q_UNUSED(rectToScroll)\r\n \/\/ qDebug() << \"scroll:\" << dx << \",\" << dy << \"\/\" << rectToScroll;\r\n d->scroolPos.setY(d->scroolPos.y() + dy);\r\n \/\/ if(d->scroolPos.y() < 0)\r\n \/\/ d->scroolPos.setY(0);\r\n\r\n qDebug() << \"scroll:\" << d->scroolPos.y();\r\n}\r\n<|endoftext|>"} {"text":"#define FTS_FUZZY_MATCH_IMPLEMENTATION\n#include \n#include \"mainwindow.h\"\n#include \n#include \n#include \n#include \n#include \n\nWindow::Window(QWidget *parent) : QMainWindow(parent)\n{\n \/\/ Initalise database\n db.setDatabaseName(\"recipes.db\");\n\n \/\/ Initialise widgets\n searchBox = new SearchBox();\n searchBox->setPlaceholderText(\"Search for recipes\");\n recipeBox = new QComboBox();\n QStringList recipeCategories;\n recipeCategories << \"All Recipes\" << \"Beef\" << \"Chicken\" << \"Dessert\" << \"Lamb\" << \"Pork\" << \"Seafood\" << \"Turkey\" << \"Veggie\";\n recipeBox->addItems(recipeCategories);\n createRecipeList();\n numResults = new QLabel();\n recipeView = new QWebEngineView();\n\n \/\/ Set layout\n centralWidget = new QWidget();\n QGridLayout *sidebar = new QGridLayout();\n sidebar->addWidget(searchBox, 0, 0, 1, 2);\n sidebar->addWidget(numResults, 1, 0, 1, 1);\n sidebar->addWidget(recipeBox, 1, 1, 1, 1);\n sidebar->addWidget(recipeList, 2, 0, 1, 2);\n\n QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);\n mainLayout->addLayout(sidebar, 1);\n mainLayout->addWidget(recipeView, 3);\n\n centralWidget->setLayout(mainLayout);\n centralWidget->show();\n setCentralWidget(centralWidget);\n\n \/\/ Create menus\n optionsMenu = new QMenu(\"Options\");\n updateDb = new QAction(\"Update database\", this);\n connect(updateDb, &QAction::triggered, this, &Window::updateDatabase);\n cleanDb = new QAction(\"Clean database\", this);\n connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase);\n optionsMenu->addAction(updateDb);\n optionsMenu->addAction(cleanDb);\n menuBar()->addMenu(optionsMenu);\n\n \/\/ Set window paramters\n setWindowTitle(tr(\"Find Recipes\"));\n setMinimumSize(940, 400);\n\n \/\/ Set signals\n connect(recipeList, &QListWidget::itemClicked, this, &Window::openFile);\n connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString)));\n connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus()));\n connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString)));\n\n \/\/ Update on startup\n updateDatabase();\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; iclear();\n QList recipes;\n\n if (searchText.isEmpty()) {\n recipes = getAllRecipes();\n for (int i=0; iaddItem(recipes[i]);\n }\n recipeList->sortItems();\n\n }else{\n recipes = getMatchingRecipes(searchText);\n for (int i=0; iaddItem(recipes[i]);\n }\n }\n\n recipeList->setDragEnabled(false);\n\n QString text = QString(\"%1 recipes\").arg(recipes.size());\n if (recipes.size() == 1){\n text = \"1 recipe\";\n }\n numResults->setText(text);\n}\n\nQList Window::getAllRecipes(){\n QList recipes;\n\n \/\/ Open database and execute query\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText();\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n while(query.next()){\n \/\/ Extract info from query results\n QString title = query.value(0).toString();\n QString img_path = query.value(1).toString();\n QString html_path = query.value(2).toString();\n\n \/\/ Create QListWidgetItems\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n db.close();\n return recipes;\n}\n\n\nQList Window::getMatchingRecipes(QString searchText){\n QList recipes;\n\n \/\/ Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order.\n std::map matchingRecipes = findMatches(searchText);\n \/\/ Build QListWidgetItems and add to QList\n \/\/ By default the map should be in ascending order, so use reverse iterator to get highest matches first\n for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){\n\n QString title = iter->second[0];\n QString img_path = iter->second[1];\n QString html_path = iter->second[2];\n\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n\n return recipes;\n}\n\nstd::map Window::findMatches(QString text)\n{\n \/\/ Open database\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText();\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n \/\/ Get matching files and their scores\n std::map matchingFiles;\n std::string txtstr = text.toStdString();\n while(query.next()){\n int score;\n QString title = query.value(0).toString();\n QString img_path = query.value(1).toString().replace(\"\\'\", \"\").replace(\",\", \"\");\n QString file_path = query.value(2).toString();\n\n std::string titlestr = title.toStdString();\n if (fts::fuzzy_match(txtstr.c_str(), titlestr.c_str(), score)){\n \/\/ If a map entry already has the current score, increase score by 0.01.\n double dbscore = (double)score;\n if (matchingFiles.count(dbscore) > 0){\n dbscore += 0.01;\n }\n matchingFiles[dbscore] = QStringList() << title << img_path << file_path;\n }\n }\n db.close();\n return matchingFiles;\n}\n\nvoid Window::createRecipeList()\n{\n recipeList = new QListWidget();\n recipeList->setViewMode(QListView::IconMode);\n recipeList->setGridSize(QSize(212, int(212\/1.51)) );\n recipeList->setIconSize(QSize(199, int(199\/1.78)) );\n recipeList->setWordWrap(true);\n recipeList->setTextElideMode(Qt::ElideNone);\n recipeList->horizontalScrollBar()->setEnabled(false);\n recipeList->horizontalScrollBar()->setVisible(false);\n}\n\nvoid Window::openFile(QListWidgetItem *recipe)\n{\n \/\/ Read hidden data to find full file path\n QString path = recipe->data(Qt::UserRole).toString();\n QString url = \"file:\/\/\" + currentDir.absoluteFilePath(path);\n recipeView->load(url);\n}\n\nvoid Window::updateDatabase(){\n int num_updates = db_ops::update_database(&db);\n QString updated_text;\n if (num_updates == 0){\n updated_text = QString(\"Search for recipes\");\n }else{\n updated_text = QString(\"Search for recipes - Updated!\").arg(num_updates);\n }\n searchBox->setPlaceholderText(updated_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::cleanDatabase(){\n int num_removals = db_ops::clean_database(&db);\n QString cleaned_text;\n if (num_removals == 1){\n cleaned_text = QString(\"Search for recipes - Removed 1 recipe!\");\n }else{\n cleaned_text = QString(\"Search for recipes - Removed %1 recipes!\").arg(num_removals);\n }\n searchBox->setPlaceholderText(cleaned_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::resizeEvent(QResizeEvent *event){\n int iconWidth, iconHeight, gridWidth, gridHeight;\n double gridRatio = 1.51;\n double iconRatio = 1.78;\n QSize recipeListSize = recipeList->size();\n\n \/\/ Set gridwith based on recipeList size and ensure it doesn't go below minimum value\n gridWidth = qMax(int(recipeListSize.width()) - 17.0, 212.0);\n \/\/ Calculate other parameters based on ratios of default values.\n gridHeight = int(gridWidth\/gridRatio);\n iconWidth = gridWidth - 13;\n iconHeight = int(iconWidth\/iconRatio);\n\n recipeList->setIconSize(QSize(iconWidth, iconHeight));\n recipeList->setGridSize(QSize(gridWidth, gridHeight));\n recipeList->setUniformItemSizes(true);\n}\n\nDisable javascript in webview, if going to source website. Should block adverts.#define FTS_FUZZY_MATCH_IMPLEMENTATION\n#include \n#include \"mainwindow.h\"\n#include \n#include \n#include \n#include \n#include \n\nWindow::Window(QWidget *parent) : QMainWindow(parent)\n{\n \/\/ Initalise database\n db.setDatabaseName(\"recipes.db\");\n\n \/\/ Initialise widgets\n searchBox = new SearchBox();\n searchBox->setPlaceholderText(\"Search for recipes\");\n recipeBox = new QComboBox();\n QStringList recipeCategories;\n recipeCategories << \"All Recipes\" << \"Beef\" << \"Chicken\" << \"Dessert\" << \"Lamb\" << \"Pork\" << \"Seafood\" << \"Turkey\" << \"Veggie\";\n recipeBox->addItems(recipeCategories);\n createRecipeList();\n numResults = new QLabel();\n recipeView = new QWebEngineView();\n recipeView->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, false);\n\n \/\/ Set layout\n centralWidget = new QWidget();\n QGridLayout *sidebar = new QGridLayout();\n sidebar->addWidget(searchBox, 0, 0, 1, 2);\n sidebar->addWidget(numResults, 1, 0, 1, 1);\n sidebar->addWidget(recipeBox, 1, 1, 1, 1);\n sidebar->addWidget(recipeList, 2, 0, 1, 2);\n\n QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);\n mainLayout->addLayout(sidebar, 1);\n mainLayout->addWidget(recipeView, 3);\n\n centralWidget->setLayout(mainLayout);\n centralWidget->show();\n setCentralWidget(centralWidget);\n\n \/\/ Create menus\n optionsMenu = new QMenu(\"Options\");\n updateDb = new QAction(\"Update database\", this);\n connect(updateDb, &QAction::triggered, this, &Window::updateDatabase);\n cleanDb = new QAction(\"Clean database\", this);\n connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase);\n optionsMenu->addAction(updateDb);\n optionsMenu->addAction(cleanDb);\n menuBar()->addMenu(optionsMenu);\n\n \/\/ Set window paramters\n setWindowTitle(tr(\"Find Recipes\"));\n setMinimumSize(940, 400);\n\n \/\/ Set signals\n connect(recipeList, &QListWidget::itemClicked, this, &Window::openFile);\n connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString)));\n connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus()));\n connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString)));\n\n \/\/ Update on startup\n updateDatabase();\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; iclear();\n QList recipes;\n\n if (searchText.isEmpty()) {\n recipes = getAllRecipes();\n for (int i=0; iaddItem(recipes[i]);\n }\n recipeList->sortItems();\n\n }else{\n recipes = getMatchingRecipes(searchText);\n for (int i=0; iaddItem(recipes[i]);\n }\n }\n\n recipeList->setDragEnabled(false);\n\n QString text = QString(\"%1 recipes\").arg(recipes.size());\n if (recipes.size() == 1){\n text = \"1 recipe\";\n }\n numResults->setText(text);\n}\n\nQList Window::getAllRecipes(){\n QList recipes;\n\n \/\/ Open database and execute query\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText();\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n while(query.next()){\n \/\/ Extract info from query results\n QString title = query.value(0).toString();\n QString img_path = query.value(1).toString();\n QString html_path = query.value(2).toString();\n\n \/\/ Create QListWidgetItems\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n db.close();\n return recipes;\n}\n\n\nQList Window::getMatchingRecipes(QString searchText){\n QList recipes;\n\n \/\/ Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order.\n std::map matchingRecipes = findMatches(searchText);\n \/\/ Build QListWidgetItems and add to QList\n \/\/ By default the map should be in ascending order, so use reverse iterator to get highest matches first\n for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){\n\n QString title = iter->second[0];\n QString img_path = iter->second[1];\n QString html_path = iter->second[2];\n\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n\n return recipes;\n}\n\nstd::map Window::findMatches(QString text)\n{\n \/\/ Open database\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText();\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"select TITLE, IMG_PATH, HTML_PATH from RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n \/\/ Get matching files and their scores\n std::map matchingFiles;\n std::string txtstr = text.toStdString();\n while(query.next()){\n int score;\n QString title = query.value(0).toString();\n QString img_path = query.value(1).toString().replace(\"\\'\", \"\").replace(\",\", \"\");\n QString file_path = query.value(2).toString();\n\n std::string titlestr = title.toStdString();\n if (fts::fuzzy_match(txtstr.c_str(), titlestr.c_str(), score)){\n \/\/ If a map entry already has the current score, increase score by 0.01.\n double dbscore = (double)score;\n if (matchingFiles.count(dbscore) > 0){\n dbscore += 0.01;\n }\n matchingFiles[dbscore] = QStringList() << title << img_path << file_path;\n }\n }\n db.close();\n return matchingFiles;\n}\n\nvoid Window::createRecipeList()\n{\n recipeList = new QListWidget();\n recipeList->setViewMode(QListView::IconMode);\n recipeList->setGridSize(QSize(212, int(212\/1.51)) );\n recipeList->setIconSize(QSize(199, int(199\/1.78)) );\n recipeList->setWordWrap(true);\n recipeList->setTextElideMode(Qt::ElideNone);\n recipeList->horizontalScrollBar()->setEnabled(false);\n recipeList->horizontalScrollBar()->setVisible(false);\n}\n\nvoid Window::openFile(QListWidgetItem *recipe)\n{\n \/\/ Read hidden data to find full file path\n QString path = recipe->data(Qt::UserRole).toString();\n QString url = \"file:\/\/\" + currentDir.absoluteFilePath(path);\n recipeView->load(url);\n}\n\nvoid Window::updateDatabase(){\n int num_updates = db_ops::update_database(&db);\n QString updated_text;\n if (num_updates == 0){\n updated_text = QString(\"Search for recipes\");\n }else{\n updated_text = QString(\"Search for recipes - Updated!\").arg(num_updates);\n }\n searchBox->setPlaceholderText(updated_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::cleanDatabase(){\n int num_removals = db_ops::clean_database(&db);\n QString cleaned_text;\n if (num_removals == 1){\n cleaned_text = QString(\"Search for recipes - Removed 1 recipe!\");\n }else{\n cleaned_text = QString(\"Search for recipes - Removed %1 recipes!\").arg(num_removals);\n }\n searchBox->setPlaceholderText(cleaned_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::resizeEvent(QResizeEvent *event){\n int iconWidth, iconHeight, gridWidth, gridHeight;\n double gridRatio = 1.51;\n double iconRatio = 1.78;\n QSize recipeListSize = recipeList->size();\n\n \/\/ Set gridwith based on recipeList size and ensure it doesn't go below minimum value\n gridWidth = qMax(int(recipeListSize.width()) - 17.0, 212.0);\n \/\/ Calculate other parameters based on ratios of default values.\n gridHeight = int(gridWidth\/gridRatio);\n iconWidth = gridWidth - 13;\n iconHeight = int(iconWidth\/iconRatio);\n\n recipeList->setIconSize(QSize(iconWidth, iconHeight));\n recipeList->setGridSize(QSize(gridWidth, gridHeight));\n recipeList->setUniformItemSizes(true);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_loop.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"ui\/views\/controls\/tabbed_pane\/tabbed_pane.h\"\n#include \"ui\/views\/test\/views_test_base.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\nnamespace views {\n\n\/\/ A view for testing that takes a fixed preferred size upon construction.\nclass FixedSizeView : public View {\n public:\n explicit FixedSizeView(const gfx::Size& size)\n : size_(size) {}\n\n \/\/ Overridden from View:\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return size_;\n }\n\n private:\n const gfx::Size size_;\n\n DISALLOW_COPY_AND_ASSIGN(FixedSizeView);\n};\n\nclass TabbedPaneTest : public ViewsTestBase {\n public:\n TabbedPaneTest() {}\n\n void TestSizeAndLayout(TabbedPane* tabbed_pane);\n\n void TestAddRemove(TabbedPane* tabbed_pane);\n\n TabbedPane* tabbed_pane_; \/\/ Owned by the |widget_|'s root View.\n\n#if defined(OS_WIN) && !defined(USE_AURA)\n TabbedPane* tabbed_pane_win_; \/\/ Owned by the |widget_|'s root View.\n#endif\n\n private:\n virtual void SetUp() OVERRIDE;\n\n scoped_ptr widget_;\n\n DISALLOW_COPY_AND_ASSIGN(TabbedPaneTest);\n};\n\nvoid TabbedPaneTest::SetUp() {\n ViewsTestBase::SetUp();\n widget_.reset(new Widget());\n Widget::InitParams params(Widget::InitParams::TYPE_POPUP);\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.bounds = gfx::Rect(0, 0, 100, 100);\n widget_->Init(params);\n tabbed_pane_ = new TabbedPane();\n \/\/ In order to properly initialize the |TabbedPane| it must be added to a\n \/\/ parent view (see the ViewHierarchyChanged method of the |TabbedPane|).\n widget_->GetRootView()->AddChildView(tabbed_pane_);\n\n#if defined(OS_WIN) && !defined(USE_AURA)\n tabbed_pane_win_ = new TabbedPane();\n tabbed_pane_win_->set_use_native_win_control(true);\n widget_->GetRootView()->AddChildView(tabbed_pane_win_);\n#endif\n}\n\nvoid TabbedPaneTest::TestSizeAndLayout(TabbedPane* tabbed_pane) {\n View* child1 = new FixedSizeView(gfx::Size(20, 10));\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab1\"), child1);\n View* child2 = new FixedSizeView(gfx::Size(5, 5));\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab2\"), child2);\n tabbed_pane->SelectTabAt(0);\n\n \/\/ The |tabbed_pane_| implementation of Views has no border by default.\n \/\/ Therefore it should be as wide as the widest tab. The native Windows\n \/\/ tabbed pane has a border that used up extra space. Therefore the preferred\n \/\/ width is larger than the largest child.\n gfx::Size pref(tabbed_pane->GetPreferredSize());\n EXPECT_GE(pref.width(), 20);\n EXPECT_GT(pref.height(), 10);\n\n \/\/ The bounds of our children should be smaller than the tabbed pane's bounds.\n tabbed_pane->SetBounds(0, 0, 100, 200);\n RunPendingMessages();\n gfx::Rect bounds(child1->bounds());\n EXPECT_GT(bounds.width(), 0);\n \/\/ The |tabbed_pane_| has no border. Therefore the children should be as wide\n \/\/ as the |tabbed_pane_|.\n EXPECT_LE(bounds.width(), 100);\n EXPECT_GT(bounds.height(), 0);\n EXPECT_LT(bounds.height(), 200);\n\n \/\/ If we switch to the other tab, it should get assigned the same bounds.\n tabbed_pane->SelectTabAt(1);\n EXPECT_EQ(bounds, child2->bounds());\n}\n\nvoid TabbedPaneTest::TestAddRemove(TabbedPane* tabbed_pane) {\n View* tab0 = new View;\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab0\"), tab0);\n EXPECT_EQ(tab0, tabbed_pane->GetSelectedTab());\n EXPECT_EQ(0, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Add more 3 tabs.\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab1\"), new View);\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab2\"), new View);\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab3\"), new View);\n EXPECT_EQ(4, tabbed_pane->GetTabCount());\n\n \/\/ Note: AddTab() doesn't select a tab if the tabbed pane isn't empty.\n\n \/\/ Select the last one.\n tabbed_pane->SelectTabAt(tabbed_pane->GetTabCount() - 1);\n EXPECT_EQ(3, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Remove the last one.\n delete tabbed_pane->RemoveTabAtIndex(3);\n EXPECT_EQ(3, tabbed_pane->GetTabCount());\n\n \/\/ After removing the last tab, check if the tabbed pane selected the previous\n \/\/ tab.\n EXPECT_EQ(2, tabbed_pane->GetSelectedTabIndex());\n\n tabbed_pane->AddTabAtIndex(0, ASCIIToUTF16(\"tab4\"), new View, true);\n\n \/\/ Assert that even adding a new tab, the tabbed pane doesn't change the\n \/\/ selection, i.e., it doesn't select the new one.\n \/\/ The last tab should remains selected, instead of the tab added at index 0.\n EXPECT_EQ(3, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Now change the selected tab.\n tabbed_pane->SelectTabAt(1);\n EXPECT_EQ(1, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Remove the first one.\n delete tabbed_pane->RemoveTabAtIndex(0);\n EXPECT_EQ(0, tabbed_pane->GetSelectedTabIndex());\n}\n\n\/\/ Tests TabbedPane::GetPreferredSize() and TabbedPane::Layout().\nTEST_F(TabbedPaneTest, SizeAndLayout) {\n TestSizeAndLayout(tabbed_pane_);\n \/\/ TODO(markusheintz): Once replacing NativeTabbedPaneWin with\n \/\/ NativeTabbedPaneView is completed (http:\/\/crbug.com\/138059), then the\n \/\/ TestSizeAndLayout method should be inlined here again and the \"ifdef\" part\n \/\/ should be deleted.\n#if defined(OS_WIN) && !defined(USE_AURA)\n TestSizeAndLayout(tabbed_pane_win_);\n#endif\n}\n\nTEST_F(TabbedPaneTest, AddRemove) {\n TestAddRemove(tabbed_pane_);\n \/\/ TODO(markusheintz): Once replacing NativeTabbedPaneWin with\n \/\/ NativeTabbedPaneView is completed (http:\/\/crbug.com\/138059), then the\n \/\/ TestAddRemove method should be inlined here again and the \"ifdef\" part\n \/\/ should be deleted.\n#if defined(OS_WIN) && !defined(USE_AURA)\n TestAddRemove(tabbed_pane_win_);\n#endif\n}\n\n} \/\/ namespace views\nValgrind\/Heapchecker: Fix leaks in TabbedPaneTest.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_loop.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"ui\/views\/controls\/tabbed_pane\/tabbed_pane.h\"\n#include \"ui\/views\/test\/views_test_base.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\nnamespace views {\n\n\/\/ A view for testing that takes a fixed preferred size upon construction.\nclass FixedSizeView : public View {\n public:\n explicit FixedSizeView(const gfx::Size& size)\n : size_(size) {}\n\n \/\/ Overridden from View:\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return size_;\n }\n\n private:\n const gfx::Size size_;\n\n DISALLOW_COPY_AND_ASSIGN(FixedSizeView);\n};\n\nclass TabbedPaneTest : public ViewsTestBase {\n public:\n TabbedPaneTest() {}\n\n void TestSizeAndLayout(TabbedPane* tabbed_pane);\n\n void TestAddRemove(TabbedPane* tabbed_pane);\n\n TabbedPane* tabbed_pane_; \/\/ Owned by the |widget_|'s root View.\n\n#if defined(OS_WIN) && !defined(USE_AURA)\n TabbedPane* tabbed_pane_win_; \/\/ Owned by the |widget_|'s root View.\n#endif\n\n private:\n virtual void SetUp() OVERRIDE;\n\n scoped_ptr widget_;\n\n DISALLOW_COPY_AND_ASSIGN(TabbedPaneTest);\n};\n\nvoid TabbedPaneTest::SetUp() {\n ViewsTestBase::SetUp();\n widget_.reset(new Widget());\n Widget::InitParams params(Widget::InitParams::TYPE_POPUP);\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.bounds = gfx::Rect(0, 0, 100, 100);\n widget_->Init(params);\n tabbed_pane_ = new TabbedPane();\n \/\/ In order to properly initialize the |TabbedPane| it must be added to a\n \/\/ parent view (see the ViewHierarchyChanged method of the |TabbedPane|).\n widget_->GetRootView()->AddChildView(tabbed_pane_);\n\n#if defined(OS_WIN) && !defined(USE_AURA)\n tabbed_pane_win_ = new TabbedPane();\n tabbed_pane_win_->set_use_native_win_control(true);\n widget_->GetRootView()->AddChildView(tabbed_pane_win_);\n#endif\n}\n\nvoid TabbedPaneTest::TestSizeAndLayout(TabbedPane* tabbed_pane) {\n View* child1 = new FixedSizeView(gfx::Size(20, 10));\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab1\"), child1);\n View* child2 = new FixedSizeView(gfx::Size(5, 5));\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab2\"), child2);\n tabbed_pane->SelectTabAt(0);\n\n \/\/ The |tabbed_pane_| implementation of Views has no border by default.\n \/\/ Therefore it should be as wide as the widest tab. The native Windows\n \/\/ tabbed pane has a border that used up extra space. Therefore the preferred\n \/\/ width is larger than the largest child.\n gfx::Size pref(tabbed_pane->GetPreferredSize());\n EXPECT_GE(pref.width(), 20);\n EXPECT_GT(pref.height(), 10);\n\n \/\/ The bounds of our children should be smaller than the tabbed pane's bounds.\n tabbed_pane->SetBounds(0, 0, 100, 200);\n RunPendingMessages();\n gfx::Rect bounds(child1->bounds());\n EXPECT_GT(bounds.width(), 0);\n \/\/ The |tabbed_pane_| has no border. Therefore the children should be as wide\n \/\/ as the |tabbed_pane_|.\n EXPECT_LE(bounds.width(), 100);\n EXPECT_GT(bounds.height(), 0);\n EXPECT_LT(bounds.height(), 200);\n\n \/\/ If we switch to the other tab, it should get assigned the same bounds.\n tabbed_pane->SelectTabAt(1);\n EXPECT_EQ(bounds, child2->bounds());\n\n \/\/ Clean up.\n delete tabbed_pane->RemoveTabAtIndex(0);\n EXPECT_EQ(1, tabbed_pane->GetTabCount());\n delete tabbed_pane->RemoveTabAtIndex(0);\n EXPECT_EQ(0, tabbed_pane->GetTabCount());\n}\n\nvoid TabbedPaneTest::TestAddRemove(TabbedPane* tabbed_pane) {\n View* tab0 = new View;\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab0\"), tab0);\n EXPECT_EQ(tab0, tabbed_pane->GetSelectedTab());\n EXPECT_EQ(0, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Add more 3 tabs.\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab1\"), new View);\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab2\"), new View);\n tabbed_pane->AddTab(ASCIIToUTF16(\"tab3\"), new View);\n EXPECT_EQ(4, tabbed_pane->GetTabCount());\n\n \/\/ Note: AddTab() doesn't select a tab if the tabbed pane isn't empty.\n\n \/\/ Select the last one.\n tabbed_pane->SelectTabAt(tabbed_pane->GetTabCount() - 1);\n EXPECT_EQ(3, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Remove the last one.\n delete tabbed_pane->RemoveTabAtIndex(3);\n EXPECT_EQ(3, tabbed_pane->GetTabCount());\n\n \/\/ After removing the last tab, check if the tabbed pane selected the previous\n \/\/ tab.\n EXPECT_EQ(2, tabbed_pane->GetSelectedTabIndex());\n\n tabbed_pane->AddTabAtIndex(0, ASCIIToUTF16(\"tab4\"), new View, true);\n\n \/\/ Assert that even adding a new tab, the tabbed pane doesn't change the\n \/\/ selection, i.e., it doesn't select the new one.\n \/\/ The last tab should remains selected, instead of the tab added at index 0.\n EXPECT_EQ(3, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Now change the selected tab.\n tabbed_pane->SelectTabAt(1);\n EXPECT_EQ(1, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Remove the first one.\n delete tabbed_pane->RemoveTabAtIndex(0);\n EXPECT_EQ(0, tabbed_pane->GetSelectedTabIndex());\n\n \/\/ Clean up the other panes.\n EXPECT_EQ(3, tabbed_pane->GetTabCount());\n delete tabbed_pane->RemoveTabAtIndex(0);\n delete tabbed_pane->RemoveTabAtIndex(0);\n delete tabbed_pane->RemoveTabAtIndex(0);\n EXPECT_EQ(0, tabbed_pane->GetTabCount());\n}\n\n\/\/ Tests TabbedPane::GetPreferredSize() and TabbedPane::Layout().\nTEST_F(TabbedPaneTest, SizeAndLayout) {\n TestSizeAndLayout(tabbed_pane_);\n \/\/ TODO(markusheintz): Once replacing NativeTabbedPaneWin with\n \/\/ NativeTabbedPaneView is completed (http:\/\/crbug.com\/138059), then the\n \/\/ TestSizeAndLayout method should be inlined here again and the \"ifdef\" part\n \/\/ should be deleted.\n#if defined(OS_WIN) && !defined(USE_AURA)\n TestSizeAndLayout(tabbed_pane_win_);\n#endif\n}\n\nTEST_F(TabbedPaneTest, AddRemove) {\n TestAddRemove(tabbed_pane_);\n \/\/ TODO(markusheintz): Once replacing NativeTabbedPaneWin with\n \/\/ NativeTabbedPaneView is completed (http:\/\/crbug.com\/138059), then the\n \/\/ TestAddRemove method should be inlined here again and the \"ifdef\" part\n \/\/ should be deleted.\n#if defined(OS_WIN) && !defined(USE_AURA)\n TestAddRemove(tabbed_pane_win_);\n#endif\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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 \".\/cyber_topology_message.h\"\n#include \".\/general_channel_message.h\"\n#include \".\/screen.h\"\n\n#include \"cyber\/message\/message_traits.h\"\n#include \"cyber\/proto\/topology_change.pb.h\"\n#include \"cyber\/proto\/role_attributes.pb.h\"\n\n#include \n#include \n#include \n\nconstexpr int SecondColumnOffset = 4;\n\nCyberTopologyMessage::CyberTopologyMessage(const std::string& channel)\n : RenderableMessage(nullptr, 1),\n second_column_(SecondColumnType::MessageFrameRatio),\n pid_(getpid()),\n col1_width_(8),\n specified_channel_(channel),\n all_channels_map_() {}\n\nCyberTopologyMessage::~CyberTopologyMessage(void) {\n for (auto item : all_channels_map_) {\n if (!GeneralChannelMessage::isErrorCode(item.second)) {\n delete item.second;\n }\n }\n}\n\nbool CyberTopologyMessage::isFromHere(const std::string& nodeName) {\n std::ostringstream outStr;\n outStr << \"MonitorReader\" << pid_;\n\n std::string templateName = outStr.str();\n const std::string baseName = nodeName.substr(0, templateName.size());\n\n return (templateName.compare(baseName) == 0);\n}\n\nRenderableMessage* CyberTopologyMessage::Child(int lineNo) const {\n RenderableMessage* ret = nullptr;\n auto iter = findChild(lineNo);\n if (!GeneralChannelMessage::isErrorCode(iter->second) && \n iter->second->is_enabled()) {\n ret = iter->second;\n }\n return ret;\n}\n\nstd::map::const_iterator CyberTopologyMessage::findChild(int lineNo) const{\n --lineNo;\n\n std::map::const_iterator ret = all_channels_map_.cend();\n\n if (lineNo > -1 && lineNo < page_item_count_) {\n int i = 0;\n\n auto iter = all_channels_map_.cbegin();\n while (i < page_index_ * page_item_count_) {\n ++iter;\n ++i;\n }\n\n for (i = 0; iter != all_channels_map_.cend(); ++iter) {\n if (i == lineNo) {\n ret = iter;\n break;\n }\n ++i;\n }\n }\n return ret;\n}\n\nvoid CyberTopologyMessage::TopologyChanged(\n const apollo::cyber::proto::ChangeMsg& changeMsg) {\n if (::apollo::cyber::proto::OperateType::OPT_JOIN ==\n changeMsg.operate_type()) {\n bool isWriter = true;\n if (::apollo::cyber::proto::RoleType::ROLE_READER ==\n changeMsg.role_type())\n isWriter = false;\n AddReaderWriter(changeMsg.role_attr(), isWriter);\n } else {\n auto iter = all_channels_map_.find(changeMsg.role_attr().channel_name());\n\n if (iter != all_channels_map_.cend() &&\n !GeneralChannelMessage::isErrorCode(iter->second)) {\n const std::string& nodeName = changeMsg.role_attr().node_name();\n if (::apollo::cyber::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n iter->second->del_writer(nodeName);\n } else {\n iter->second->del_reader(nodeName);\n }\n }\n }\n}\n\nvoid CyberTopologyMessage::AddReaderWriter(\n const apollo::cyber::proto::RoleAttributes& role, bool isWriter) {\n const std::string& channelName = role.channel_name();\n\n if (!specified_channel_.empty() && specified_channel_ != channelName) {\n return;\n }\n\n if (static_cast(channelName.length()) > col1_width_) {\n col1_width_ = static_cast(channelName.length());\n }\n\n const std::string& nodeName = role.node_name();\n if (isFromHere(nodeName)) {\n return;\n }\n\n GeneralChannelMessage* channelMsg = nullptr;\n const std::string& msgTypeName = role.message_type();\n auto iter = all_channels_map_.find(channelName);\n if (iter == all_channels_map_.cend()) {\n static int index = 0;\n\n std::ostringstream outStr;\n outStr << \"MonitorReader\" << pid_ << '-' << index++;\n\n channelMsg = new GeneralChannelMessage(outStr.str(), this);\n\n if(channelMsg != nullptr){\n if (!GeneralChannelMessage::isErrorCode(channelMsg->OpenChannel(channelName))) {\n channelMsg->set_message_type(msgTypeName);\n channelMsg->add_reader(channelMsg->NodeName());\n }\n } else {\n channelMsg = GeneralChannelMessage::castErrorCode2Ptr(GeneralChannelMessage::ErrorCode::NewSubClassFailed);\n }\n all_channels_map_[channelName] = channelMsg;\n } else {\n channelMsg = iter->second;\n }\n\n if (!GeneralChannelMessage::isErrorCode(channelMsg)) {\n if (isWriter) {\n if (msgTypeName != apollo::cyber::message::MessageType<\n apollo::cyber::message::RawMessage>()) {\n channelMsg->set_message_type(msgTypeName);\n }\n\n channelMsg->add_writer(nodeName);\n } else {\n channelMsg->add_reader(nodeName);\n }\n }\n}\n\nvoid CyberTopologyMessage::ChangeState(const Screen* s, int key) {\n switch (key) {\n case 'f':\n case 'F':\n second_column_ = SecondColumnType::MessageFrameRatio;\n break;\n\n case 't':\n case 'T':\n second_column_ = SecondColumnType::MessageType;\n break;\n\n case ' ': {\n auto iter = findChild(*line_no());\n if (!GeneralChannelMessage::isErrorCode(iter->second)) {\n GeneralChannelMessage* child = iter->second;\n if(child->is_enabled()){\n child->CloseChannel();\n } else {\n GeneralChannelMessage* ret = child->OpenChannel(iter->first);\n if(GeneralChannelMessage::isErrorCode(ret)){\n delete child;\n all_channels_map_[iter->first] = ret;\n } else {\n child->add_reader(child->NodeName());\n }\n }\n }\n }\n\n default: {}\n }\n}\n\nvoid CyberTopologyMessage::Render(const Screen* s, int key) {\n page_item_count_ = s->Height() - 1;\n pages_ = static_cast(all_channels_map_.size()) \/ page_item_count_ + 1;\n ChangeState(s, key);\n SplitPages(key);\n\n s->AddStr(0, 0, Screen::WHITE_BLACK, \"Channels\");\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, 0, Screen::WHITE_BLACK,\n \"TypeName\");\n break;\n case SecondColumnType::MessageFrameRatio:\n s->AddStr(col1_width_ + SecondColumnOffset, 0, Screen::WHITE_BLACK,\n \"FrameRatio\");\n break;\n }\n\n auto iter = all_channels_map_.cbegin();\n register int tmp = page_index_ * page_item_count_;\n register int line = 0;\n while (line < tmp) {\n ++iter;\n ++line;\n }\n\n Screen::ColorPair color;\n std::ostringstream outStr;\n\n tmp = page_item_count_ + 1;\n for (line = 1; iter != all_channels_map_.cend() && line < tmp;\n ++iter, ++line) {\n color = Screen::RED_BLACK;\n\n if (!GeneralChannelMessage::isErrorCode(iter->second)) {\n if (iter->second->has_message_come()) {\n if (iter->second->is_enabled()) {\n color = Screen::GREEN_BLACK;\n } else {\n color = Screen::YELLOW_BLACK;\n }\n }\n }\n\n s->SetCurrentColor(color);\n s->AddStr(0, line, iter->first.c_str());\n\n if (!GeneralChannelMessage::isErrorCode(iter->second)) {\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, line,\n iter->second->message_type().c_str());\n break;\n case SecondColumnType::MessageFrameRatio: {\n outStr.str(\"\");\n outStr << std::fixed << std::setprecision(GeneralChannelMessage::FrameRatio_Precision)\n << iter->second->frame_ratio();\n s->AddStr(col1_width_ + SecondColumnOffset, line,\n outStr.str().c_str());\n } break;\n }\n } else {\n GeneralChannelMessage::ErrorCode errcode =\n GeneralChannelMessage::castPtr2ErrorCode(iter->second);\n s->AddStr(col1_width_ + SecondColumnOffset, line,\n GeneralChannelMessage::errCode2Str(errcode));\n }\n s->ClearCurrentColor();\n }\n}\nFramework: delete the redundant code, adjust frame ratio for UI\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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 \".\/cyber_topology_message.h\"\n#include \".\/general_channel_message.h\"\n#include \".\/screen.h\"\n\n#include \"cyber\/message\/message_traits.h\"\n#include \"cyber\/proto\/topology_change.pb.h\"\n#include \"cyber\/proto\/role_attributes.pb.h\"\n\n#include \n#include \n#include \n\nconstexpr int SecondColumnOffset = 4;\n\nCyberTopologyMessage::CyberTopologyMessage(const std::string& channel)\n : RenderableMessage(nullptr, 1),\n second_column_(SecondColumnType::MessageFrameRatio),\n pid_(getpid()),\n col1_width_(8),\n specified_channel_(channel),\n all_channels_map_() {}\n\nCyberTopologyMessage::~CyberTopologyMessage(void) {\n for (auto item : all_channels_map_) {\n if (!GeneralChannelMessage::isErrorCode(item.second)) {\n delete item.second;\n }\n }\n}\n\nbool CyberTopologyMessage::isFromHere(const std::string& nodeName) {\n std::ostringstream outStr;\n outStr << \"MonitorReader\" << pid_;\n\n std::string templateName = outStr.str();\n const std::string baseName = nodeName.substr(0, templateName.size());\n\n return (templateName.compare(baseName) == 0);\n}\n\nRenderableMessage* CyberTopologyMessage::Child(int lineNo) const {\n RenderableMessage* ret = nullptr;\n auto iter = findChild(lineNo);\n if (!GeneralChannelMessage::isErrorCode(iter->second) && \n iter->second->is_enabled()) {\n ret = iter->second;\n }\n return ret;\n}\n\nstd::map::const_iterator CyberTopologyMessage::findChild(int lineNo) const{\n --lineNo;\n\n std::map::const_iterator ret = all_channels_map_.cend();\n\n if (lineNo > -1 && lineNo < page_item_count_) {\n int i = 0;\n\n auto iter = all_channels_map_.cbegin();\n while (i < page_index_ * page_item_count_) {\n ++iter;\n ++i;\n }\n\n for (i = 0; iter != all_channels_map_.cend(); ++iter) {\n if (i == lineNo) {\n ret = iter;\n break;\n }\n ++i;\n }\n }\n return ret;\n}\n\nvoid CyberTopologyMessage::TopologyChanged(\n const apollo::cyber::proto::ChangeMsg& changeMsg) {\n if (::apollo::cyber::proto::OperateType::OPT_JOIN ==\n changeMsg.operate_type()) {\n bool isWriter = true;\n if (::apollo::cyber::proto::RoleType::ROLE_READER ==\n changeMsg.role_type())\n isWriter = false;\n AddReaderWriter(changeMsg.role_attr(), isWriter);\n } else {\n auto iter = all_channels_map_.find(changeMsg.role_attr().channel_name());\n\n if (iter != all_channels_map_.cend() &&\n !GeneralChannelMessage::isErrorCode(iter->second)) {\n const std::string& nodeName = changeMsg.role_attr().node_name();\n if (::apollo::cyber::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n iter->second->del_writer(nodeName);\n } else {\n iter->second->del_reader(nodeName);\n }\n }\n }\n}\n\nvoid CyberTopologyMessage::AddReaderWriter(\n const apollo::cyber::proto::RoleAttributes& role, bool isWriter) {\n const std::string& channelName = role.channel_name();\n\n if (!specified_channel_.empty() && specified_channel_ != channelName) {\n return;\n }\n\n if (static_cast(channelName.length()) > col1_width_) {\n col1_width_ = static_cast(channelName.length());\n }\n\n const std::string& nodeName = role.node_name();\n if (isFromHere(nodeName)) {\n return;\n }\n\n GeneralChannelMessage* channelMsg = nullptr;\n const std::string& msgTypeName = role.message_type();\n auto iter = all_channels_map_.find(channelName);\n if (iter == all_channels_map_.cend()) {\n static int index = 0;\n\n std::ostringstream outStr;\n outStr << \"MonitorReader\" << pid_ << '-' << index++;\n\n channelMsg = new GeneralChannelMessage(outStr.str(), this);\n\n if(channelMsg != nullptr){\n if (!GeneralChannelMessage::isErrorCode(channelMsg->OpenChannel(channelName))) {\n channelMsg->set_message_type(msgTypeName);\n channelMsg->add_reader(channelMsg->NodeName());\n }\n } else {\n channelMsg = GeneralChannelMessage::castErrorCode2Ptr(GeneralChannelMessage::ErrorCode::NewSubClassFailed);\n }\n all_channels_map_[channelName] = channelMsg;\n } else {\n channelMsg = iter->second;\n }\n\n if (!GeneralChannelMessage::isErrorCode(channelMsg)) {\n if (isWriter) {\n if (msgTypeName != apollo::cyber::message::MessageType<\n apollo::cyber::message::RawMessage>()) {\n channelMsg->set_message_type(msgTypeName);\n }\n\n channelMsg->add_writer(nodeName);\n } else {\n channelMsg->add_reader(nodeName);\n }\n }\n}\n\nvoid CyberTopologyMessage::ChangeState(const Screen* s, int key) {\n switch (key) {\n case 'f':\n case 'F':\n second_column_ = SecondColumnType::MessageFrameRatio;\n break;\n\n case 't':\n case 'T':\n second_column_ = SecondColumnType::MessageType;\n break;\n\n case ' ': {\n auto iter = findChild(*line_no());\n if (!GeneralChannelMessage::isErrorCode(iter->second)) {\n GeneralChannelMessage* child = iter->second;\n if(child->is_enabled()){\n child->CloseChannel();\n } else {\n GeneralChannelMessage* ret = child->OpenChannel(iter->first);\n if(GeneralChannelMessage::isErrorCode(ret)){\n delete child;\n all_channels_map_[iter->first] = ret;\n } else {\n child->add_reader(child->NodeName());\n }\n }\n }\n }\n\n default: {}\n }\n}\n\nvoid CyberTopologyMessage::Render(const Screen* s, int key) {\n page_item_count_ = s->Height() - 1;\n pages_ = static_cast(all_channels_map_.size()) \/ page_item_count_ + 1;\n ChangeState(s, key);\n SplitPages(key);\n\n s->AddStr(0, 0, Screen::WHITE_BLACK, \"Channels\");\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, 0, Screen::WHITE_BLACK,\n \"TypeName\");\n break;\n case SecondColumnType::MessageFrameRatio:\n s->AddStr(col1_width_ + SecondColumnOffset, 0, Screen::WHITE_BLACK,\n \"FrameRatio\");\n break;\n }\n\n auto iter = all_channels_map_.cbegin();\n register int tmp = page_index_ * page_item_count_;\n register int line = 0;\n while (line < tmp) {\n ++iter;\n ++line;\n }\n\n Screen::ColorPair color;\n std::ostringstream outStr;\n\n tmp = page_item_count_ + 1;\n for (line = 1; iter != all_channels_map_.cend() && line < tmp;\n ++iter, ++line) {\n color = Screen::RED_BLACK;\n\n if (!GeneralChannelMessage::isErrorCode(iter->second)) {\n if (iter->second->has_message_come()) {\n if (iter->second->is_enabled()) {\n color = Screen::GREEN_BLACK;\n } else {\n color = Screen::YELLOW_BLACK;\n }\n }\n }\n\n s->SetCurrentColor(color);\n s->AddStr(0, line, iter->first.c_str());\n\n if (!GeneralChannelMessage::isErrorCode(iter->second)) {\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, line,\n iter->second->message_type().c_str());\n break;\n case SecondColumnType::MessageFrameRatio: {\n outStr.str(\"\");\n outStr << std::fixed << std::setprecision(FrameRatio_Precision)\n << iter->second->frame_ratio();\n s->AddStr(col1_width_ + SecondColumnOffset, line,\n outStr.str().c_str());\n } break;\n }\n } else {\n GeneralChannelMessage::ErrorCode errcode =\n GeneralChannelMessage::castPtr2ErrorCode(iter->second);\n s->AddStr(col1_width_ + SecondColumnOffset, line,\n GeneralChannelMessage::errCode2Str(errcode));\n }\n s->ClearCurrentColor();\n }\n}\n<|endoftext|>"} {"text":"#include \"drawer.hpp\"\n#include \"proto_to_styles.hpp\"\n\n#include \"..\/std\/bind.hpp\"\n\n#include \"..\/indexer\/drawing_rules.hpp\"\n#include \"..\/indexer\/scales.hpp\"\n\n#include \"..\/graphics\/defines.hpp\"\n#include \"..\/graphics\/screen.hpp\"\n#include \"..\/graphics\/resource_manager.hpp\"\n\n#include \"..\/geometry\/screenbase.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n#include \"..\/base\/buffer_vector.hpp\"\n\nDrawer::Params::Params()\n : m_visualScale(1)\n{\n}\n\ndi::DrawInfo::DrawInfo(string const & name,\n string const & secondaryName,\n string const & road,\n double rank)\n : m_name(name),\n m_secondaryName(secondaryName),\n m_road(road),\n m_rank(rank)\n{}\n\nstring const di::DrawInfo::GetPathName() const\n{\n if (m_secondaryName.empty())\n return m_name;\n else\n return m_name + \" \" + m_secondaryName;\n}\n\nuint32_t di::DrawRule::GetID(size_t threadSlot) const\n{\n return (m_transparent ? m_rule->GetID2(threadSlot) : m_rule->GetID(threadSlot));\n}\n\nvoid di::DrawRule::SetID(size_t threadSlot, uint32_t id) const\n{\n m_transparent ? m_rule->SetID2(threadSlot, id) : m_rule->SetID(threadSlot, id);\n}\n\nDrawer::Drawer(Params const & params)\n : m_visualScale(params.m_visualScale)\n{\n m_pScreen = shared_ptr(new graphics::Screen(params));\n\n for (unsigned i = 0; i < m_pScreen->pipelinesCount(); ++i)\n m_pScreen->addClearPageFn(i, bind(&Drawer::ClearResourceCache, ThreadSlot(), i), 0);\n}\n\nnamespace\n{\n struct DoMakeInvalidRule\n {\n size_t m_threadSlot;\n uint32_t m_pipelineIDMask;\n\n DoMakeInvalidRule(size_t threadSlot, uint8_t pipelineID)\n : m_threadSlot(threadSlot), m_pipelineIDMask(pipelineID << 24)\n {}\n\n void operator() (int, int, int, drule::BaseRule * p)\n {\n if ((p->GetID(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)\n p->MakeEmptyID(m_threadSlot);\n if ((p->GetID2(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)\n p->MakeEmptyID2(m_threadSlot);\n }\n };\n}\n\nvoid Drawer::ClearResourceCache(size_t threadSlot, uint8_t pipelineID)\n{\n drule::rules().ForEachRule(DoMakeInvalidRule(threadSlot, pipelineID));\n}\n\nvoid Drawer::beginFrame()\n{\n m_pScreen->beginFrame();\n}\n\nvoid Drawer::endFrame()\n{\n m_pScreen->endFrame();\n}\n\nvoid Drawer::clear(graphics::Color const & c, bool clearRT, float depth, bool clearDepth)\n{\n m_pScreen->clear(c, clearRT, depth, clearDepth);\n}\n\nvoid Drawer::onSize(int w, int h)\n{\n m_pScreen->onSize(w, h);\n}\n\nvoid Drawer::drawSymbol(m2::PointD const & pt,\n string const & symbolName,\n graphics::EPosition pos,\n int depth)\n{\n m_pScreen->drawSymbol(pt, symbolName, pos, depth);\n}\n\nvoid Drawer::drawCircle(m2::PointD const & pt, rule_ptr_t pRule,\n graphics::EPosition pos, int depth, FeatureID const & id)\n{\n graphics::Circle::Info ci;\n ConvertStyle(pRule->GetCircle(), m_visualScale, ci);\n\n m_pScreen->drawCircle(pt, ci, pos, depth);\n}\n\nvoid Drawer::drawSymbol(m2::PointD const & pt,\n rule_ptr_t pRule,\n graphics::EPosition pos,\n int depth,\n FeatureID const & id)\n{\n graphics::Icon::Info info;\n ConvertStyle(pRule->GetSymbol(), info);\n\n graphics::SymbolElement::Params params;\n params.m_depth = depth;\n params.m_position = pos;\n params.m_pivot = pt;\n params.m_info = info;\n params.m_renderer = m_pScreen.get();\n params.m_userInfo.m_mwmID = id.first;\n params.m_userInfo.m_offset = id.second;\n\n m_pScreen->drawSymbol(params);\n}\n\nvoid Drawer::drawPath(di::PathInfo const & info, di::DrawRule const * rules, size_t count)\n{\n \/\/ if any rule needs caching - cache as a whole vector\n bool flag = false;\n for (size_t i = 0; i < count; ++i)\n {\n if (rules[i].GetID(m_pScreen->threadSlot()) == drule::BaseRule::empty_id)\n {\n flag = true;\n break;\n }\n }\n\n buffer_vector penInfos(count);\n buffer_vector infos(count);\n buffer_vector resIDs(count);\n\n if (flag)\n {\n \/\/ collect graphics::PenInfo into array and pack them as a whole\n for (size_t i = 0; i < count; ++i)\n {\n ConvertStyle(rules[i].m_rule->GetLine(), m_visualScale, penInfos[i]);\n\n infos[i] = &penInfos[i];\n\n if (rules[i].m_transparent)\n penInfos[i].m_color.a = 100;\n\n resIDs[i] = m_pScreen->invalidHandle();\n }\n\n \/\/ map array of pens\n if (m_pScreen->mapInfo(&infos[0], &resIDs[0], count))\n {\n for (size_t i = 0; i < count; ++i)\n rules[i].SetID(ThreadSlot(), resIDs[i]);\n }\n else\n {\n LOG(LERROR, (\"couldn't successfully pack a sequence of path styles as a whole\"));\n return;\n }\n }\n\n \/\/ draw path with array of rules\n for (size_t i = 0; i < count; ++i)\n m_pScreen->drawPath(&info.m_path[0], info.m_path.size(), -info.GetOffset(), rules[i].GetID(ThreadSlot()), rules[i].m_depth);\n}\n\nvoid Drawer::drawArea(vector const & pts, rule_ptr_t pRule, int depth)\n{\n \/\/ DO NOT cache 'id' in pRule, because one rule can use in drawPath and drawArea.\n \/\/ Leave CBaseRule::m_id for drawPath. mapColor working fast enough.\n\n graphics::Brush::Info info;\n ConvertStyle(pRule->GetArea(), info);\n\n uint32_t const id = m_pScreen->mapInfo(info);\n ASSERT ( id != -1, () );\n\n m_pScreen->drawTrianglesList(&pts[0], pts.size()\/*, res*\/, id, depth);\n}\n\nuint8_t Drawer::get_text_font_size(rule_ptr_t pRule) const\n{\n return GetFontSize(pRule->GetCaption(0)) * m_visualScale;\n}\n\nbool Drawer::filter_text_size(rule_ptr_t pRule) const\n{\n if (pRule->GetCaption(0))\n return (GetFontSize(pRule->GetCaption(0)) < 3);\n else\n {\n \/\/ this rule is not a caption at all\n return true;\n }\n}\n\nvoid Drawer::drawText(m2::PointD const & pt, di::DrawInfo const * pInfo, rule_ptr_t pRule,\n graphics::EPosition pos, int depth, FeatureID const & id)\n{\n graphics::FontDesc font;\n ConvertStyle(pRule->GetCaption(0), m_visualScale, font);\n font.SetRank(pInfo->m_rank);\n\n graphics::FontDesc smallFont;\n if (pRule->GetCaption(1))\n {\n ConvertStyle(pRule->GetCaption(1), m_visualScale, smallFont);\n smallFont.SetRank(pInfo->m_rank);\n }\n\n m_pScreen->drawTextEx(font, smallFont, pt, pos,\n pInfo->m_name, pInfo->m_secondaryName,\n depth, true, true);\n}\n\nbool Drawer::drawPathText(di::PathInfo const & info, di::DrawInfo const * pInfo, rule_ptr_t pRule, int depth)\n{\n graphics::FontDesc font;\n ConvertStyle(pRule->GetCaption(0), m_visualScale, font);\n\n return m_pScreen->drawPathText(font,\n &info.m_path[0],\n info.m_path.size(),\n pInfo->GetPathName(),\n info.GetFullLength(),\n info.GetOffset(),\n graphics::EPosCenter,\n depth);\n}\n\nvoid Drawer::drawPathNumber(di::PathInfo const & path, di::DrawInfo const * pInfo)\n{\n int const textHeight = static_cast(12 * m_visualScale);\n m2::PointD pt;\n double const length = path.GetFullLength();\n if (length >= (pInfo->m_road.size() + 2)*textHeight)\n {\n size_t const count = size_t(length \/ 1000.0) + 2;\n\n for (size_t j = 1; j < count; ++j)\n {\n if (path.GetSmPoint(double(j) \/ double(count), pt))\n {\n graphics::FontDesc fontDesc(\n textHeight,\n graphics::Color(150, 75, 0, 255), \/\/ brown\n true,\n graphics::Color(255, 255, 255, 255));\n\n m_pScreen->drawText(fontDesc, pt, graphics::EPosCenter, pInfo->m_road, graphics::maxDepth, true);\n }\n }\n }\n}\n\nshared_ptr Drawer::screen() const\n{\n return m_pScreen;\n}\n\ndouble Drawer::VisualScale() const\n{\n return m_visualScale;\n}\n\nvoid Drawer::SetScale(int level)\n{\n m_level = level;\n}\n\nvoid Drawer::Draw(di::DrawInfo const * pInfo, di::DrawRule const * rules, size_t count,\n FeatureID const & id)\n{\n buffer_vector pathRules;\n\n bool const isPath = !pInfo->m_pathes.empty();\n bool const isArea = !pInfo->m_areas.empty();\n\n \/\/ separating path rules from other\n for (size_t i = 0; i < count; ++i)\n {\n rule_ptr_t pRule = rules[i].m_rule;\n\n bool const hasSymbol = pRule->GetSymbol() != 0;\n bool const isCaption = pRule->GetCaption(0) != 0;\n\n if (!isCaption && isPath && !hasSymbol && (pRule->GetLine() != 0))\n pathRules.push_back(rules[i]);\n }\n\n if (!pathRules.empty())\n {\n for (list::const_iterator i = pInfo->m_pathes.begin(); i != pInfo->m_pathes.end(); ++i)\n {\n drawPath(*i, pathRules.data(), pathRules.size());\n }\n }\n\n for (size_t i = 0; i < count; ++i)\n {\n rule_ptr_t pRule = rules[i].m_rule;\n int const depth = rules[i].m_depth;\n\n bool const isCaption = pRule->GetCaption(0) != 0;\n bool const hasSymbol = pRule->GetSymbol() != 0;\n bool const isCircle = pRule->GetCircle() != 0;\n\n if (!isCaption)\n {\n double const sm = 2.0 * m_visualScale;\n\n \/\/ draw area\n if (isArea)\n {\n bool const isFill = pRule->GetArea() != 0;\n bool const hasSym = hasSymbol && ((pRule->GetType() & drule::way) != 0);\n\n for (list::const_iterator i = pInfo->m_areas.begin(); i != pInfo->m_areas.end(); ++i)\n {\n if (isFill)\n drawArea(i->m_path, pRule, depth);\n else if (hasSym)\n drawSymbol(i->GetCenter() + m2::PointD(0.0, sm), pRule, graphics::EPosUnder, depth, id);\n }\n }\n\n \/\/ draw point symbol\n if (!isPath && !isArea && ((pRule->GetType() & drule::node) != 0))\n {\n if (hasSymbol)\n drawSymbol(pInfo->m_point + m2::PointD(0.0, sm), pRule, graphics::EPosUnder, depth, id);\n else if (isCircle)\n drawCircle(pInfo->m_point + m2::PointD(0.0, sm), pRule, graphics::EPosUnder, depth, id);\n }\n }\n else\n {\n if (!pInfo->m_name.empty())\n {\n bool isN = ((pRule->GetType() & drule::way) != 0);\n\n \/\/ draw area text\n if (isArea\/* && isN*\/)\n {\n for (list::const_iterator i = pInfo->m_areas.begin(); i != pInfo->m_areas.end(); ++i)\n drawText(i->GetCenter(), pInfo, pRule, graphics::EPosAbove, depth, id);\n }\n\n \/\/ draw way name\n if (isPath && !isArea && isN && !filter_text_size(pRule))\n {\n for (list::const_iterator i = pInfo->m_pathes.begin(); i != pInfo->m_pathes.end(); ++i)\n drawPathText(*i, pInfo, pRule, depth);\n }\n\n \/\/ draw point text\n isN = ((pRule->GetType() & drule::node) != 0);\n if (!isPath && !isArea && isN)\n drawText(pInfo->m_point, pInfo, pRule, graphics::EPosAbove, depth, id);\n }\n }\n }\n\n \/\/ draw road numbers\n if (isPath && !pInfo->m_road.empty() && m_level >= 12)\n {\n for (list::const_iterator i = pInfo->m_pathes.begin(); i != pInfo->m_pathes.end(); ++i)\n drawPathNumber(*i, pInfo);\n }\n}\n\nint Drawer::ThreadSlot() const\n{\n return m_pScreen->threadSlot();\n}\naligning area texts to center point.#include \"drawer.hpp\"\n#include \"proto_to_styles.hpp\"\n\n#include \"..\/std\/bind.hpp\"\n\n#include \"..\/indexer\/drawing_rules.hpp\"\n#include \"..\/indexer\/scales.hpp\"\n\n#include \"..\/graphics\/defines.hpp\"\n#include \"..\/graphics\/screen.hpp\"\n#include \"..\/graphics\/resource_manager.hpp\"\n\n#include \"..\/geometry\/screenbase.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n#include \"..\/base\/buffer_vector.hpp\"\n\nDrawer::Params::Params()\n : m_visualScale(1)\n{\n}\n\ndi::DrawInfo::DrawInfo(string const & name,\n string const & secondaryName,\n string const & road,\n double rank)\n : m_name(name),\n m_secondaryName(secondaryName),\n m_road(road),\n m_rank(rank)\n{}\n\nstring const di::DrawInfo::GetPathName() const\n{\n if (m_secondaryName.empty())\n return m_name;\n else\n return m_name + \" \" + m_secondaryName;\n}\n\nuint32_t di::DrawRule::GetID(size_t threadSlot) const\n{\n return (m_transparent ? m_rule->GetID2(threadSlot) : m_rule->GetID(threadSlot));\n}\n\nvoid di::DrawRule::SetID(size_t threadSlot, uint32_t id) const\n{\n m_transparent ? m_rule->SetID2(threadSlot, id) : m_rule->SetID(threadSlot, id);\n}\n\nDrawer::Drawer(Params const & params)\n : m_visualScale(params.m_visualScale)\n{\n m_pScreen = shared_ptr(new graphics::Screen(params));\n\n for (unsigned i = 0; i < m_pScreen->pipelinesCount(); ++i)\n m_pScreen->addClearPageFn(i, bind(&Drawer::ClearResourceCache, ThreadSlot(), i), 0);\n}\n\nnamespace\n{\n struct DoMakeInvalidRule\n {\n size_t m_threadSlot;\n uint32_t m_pipelineIDMask;\n\n DoMakeInvalidRule(size_t threadSlot, uint8_t pipelineID)\n : m_threadSlot(threadSlot), m_pipelineIDMask(pipelineID << 24)\n {}\n\n void operator() (int, int, int, drule::BaseRule * p)\n {\n if ((p->GetID(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)\n p->MakeEmptyID(m_threadSlot);\n if ((p->GetID2(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)\n p->MakeEmptyID2(m_threadSlot);\n }\n };\n}\n\nvoid Drawer::ClearResourceCache(size_t threadSlot, uint8_t pipelineID)\n{\n drule::rules().ForEachRule(DoMakeInvalidRule(threadSlot, pipelineID));\n}\n\nvoid Drawer::beginFrame()\n{\n m_pScreen->beginFrame();\n}\n\nvoid Drawer::endFrame()\n{\n m_pScreen->endFrame();\n}\n\nvoid Drawer::clear(graphics::Color const & c, bool clearRT, float depth, bool clearDepth)\n{\n m_pScreen->clear(c, clearRT, depth, clearDepth);\n}\n\nvoid Drawer::onSize(int w, int h)\n{\n m_pScreen->onSize(w, h);\n}\n\nvoid Drawer::drawSymbol(m2::PointD const & pt,\n string const & symbolName,\n graphics::EPosition pos,\n int depth)\n{\n m_pScreen->drawSymbol(pt, symbolName, pos, depth);\n}\n\nvoid Drawer::drawCircle(m2::PointD const & pt, rule_ptr_t pRule,\n graphics::EPosition pos, int depth, FeatureID const & id)\n{\n graphics::Circle::Info ci;\n ConvertStyle(pRule->GetCircle(), m_visualScale, ci);\n\n m_pScreen->drawCircle(pt, ci, pos, depth);\n}\n\nvoid Drawer::drawSymbol(m2::PointD const & pt,\n rule_ptr_t pRule,\n graphics::EPosition pos,\n int depth,\n FeatureID const & id)\n{\n graphics::Icon::Info info;\n ConvertStyle(pRule->GetSymbol(), info);\n\n graphics::SymbolElement::Params params;\n params.m_depth = depth;\n params.m_position = pos;\n params.m_pivot = pt;\n params.m_info = info;\n params.m_renderer = m_pScreen.get();\n params.m_userInfo.m_mwmID = id.first;\n params.m_userInfo.m_offset = id.second;\n\n m_pScreen->drawSymbol(params);\n}\n\nvoid Drawer::drawPath(di::PathInfo const & info, di::DrawRule const * rules, size_t count)\n{\n \/\/ if any rule needs caching - cache as a whole vector\n bool flag = false;\n for (size_t i = 0; i < count; ++i)\n {\n if (rules[i].GetID(m_pScreen->threadSlot()) == drule::BaseRule::empty_id)\n {\n flag = true;\n break;\n }\n }\n\n buffer_vector penInfos(count);\n buffer_vector infos(count);\n buffer_vector resIDs(count);\n\n if (flag)\n {\n \/\/ collect graphics::PenInfo into array and pack them as a whole\n for (size_t i = 0; i < count; ++i)\n {\n ConvertStyle(rules[i].m_rule->GetLine(), m_visualScale, penInfos[i]);\n\n infos[i] = &penInfos[i];\n\n if (rules[i].m_transparent)\n penInfos[i].m_color.a = 100;\n\n resIDs[i] = m_pScreen->invalidHandle();\n }\n\n \/\/ map array of pens\n if (m_pScreen->mapInfo(&infos[0], &resIDs[0], count))\n {\n for (size_t i = 0; i < count; ++i)\n rules[i].SetID(ThreadSlot(), resIDs[i]);\n }\n else\n {\n LOG(LERROR, (\"couldn't successfully pack a sequence of path styles as a whole\"));\n return;\n }\n }\n\n \/\/ draw path with array of rules\n for (size_t i = 0; i < count; ++i)\n m_pScreen->drawPath(&info.m_path[0], info.m_path.size(), -info.GetOffset(), rules[i].GetID(ThreadSlot()), rules[i].m_depth);\n}\n\nvoid Drawer::drawArea(vector const & pts, rule_ptr_t pRule, int depth)\n{\n \/\/ DO NOT cache 'id' in pRule, because one rule can use in drawPath and drawArea.\n \/\/ Leave CBaseRule::m_id for drawPath. mapColor working fast enough.\n\n graphics::Brush::Info info;\n ConvertStyle(pRule->GetArea(), info);\n\n uint32_t const id = m_pScreen->mapInfo(info);\n ASSERT ( id != -1, () );\n\n m_pScreen->drawTrianglesList(&pts[0], pts.size()\/*, res*\/, id, depth);\n}\n\nuint8_t Drawer::get_text_font_size(rule_ptr_t pRule) const\n{\n return GetFontSize(pRule->GetCaption(0)) * m_visualScale;\n}\n\nbool Drawer::filter_text_size(rule_ptr_t pRule) const\n{\n if (pRule->GetCaption(0))\n return (GetFontSize(pRule->GetCaption(0)) < 3);\n else\n {\n \/\/ this rule is not a caption at all\n return true;\n }\n}\n\nvoid Drawer::drawText(m2::PointD const & pt, di::DrawInfo const * pInfo, rule_ptr_t pRule,\n graphics::EPosition pos, int depth, FeatureID const & id)\n{\n graphics::FontDesc font;\n ConvertStyle(pRule->GetCaption(0), m_visualScale, font);\n font.SetRank(pInfo->m_rank);\n\n graphics::FontDesc smallFont;\n if (pRule->GetCaption(1))\n {\n ConvertStyle(pRule->GetCaption(1), m_visualScale, smallFont);\n smallFont.SetRank(pInfo->m_rank);\n }\n\n m_pScreen->drawTextEx(font, smallFont, pt, pos,\n pInfo->m_name, pInfo->m_secondaryName,\n depth, true, true);\n}\n\nbool Drawer::drawPathText(di::PathInfo const & info, di::DrawInfo const * pInfo, rule_ptr_t pRule, int depth)\n{\n graphics::FontDesc font;\n ConvertStyle(pRule->GetCaption(0), m_visualScale, font);\n\n return m_pScreen->drawPathText(font,\n &info.m_path[0],\n info.m_path.size(),\n pInfo->GetPathName(),\n info.GetFullLength(),\n info.GetOffset(),\n graphics::EPosCenter,\n depth);\n}\n\nvoid Drawer::drawPathNumber(di::PathInfo const & path, di::DrawInfo const * pInfo)\n{\n int const textHeight = static_cast(12 * m_visualScale);\n m2::PointD pt;\n double const length = path.GetFullLength();\n if (length >= (pInfo->m_road.size() + 2)*textHeight)\n {\n size_t const count = size_t(length \/ 1000.0) + 2;\n\n for (size_t j = 1; j < count; ++j)\n {\n if (path.GetSmPoint(double(j) \/ double(count), pt))\n {\n graphics::FontDesc fontDesc(\n textHeight,\n graphics::Color(150, 75, 0, 255), \/\/ brown\n true,\n graphics::Color(255, 255, 255, 255));\n\n m_pScreen->drawText(fontDesc, pt, graphics::EPosCenter, pInfo->m_road, graphics::maxDepth, true);\n }\n }\n }\n}\n\nshared_ptr Drawer::screen() const\n{\n return m_pScreen;\n}\n\ndouble Drawer::VisualScale() const\n{\n return m_visualScale;\n}\n\nvoid Drawer::SetScale(int level)\n{\n m_level = level;\n}\n\nvoid Drawer::Draw(di::DrawInfo const * pInfo, di::DrawRule const * rules, size_t count,\n FeatureID const & id)\n{\n buffer_vector pathRules;\n\n bool const isPath = !pInfo->m_pathes.empty();\n bool const isArea = !pInfo->m_areas.empty();\n\n \/\/ separating path rules from other\n for (size_t i = 0; i < count; ++i)\n {\n rule_ptr_t pRule = rules[i].m_rule;\n\n bool const hasSymbol = pRule->GetSymbol() != 0;\n bool const isCaption = pRule->GetCaption(0) != 0;\n\n if (!isCaption && isPath && !hasSymbol && (pRule->GetLine() != 0))\n pathRules.push_back(rules[i]);\n }\n\n if (!pathRules.empty())\n {\n for (list::const_iterator i = pInfo->m_pathes.begin(); i != pInfo->m_pathes.end(); ++i)\n {\n drawPath(*i, pathRules.data(), pathRules.size());\n }\n }\n\n for (size_t i = 0; i < count; ++i)\n {\n rule_ptr_t pRule = rules[i].m_rule;\n int const depth = rules[i].m_depth;\n\n bool const isCaption = pRule->GetCaption(0) != 0;\n bool const hasSymbol = pRule->GetSymbol() != 0;\n bool const isCircle = pRule->GetCircle() != 0;\n\n if (!isCaption)\n {\n double const sm = 2.0 * m_visualScale;\n\n \/\/ draw area\n if (isArea)\n {\n bool const isFill = pRule->GetArea() != 0;\n bool const hasSym = hasSymbol && ((pRule->GetType() & drule::way) != 0);\n\n for (list::const_iterator i = pInfo->m_areas.begin(); i != pInfo->m_areas.end(); ++i)\n {\n if (isFill)\n drawArea(i->m_path, pRule, depth);\n else if (hasSym)\n drawSymbol(i->GetCenter() + m2::PointD(0.0, sm), pRule, graphics::EPosUnder, depth, id);\n }\n }\n\n \/\/ draw point symbol\n if (!isPath && !isArea && ((pRule->GetType() & drule::node) != 0))\n {\n if (hasSymbol)\n drawSymbol(pInfo->m_point + m2::PointD(0.0, sm), pRule, graphics::EPosUnder, depth, id);\n else if (isCircle)\n drawCircle(pInfo->m_point + m2::PointD(0.0, sm), pRule, graphics::EPosUnder, depth, id);\n }\n }\n else\n {\n if (!pInfo->m_name.empty())\n {\n bool isN = ((pRule->GetType() & drule::way) != 0);\n\n \/\/ draw area text\n if (isArea\/* && isN*\/)\n {\n for (list::const_iterator i = pInfo->m_areas.begin(); i != pInfo->m_areas.end(); ++i)\n drawText(i->GetCenter(), pInfo, pRule, graphics::EPosCenter, depth, id);\n }\n\n \/\/ draw way name\n if (isPath && !isArea && isN && !filter_text_size(pRule))\n {\n for (list::const_iterator i = pInfo->m_pathes.begin(); i != pInfo->m_pathes.end(); ++i)\n drawPathText(*i, pInfo, pRule, depth);\n }\n\n \/\/ draw point text\n isN = ((pRule->GetType() & drule::node) != 0);\n if (!isPath && !isArea && isN)\n drawText(pInfo->m_point, pInfo, pRule, graphics::EPosAbove, depth, id);\n }\n }\n }\n\n \/\/ draw road numbers\n if (isPath && !pInfo->m_road.empty() && m_level >= 12)\n {\n for (list::const_iterator i = pInfo->m_pathes.begin(); i != pInfo->m_pathes.end(); ++i)\n drawPathNumber(*i, pInfo);\n }\n}\n\nint Drawer::ThreadSlot() const\n{\n return m_pScreen->threadSlot();\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n\n#include \"qmediasource.h\"\n\n\nclass QMediaSourcePrivate : public QSharedData\n{\npublic:\n QMediaSourcePrivate() {}\n QMediaSourcePrivate(const QMediaResourceList &r):\n resources(r) {}\n\n QMediaResourceList resources;\n};\n\n\n\/*!\n \\class QMediaSource\n \\preliminary\n \\brief The QMediaSource class provides access to the resources relating to a media content.\n\n QMediaSource is used within the multimedia framework as the logical handle\n to media content. Media content can have multiple forms or other meta-data\n like items attached, some examples would be different quality variants of\n the primary stream, or extended meta-data such as a Poster for a movie.\n\n A non-null QMediaSource will always have a primary or canonical reference to\n the content available through the contentUri() or contentResource()\n methods, all other resources are optional.\n*\/\n\n\n\/*!\n Constructs a null QMediaSource.\n*\/\n\nQMediaSource::QMediaSource()\n{\n}\n\n\/*!\n Constructs a media source with \\a contentUri providing a reference to the content.\n*\/\n\nQMediaSource::QMediaSource(const QUrl &contentUri):\n d(new QMediaSourcePrivate)\n{\n d->resources << QMediaResource(contentUrl);\n}\n\n\/*!\n Constructs a media source with \\a contentResource providing a reference to the content.\n*\/\n\nQMediaSource::QMediaSource(const QMediaResource &contentResource):\n d(new QMediaSourcePrivate)\n{\n d->resources << contentResource;\n}\n\n\/*!\n Constructs a media source with \\a resources providing a reference to the content.\n*\/\n\nQMediaSource::QMediaSource(const QMediaResourceList &resources):\n d(new QMediaSourcePrivate(resources))\n{\n}\n\n\/*!\n Constructs a copy of media source \\a other.\n*\/\n\nQMediaSource::QMediaSource(const QMediaSource &other):\n d(other.d)\n{\n}\n\n\/*!\n Destroys the media source object.\n*\/\n\nQMediaSource::~QMediaSource()\n{\n}\n\n\/*!\n Assigns the value of \\a other to this media source.\n*\/\n\nQMediaSource& QMediaSource::operator=(const QMediaSource &other)\n{\n d = other.d;\n return *this;\n}\n\n\/*!\n Returns true if \\a other is equivalent to this media source; false otherwise.\n*\/\n\nbool QMediaSource::operator==(const QMediaSource &other) const\n{\n return (d.constData() == 0 && other.d.constData() == 0) ||\n (d.constData() != 0 && other.d.constData() != 0 &&\n d->resources == other.d->resources);\n}\n\n\/*!\n Returns true if \\a other is not equivalent to this media source; false otherwise.\n*\/\n\nbool QMediaSource::operator!=(const QMediaSource &other) const\n{\n return !(*this == other);\n}\n\n\/*!\n Returns true if this media source is null (uninitialized); false otherwise.\n*\/\n\nbool QMediaSource::isNull() const\n{\n return d.constData() == 0;\n}\n\n\/*!\n Returns a QUrl that represents that canonical content resource for this media source.\n*\/\n\nQUrl QMediaSource::contentUri() const\n{\n return contentResource().uri();\n}\n\n\/*!\n Returns a QMediaResource that represents that canonical content resource for this media source.\n*\/\n\nQMediaResource QMediaSource::contentResource() const\n{\n foreach (const QMediaResource &resource, d->resources) {\n if (resource.role() == QMediaResource::ContentRole)\n return resource;\n }\n\n return QMediaResource();\n}\n\n\/*!\n Returns a QMediaResourceList that contains all the QMediaResources that match the resource \\a role.\n\n \\sa QMediaResource::ResourceRole\n*\/\n\nQMediaResourceList QMediaSource::resources(QMediaResource::ResourceRole role) const\n{\n QMediaResourceList rc;\n\n foreach (const QMediaResource &resource, d->resources) {\n if (resource.role() == role)\n rc << resource;\n }\n\n return rc;\n}\n\nFix typo\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n\n#include \"qmediasource.h\"\n\n\nclass QMediaSourcePrivate : public QSharedData\n{\npublic:\n QMediaSourcePrivate() {}\n QMediaSourcePrivate(const QMediaResourceList &r):\n resources(r) {}\n\n QMediaResourceList resources;\n};\n\n\n\/*!\n \\class QMediaSource\n \\preliminary\n \\brief The QMediaSource class provides access to the resources relating to a media content.\n\n QMediaSource is used within the multimedia framework as the logical handle\n to media content. Media content can have multiple forms or other meta-data\n like items attached, some examples would be different quality variants of\n the primary stream, or extended meta-data such as a Poster for a movie.\n\n A non-null QMediaSource will always have a primary or canonical reference to\n the content available through the contentUri() or contentResource()\n methods, all other resources are optional.\n*\/\n\n\n\/*!\n Constructs a null QMediaSource.\n*\/\n\nQMediaSource::QMediaSource()\n{\n}\n\n\/*!\n Constructs a media source with \\a contentUri providing a reference to the content.\n*\/\n\nQMediaSource::QMediaSource(const QUrl &contentUri):\n d(new QMediaSourcePrivate)\n{\n d->resources << QMediaResource(contentUri);\n}\n\n\/*!\n Constructs a media source with \\a contentResource providing a reference to the content.\n*\/\n\nQMediaSource::QMediaSource(const QMediaResource &contentResource):\n d(new QMediaSourcePrivate)\n{\n d->resources << contentResource;\n}\n\n\/*!\n Constructs a media source with \\a resources providing a reference to the content.\n*\/\n\nQMediaSource::QMediaSource(const QMediaResourceList &resources):\n d(new QMediaSourcePrivate(resources))\n{\n}\n\n\/*!\n Constructs a copy of media source \\a other.\n*\/\n\nQMediaSource::QMediaSource(const QMediaSource &other):\n d(other.d)\n{\n}\n\n\/*!\n Destroys the media source object.\n*\/\n\nQMediaSource::~QMediaSource()\n{\n}\n\n\/*!\n Assigns the value of \\a other to this media source.\n*\/\n\nQMediaSource& QMediaSource::operator=(const QMediaSource &other)\n{\n d = other.d;\n return *this;\n}\n\n\/*!\n Returns true if \\a other is equivalent to this media source; false otherwise.\n*\/\n\nbool QMediaSource::operator==(const QMediaSource &other) const\n{\n return (d.constData() == 0 && other.d.constData() == 0) ||\n (d.constData() != 0 && other.d.constData() != 0 &&\n d->resources == other.d->resources);\n}\n\n\/*!\n Returns true if \\a other is not equivalent to this media source; false otherwise.\n*\/\n\nbool QMediaSource::operator!=(const QMediaSource &other) const\n{\n return !(*this == other);\n}\n\n\/*!\n Returns true if this media source is null (uninitialized); false otherwise.\n*\/\n\nbool QMediaSource::isNull() const\n{\n return d.constData() == 0;\n}\n\n\/*!\n Returns a QUrl that represents that canonical content resource for this media source.\n*\/\n\nQUrl QMediaSource::contentUri() const\n{\n return contentResource().uri();\n}\n\n\/*!\n Returns a QMediaResource that represents that canonical content resource for this media source.\n*\/\n\nQMediaResource QMediaSource::contentResource() const\n{\n foreach (const QMediaResource &resource, d->resources) {\n if (resource.role() == QMediaResource::ContentRole)\n return resource;\n }\n\n return QMediaResource();\n}\n\n\/*!\n Returns a QMediaResourceList that contains all the QMediaResources that match the resource \\a role.\n\n \\sa QMediaResource::ResourceRole\n*\/\n\nQMediaResourceList QMediaSource::resources(QMediaResource::ResourceRole role) const\n{\n QMediaResourceList rc;\n\n foreach (const QMediaResource &resource, d->resources) {\n if (resource.role() == role)\n rc << resource;\n }\n\n return rc;\n}\n\n<|endoftext|>"} {"text":"\/* ffsdumper.cpp\n\nCopyright (c) 2015, Nikolaj Schlej. All rights reserved.\nThis program and the accompanying materials\nare licensed and made available under the terms and conditions of the BSD License\nwhich accompanies this distribution. The full text of the license may be found at\nhttp:\/\/opensource.org\/licenses\/bsd-license.php\n\nTHE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\n\n*\/\n\n#include \"ffsdumper.h\"\n\n#include \n\nUSTATUS FfsDumper::dump(const UModelIndex & root, const UString & path, const DumpMode dumpMode, const UINT8 sectionType, const UString & guid)\n{\n dumped = false;\n counterHeader = counterBody = counterRaw = counterInfo = 0;\n\n if (changeDirectory(path))\n return U_DIR_ALREADY_EXIST;\n\n USTATUS result = recursiveDump(root, path, dumpMode, sectionType, guid);\n if (result)\n return result;\n else if (!dumped)\n return U_ITEM_NOT_FOUND;\n return U_SUCCESS;\n}\n\nUSTATUS FfsDumper::recursiveDump(const UModelIndex & index, const UString & path, const DumpMode dumpMode, const UINT8 sectionType, const UString & guid)\n{\n if (!index.isValid())\n return U_INVALID_PARAMETER;\n\n if (guid.isEmpty() ||\n (model->subtype(index) == EFI_SECTION_FREEFORM_SUBTYPE_GUID &&\n guidToUString(readMisaligned((const EFI_GUID*)(model->header(index).constData() + sizeof(EFI_COMMON_SECTION_HEADER)))) == guid) ||\n guidToUString(readMisaligned((const EFI_GUID*)model->header(index).constData())) == guid ||\n guidToUString(readMisaligned((const EFI_GUID*)model->header(model->findParentOfType(index, Types::File)).constData())) == guid) {\n\n if (!changeDirectory(path) && !makeDirectory(path))\n return U_DIR_CREATE;\n\n counterHeader = counterBody = counterRaw = counterInfo = 0;\n\n if (dumpMode == DUMP_ALL || model->rowCount(index) == 0) { \/\/ Dump if leaf item or dumpAll is true\n if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_HEADER) {\n if (!model->header(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UString filename;\n if (counterHeader == 0)\n filename = usprintf(\"%s\/header.bin\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/header_%d.bin\", path.toLocal8Bit(), counterHeader);\n counterHeader++;\n std::ofstream file(filename.toLocal8Bit(), std::ofstream::binary);\n if (!file)\n return U_FILE_OPEN;\n const UByteArray &data = model->header(index);\n file.write(data.constData(), data.size());\n }\n }\n\n if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_BODY) {\n if (!model->body(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UString filename;\n if (counterBody == 0)\n filename = usprintf(\"%s\/body.bin\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/body_%d.bin\", path.toLocal8Bit(), counterBody);\n counterBody++;\n std::ofstream file(filename.toLocal8Bit(), std::ofstream::binary);\n if (!file)\n return U_FILE_OPEN;\n const UByteArray &data = model->body(index);\n file.write(data.constData(), data.size());\n }\n }\n\n if (dumpMode == DUMP_FILE && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UModelIndex fileIndex = model->findParentOfType(index, Types::File);\n if (!fileIndex.isValid())\n fileIndex = index;\n UString filename;\n if (counterRaw == 0)\n filename = usprintf(\"%s\/file.ffs\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/file_%d.bin\", path.toLocal8Bit(), counterRaw);\n counterRaw++;\n std::ofstream file(filename.toLocal8Bit(), std::ofstream::binary);\n if (!file)\n return U_FILE_OPEN;\n const UByteArray &headerData = model->header(index);\n const UByteArray &bodyData = model->body(index);\n const UByteArray &tailData = model->tail(index);\n file.write(headerData.constData(), headerData.size());\n file.write(bodyData.constData(), bodyData.size());\n file.write(tailData.constData(), tailData.size());\n }\n }\n\n \/\/ Always dump info unless explicitly prohibited\n if ((dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_INFO)\n && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UString info = usprintf(\"Type: %s\\nSubtype: %s\\n%s%s\\n\",\n itemTypeToUString(model->type(index)).toLocal8Bit(),\n itemSubtypeToUString(model->type(index), model->subtype(index)).toLocal8Bit(),\n (model->text(index).isEmpty() ? UString(\"\") :\n usprintf(\"Text: %s\\n\", model->text(index).toLocal8Bit())).toLocal8Bit(),\n model->info(index).toLocal8Bit());\n UString filename;\n if (counterInfo == 0)\n filename = usprintf(\"%s\/info.txt\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/info_%d.txt\", path.toLocal8Bit(), counterInfo);\n counterInfo++;\n std::ofstream file(filename.toLocal8Bit());\n if (!file)\n return U_FILE_OPEN;\n file << info.toLocal8Bit();\n }\n\n dumped = true;\n }\n\n USTATUS result;\n for (int i = 0; i < model->rowCount(index); i++) {\n UModelIndex childIndex = index.child(i, 0);\n bool useText = FALSE;\n if (model->type(childIndex) != Types::Volume)\n useText = !model->text(childIndex).isEmpty();\n\n UString childPath = path;\n if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT)\n childPath = usprintf(\"%s\/%d %s\", path.toLocal8Bit(), i,\n (useText ? model->text(childIndex) : model->name(childIndex)).toLocal8Bit());\n result = recursiveDump(childIndex, childPath, dumpMode, sectionType, guid);\n if (result)\n return result;\n }\n\n return U_SUCCESS;\n}\nFix file extraction in UEFIExtract\/* ffsdumper.cpp\n\nCopyright (c) 2015, Nikolaj Schlej. All rights reserved.\nThis program and the accompanying materials\nare licensed and made available under the terms and conditions of the BSD License\nwhich accompanies this distribution. The full text of the license may be found at\nhttp:\/\/opensource.org\/licenses\/bsd-license.php\n\nTHE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\n\n*\/\n\n#include \"ffsdumper.h\"\n\n#include \n\nUSTATUS FfsDumper::dump(const UModelIndex & root, const UString & path, const DumpMode dumpMode, const UINT8 sectionType, const UString & guid)\n{\n dumped = false;\n counterHeader = counterBody = counterRaw = counterInfo = 0;\n\n if (changeDirectory(path))\n return U_DIR_ALREADY_EXIST;\n\n USTATUS result = recursiveDump(root, path, dumpMode, sectionType, guid);\n if (result)\n return result;\n else if (!dumped)\n return U_ITEM_NOT_FOUND;\n return U_SUCCESS;\n}\n\nUSTATUS FfsDumper::recursiveDump(const UModelIndex & index, const UString & path, const DumpMode dumpMode, const UINT8 sectionType, const UString & guid)\n{\n if (!index.isValid())\n return U_INVALID_PARAMETER;\n\n if (guid.isEmpty() ||\n (model->subtype(index) == EFI_SECTION_FREEFORM_SUBTYPE_GUID &&\n guidToUString(readMisaligned((const EFI_GUID*)(model->header(index).constData() + sizeof(EFI_COMMON_SECTION_HEADER)))) == guid) ||\n guidToUString(readMisaligned((const EFI_GUID*)model->header(index).constData())) == guid ||\n guidToUString(readMisaligned((const EFI_GUID*)model->header(model->findParentOfType(index, Types::File)).constData())) == guid) {\n\n if (!changeDirectory(path) && !makeDirectory(path))\n return U_DIR_CREATE;\n\n counterHeader = counterBody = counterRaw = counterInfo = 0;\n\n if (dumpMode == DUMP_ALL || model->rowCount(index) == 0) { \/\/ Dump if leaf item or dumpAll is true\n if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_HEADER) {\n if (!model->header(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UString filename;\n if (counterHeader == 0)\n filename = usprintf(\"%s\/header.bin\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/header_%d.bin\", path.toLocal8Bit(), counterHeader);\n counterHeader++;\n std::ofstream file(filename.toLocal8Bit(), std::ofstream::binary);\n if (!file)\n return U_FILE_OPEN;\n const UByteArray &data = model->header(index);\n file.write(data.constData(), data.size());\n }\n }\n\n if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_BODY) {\n if (!model->body(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UString filename;\n if (counterBody == 0)\n filename = usprintf(\"%s\/body.bin\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/body_%d.bin\", path.toLocal8Bit(), counterBody);\n counterBody++;\n std::ofstream file(filename.toLocal8Bit(), std::ofstream::binary);\n if (!file)\n return U_FILE_OPEN;\n const UByteArray &data = model->body(index);\n file.write(data.constData(), data.size());\n }\n }\n\n if (dumpMode == DUMP_FILE && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UModelIndex fileIndex = model->findParentOfType(index, Types::File);\n if (!fileIndex.isValid())\n fileIndex = index;\n UString filename;\n if (counterRaw == 0)\n filename = usprintf(\"%s\/file.ffs\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/file_%d.bin\", path.toLocal8Bit(), counterRaw);\n counterRaw++;\n std::ofstream file(filename.toLocal8Bit(), std::ofstream::binary);\n if (!file)\n return U_FILE_OPEN;\n const UByteArray &headerData = model->header(fileIndex);\n const UByteArray &bodyData = model->body(fileIndex);\n const UByteArray &tailData = model->tail(fileIndex);\n file.write(headerData.constData(), headerData.size());\n file.write(bodyData.constData(), bodyData.size());\n file.write(tailData.constData(), tailData.size());\n }\n }\n\n \/\/ Always dump info unless explicitly prohibited\n if ((dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_INFO)\n && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {\n UString info = usprintf(\"Type: %s\\nSubtype: %s\\n%s%s\\n\",\n itemTypeToUString(model->type(index)).toLocal8Bit(),\n itemSubtypeToUString(model->type(index), model->subtype(index)).toLocal8Bit(),\n (model->text(index).isEmpty() ? UString(\"\") :\n usprintf(\"Text: %s\\n\", model->text(index).toLocal8Bit())).toLocal8Bit(),\n model->info(index).toLocal8Bit());\n UString filename;\n if (counterInfo == 0)\n filename = usprintf(\"%s\/info.txt\", path.toLocal8Bit());\n else\n filename = usprintf(\"%s\/info_%d.txt\", path.toLocal8Bit(), counterInfo);\n counterInfo++;\n std::ofstream file(filename.toLocal8Bit());\n if (!file)\n return U_FILE_OPEN;\n file << info.toLocal8Bit();\n }\n\n dumped = true;\n }\n\n USTATUS result;\n for (int i = 0; i < model->rowCount(index); i++) {\n UModelIndex childIndex = index.child(i, 0);\n bool useText = FALSE;\n if (model->type(childIndex) != Types::Volume)\n useText = !model->text(childIndex).isEmpty();\n\n UString childPath = path;\n if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT)\n childPath = usprintf(\"%s\/%d %s\", path.toLocal8Bit(), i,\n (useText ? model->text(childIndex) : model->name(childIndex)).toLocal8Bit());\n result = recursiveDump(childIndex, childPath, dumpMode, sectionType, guid);\n if (result)\n return result;\n }\n\n return U_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* Copyright (C) 2003 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program 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 General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#ifndef NDB_VECTOR_HPP\n#define NDB_VECTOR_HPP\n\n#include \n#include \n\ntemplate\nstruct Vector {\npublic:\n Vector(int sz = 10);\n ~Vector();\n\n T& operator[](unsigned i);\n const T& operator[](unsigned i) const;\n unsigned size() const { return m_size; };\n \n void push_back(const T &);\n T& back();\n \n void erase(unsigned index);\n \n void clear();\n \n void fill(unsigned new_size, T & obj);\n\n Vector& operator=(const Vector&);\n\n T* getBase() { return m_items;}\n const T* getBase() const { return m_items;}\nprivate:\n T * m_items;\n unsigned m_size;\n unsigned m_incSize;\n unsigned m_arraySize;\n};\n\ntemplate\nVector::Vector(int i){\n m_items = new T[i];\n m_size = 0;\n m_arraySize = i;\n m_incSize = 50;\n}\n\ntemplate\nVector::~Vector(){\n delete[] m_items;\n \/\/ safety for placement new usage\n m_items = 0;\n m_size = 0;\n m_arraySize = 0;\n}\n\ntemplate\nT &\nVector::operator[](unsigned i){\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nconst T &\nVector::operator[](unsigned i) const {\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nT &\nVector::back(){\n return (* this)[m_size - 1];\n}\n\ntemplate\nvoid\nVector::push_back(const T & t){\n if(m_size == m_arraySize){\n T * tmp = new T [m_arraySize + m_incSize];\n for (unsigned k = 0; k < m_size; k++)\n tmp[k] = m_items[k];\n delete[] m_items;\n m_items = tmp;\n m_arraySize = m_arraySize + m_incSize;\n }\n m_items[m_size] = t;\n m_size++;\n}\n\ntemplate\nvoid\nVector::erase(unsigned i){\n if(i >= m_size)\n abort();\n \n for (unsigned k = i; k + 1 < m_size; k++)\n m_items[k] = m_items[k + 1];\n m_size--;\n}\n\ntemplate\nvoid\nVector::clear(){\n m_size = 0;\n}\n\ntemplate\nvoid \nVector::fill(unsigned new_size, T & obj){\n while(m_size <= new_size)\n push_back(obj);\n}\n\ntemplate\nVector& \nVector::operator=(const Vector& obj){\n if(this != &obj){\n clear();\n for(size_t i = 0; i\nstruct MutexVector : public NdbLockable {\n MutexVector(int sz = 10);\n ~MutexVector();\n\n T& operator[](unsigned i);\n const T& operator[](unsigned i) const;\n unsigned size() const { return m_size; };\n \n void push_back(const T &);\n void push_back(const T &, bool lockMutex);\n T& back();\n \n void erase(unsigned index);\n void erase(unsigned index, bool lockMutex);\n\n void clear();\n void clear(bool lockMutex);\n\n void fill(unsigned new_size, T & obj);\nprivate:\n T * m_items;\n unsigned m_size;\n unsigned m_incSize;\n unsigned m_arraySize;\n};\n\ntemplate\nMutexVector::MutexVector(int i){\n m_items = new T[i];\n m_size = 0;\n m_arraySize = i;\n m_incSize = 50;\n}\n\ntemplate\nMutexVector::~MutexVector(){\n delete[] m_items;\n \/\/ safety for placement new usage\n m_items = 0;\n m_size = 0;\n m_arraySize = 0;\n}\n\ntemplate\nT &\nMutexVector::operator[](unsigned i){\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nconst T &\nMutexVector::operator[](unsigned i) const {\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nT &\nMutexVector::back(){\n return (* this)[m_size - 1];\n}\n\ntemplate\nvoid\nMutexVector::push_back(const T & t){\n lock();\n if(m_size == m_arraySize){\n T * tmp = new T [m_arraySize + m_incSize];\n for (unsigned k = 0; k < m_size; k++)\n tmp[k] = m_items[k];\n delete[] m_items;\n m_items = tmp;\n m_arraySize = m_arraySize + m_incSize;\n }\n m_items[m_size] = t;\n m_size++;\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::push_back(const T & t, bool lockMutex){\n if(lockMutex) \n lock();\n if(m_size == m_arraySize){\n T * tmp = new T [m_arraySize + m_incSize];\n for (unsigned k = 0; k < m_size; k++)\n tmp[k] = m_items[k];\n delete[] m_items;\n m_items = tmp;\n m_arraySize = m_arraySize + m_incSize;\n }\n m_items[m_size] = t;\n m_size++;\n if(lockMutex)\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::erase(unsigned i){\n if(i >= m_size)\n abort();\n \n lock();\n for (unsigned k = i; k + 1 < m_size; k++)\n m_items[k] = m_items[k + 1];\n m_size--;\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::erase(unsigned i, bool _lock){\n if(i >= m_size)\n abort();\n \n if(_lock) \n lock();\n for (unsigned k = i; k + 1 < m_size; k++)\n m_items[k] = m_items[k + 1];\n m_size--;\n if(_lock) \n unlock();\n}\n\ntemplate\nvoid\nMutexVector::clear(){\n lock();\n m_size = 0;\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::clear(bool l){\n if(l) lock();\n m_size = 0;\n if(l) unlock();\n}\n\ntemplate\nvoid \nMutexVector::fill(unsigned new_size, T & obj){\n while(m_size <= new_size)\n push_back(obj);\n}\n\n#endif\nBUG#22299 mgmd crash due to unchecked TransporterFacade::ThreadData expand()\/* Copyright (C) 2003 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program 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 General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#ifndef NDB_VECTOR_HPP\n#define NDB_VECTOR_HPP\n\n#include \n#include \n\ntemplate\nstruct Vector {\npublic:\n Vector(int sz = 10);\n ~Vector();\n\n T& operator[](unsigned i);\n const T& operator[](unsigned i) const;\n unsigned size() const { return m_size; };\n \n void push_back(const T &);\n T& back();\n \n void erase(unsigned index);\n \n void clear();\n \n void fill(unsigned new_size, T & obj);\n\n Vector& operator=(const Vector&);\n\n T* getBase() { return m_items;}\n const T* getBase() const { return m_items;}\nprivate:\n T * m_items;\n unsigned m_size;\n unsigned m_incSize;\n unsigned m_arraySize;\n};\n\ntemplate\nVector::Vector(int i){\n m_items = new T[i];\n m_size = 0;\n m_arraySize = i;\n m_incSize = 50;\n}\n\ntemplate\nVector::~Vector(){\n delete[] m_items;\n \/\/ safety for placement new usage\n m_items = 0;\n m_size = 0;\n m_arraySize = 0;\n}\n\ntemplate\nT &\nVector::operator[](unsigned i){\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nconst T &\nVector::operator[](unsigned i) const {\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nT &\nVector::back(){\n return (* this)[m_size - 1];\n}\n\ntemplate\nvoid\nVector::push_back(const T & t){\n if(m_size == m_arraySize){\n T * tmp = new T [m_arraySize + m_incSize];\n if(!tmp)\n abort();\n for (unsigned k = 0; k < m_size; k++)\n tmp[k] = m_items[k];\n delete[] m_items;\n m_items = tmp;\n m_arraySize = m_arraySize + m_incSize;\n }\n m_items[m_size] = t;\n m_size++;\n}\n\ntemplate\nvoid\nVector::erase(unsigned i){\n if(i >= m_size)\n abort();\n \n for (unsigned k = i; k + 1 < m_size; k++)\n m_items[k] = m_items[k + 1];\n m_size--;\n}\n\ntemplate\nvoid\nVector::clear(){\n m_size = 0;\n}\n\ntemplate\nvoid \nVector::fill(unsigned new_size, T & obj){\n while(m_size <= new_size)\n push_back(obj);\n}\n\ntemplate\nVector& \nVector::operator=(const Vector& obj){\n if(this != &obj){\n clear();\n for(size_t i = 0; i\nstruct MutexVector : public NdbLockable {\n MutexVector(int sz = 10);\n ~MutexVector();\n\n T& operator[](unsigned i);\n const T& operator[](unsigned i) const;\n unsigned size() const { return m_size; };\n \n void push_back(const T &);\n void push_back(const T &, bool lockMutex);\n T& back();\n \n void erase(unsigned index);\n void erase(unsigned index, bool lockMutex);\n\n void clear();\n void clear(bool lockMutex);\n\n void fill(unsigned new_size, T & obj);\nprivate:\n T * m_items;\n unsigned m_size;\n unsigned m_incSize;\n unsigned m_arraySize;\n};\n\ntemplate\nMutexVector::MutexVector(int i){\n m_items = new T[i];\n m_size = 0;\n m_arraySize = i;\n m_incSize = 50;\n}\n\ntemplate\nMutexVector::~MutexVector(){\n delete[] m_items;\n \/\/ safety for placement new usage\n m_items = 0;\n m_size = 0;\n m_arraySize = 0;\n}\n\ntemplate\nT &\nMutexVector::operator[](unsigned i){\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nconst T &\nMutexVector::operator[](unsigned i) const {\n if(i >= m_size)\n abort();\n return m_items[i];\n}\n\ntemplate\nT &\nMutexVector::back(){\n return (* this)[m_size - 1];\n}\n\ntemplate\nvoid\nMutexVector::push_back(const T & t){\n lock();\n if(m_size == m_arraySize){\n T * tmp = new T [m_arraySize + m_incSize];\n for (unsigned k = 0; k < m_size; k++)\n tmp[k] = m_items[k];\n delete[] m_items;\n m_items = tmp;\n m_arraySize = m_arraySize + m_incSize;\n }\n m_items[m_size] = t;\n m_size++;\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::push_back(const T & t, bool lockMutex){\n if(lockMutex) \n lock();\n if(m_size == m_arraySize){\n T * tmp = new T [m_arraySize + m_incSize];\n for (unsigned k = 0; k < m_size; k++)\n tmp[k] = m_items[k];\n delete[] m_items;\n m_items = tmp;\n m_arraySize = m_arraySize + m_incSize;\n }\n m_items[m_size] = t;\n m_size++;\n if(lockMutex)\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::erase(unsigned i){\n if(i >= m_size)\n abort();\n \n lock();\n for (unsigned k = i; k + 1 < m_size; k++)\n m_items[k] = m_items[k + 1];\n m_size--;\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::erase(unsigned i, bool _lock){\n if(i >= m_size)\n abort();\n \n if(_lock) \n lock();\n for (unsigned k = i; k + 1 < m_size; k++)\n m_items[k] = m_items[k + 1];\n m_size--;\n if(_lock) \n unlock();\n}\n\ntemplate\nvoid\nMutexVector::clear(){\n lock();\n m_size = 0;\n unlock();\n}\n\ntemplate\nvoid\nMutexVector::clear(bool l){\n if(l) lock();\n m_size = 0;\n if(l) unlock();\n}\n\ntemplate\nvoid \nMutexVector::fill(unsigned new_size, T & obj){\n while(m_size <= new_size)\n push_back(obj);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\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 * #L%\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"joynr\/JoynrRuntime.h\"\n#include \"joynr\/Logger.h\"\n#include \"joynr\/Semaphore.h\"\n#include \"joynr\/types\/ProviderQos.h\"\n#include \"joynr\/types\/ProviderScope.h\"\n#include \"SystemIntegrationTestProvider.h\"\n#include \"SitUtil.h\"\n#ifdef JOYNR_ENABLE_DLT_LOGGING\n#include \n#endif \/\/ JOYNR_ENABLE_DLT_LOGGING\n\nusing namespace joynr;\n\nint main(int argc, char* argv[])\n{\n#ifdef JOYNR_ENABLE_DLT_LOGGING\n \/\/ Register app at the dlt-daemon for logging\n DLT_REGISTER_APP(\"JYSP\", argv[0]);\n#endif \/\/ JOYNR_ENABLE_DLT_LOGGING\n\n \/\/ Get a logger\n Logger logger(\"ProviderApplication\");\n\n namespace po = boost::program_options;\n\n po::positional_options_description positionalCmdLineOptions;\n positionalCmdLineOptions.add(\"domain\", 1);\n positionalCmdLineOptions.add(\"runForever\", 1);\n\n std::string providerDomain;\n bool runForever = false;\n std::string pathToSettings;\n std::string sslCertFilename;\n std::string sslPrivateKeyFilename;\n std::string sslCaCertFilename;\n\n po::options_description cmdLineOptions;\n cmdLineOptions.add_options()(\"domain,d\", po::value(&providerDomain)->required())(\n \"runForever,r\", po::value(&runForever)->default_value(false))(\n \"pathtosettings,p\", po::value(&pathToSettings))(\n \"ssl-cert-pem\", po::value(&sslCertFilename))(\n \"ssl-privatekey-pem\", po::value(&sslPrivateKeyFilename))(\n \"ssl-ca-cert-pem\", po::value(&sslCaCertFilename));\n\n try {\n po::variables_map variablesMap;\n po::store(po::command_line_parser(argc, argv)\n .options(cmdLineOptions)\n .positional(positionalCmdLineOptions)\n .run(),\n variablesMap);\n po::notify(variablesMap);\n } catch (const std::exception& e) {\n std::cerr << e.what();\n return -1;\n }\n\n JOYNR_LOG_INFO(logger, \"Registering provider on domain {}\", providerDomain);\n\n if (pathToSettings.empty()) {\n boost::filesystem::path appFilename = boost::filesystem::path(argv[0]);\n std::string appDirectory =\n boost::filesystem::system_complete(appFilename).parent_path().string();\n pathToSettings = appDirectory + \"\/resources\/systemintegrationtest-provider.settings\";\n }\n\n const std::string pathToMessagingSettingsDefault(\"\");\n std::shared_ptr keychain;\n\n try {\n keychain = tryLoadKeychainFromCmdLineArgs(\n sslCertFilename, sslPrivateKeyFilename, sslCaCertFilename);\n } catch (const std::invalid_argument& e) {\n JOYNR_LOG_FATAL(logger, e.what());\n return -1;\n }\n\n std::shared_ptr runtime =\n JoynrRuntime::createRuntime(pathToSettings, pathToMessagingSettingsDefault, keychain);\n\n joynr::Semaphore semaphore;\n\n auto provider = std::make_shared([&]() { semaphore.notify(); });\n\n joynr::types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n\n \/\/ Register the provider\n runtime->registerProvider(\n providerDomain, provider, providerQos);\n\n if (runForever) {\n while (true) {\n semaphore.wait();\n }\n } else {\n bool successful = semaphore.waitFor(std::chrono::milliseconds(30000));\n\n \/\/ Unregister the provider\n runtime->unregisterProvider(providerDomain, provider);\n\n return successful ? 0 : -1;\n }\n}\n[C++] Catch exceptions in ProviderApplication to avoid std::terminate\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\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 * #L%\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"joynr\/JoynrRuntime.h\"\n#include \"joynr\/Logger.h\"\n#include \"joynr\/Semaphore.h\"\n#include \"joynr\/types\/ProviderQos.h\"\n#include \"joynr\/types\/ProviderScope.h\"\n#include \"SystemIntegrationTestProvider.h\"\n#include \"SitUtil.h\"\n#ifdef JOYNR_ENABLE_DLT_LOGGING\n#include \n#endif \/\/ JOYNR_ENABLE_DLT_LOGGING\n\nusing namespace joynr;\n\nint main(int argc, char* argv[])\n{\n#ifdef JOYNR_ENABLE_DLT_LOGGING\n \/\/ Register app at the dlt-daemon for logging\n DLT_REGISTER_APP(\"JYSP\", argv[0]);\n#endif \/\/ JOYNR_ENABLE_DLT_LOGGING\n\n \/\/ Get a logger\n Logger logger(\"ProviderApplication\");\n\n namespace po = boost::program_options;\n\n po::positional_options_description positionalCmdLineOptions;\n positionalCmdLineOptions.add(\"domain\", 1);\n positionalCmdLineOptions.add(\"runForever\", 1);\n\n std::string providerDomain;\n bool runForever = false;\n std::string pathToSettings;\n std::string sslCertFilename;\n std::string sslPrivateKeyFilename;\n std::string sslCaCertFilename;\n\n po::options_description cmdLineOptions;\n cmdLineOptions.add_options()(\"domain,d\", po::value(&providerDomain)->required())(\n \"runForever,r\", po::value(&runForever)->default_value(false))(\n \"pathtosettings,p\", po::value(&pathToSettings))(\n \"ssl-cert-pem\", po::value(&sslCertFilename))(\n \"ssl-privatekey-pem\", po::value(&sslPrivateKeyFilename))(\n \"ssl-ca-cert-pem\", po::value(&sslCaCertFilename));\n\n try {\n po::variables_map variablesMap;\n po::store(po::command_line_parser(argc, argv)\n .options(cmdLineOptions)\n .positional(positionalCmdLineOptions)\n .run(),\n variablesMap);\n po::notify(variablesMap);\n } catch (const std::exception& e) {\n std::cerr << e.what();\n return EXIT_FAILURE;\n }\n\n JOYNR_LOG_INFO(logger, \"Registering provider on domain {}\", providerDomain);\n\n if (pathToSettings.empty()) {\n boost::filesystem::path appFilename = boost::filesystem::path(argv[0]);\n std::string appDirectory =\n boost::filesystem::system_complete(appFilename).parent_path().string();\n pathToSettings = appDirectory + \"\/resources\/systemintegrationtest-provider.settings\";\n }\n\n const std::string pathToMessagingSettingsDefault(\"\");\n std::shared_ptr keychain;\n\n try {\n keychain = tryLoadKeychainFromCmdLineArgs(\n sslCertFilename, sslPrivateKeyFilename, sslCaCertFilename);\n } catch (const std::invalid_argument& e) {\n JOYNR_LOG_FATAL(logger, e.what());\n return EXIT_FAILURE;\n }\n\n try {\n std::shared_ptr runtime = JoynrRuntime::createRuntime(\n pathToSettings, pathToMessagingSettingsDefault, keychain);\n\n joynr::Semaphore semaphore;\n\n auto provider =\n std::make_shared([&]() { semaphore.notify(); });\n\n joynr::types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n\n \/\/ Register the provider\n runtime->registerProvider(\n providerDomain, provider, providerQos);\n\n if (runForever) {\n while (true) {\n semaphore.wait();\n }\n } else {\n bool successful = semaphore.waitFor(std::chrono::milliseconds(30000));\n\n \/\/ Unregister the provider\n runtime->unregisterProvider(\n providerDomain, provider);\n\n return successful ? EXIT_SUCCESS : EXIT_FAILURE;\n }\n } catch (exceptions::JoynrRuntimeException& e) {\n JOYNR_LOG_FATAL(logger, e.what());\n return EXIT_FAILURE;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2009-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\n *\/\n\n\/\/ STL\n#include \n\n\/\/ PCL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint \nmain(int argc, char **argv)\n{\n pcl::PointCloud::Ptr cloud_ptr (new pcl::PointCloud ());\n pcl::PointCloud::Ptr cloud_normals (new pcl::PointCloud ());\n pcl::PCDWriter writer;\n\t\n if(pcl::io::loadPCDFile (argv[1], *cloud_ptr) == -1)\n {\n cout<<\"Couldn't read the file \"<points.size () << std::endl;\n\n \/\/ Normal estimation\n pcl::NormalEstimation ne;\n ne.setInputCloud(cloud_ptr);\n\n pcl::search::KdTree::Ptr tree_n (new pcl::search::KdTree());\n ne.setSearchMethod(tree_n);\n ne.setRadiusSearch(0.03);\n ne.compute(*cloud_normals);\n std::cout << \"Estimated the normals\" << std::endl;\n\n \/\/ Creating the kdtree object for the search method of the extraction\n boost::shared_ptr > tree_ec (new pcl::KdTreeFLANN ());\n tree_ec->setInputCloud (cloud_ptr);\n \n \/\/ Extracting Euclidean clusters using cloud and its normals\n std::vector indices;\n std::vector cluster_indices;\n const float tolerance = 0.5f; \/\/ 50cm tolerance in (x, y, z) coordinate system\n const double eps_angle = 5*(M_PI\/180); \/\/ 5degree tolerance in normals\n const unsigned int min_cluster_size = 50;\n \n pcl::extractEuclideanClusters(*cloud_ptr, *cloud_normals, tolerance, tree_ec, cluster_indices, eps_angle, min_cluster_size);\n\n\n std::cout << \"No of clusters formed are \" << cluster_indices.size () << std::endl;\n\n int j = 0;\n for (std::vector::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)\n {\n pcl::PointCloud::Ptr cloud_cluster (new pcl::PointCloud);\n for (std::vector::const_iterator pit = it->indices.begin (); pit != it->indices.end (); pit++)\n cloud_cluster->points.push_back (cloud_ptr->points[*pit]); \n cloud_cluster->width = cloud_cluster->points.size ();\n cloud_cluster->height = 1;\n cloud_cluster->is_dense = true;\n\n std::cout << \"PointCloud representing the Cluster using xyzn: \" << cloud_cluster->points.size () << \" data points.\" << std::endl;\n std::stringstream ss;\n ss << \".\/cloud_cluster_\" << j << \".pcd\";\n writer.write (ss.str (), *cloud_cluster, false); \n j++;\n }\n\n return 0;\n}\nadding some comments to example_extract_clusters_normals.cpp\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2009-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\n *\/\n\n\/\/ STL\n#include \n\n\/\/ PCL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint \nmain(int argc, char **argv)\n{\n pcl::PointCloud::Ptr cloud_ptr (new pcl::PointCloud ());\n pcl::PointCloud::Ptr cloud_normals (new pcl::PointCloud ());\n pcl::PCDWriter writer;\n\t\n if(pcl::io::loadPCDFile (argv[1], *cloud_ptr) == -1)\n {\n cout<<\"Couldn't read the file \"<points.size () << std::endl;\n\n \/\/ Normal estimation\n pcl::NormalEstimation ne;\n ne.setInputCloud(cloud_ptr);\n\n pcl::search::KdTree::Ptr tree_n (new pcl::search::KdTree());\n ne.setSearchMethod(tree_n);\n ne.setRadiusSearch(0.03);\n ne.compute(*cloud_normals);\n std::cout << \"Estimated the normals\" << std::endl;\n\n \/\/ Creating the kdtree object for the search method of the extraction\n boost::shared_ptr > tree_ec (new pcl::KdTreeFLANN ());\n tree_ec->setInputCloud (cloud_ptr);\n \n \/\/ Extracting Euclidean clusters using cloud and its normals\n std::vector indices;\n std::vector cluster_indices;\n const float tolerance = 0.5f; \/\/ 50cm tolerance in (x, y, z) coordinate system\n const double eps_angle = 5*(M_PI\/180); \/\/ 5degree tolerance in normals\n const unsigned int min_cluster_size = 50;\n \n pcl::extractEuclideanClusters(*cloud_ptr, *cloud_normals, tolerance, tree_ec, cluster_indices, eps_angle, min_cluster_size);\n\n\n std::cout << \"No of clusters formed are \" << cluster_indices.size () << std::endl;\n\n \/\/ Saving the clusters in seperate pcd files\n int j = 0;\n for (std::vector::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)\n {\n pcl::PointCloud::Ptr cloud_cluster (new pcl::PointCloud);\n for (std::vector::const_iterator pit = it->indices.begin (); pit != it->indices.end (); pit++)\n cloud_cluster->points.push_back (cloud_ptr->points[*pit]); \n cloud_cluster->width = cloud_cluster->points.size ();\n cloud_cluster->height = 1;\n cloud_cluster->is_dense = true;\n\n std::cout << \"PointCloud representing the Cluster using xyzn: \" << cloud_cluster->points.size () << \" data points.\" << std::endl;\n std::stringstream ss;\n ss << \".\/cloud_cluster_\" << j << \".pcd\";\n writer.write (ss.str (), *cloud_cluster, false); \n j++;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"con_thread.hpp\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"io_utils.hpp\"\n\nusing namespace std;\nnamespace co = boost::coroutines;\n\nenum connection_co_status\n{\n\tSTATUS_ERROR = -1,\n\tSTATUS_DONE = 0,\n\tSTATUS_WAIT_READ,\n\tSTATUS_WAIT_WRITE\n};\n\ntemplate \nstatic io_status read_n_co(YieldType& yield, int fd, void *buf, std::size_t count, std::size_t& count_out)\n{\n\tio_status result;\n\twhile((result = read_n(fd, buf, count, count_out)) == IO_AGAIN && count_out == 0)\n\t{\n\t\tyield(STATUS_WAIT_READ);\n\t}\n\treturn result;\n}\n\ntemplate \nstatic io_status write_n_co(YieldType& yield, int fd, const void *buf, std::size_t count, std::size_t& count_out)\n{\n\tio_status result;\n\twhile((result = write_n(fd, buf, count, count_out)) == IO_AGAIN && count_out == 0)\n\t{\n\t\tyield(STATUS_WAIT_WRITE);\n\t}\n\treturn result;\n}\n\nvoid echo_connection_co_func(co::symmetric_coroutine::yield_type& yield)\n{\n\tauto read_yielder =\n\t[\n}\n\nvoid con_thread_func(int epoll_fd, const std::atomic_bool& run)\n{\n\tstruct con_state\n\t{\n\t\tstd::array data;\n\t\tstd::size_t size;\n\t\tbool writable;\n\n\t\tcon_state(): size(0), writable(false) {}\n\t};\n\tstd::unordered_map con_data;\n\n\tchar buffer[256];\n\t\n\tint con_sock;\n\twhile(run.load())\n\t{\n\t\tstruct epoll_event events[8];\n\t\tint num = epoll_wait(epoll_fd, events, 8, 50);\n\t\tfor(int i = 0; i < num; ++i)\n\t\t{\n\t\t\tfprintf(stderr, \"Handling input\\n\");\n\t\t\tint fd = events[i].data.fd;\n\t\t\tuint32_t ev = events[i].events;\n\t\t\tif(ev & EPOLLRDHUP || ev & EPOLLHUP || ev & EPOLLERR)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\tclose(fd);\n\t\t\t\tcon_data.erase(fd);\n\t\t\t\tcontinue; \/\/ Go to next fd\n\t\t\t}\n\n\t\t\tcon_state& s = con_data[fd];\n\t\t\t\n\t\t\tif(ev & EPOLLOUT)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"EPOLLOUT\\n\");\n\t\t\t\tsize_t written = 0;\n\t\t\t\tif(s.size > 0)\n\t\t\t\t{\n\t\t\t\t\tio_result result = write_n(fd, &s.data[0], s.size, written);\n\t\t\t\t\tif(result == IO_FAIL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tif(written < s.size && written > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::copy(s.data.begin() + written, s.data.begin() + s.size, s.data.begin());\n\t\t\t\t\t\ts.size -= written;\n\t\t\t\t\t}\n\t\t\t\t\telse if(written == s.size)\n\t\t\t\t\t{\n\t\t\t\t\t\ts.size = 0;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tif(result == IO_SUCCESS)\n\t\t\t\t\t{\n\t\t\t\t\t\ts.writable = true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ts.writable = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts.writable = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(ev & EPOLLIN)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"EPOLLIN\\n\");\n\t\t\t\tio_result read_result = IO_SUCCESS, write_result = IO_SUCCESS;\n\t\t\t\twhile(s.writable)\n\t\t\t\t{\n\t\t\t\t\tsize_t count = 0;\n\t\t\t\t\tread_result = read_n(fd, buffer, sizeof(buffer), count);\n\t\t\t\t if(read_result == IO_FAIL)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tif(count > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t written = 0;\n\t\t\t\t\t\twrite_result = write_n(fd, buffer, count, written);\n\t\t\t\t\t\tif(write_result == IO_FAIL)\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tif(write_result == IO_AGAIN)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::copy(buffer + written, buffer + count, s.data.begin());\n\t\t\t\t\t\t\ts.size = count - written;\n\t\t\t\t\t\t\ts.writable = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(read_result == IO_AGAIN)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(read_result == IO_FAIL || write_result == IO_FAIL)\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\t\tclose(fd);\n\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(read_result == IO_SUCCESS)\n\t\t\t\t{\n\t\t\t\t if(s.size < s.data.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t count = 0;\n\t\t\t\t\t\tread_result = read_n(fd, &s.data[0], s.data.size() - s.size, count);\n\t\t\t\t\t\tif(read_result == IO_FAIL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ts.size += count;\n\t\t\t\t\t}\n\t\t\t\t \/\/ Just discard any more bytes once fd buffer is full\n\t\t\t\t\twhile(read_result == IO_SUCCESS)\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t count = 0;\n\t\t\t\t\t\tread_result = read_n(fd, buffer, sizeof(buffer), count);\n\t\t\t\t\t}\n\t\t\t\t\tif(read_result == IO_FAIL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t \/\/ struct epoll_event new_event;\n\t\t \/\/ new_event.events = EPOLL_EVENTS;\n\t\t\t\/\/ new_event.data.fd = fd;\n\t\t\t\/\/ epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &new_event);\n\t\t}\n\t}\n}\nCoroutines#include \"con_thread.hpp\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"io_utils.hpp\"\n\nusing namespace std;\nnamespace co = boost::coroutines;\n\nenum connection_co_status\n{\n\tSTATUS_ERROR = -1,\n\tSTATUS_DONE = 0,\n\tSTATUS_WAIT_READ,\n\tSTATUS_WAIT_WRITE\n};\n\ntemplate \nstatic io_status read_n_co(YieldType& yield, int fd, void *buf, std::size_t count, std::size_t& count_out)\n{\n\tio_status result;\n\twhile((result = read_n(fd, buf, count, count_out)) == IO_AGAIN && count_out == 0)\n\t{\n\t\tyield(STATUS_WAIT_READ);\n\t}\n\treturn result;\n}\n\ntemplate \nstatic io_status write_n_co(YieldType& yield, int fd, const void *buf, std::size_t count, std::size_t& count_out)\n{\n\tio_status result;\n\twhile((result = write_n(fd, buf, count, count_out)) == IO_AGAIN && count_out == 0)\n\t{\n\t\tyield(STATUS_WAIT_WRITE);\n\t}\n\treturn result;\n}\n\nusing connection_coroutine = co::symmetric_coroutine;\nusing poller_coroutine = co::symmetric_coroutine;\n\nstruct connection_data\n{\n\tint fd;\n\tconnection_co_status status;\n};\n\nstatic void connection_co_func(connection_coroutine::yield_type& yield, poller_coroutine& poller, connection_data& data)\n{\n\tauto yielder = bind(yield, ref(poller), placeholders::_1);\n\n\tchar buffer[256];\n\tio_status result;\n\twhile(true)\n\t{\n\t\tsize_t count;\n\t\tresult = read_n_co(yielder, data.fd, buffer, sizeof(buffer), count);\n\t\tif(result == IO_FAIL)\n\t\t\tbreak;\n\t\tresult = write_n_co(yielder, data.fd, buffer, sizeof(buffer), count);\n\t\tif(result == IO_FAIL)\n\t\t\tbreak;\n\t}\n\n\tyield(poller, STATUS_DONE);\n}\n\nstruct connection\n{\n\tconnection_coroutine co;\n\tconnection_data data;\n}\n\nstatic void poller_co_func(poller_coroutine::yield_type& yield, poller_coroutine& this_co, int epoll_fd, atomic_bool& should_run)\n{\n\tmap cons;\n\twhile(should_run.load())\n\t{\n\t\tstruct epoll_event events[8];\n\t\tint num_events = epoll_wait(epoll_fd, events, 8, 50);\n\t\tfor(int i = 0; i < num_events; ++i)\n\t\t{\n\t\t\tint fd = events[i].data.fd;\n\t\t uint32_t event_mask = events[i].events;\n\t\t\tauto it = cons.find(fd);\n\t\t\tif(it == cons.end())\n\t\t\t{\n\t\t\t\tit = cons.emplace(fd, connection{});\n\t\t\t\tit->second.co = bind(connection_co_func, placeholders::_1, ref(this_co), ref(it->second));\n\t\t\t\tit->second.data = {fd, STATUS_WAIT_READ};\n\t\t\t}\n\n\t\t\tconnection_co_status status = it->second.data.status;\n\t\t\tif((status == STATUS_WAIT_READ && (event_mask & EPOLLIN)) || (status == STATUS_WAIT_WRITE && (event_mask & EPOLLOUT)))\n\t\t\t{\n\t\t\t\tyield(it->second.co);\n\t\t\t\tstatus = yield.get();\n\t\t\t}\n\n\t\t\tif(status == STATUS_DONE || status == STATUS_FAIL)\n\t\t\t{\n\t\t\t\tgoto end_con;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t\t\n\t\tend_con:\n\t\t\tclose(fd);\n\t\t\tcons.erase(it);\n\t\t}\n\t}\n}\n\nvoid con_thread_func(int epoll_fd, const std::atomic_bool& run)\n{\n\tstruct con_state\n\t{\n\t\tstd::array data;\n\t\tstd::size_t size;\n\t\tbool writable;\n\n\t\tcon_state(): size(0), writable(false) {}\n\t};\n\tstd::unordered_map con_data;\n\n\tchar buffer[256];\n\t\n\tint con_sock;\n\twhile(run.load())\n\t{\n\t\tstruct epoll_event events[8];\n\t\tint num = epoll_wait(epoll_fd, events, 8, 50);\n\t\tfor(int i = 0; i < num; ++i)\n\t\t{\n\t\t\tfprintf(stderr, \"Handling input\\n\");\n\t\t\tint fd = events[i].data.fd;\n\t\t\tuint32_t ev = events[i].events;\n\t\t\tif(ev & EPOLLRDHUP || ev & EPOLLHUP || ev & EPOLLERR)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\tclose(fd);\n\t\t\t\tcon_data.erase(fd);\n\t\t\t\tcontinue; \/\/ Go to next fd\n\t\t\t}\n\n\t\t\tcon_state& s = con_data[fd];\n\t\t\t\n\t\t\tif(ev & EPOLLOUT)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"EPOLLOUT\\n\");\n\t\t\t\tsize_t written = 0;\n\t\t\t\tif(s.size > 0)\n\t\t\t\t{\n\t\t\t\t\tio_result result = write_n(fd, &s.data[0], s.size, written);\n\t\t\t\t\tif(result == IO_FAIL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tif(written < s.size && written > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::copy(s.data.begin() + written, s.data.begin() + s.size, s.data.begin());\n\t\t\t\t\t\ts.size -= written;\n\t\t\t\t\t}\n\t\t\t\t\telse if(written == s.size)\n\t\t\t\t\t{\n\t\t\t\t\t\ts.size = 0;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tif(result == IO_SUCCESS)\n\t\t\t\t\t{\n\t\t\t\t\t\ts.writable = true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ts.writable = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts.writable = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(ev & EPOLLIN)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"EPOLLIN\\n\");\n\t\t\t\tio_result read_result = IO_SUCCESS, write_result = IO_SUCCESS;\n\t\t\t\twhile(s.writable)\n\t\t\t\t{\n\t\t\t\t\tsize_t count = 0;\n\t\t\t\t\tread_result = read_n(fd, buffer, sizeof(buffer), count);\n\t\t\t\t if(read_result == IO_FAIL)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tif(count > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t written = 0;\n\t\t\t\t\t\twrite_result = write_n(fd, buffer, count, written);\n\t\t\t\t\t\tif(write_result == IO_FAIL)\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tif(write_result == IO_AGAIN)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::copy(buffer + written, buffer + count, s.data.begin());\n\t\t\t\t\t\t\ts.size = count - written;\n\t\t\t\t\t\t\ts.writable = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(read_result == IO_AGAIN)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(read_result == IO_FAIL || write_result == IO_FAIL)\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\t\tclose(fd);\n\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(read_result == IO_SUCCESS)\n\t\t\t\t{\n\t\t\t\t if(s.size < s.data.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t count = 0;\n\t\t\t\t\t\tread_result = read_n(fd, &s.data[0], s.data.size() - s.size, count);\n\t\t\t\t\t\tif(read_result == IO_FAIL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ts.size += count;\n\t\t\t\t\t}\n\t\t\t\t \/\/ Just discard any more bytes once fd buffer is full\n\t\t\t\t\twhile(read_result == IO_SUCCESS)\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t count = 0;\n\t\t\t\t\t\tread_result = read_n(fd, buffer, sizeof(buffer), count);\n\t\t\t\t\t}\n\t\t\t\t\tif(read_result == IO_FAIL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"Closed\\n\");\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\tcon_data.erase(fd);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t \/\/ struct epoll_event new_event;\n\t\t \/\/ new_event.events = EPOLL_EVENTS;\n\t\t\t\/\/ new_event.data.fd = fd;\n\t\t\t\/\/ epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &new_event);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ LuaWindow.cpp\n\n\/\/ Implements the cLuaWindow class representing a virtual window that plugins may create and open for the player\n\n#include \"Globals.h\"\n#include \"LuaWindow.h\"\n#include \"..\/Entities\/Player.h\"\n#include \"..\/UI\/SlotArea.h\"\n#include \"PluginLua.h\"\n#include \"lua\/src\/lauxlib.h\" \/\/ Needed for LUA_REFNIL\n#include \"..\/Root.h\"\n#include \"..\/ClientHandle.h\"\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cLuaWindow:\n\ncLuaWindow::cLuaWindow(cLuaState & a_LuaState, cWindow::WindowType a_WindowType, int a_SlotsX, int a_SlotsY, const AString & a_Title) :\n\tSuper(a_WindowType, a_Title),\n\tm_Contents(a_SlotsX, a_SlotsY),\n\tm_LuaState(a_LuaState.QueryCanonLuaState())\n{\n\tASSERT(m_LuaState != nullptr); \/\/ We must have a valid Lua state; this assert fails only if there was no Canon Lua state\n\n\tm_Contents.AddListener(*this);\n\tm_SlotAreas.push_back(new cSlotAreaItemGrid(m_Contents, *this));\n\n\t\/\/ If appropriate, add an Armor slot area:\n\tswitch (a_WindowType)\n\t{\n\t\tcase cWindow::wtInventory:\n\t\tcase cWindow::wtWorkbench:\n\t\t{\n\t\t\tm_SlotAreas.push_back(new cSlotAreaArmor(*this));\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tm_SlotAreas.push_back(new cSlotAreaInventory(*this));\n\tm_SlotAreas.push_back(new cSlotAreaHotBar(*this));\n}\n\n\n\n\n\ncLuaWindow::~cLuaWindow()\n{\n\tm_Contents.RemoveListener(*this);\n\n\t\/\/ Close open lua window from players, to avoid dangling pointers\n\tcRoot::Get()->ForEachPlayer([this](cPlayer & a_Player)\n\t\t{\n\t\t\tif (a_Player.GetWindow() == this)\n\t\t\t{\n\t\t\t\ta_Player.CloseWindow(false);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t);\n\n\t\/\/ Must delete slot areas now, because they are referencing this->m_Contents and would try to access it in cWindow's\n\t\/\/ destructor, when the member is already gone.\n\tfor (cSlotAreas::iterator itr = m_SlotAreas.begin(), end = m_SlotAreas.end(); itr != end; ++itr)\n\t{\n\t\tdelete *itr;\n\t}\n\tm_SlotAreas.clear();\n\n\tASSERT(m_OpenedBy.empty());\n}\n\n\n\n\n\nvoid cLuaWindow::SetOnClicked(cLuaState::cCallbackPtr && a_OnClicked)\n{\n\t\/\/ Only one Lua state can be a cLuaWindow object callback:\n\tASSERT(a_OnClicked->IsSameLuaState(*m_LuaState));\n\n\t\/\/ Store the new reference, releasing the old one if appropriate:\n\tm_OnClicked = std::move(a_OnClicked);\n}\n\n\n\n\n\nvoid cLuaWindow::SetOnClosing(cLuaState::cCallbackPtr && a_OnClosing)\n{\n\t\/\/ Only one Lua state can be a cLuaWindow object callback:\n\tASSERT(a_OnClosing->IsSameLuaState(*m_LuaState));\n\n\t\/\/ Store the new reference, releasing the old one if appropriate:\n\tm_OnClosing = std::move(a_OnClosing);\n}\n\n\n\n\n\nvoid cLuaWindow::SetOnSlotChanged(cLuaState::cCallbackPtr && a_OnSlotChanged)\n{\n\t\/\/ Only one Lua state can be a cLuaWindow object callback:\n\tASSERT(a_OnSlotChanged->IsSameLuaState(*m_LuaState));\n\n\t\/\/ Store the new reference, releasing the old one if appropriate:\n\tm_OnSlotChanged = std::move(a_OnSlotChanged);\n}\n\n\n\n\n\nvoid cLuaWindow::OpenedByPlayer(cPlayer & a_Player)\n{\n\t\/\/ If the first player is opening the window, create a Lua Reference to the window object so that Lua will not GC it until the last player closes the window:\n\tif (m_PlayerCount == 0)\n\t{\n\t\tm_LuaRef.CreateFromObject(*m_LuaState, this);\n\t}\n\n\t++m_PlayerCount;\n\tSuper::OpenedByPlayer(a_Player);\n}\n\n\n\n\n\nbool cLuaWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse)\n{\n\t\/\/ First notify the plugin through the registered callback:\n\tif (m_OnClosing != nullptr)\n\t{\n\t\tbool res;\n\t\tif (\n\t\t\tm_OnClosing->Call(this, &a_Player, a_CanRefuse, cLuaState::Return, res) && \/\/ The callback succeeded\n\t\t\tres \/\/ The callback says not to close the window\n\t\t)\n\t\t{\n\t\t\t\/\/ The callback disagrees (the higher levels check the CanRefuse flag compliance)\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ If the last player has closed the window, release the Lua reference, so that Lua may GC the object:\n\t--m_PlayerCount;\n\tif (m_PlayerCount == 0)\n\t{\n\t\tm_LuaRef.UnRef();\n\t}\n\n\treturn Super::ClosedByPlayer(a_Player, a_CanRefuse);\n}\n\n\n\n\n\nvoid cLuaWindow::Destroy(void)\n{\n\tSuper::Destroy();\n\n\t\/\/ Lua will take care of this object, it will garbage-collect it, so we must not delete it!\n\tm_IsDestroyed = false;\n}\n\n\n\n\n\nvoid cLuaWindow::DistributeStack(cItem & a_ItemStack, int a_Slot, cPlayer & a_Player, cSlotArea * a_ClickedArea, bool a_ShouldApply)\n{\n\tcSlotAreas Areas;\n\tfor (auto && Area : m_SlotAreas)\n\t{\n\t\tif (Area != a_ClickedArea)\n\t\t{\n\t\t\tAreas.push_back(Area);\n\t\t}\n\t}\n\n\tSuper::DistributeStackToAreas(a_ItemStack, a_Player, Areas, a_ShouldApply, false);\n}\n\n\n\n\n\nvoid cLuaWindow::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum)\n{\n\tif (a_ItemGrid != &m_Contents)\n\t{\n\t\tASSERT(!\"Invalid ItemGrid in callback\");\n\t\treturn;\n\t}\n\n\t\/\/ If an OnSlotChanged callback has been registered, call it:\n\tif (m_OnSlotChanged != nullptr)\n\t{\n\t\tm_OnSlotChanged->Call(this, a_SlotNum);\n\t}\n}\n\n\n\n\n\nvoid cLuaWindow::Clicked(cPlayer & a_Player, int a_WindowID, short a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem)\n{\n\tif (m_OnClicked != nullptr)\n\t{\n\t\t\/\/ Plugin can stop a click\n\t\tif (m_OnClicked->Call(this, &a_Player, a_SlotNum, a_ClickAction, a_ClickedItem))\n\t\t{\n\t\t\t\/\/ Tell the client the actual state of the window\n\t\t\ta_Player.GetClientHandle()->SendInventorySlot(-1, -1, a_Player.GetDraggingItem());\n\t\t\tBroadcastWholeWindow();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tcWindow::Clicked(a_Player, a_WindowID, a_SlotNum, a_ClickAction, a_ClickedItem);\n}\n\n\n\n\nRespect return value of cLuaWindow's OnClicked handler (#4322)\/\/ LuaWindow.cpp\n\n\/\/ Implements the cLuaWindow class representing a virtual window that plugins may create and open for the player\n\n#include \"Globals.h\"\n#include \"LuaWindow.h\"\n#include \"..\/Entities\/Player.h\"\n#include \"..\/UI\/SlotArea.h\"\n#include \"PluginLua.h\"\n#include \"lua\/src\/lauxlib.h\" \/\/ Needed for LUA_REFNIL\n#include \"..\/Root.h\"\n#include \"..\/ClientHandle.h\"\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cLuaWindow:\n\ncLuaWindow::cLuaWindow(cLuaState & a_LuaState, cWindow::WindowType a_WindowType, int a_SlotsX, int a_SlotsY, const AString & a_Title) :\n\tSuper(a_WindowType, a_Title),\n\tm_Contents(a_SlotsX, a_SlotsY),\n\tm_LuaState(a_LuaState.QueryCanonLuaState())\n{\n\tASSERT(m_LuaState != nullptr); \/\/ We must have a valid Lua state; this assert fails only if there was no Canon Lua state\n\n\tm_Contents.AddListener(*this);\n\tm_SlotAreas.push_back(new cSlotAreaItemGrid(m_Contents, *this));\n\n\t\/\/ If appropriate, add an Armor slot area:\n\tswitch (a_WindowType)\n\t{\n\t\tcase cWindow::wtInventory:\n\t\tcase cWindow::wtWorkbench:\n\t\t{\n\t\t\tm_SlotAreas.push_back(new cSlotAreaArmor(*this));\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tm_SlotAreas.push_back(new cSlotAreaInventory(*this));\n\tm_SlotAreas.push_back(new cSlotAreaHotBar(*this));\n}\n\n\n\n\n\ncLuaWindow::~cLuaWindow()\n{\n\tm_Contents.RemoveListener(*this);\n\n\t\/\/ Close open lua window from players, to avoid dangling pointers\n\tcRoot::Get()->ForEachPlayer([this](cPlayer & a_Player)\n\t\t{\n\t\t\tif (a_Player.GetWindow() == this)\n\t\t\t{\n\t\t\t\ta_Player.CloseWindow(false);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t);\n\n\t\/\/ Must delete slot areas now, because they are referencing this->m_Contents and would try to access it in cWindow's\n\t\/\/ destructor, when the member is already gone.\n\tfor (cSlotAreas::iterator itr = m_SlotAreas.begin(), end = m_SlotAreas.end(); itr != end; ++itr)\n\t{\n\t\tdelete *itr;\n\t}\n\tm_SlotAreas.clear();\n\n\tASSERT(m_OpenedBy.empty());\n}\n\n\n\n\n\nvoid cLuaWindow::SetOnClicked(cLuaState::cCallbackPtr && a_OnClicked)\n{\n\t\/\/ Only one Lua state can be a cLuaWindow object callback:\n\tASSERT(a_OnClicked->IsSameLuaState(*m_LuaState));\n\n\t\/\/ Store the new reference, releasing the old one if appropriate:\n\tm_OnClicked = std::move(a_OnClicked);\n}\n\n\n\n\n\nvoid cLuaWindow::SetOnClosing(cLuaState::cCallbackPtr && a_OnClosing)\n{\n\t\/\/ Only one Lua state can be a cLuaWindow object callback:\n\tASSERT(a_OnClosing->IsSameLuaState(*m_LuaState));\n\n\t\/\/ Store the new reference, releasing the old one if appropriate:\n\tm_OnClosing = std::move(a_OnClosing);\n}\n\n\n\n\n\nvoid cLuaWindow::SetOnSlotChanged(cLuaState::cCallbackPtr && a_OnSlotChanged)\n{\n\t\/\/ Only one Lua state can be a cLuaWindow object callback:\n\tASSERT(a_OnSlotChanged->IsSameLuaState(*m_LuaState));\n\n\t\/\/ Store the new reference, releasing the old one if appropriate:\n\tm_OnSlotChanged = std::move(a_OnSlotChanged);\n}\n\n\n\n\n\nvoid cLuaWindow::OpenedByPlayer(cPlayer & a_Player)\n{\n\t\/\/ If the first player is opening the window, create a Lua Reference to the window object so that Lua will not GC it until the last player closes the window:\n\tif (m_PlayerCount == 0)\n\t{\n\t\tm_LuaRef.CreateFromObject(*m_LuaState, this);\n\t}\n\n\t++m_PlayerCount;\n\tSuper::OpenedByPlayer(a_Player);\n}\n\n\n\n\n\nbool cLuaWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse)\n{\n\t\/\/ First notify the plugin through the registered callback:\n\tif (m_OnClosing != nullptr)\n\t{\n\t\tbool res;\n\t\tif (\n\t\t\tm_OnClosing->Call(this, &a_Player, a_CanRefuse, cLuaState::Return, res) && \/\/ The callback succeeded\n\t\t\tres \/\/ The callback says not to close the window\n\t\t)\n\t\t{\n\t\t\t\/\/ The callback disagrees (the higher levels check the CanRefuse flag compliance)\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ If the last player has closed the window, release the Lua reference, so that Lua may GC the object:\n\t--m_PlayerCount;\n\tif (m_PlayerCount == 0)\n\t{\n\t\tm_LuaRef.UnRef();\n\t}\n\n\treturn Super::ClosedByPlayer(a_Player, a_CanRefuse);\n}\n\n\n\n\n\nvoid cLuaWindow::Destroy(void)\n{\n\tSuper::Destroy();\n\n\t\/\/ Lua will take care of this object, it will garbage-collect it, so we must not delete it!\n\tm_IsDestroyed = false;\n}\n\n\n\n\n\nvoid cLuaWindow::DistributeStack(cItem & a_ItemStack, int a_Slot, cPlayer & a_Player, cSlotArea * a_ClickedArea, bool a_ShouldApply)\n{\n\tcSlotAreas Areas;\n\tfor (auto && Area : m_SlotAreas)\n\t{\n\t\tif (Area != a_ClickedArea)\n\t\t{\n\t\t\tAreas.push_back(Area);\n\t\t}\n\t}\n\n\tSuper::DistributeStackToAreas(a_ItemStack, a_Player, Areas, a_ShouldApply, false);\n}\n\n\n\n\n\nvoid cLuaWindow::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum)\n{\n\tif (a_ItemGrid != &m_Contents)\n\t{\n\t\tASSERT(!\"Invalid ItemGrid in callback\");\n\t\treturn;\n\t}\n\n\t\/\/ If an OnSlotChanged callback has been registered, call it:\n\tif (m_OnSlotChanged != nullptr)\n\t{\n\t\tm_OnSlotChanged->Call(this, a_SlotNum);\n\t}\n}\n\n\n\n\n\nvoid cLuaWindow::Clicked(cPlayer & a_Player, int a_WindowID, short a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem)\n{\n\tif (m_OnClicked != nullptr)\n\t{\n\t\t\/\/ Plugin can stop a click\n\t\tbool res;\n\t\tif (m_OnClicked->Call(this, &a_Player, a_SlotNum, a_ClickAction, a_ClickedItem, cLuaState::Return, res) && res)\n\t\t{\n\t\t\t\/\/ Tell the client the actual state of the window\n\t\t\ta_Player.GetClientHandle()->SendInventorySlot(-1, -1, a_Player.GetDraggingItem());\n\t\t\tBroadcastWholeWindow();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tcWindow::Clicked(a_Player, a_WindowID, a_SlotNum, a_ClickAction, a_ClickedItem);\n}\n\n\n\n\n<|endoftext|>"} {"text":"Fix special case registers to be per-thread. Remove RMOR.<|endoftext|>"} {"text":"#include \"MainForm.moc\"\n\n#include \"..\/assemble.h\"\n#include \n\nMainForm::MainForm(QGraphicsScene* img, nbt* bf, QWidget* parent_)\n : QGraphicsView(img, parent_), scene_(), bf_(bf), scale_(1),\n images() {\n connect(this, SIGNAL(scaleSig()), this, SLOT(scale()));\n connect(this, SIGNAL(renderNewImage()), this, SLOT(populateSceneItem()));\n connect(this, SIGNAL(saveToFileSignal()), this, SLOT(saveToFile()));\n setTransformationAnchor(QGraphicsView::AnchorUnderMouse);\n}\n\nclass ApplyFooQT {\n mutable MainForm* mainform_;\n int i_;\n mutable tbb::atomic* index_;\n public:\n void operator()( const tbb::blocked_range::iterator>& r ) const {\n for(std::vector::iterator j=r.begin(); j!=r.end(); ++j) {\n bool result = false;\n std::pair bp = projectCoords(std::make_pair(*j, i_),\n (4 - mainform_->bf_->set().rotate) % 4);\n Image image = mainform_->bf_->getImage(bp.first, bp.second, &result);\n if (!result) {\n continue;\n }\n *index_ += 1;\n mainform_->images.push(MainForm::image_coords(image, QPoint(bp.first,\n bp.second)));\n mainform_->renderNewImageEmitter();\n }\n }\n ApplyFooQT(MainForm* mainform, int i, tbb::atomic* index)\n : mainform_(mainform), i_(i), index_(index) {}\n \/* just for the compiler *\/\n ApplyFooQT(const ApplyFooQT& rhs)\n : mainform_(rhs.mainform_), i_(rhs.i_), index_(rhs.index_) {}\n private:\n ApplyFooQT& operator=(const ApplyFoo&);\n};\n\n\nvoid MainForm::populateScene() {\n std::pair min_norm, max_norm;\n calculateMinMaxPoint(min_norm, max_norm, *bf_);\n size_t range = static_cast(max_norm.second - min_norm.second + 1);\n boost::progress_display show_progress(range);\n std::list > tiles(range);\n size_t tiles_nr = fillTiles(tiles, *bf_, min_norm, max_norm, show_progress);\n tbb::atomic progress_index, mem_index;\n progress_index = 0;\n mem_index = 0;\n show_progress.restart(tiles_nr);\n std::list >::iterator it = tiles.begin();\n tbb::task_scheduler_init init;\n for (int i = min_norm.second; i <= max_norm.second; ++i) {\n tbb::parallel_for(tbb::blocked_range::iterator>\n (it->begin(), it->end()),\n ApplyFooQT(this, i, &progress_index));\n mem_index += progress_index;\n if (mem_index > 10000) {\n mem_index = 0;\n bf_->clearCache();\n }\n ++it;\n show_progress += progress_index;\n progress_index = 0;\n }\n bf_->clearCache();\n emit saveToFileSignal();\n}\n\nvoid MainForm::renderNewImageEmitter() {\n emit renderNewImage();\n}\n\nvoid MainForm::saveToFile() {\n QImage image(scene()->sceneRect().toRect().size(), QImage::Format_ARGB32);\n image.fill(0);\n QPainter painter(&image);\n scene()->render(&painter, painter.viewport(), scene()->sceneRect());\n image.save(\"image.png\");\n fprintf(stderr, \"image saved!\\n\");\n \/\/ throw std::runtime_error(\"image saved!\");\n}\n\nvoid MainForm::populateSceneItem() {\n MainForm::image_coords img_coor;\n if (images.pop_if_present(img_coor)) {\n QImage img(&(img_coor.first.data[0]),\n img_coor.first.cols,\n img_coor.first.rows,\n QImage::Format_ARGB32);\n QGraphicsPixmapItem* pi = scene()->addPixmap(QPixmap::fromImage(img));\n pi->setFlag(QGraphicsItem::ItemIsMovable, false);\n pi->setFlag(QGraphicsItem::ItemIsSelectable, false);\n std::pair p = projectCoords(\n std::make_pair(16 * img_coor.second.x(),\n 16 * img_coor.second.y()),\n bf_->set().rotate);\n if (bf_->set().isometric) {\n p = std::make_pair(2 * p.first - 2 * p.second, p.first + p.second);\n }\n pi->setPos(p.first, p.second);\n pi->setZValue(p.second);\n } else {\n throw std::runtime_error(\"must not happen in populateSceneItem()!\");\n }\n}\n\nvoid MainForm::scale() {\n if (scale_ <= 0) {\n setTransform(QTransform().scale(1.0 \/ pow(2.0, abs(scale_ - 1)),\n 1.0 \/ pow(2.0, abs(scale_ - 1))));\n } else {\n setTransform(QTransform().scale(scale_, scale_));\n }\n}\n\nvoid MainForm::mousePressEvent(QMouseEvent* mevent) {\n switch (mevent->button()) {\n case Qt::LeftButton:\n ++scale_;\n emit scaleSig();\n break;\n case Qt::MidButton:\n break;\n case Qt::RightButton:\n --scale_;\n emit scaleSig();\n break;\n default:\n break;\n }\n return;\n}\n\nvoid MainForm::mouseDoubleClickEvent(QMouseEvent* mevent) {\n mousePressEvent(mevent);\n return;\n}\nfix bug with older Qt, where 0,0 was in scene rect#include \"MainForm.moc\"\n\n#include \"..\/assemble.h\"\n#include \n\nMainForm::MainForm(QGraphicsScene* img, nbt* bf, QWidget* parent_)\n : QGraphicsView(img, parent_), scene_(), bf_(bf), scale_(1),\n images() {\n connect(this, SIGNAL(scaleSig()), this, SLOT(scale()));\n connect(this, SIGNAL(renderNewImage()), this, SLOT(populateSceneItem()));\n connect(this, SIGNAL(saveToFileSignal()), this, SLOT(saveToFile()));\n setTransformationAnchor(QGraphicsView::AnchorUnderMouse);\n}\n\nclass ApplyFooQT {\n mutable MainForm* mainform_;\n int i_;\n mutable tbb::atomic* index_;\n public:\n void operator()( const tbb::blocked_range::iterator>& r ) const {\n for(std::vector::iterator j=r.begin(); j!=r.end(); ++j) {\n bool result = false;\n std::pair bp = projectCoords(std::make_pair(*j, i_),\n (4 - mainform_->bf_->set().rotate) % 4);\n Image image = mainform_->bf_->getImage(bp.first, bp.second, &result);\n if (!result) {\n continue;\n }\n *index_ += 1;\n mainform_->images.push(MainForm::image_coords(image, QPoint(bp.first,\n bp.second)));\n mainform_->renderNewImageEmitter();\n }\n }\n ApplyFooQT(MainForm* mainform, int i, tbb::atomic* index)\n : mainform_(mainform), i_(i), index_(index) {}\n \/* just for the compiler *\/\n ApplyFooQT(const ApplyFooQT& rhs)\n : mainform_(rhs.mainform_), i_(rhs.i_), index_(rhs.index_) {}\n private:\n ApplyFooQT& operator=(const ApplyFoo&);\n};\n\n\nvoid MainForm::populateScene() {\n std::pair min_norm, max_norm;\n calculateMinMaxPoint(min_norm, max_norm, *bf_);\n size_t range = static_cast(max_norm.second - min_norm.second + 1);\n boost::progress_display show_progress(range);\n std::list > tiles(range);\n size_t tiles_nr = fillTiles(tiles, *bf_, min_norm, max_norm, show_progress);\n tbb::atomic progress_index, mem_index;\n progress_index = 0;\n mem_index = 0;\n show_progress.restart(tiles_nr);\n std::list >::iterator it = tiles.begin();\n tbb::task_scheduler_init init;\n for (int i = min_norm.second; i <= max_norm.second; ++i) {\n tbb::parallel_for(tbb::blocked_range::iterator>\n (it->begin(), it->end()),\n ApplyFooQT(this, i, &progress_index));\n mem_index += progress_index;\n if (mem_index > 10000) {\n mem_index = 0;\n bf_->clearCache();\n }\n ++it;\n show_progress += progress_index;\n progress_index = 0;\n }\n bf_->clearCache();\n emit saveToFileSignal();\n}\n\nvoid MainForm::renderNewImageEmitter() {\n emit renderNewImage();\n}\n\nvoid MainForm::saveToFile() {\n QImage image(scene()->sceneRect().toRect().size(), QImage::Format_ARGB32);\n image.fill(0);\n QPainter painter(&image);\n scene()->render(&painter, painter.viewport(), scene()->sceneRect());\n image.save(\"image.png\");\n fprintf(stderr, \"image saved!\\n\");\n \/\/ throw std::runtime_error(\"image saved!\");\n}\n\nvoid MainForm::populateSceneItem() {\n MainForm::image_coords img_coor;\n if (images.pop_if_present(img_coor)) {\n QImage img(&(img_coor.first.data[0]),\n img_coor.first.cols,\n img_coor.first.rows,\n QImage::Format_ARGB32);\n std::pair p = projectCoords(\n std::make_pair(16 * img_coor.second.x(),\n 16 * img_coor.second.y()),\n bf_->set().rotate);\n if (bf_->set().isometric) {\n p = std::make_pair(2 * p.first - 2 * p.second, p.first + p.second);\n }\n QGraphicsPixmapItem* pi = new QGraphicsPixmapItem(QPixmap::fromImage(img));\n pi->setPos(p.first, p.second);\n pi->setZValue(p.second);\n pi->setFlag(QGraphicsItem::ItemIsMovable, false);\n pi->setFlag(QGraphicsItem::ItemIsSelectable, false);\n scene()->addItem(pi);\n } else {\n throw std::runtime_error(\"must not happen in populateSceneItem()!\");\n }\n}\n\nvoid MainForm::scale() {\n if (scale_ <= 0) {\n setTransform(QTransform().scale(1.0 \/ pow(2.0, abs(scale_ - 1)),\n 1.0 \/ pow(2.0, abs(scale_ - 1))));\n } else {\n setTransform(QTransform().scale(scale_, scale_));\n }\n}\n\nvoid MainForm::mousePressEvent(QMouseEvent* mevent) {\n switch (mevent->button()) {\n case Qt::LeftButton:\n ++scale_;\n emit scaleSig();\n break;\n case Qt::MidButton:\n break;\n case Qt::RightButton:\n --scale_;\n emit scaleSig();\n break;\n default:\n break;\n }\n return;\n}\n\nvoid MainForm::mouseDoubleClickEvent(QMouseEvent* mevent) {\n mousePressEvent(mevent);\n return;\n}\n<|endoftext|>"} {"text":"\/**\n * @file Dcm.hpp\n *\n * A direction cosine matrix class.\n * All rotations and axis systems follow the right-hand rule.\n *\n * This library uses the convention that premultiplying a three dimensional\n * vector represented in coordinate system 1 will apply a rotation from coordinate system\n * 1 to coordinate system 2 to the vector.\n * Likewise, a matrix instance of this class also represents a coordinate transformation\n * from frame 2 to frame 1.\n *\n * @author James Goppert \n *\/\n\n#pragma once\n\n#include \"math.hpp\"\n\n\nnamespace matrix\n{\n\ntemplate\nclass Quaternion;\n\ntemplate\nclass Euler;\n\ntemplate\nclass AxisAngle;\n\n\n\/**\n * Direction cosine matrix class\n *\n * The rotation between two coordinate frames is\n * described by this class.\n *\/\ntemplate\nclass Dcm : public Matrix\n{\npublic:\n virtual ~Dcm() {};\n\n typedef Matrix Vector3;\n\n \/**\n * Standard constructor\n *\n * Initializes to identity\n *\/\n Dcm() : Matrix()\n {\n (*this) = eye();\n }\n\n \/**\n * Constructor from array\n *\n * @param _data pointer to array\n *\/\n Dcm(const Type *data_) : Matrix(data_)\n {\n }\n\n \/**\n * Copy constructor\n *\n * @param other Matrix33 to set dcm to\n *\/\n Dcm(const Matrix &other) : Matrix(other)\n {\n }\n\n \/**\n * Constructor from quaternion\n *\n * Instance is initialized from quaternion representing\n * coordinate transformation from frame 2 to frame 1.\n *\n * @param q quaternion to set dcm to\n *\/\n Dcm(const Quaternion &q)\n {\n Dcm &dcm = *this;\n Type a = q(0);\n Type b = q(1);\n Type c = q(2);\n Type d = q(3);\n Type aSq = a * a;\n Type bSq = b * b;\n Type cSq = c * c;\n Type dSq = d * d;\n dcm(0, 0) = aSq + bSq - cSq - dSq;\n dcm(0, 1) = 2 * (b * c - a * d);\n dcm(0, 2) = 2 * (a * c + b * d);\n dcm(1, 0) = 2 * (b * c + a * d);\n dcm(1, 1) = aSq - bSq + cSq - dSq;\n dcm(1, 2) = 2 * (c * d - a * b);\n dcm(2, 0) = 2 * (b * d - a * c);\n dcm(2, 1) = 2 * (a * b + c * d);\n dcm(2, 2) = aSq - bSq - cSq + dSq;\n }\n\n \/**\n * Constructor from euler angles\n *\n * This sets the transformation matrix from frame 2 to frame 1 where the rotation\n * from frame 1 to frame 2 is described by a 3-2-1 intrinsic Tait-Bryan rotation sequence.\n *\n *\n * @param euler euler angle instance\n *\/\n Dcm(const Euler &euler)\n {\n Dcm &dcm = *this;\n Type cosPhi = Type(cos(euler.phi()));\n Type sinPhi = Type(sin(euler.phi()));\n Type cosThe = Type(cos(euler.theta()));\n Type sinThe = Type(sin(euler.theta()));\n Type cosPsi = Type(cos(euler.psi()));\n Type sinPsi = Type(sin(euler.psi()));\n\n dcm(0, 0) = cosThe * cosPsi;\n dcm(0, 1) = -cosPhi * sinPsi + sinPhi * sinThe * cosPsi;\n dcm(0, 2) = sinPhi * sinPsi + cosPhi * sinThe * cosPsi;\n\n dcm(1, 0) = cosThe * sinPsi;\n dcm(1, 1) = cosPhi * cosPsi + sinPhi * sinThe * sinPsi;\n dcm(1, 2) = -sinPhi * cosPsi + cosPhi * sinThe * sinPsi;\n\n dcm(2, 0) = -sinThe;\n dcm(2, 1) = sinPhi * cosThe;\n dcm(2, 2) = cosPhi * cosThe;\n }\n\n\n \/**\n * Constructor from axis angle\n *\n * This sets the transformation matrix from frame 2 to frame 1 where the rotation\n * from frame 1 to frame 2 is described by a 3-2-1 intrinsic Tait-Bryan rotation sequence.\n *\n *\n * @param euler euler angle instance\n *\/\n Dcm(const AxisAngle &aa)\n {\n Dcm &dcm = *this;\n dcm = Quaternion(aa);\n }\n\n Vector vee() const \/\/ inverse to Vector.hat() operation\n {\n const Dcm &A(*this);\n Vector v;\n v(0) = -A(1, 2);\n v(1) = A(0, 2);\n v(2) = -A(0, 1);\n return v;\n }\n\n void renormalize()\n {\n \/* renormalize rows *\/\n for (int row = 0; row < 3; row++) {\n matrix::Vector3f rvec(this->_data[row]);\n this->setRow(row, rvec.normalized());\n }\n }\n};\n\ntypedef Dcm Dcmf;\n\n} \/\/ namespace matrix\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\nChanged Dcm to inherit from SquareMatrix because it is square and we can use the trace method\/**\n * @file Dcm.hpp\n *\n * A direction cosine matrix class.\n * All rotations and axis systems follow the right-hand rule.\n *\n * This library uses the convention that premultiplying a three dimensional\n * vector represented in coordinate system 1 will apply a rotation from coordinate system\n * 1 to coordinate system 2 to the vector.\n * Likewise, a matrix instance of this class also represents a coordinate transformation\n * from frame 2 to frame 1.\n *\n * @author James Goppert \n *\/\n\n#pragma once\n\n#include \"math.hpp\"\n\n\nnamespace matrix\n{\n\ntemplate\nclass Quaternion;\n\ntemplate\nclass Euler;\n\ntemplate\nclass AxisAngle;\n\n\n\/**\n * Direction cosine matrix class\n *\n * The rotation between two coordinate frames is\n * described by this class.\n *\/\ntemplate\nclass Dcm : public SquareMatrix\n{\npublic:\n virtual ~Dcm() {};\n\n typedef Matrix Vector3;\n\n \/**\n * Standard constructor\n *\n * Initializes to identity\n *\/\n Dcm() : SquareMatrix()\n {\n (*this) = eye();\n }\n\n \/**\n * Constructor from array\n *\n * @param _data pointer to array\n *\/\n Dcm(const Type *data_) : SquareMatrix(data_)\n {\n }\n\n \/**\n * Copy constructor\n *\n * @param other Matrix33 to set dcm to\n *\/\n Dcm(const Matrix &other) : SquareMatrix(other)\n {\n }\n\n \/**\n * Constructor from quaternion\n *\n * Instance is initialized from quaternion representing\n * coordinate transformation from frame 2 to frame 1.\n *\n * @param q quaternion to set dcm to\n *\/\n Dcm(const Quaternion &q)\n {\n Dcm &dcm = *this;\n Type a = q(0);\n Type b = q(1);\n Type c = q(2);\n Type d = q(3);\n Type aSq = a * a;\n Type bSq = b * b;\n Type cSq = c * c;\n Type dSq = d * d;\n dcm(0, 0) = aSq + bSq - cSq - dSq;\n dcm(0, 1) = 2 * (b * c - a * d);\n dcm(0, 2) = 2 * (a * c + b * d);\n dcm(1, 0) = 2 * (b * c + a * d);\n dcm(1, 1) = aSq - bSq + cSq - dSq;\n dcm(1, 2) = 2 * (c * d - a * b);\n dcm(2, 0) = 2 * (b * d - a * c);\n dcm(2, 1) = 2 * (a * b + c * d);\n dcm(2, 2) = aSq - bSq - cSq + dSq;\n }\n\n \/**\n * Constructor from euler angles\n *\n * This sets the transformation matrix from frame 2 to frame 1 where the rotation\n * from frame 1 to frame 2 is described by a 3-2-1 intrinsic Tait-Bryan rotation sequence.\n *\n *\n * @param euler euler angle instance\n *\/\n Dcm(const Euler &euler)\n {\n Dcm &dcm = *this;\n Type cosPhi = Type(cos(euler.phi()));\n Type sinPhi = Type(sin(euler.phi()));\n Type cosThe = Type(cos(euler.theta()));\n Type sinThe = Type(sin(euler.theta()));\n Type cosPsi = Type(cos(euler.psi()));\n Type sinPsi = Type(sin(euler.psi()));\n\n dcm(0, 0) = cosThe * cosPsi;\n dcm(0, 1) = -cosPhi * sinPsi + sinPhi * sinThe * cosPsi;\n dcm(0, 2) = sinPhi * sinPsi + cosPhi * sinThe * cosPsi;\n\n dcm(1, 0) = cosThe * sinPsi;\n dcm(1, 1) = cosPhi * cosPsi + sinPhi * sinThe * sinPsi;\n dcm(1, 2) = -sinPhi * cosPsi + cosPhi * sinThe * sinPsi;\n\n dcm(2, 0) = -sinThe;\n dcm(2, 1) = sinPhi * cosThe;\n dcm(2, 2) = cosPhi * cosThe;\n }\n\n\n \/**\n * Constructor from axis angle\n *\n * This sets the transformation matrix from frame 2 to frame 1 where the rotation\n * from frame 1 to frame 2 is described by a 3-2-1 intrinsic Tait-Bryan rotation sequence.\n *\n *\n * @param euler euler angle instance\n *\/\n Dcm(const AxisAngle &aa)\n {\n Dcm &dcm = *this;\n dcm = Quaternion(aa);\n }\n\n Vector vee() const \/\/ inverse to Vector.hat() operation\n {\n const Dcm &A(*this);\n Vector v;\n v(0) = -A(1, 2);\n v(1) = A(0, 2);\n v(2) = -A(0, 1);\n return v;\n }\n\n void renormalize()\n {\n \/* renormalize rows *\/\n for (int row = 0; row < 3; row++) {\n matrix::Vector3f rvec(this->_data[row]);\n this->setRow(row, rvec.normalized());\n }\n }\n};\n\ntypedef Dcm Dcmf;\n\n} \/\/ namespace matrix\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2012 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n\/*\n * ExpressionEditor.cpp\n *\n * Created on: Jan 11, 2012\n * Author: Dimitar Asenov\n *\/\n\n#include \"expression_editor\/ExpressionEditor.h\"\n\n#include \"expression_editor\/parser\/Token.h\"\n#include \"expression_editor\/parser\/Parser.h\"\n#include \"expression_editor\/tree_builder\/ExpressionTreeBuilder.h\"\n\nnamespace Interaction {\n\nExpression* ExpressionEditor::parse(const QString& expression_text)\n{\n\tif (!expression_text.isNull()) setText(expression_text);\n\n\treturn ExpressionTreeBuilder().build( Parser(ops_).parse( Token::tokenize(text_, ops_)) );\n}\n\n} \/* namespace InteractionBase *\/\nFix ExpressionEditor::parse to adjust the result for operator precedence\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2012 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n\/*\n * ExpressionEditor.cpp\n *\n * Created on: Jan 11, 2012\n * Author: Dimitar Asenov\n *\/\n\n#include \"expression_editor\/ExpressionEditor.h\"\n\n#include \"expression_editor\/parser\/Token.h\"\n#include \"expression_editor\/parser\/Parser.h\"\n#include \"expression_editor\/tree_builder\/ExpressionTreeBuilder.h\"\n#include \"expression_editor\/ExpressionTreeUtils.h\"\n\nnamespace Interaction {\n\nExpression* ExpressionEditor::parse(const QString& expression_text)\n{\n\tif (!expression_text.isNull()) setText(expression_text);\n\n\tExpression* top = ExpressionTreeBuilder().build( Parser(ops_).parse( Token::tokenize(text_, ops_)) );\n\tExpressionTreeUtils::fixTop(top);\n\treturn top;\n}\n\n} \/* namespace InteractionBase *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main()\n{\n\t\/\/srand((unsigned)time(NULL));\n\t\/\/int val = rand();\n\t\/\/char Hex[33];\n\t\/\/itoa(val, Hex, 16);\n\t\/\/cout << \"Random Decimal Byte:\" << val;\n\t\/\/cout << \"\\nEquivalent Hex Byte: \" << Hex << endl;\n\n\t\/\/\/\/\/\/\/\n\tconst int DNAs = 2;\/\/ 1048575;\n\tsrand((unsigned)time(NULL));\n\n\n\tvector dnas;\n\tset uniqueDNAs;\n\n\tint ints[5] = { 0 };\n\tint currSize = 2;\n\tfor (size_t row = 1; row <= DNAs; row++)\n\t{\n\t\tostringstream oss;\n\t\tstring currDNA;\n\t\toss << hex << std::setw(5) << std::setfill('0') << row;\n\n\t\tcurrDNA = oss.str();\n\t\tbool is_in = uniqueDNAs.find(currDNA) != uniqueDNAs.end();\n\t\tif (is_in)\n\t\t{\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\tuniqueDNAs.insert(currDNA);\n\t\t\tfor (size_t col = 0; col < currSize; col++)\n\t\t\t{\n\t\t\t\tdnas.push_back(currDNA);\n\t\t\t}\n\t\t}\n\n\t\tcurrSize += 2;\n\t}\n\n\tdnas.push_back(\"fffff\");\n\n\tstd::random_shuffle(dnas.begin(), dnas.end());\n\n\tofstream fileOutput(\"test1.txt\");\n\tfor (const auto& dna : dnas)\n\t{\n\t\tfileOutput << dna << endl;\n\t}\n\n\t\/\/fileOutput << oss.str() << endl;\n\n\treturn 0;\n}change in algorithm#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main()\n{\n\t\/\/ srand((unsigned)time(NULL));\n\n\tconst int DNAs = 1000;\/\/ 1048575;\n\n\tvector dnas;\n\tset uniqueDNAs;\n\n\tint currSize = 2;\n\tfor (size_t row = 1; row <= DNAs; row++)\n\t{\n\t\tostringstream oss;\n\t\tstring currDNA;\n\t\toss << hex << std::setw(5) << std::setfill('0') << row;\n\n\t\tcurrDNA = oss.str();\n\n\t\tuniqueDNAs.insert(currDNA);\n\t\tfor (size_t col = 0; col < currSize; col++)\n\t\t{\n\t\t\tdnas.push_back(currDNA);\n\t\t}\n\n\t\tcurrSize += 2;\n\t}\n\n\tdnas.push_back(\"fffff\");\n\n\tstd::random_shuffle(dnas.begin(), dnas.end());\n\n\tofstream fileOutput(\"test1.txt\");\n\tfor (const auto& dna : dnas)\n\t{\n\t\tfileOutput << dna;\n\t}\n\n\treturn 0;\n}<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 The Android Open Source Project\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 \"class_linker.h\"\n#include \"interpreter\/interpreter.h\"\n#include \"invoke_arg_array_builder.h\"\n#include \"mirror\/art_method-inl.h\"\n#include \"mirror\/object-inl.h\"\n#include \"object_utils.h\"\n#include \"runtime.h\"\n#include \"stack.h\"\n\nnamespace art {\n\nextern \"C\" void artInterpreterToCompiledCodeBridge(Thread* self, MethodHelper& mh,\n const DexFile::CodeItem* code_item,\n ShadowFrame* shadow_frame, JValue* result) {\n mirror::ArtMethod* method = shadow_frame->GetMethod();\n \/\/ Ensure static methods are initialized.\n if (method->IsStatic()) {\n mirror::Class* declaringClass = method->GetDeclaringClass();\n if (UNLIKELY(!declaringClass->IsInitializing())) {\n if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaringClass,\n true, true))) {\n DCHECK(Thread::Current()->IsExceptionPending());\n return;\n }\n CHECK(declaringClass->IsInitializing());\n }\n }\n uint16_t arg_offset = (code_item == NULL) ? 0 : code_item->registers_size_ - code_item->ins_size_;\n#if defined(ART_USE_PORTABLE_COMPILER)\n ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());\n arg_array.BuildArgArrayFromFrame(shadow_frame, arg_offset);\n method->Invoke(self, arg_array.GetArray(), arg_array.GetNumBytes(), result, mh.GetShorty()[0]);\n#else\n method->Invoke(self, shadow_frame->GetVRegArgs(arg_offset),\n (shadow_frame->NumberOfVRegs() - arg_offset) * sizeof(uint32_t),\n result, mh.GetShorty()[0]);\n#endif\n}\n\n} \/\/ namespace art\nam 76f55230: Merge \"Add missing push\/pop shadow frame to artInterpreterToCompiledCodeBridge.\"\/*\n * Copyright (C) 2012 The Android Open Source Project\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 \"class_linker.h\"\n#include \"interpreter\/interpreter.h\"\n#include \"invoke_arg_array_builder.h\"\n#include \"mirror\/art_method-inl.h\"\n#include \"mirror\/object-inl.h\"\n#include \"object_utils.h\"\n#include \"runtime.h\"\n#include \"stack.h\"\n\nnamespace art {\n\nextern \"C\" void artInterpreterToCompiledCodeBridge(Thread* self, MethodHelper& mh,\n const DexFile::CodeItem* code_item,\n ShadowFrame* shadow_frame, JValue* result) {\n mirror::ArtMethod* method = shadow_frame->GetMethod();\n \/\/ Ensure static methods are initialized.\n if (method->IsStatic()) {\n mirror::Class* declaringClass = method->GetDeclaringClass();\n if (UNLIKELY(!declaringClass->IsInitializing())) {\n self->PushShadowFrame(shadow_frame);\n if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaringClass,\n true, true))) {\n self->PopShadowFrame();\n DCHECK(self->IsExceptionPending());\n return;\n }\n self->PopShadowFrame();\n CHECK(declaringClass->IsInitializing());\n }\n }\n uint16_t arg_offset = (code_item == NULL) ? 0 : code_item->registers_size_ - code_item->ins_size_;\n#if defined(ART_USE_PORTABLE_COMPILER)\n ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());\n arg_array.BuildArgArrayFromFrame(shadow_frame, arg_offset);\n method->Invoke(self, arg_array.GetArray(), arg_array.GetNumBytes(), result, mh.GetShorty()[0]);\n#else\n method->Invoke(self, shadow_frame->GetVRegArgs(arg_offset),\n (shadow_frame->NumberOfVRegs() - arg_offset) * sizeof(uint32_t),\n result, mh.GetShorty()[0]);\n#endif\n}\n\n} \/\/ namespace art\n<|endoftext|>"} {"text":"\/*\n * lambda.cpp\n *\n * Created on: Jan 14, 2015\n * Author: radoslav\n *\/\n\n#include \"lambda.h\"\n#include \"strtok.h\"\n#include \"identifier.h\"\n#include \n\n\nvoid Lambda::copy(const Lambda& other)\n{\n\tsignature = other.signature;\n\tbody = other.body->clone();\n}\n\nvoid Lambda::destroy()\n{\n\tdelete body;\n}\n\nLambda::Lambda(const char*& code): Value(VALUE_LAMBDA)\n{\n\tif (!gotoToken(code, \" \\t\\n\\r\") || *code != '\\\\')\n\t{\n\t\ttype = VALUE_INVALID;\n\t\treturn;\n\t}\n\n\tcode++;\n\n\tif (!gotoToken(code, \" \\t\\n\\r\") || *code != '(')\n\t{\n\t\ttype = VALUE_INVALID;\n\t\treturn;\n\t}\n\n\tcode++;\n\n\twhile (gotoToken(code, \", \\t\\n\\r\") && *code != ')')\n\t\tsignature.push_back(Identifier(code));\n\n\tif (*code != ')')\n\t\ttype = VALUE_INVALID;\n\telse\n\t{\n\t\tcode++;\n\t\tbody = Statement::createStatement(code);\n\t}\n}\n\nLambda::Lambda(const Lambda& other): Value(other)\n{\n\tcopy(other);\n}\n\nLambda& Lambda::operator=(const Lambda& other)\n{\n\tif (&other != this)\n\t{\n\t\tdestroy();\n\t\tValue::operator=(other);\n\t\tcopy(other);\n\t}\n\n\treturn *this;\n}\n\nLambda::~Lambda()\n{\n\tdestroy();\n}\n\nrenamed method\/*\n * lambda.cpp\n *\n * Created on: Jan 14, 2015\n * Author: radoslav\n *\/\n\n#include \"lambda.h\"\n#include \"strtok.h\"\n#include \"identifier.h\"\n#include \n\n\nvoid Lambda::copy(const Lambda& other)\n{\n\tsignature = other.signature;\n\tbody = other.body->clone();\n}\n\nvoid Lambda::destroy()\n{\n\tdelete body;\n}\n\nLambda::Lambda(const char*& code): Value(VALUE_LAMBDA)\n{\n\tif (!gotoToken(code, \" \\t\\n\\r\") || *code != '\\\\')\n\t{\n\t\ttype = VALUE_INVALID;\n\t\treturn;\n\t}\n\n\tcode++;\n\n\tif (!gotoToken(code, \" \\t\\n\\r\") || *code != '(')\n\t{\n\t\ttype = VALUE_INVALID;\n\t\treturn;\n\t}\n\n\tcode++;\n\n\twhile (gotoToken(code, \", \\t\\n\\r\") && *code != ')')\n\t\tsignature.push_back(Identifier(code));\n\n\tif (*code != ')')\n\t\ttype = VALUE_INVALID;\n\telse\n\t{\n\t\tcode++;\n\t\tbody = Statement::create(code);\n\t}\n}\n\nLambda::Lambda(const Lambda& other): Value(other)\n{\n\tcopy(other);\n}\n\nLambda& Lambda::operator=(const Lambda& other)\n{\n\tif (&other != this)\n\t{\n\t\tdestroy();\n\t\tValue::operator=(other);\n\t\tcopy(other);\n\t}\n\n\treturn *this;\n}\n\nLambda::~Lambda()\n{\n\tdestroy();\n}\n\n<|endoftext|>"} {"text":"#include \"bookmark.h\"\n\n\/**\n * @brief Bookmark::Bookmark\n * @param frame_nbr Frame number associated with the bookmark.\n * @param frame Frame associated with the bookmark.\n * @param dir_path Path to the directory to store image in.\n * @param text Text description of the bookmark.\n *\/\nBookmark::Bookmark(int frame_nbr, QImage frame, QString dir_path, QString text) {\n this->frame_number = frame_nbr;\n this->frame = frame;\n this->dir_path = dir_path;\n this->description = text;\n \/\/ There's no file path yet, since the frame has not been exported\n this->file_path = QString();\n}\n\n\/**\n * @brief Bookmark::Bookmark\n * Null initializing constructor.\n *\/\nBookmark::Bookmark() {\n frame_number = 0;\n frame = QImage();\n dir_path = QString();\n file_path = QString();\n description = QString();\n}\n\n\/**\n * @brief Bookmark::get_frame_number\n * @return Returns the frame number that the bookmark points to.\n *\/\nint Bookmark::get_frame_number() {\n return frame_number;\n}\n\n\/**\n * @brief Bookmark::get_frame\n * @return Returns the frame of the bookmark.\n *\/\nQImage Bookmark::get_frame() {\n return frame;\n}\n\n\/**\n * @brief Bookmark::get_file_path\n * @return Returns the file_path of the exported bookmark.\n * If bookmark is not exported yet, an empty string is returned\n *\/\nQString Bookmark::get_file_path() {\n return file_path;\n}\n\n\/**\n * @brief Bookmark::get_description\n * @return Returns the description associated with the bookmark.\n *\/\nQString Bookmark::get_description() {\n return description;\n}\n\n\/**\n * @brief Bookmark::read\n * @param json\n * Reads a bookmark from a Json object.\n *\/\nvoid Bookmark::read(const QJsonObject& json){\n this->frame_number = json[\"frame\"].toInt();\n this->dir_path = json[\"dir\"].toString();\n this->file_path = json[\"path\"].toString();\n this->description = json[\"note\"].toString();\n frame.load(file_path);\n}\n\n\/**\n * @brief Bookmark::write\n * @param json\n * Writes a bookmark to a Json object, and exports the frame.\n *\/\nvoid Bookmark::write(QJsonObject& json){\n \/\/ Exports the frame and updates file_path.\n export_frame();\n\n json[\"frame\"] = this->frame_number;\n json[\"dir\"] = this->dir_path;\n json[\"path\"] = this->file_path;\n json[\"note\"] = this->description;\n}\n\n\/**\n * @brief Bookmark::export_frame\n * Export the frame of the bookmark to a tiff-file in the project folder.\n *\/\nvoid Bookmark::export_frame() {\n \/\/ Update file path in case there's already a file with this file name\n create_file_path();\n QImageWriter writer(file_path, \"tiff\");\n writer.write(frame);\n}\n\n\/**\n * @brief Bookmark::create_file_path\n * Creates and updates the file path to export the bookmark frame to.\n *\/\nvoid Bookmark::create_file_path() {\n\n \/\/ Append FRAMENR.tiff to the directory path\n QString path = QString(dir_path);\n path.append(\"\/\");\n path.append(QString::number(frame_number));\n path.append(\".tiff\");\n- int counter = 1;\t\t\n - while (QFile::exists(path)) {\t\t\n - \/\/ If file exists, try FRAMENR(X).tiff\t\t\n - path = QString(dir_path);\t\t\n - path.append(\"\/\");\t\t\n - path.append(QString::number(frame_number));\t\t\n - path.append(\"(\");\t\t\n - path.append(QString::number(counter));\t\t\n - path.append(\").tiff\");\t\t\n - counter++;\t\t\n - }\n \/\/ Update file path variable\n file_path = path;\n}\n\n\/**\n * @brief Bookmark::remove_exported_image\n * Removes the exported image, if there is one.\n *\/\nvoid Bookmark::remove_exported_image() {\n \/\/ If the file path is empty, then the frame has not been exported so there's nothing to remove.\n if (!file_path.isEmpty()) {\n QFile file(file_path);\n file.remove();\n }\n}\nUpdate bookmark.cpp#include \"bookmark.h\"\n\n\/**\n * @brief Bookmark::Bookmark\n * @param frame_nbr Frame number associated with the bookmark.\n * @param frame Frame associated with the bookmark.\n * @param dir_path Path to the directory to store image in.\n * @param text Text description of the bookmark.\n *\/\nBookmark::Bookmark(int frame_nbr, QImage frame, QString dir_path, QString text) {\n this->frame_number = frame_nbr;\n this->frame = frame;\n this->dir_path = dir_path;\n this->description = text;\n \/\/ There's no file path yet, since the frame has not been exported\n this->file_path = QString();\n}\n\n\/**\n * @brief Bookmark::Bookmark\n * Null initializing constructor.\n *\/\nBookmark::Bookmark() {\n frame_number = 0;\n frame = QImage();\n dir_path = QString();\n file_path = QString();\n description = QString();\n}\n\n\/**\n * @brief Bookmark::get_frame_number\n * @return Returns the frame number that the bookmark points to.\n *\/\nint Bookmark::get_frame_number() {\n return frame_number;\n}\n\n\/**\n * @brief Bookmark::get_frame\n * @return Returns the frame of the bookmark.\n *\/\nQImage Bookmark::get_frame() {\n return frame;\n}\n\n\/**\n * @brief Bookmark::get_file_path\n * @return Returns the file_path of the exported bookmark.\n * If bookmark is not exported yet, an empty string is returned\n *\/\nQString Bookmark::get_file_path() {\n return file_path;\n}\n\n\/**\n * @brief Bookmark::get_description\n * @return Returns the description associated with the bookmark.\n *\/\nQString Bookmark::get_description() {\n return description;\n}\n\n\/**\n * @brief Bookmark::read\n * @param json\n * Reads a bookmark from a Json object.\n *\/\nvoid Bookmark::read(const QJsonObject& json){\n this->frame_number = json[\"frame\"].toInt();\n this->dir_path = json[\"dir\"].toString();\n this->file_path = json[\"path\"].toString();\n this->description = json[\"note\"].toString();\n frame.load(file_path);\n}\n\n\/**\n * @brief Bookmark::write\n * @param json\n * Writes a bookmark to a Json object, and exports the frame.\n *\/\nvoid Bookmark::write(QJsonObject& json){\n \/\/ Exports the frame and updates file_path.\n export_frame();\n\n json[\"frame\"] = this->frame_number;\n json[\"dir\"] = this->dir_path;\n json[\"path\"] = this->file_path;\n json[\"note\"] = this->description;\n}\n\n\/**\n * @brief Bookmark::export_frame\n * Export the frame of the bookmark to a tiff-file in the project folder.\n *\/\nvoid Bookmark::export_frame() {\n \/\/ Update file path in case there's already a file with this file name\n create_file_path();\n QImageWriter writer(file_path, \"tiff\");\n writer.write(frame);\n}\n\n\/**\n * @brief Bookmark::create_file_path\n * Creates and updates the file path to export the bookmark frame to.\n *\/\nvoid Bookmark::create_file_path() {\n\n \/\/ Append FRAMENR.tiff to the directory path\n QString path = QString(dir_path);\n path.append(\"\/\");\n path.append(QString::number(frame_number));\n path.append(\".tiff\");\n- \n int counter = 1;\t\t\n - while (QFile::exists(path)) {\t\t\n - \/\/ If file exists, try FRAMENR(X).tiff\t\t\n - path = QString(dir_path);\t\t\n - path.append(\"\/\");\t\t\n - path.append(QString::number(frame_number));\t\t\n - path.append(\"(\");\t\t\n - path.append(QString::number(counter));\t\t\n - path.append(\").tiff\");\t\t\n - counter++;\t\t\n - }\n \/\/ Update file path variable\n file_path = path;\n}\n\n\/**\n * @brief Bookmark::remove_exported_image\n * Removes the exported image, if there is one.\n *\/\nvoid Bookmark::remove_exported_image() {\n \/\/ If the file path is empty, then the frame has not been exported so there's nothing to remove.\n if (!file_path.isEmpty()) {\n QFile file(file_path);\n file.remove();\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Rule.cc\n *\n * Copyright (C) 2015 Misgana Bayetta\n *\n * Author: Misgana Bayetta 2015\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program 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 General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"Rule.h\"\n\nusing namespace opencog;\n\nRule::Rule(Handle rule)\n{\n\tif (!rule->isType(MEMBER_LINK, true))\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t \"Rule '%s' is expected to be a MemberLink\",\n\t\t rule->toString().c_str());\n\n\tHandle name_h = LinkCast(rule)->getOutgoingAtom(0),\n\t\trbs_h = LinkCast(rule)->getOutgoingAtom(1);\n\n\trule_handle_ = DefineLink::get_definition(name_h);\n\tname_ = NodeCast(name_h)->getName();\n\tcategory_ = NodeCast(rbs_h)->getName();\n\tweight_ = rule->getTruthValue()->getMean();\n}\n\nfloat Rule::get_weight()\n{\n\treturn weight_;\n}\n\nvoid Rule::set_category(const string& name)\n{\n\tcategory_ = name;\n}\n\nstring& Rule::get_category()\n{\n\treturn category_;\n}\n\nconst string& Rule::get_category() const\n{\n\treturn category_;\n}\n\nvoid Rule::set_name(const string& name)\n{\n\tname_ = name;\n}\n\nstring& Rule::get_name()\n{\n\treturn name_;\n}\n\nconst string& Rule::get_name() const\n{\n\treturn name_;\n}\n\nvoid Rule::set_handle(Handle h) throw (InvalidParamException)\n{\n\trule_handle_ = h;\n}\n\nHandle Rule::get_handle()\n{\n\treturn rule_handle_;\n}\n\n\/**\n * Get the typed variable list of the Rule.\n *\n * @return the VariableList or the lone VariableNode\n *\/\nHandle Rule::get_vardecl()\n{\n\treturn LinkCast(rule_handle_)->getOutgoingAtom(0);\n}\n\n\/**\n * Get the implicant (input) of the rule defined in a BindLink.\n *\n * @return the Handle of the implicant\n *\/\nHandle Rule::get_implicant()\n{\n\t\/\/ if the rule's handle has not been set yet\n\tif (rule_handle_ == Handle::UNDEFINED)\n\t\treturn Handle::UNDEFINED;\n\n\treturn BindLinkCast(rule_handle_)->get_body();\n}\n\n\/**\n * Get the set of members of the implicant which are\n * connected by a root logical link.\n *\n * @return HandleSeq of members of the implicant\n *\/\nHandleSeq Rule::get_implicant_seq()\n{\n Handle implicant= get_implicant();\n Type t = implicant->getType();\n HandleSeq hs;\n\n if (t == AND_LINK or t == OR_LINK)\n hs = LinkCast(implicant)->getOutgoingSet();\n else\n hs.push_back(implicant);\n\n return hs;\n}\n\/**\n * Get the implicand (output) of the rule defined in a BindLink.\n *\n * @return the Handle of the implicand\n *\/\nHandle Rule::get_implicand()\n{\n\t\/\/ if the rule's handle has not been set yet\n\tif (rule_handle_ == Handle::UNDEFINED)\n\t\treturn Handle::UNDEFINED;\n\n\treturn BindLinkCast(rule_handle_)->get_implicand();\n}\n\n\/**\n * Get the implicand (output) of the rule defined in a BindLink.\n *\n * This function does extra processing to find the real output over an\n * ExecutionOutputLink. ie, skip to the ListLink under the ExLink.\n *\n * @return the HandleSeq of the implicand\n *\/\nHandleSeq Rule::get_implicand_seq()\n{\n\t\/\/ if the rule's handle has not been set yet\n\tif (rule_handle_ == Handle::UNDEFINED)\n\t\treturn HandleSeq();\n\n\tHandle implicand = BindLinkCast(rule_handle_)->get_implicand();\n\n\tstd::queue pre_output;\n\tHandleSeq final_output;\n\n\t\/\/ skip the top level ListLink\n\tif (implicand->getType() == LIST_LINK)\n\t{\n\t\tfor (Handle h : LinkCast(implicand)->getOutgoingSet())\n\t\t\tpre_output.push(h);\n\t}\n\telse\n\t{\n\t\tpre_output.push(implicand);\n\t}\n\n\t\/\/ check all output of ExecutionOutputLink\n\twhile (not pre_output.empty())\n\t{\n\t\tHandle hfront = pre_output.front();\n\t\tpre_output.pop();\n\n\t\tif (hfront->getType() == EXECUTION_OUTPUT_LINK)\n\t\t{\n\t\t\t\/\/ get the ListLink containing the arguments of the ExecutionOutputLink\n\t\t\tHandle harg = LinkCast(hfront)->getOutgoingSet()[1];\n\n\t\t\tfor (Handle h : LinkCast(harg)->getOutgoingSet())\n\t\t\t\tpre_output.push(h);\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ if not an ExecutionOutputLink, it is a final output\n\t\tfinal_output.push_back(hfront);\n\t}\n\n\treturn final_output;\n}\n\nvoid Rule::set_weight(float p)\n{\n\tweight_ = p;\n}\n\n\/**\n * Create a new rule where all variables are renamed.\n *\n * @param as pointer to the atomspace where the new BindLink will be added\n * @return a new Rule object with its own new BindLink\n *\/\nRule Rule::gen_standardize_apart(AtomSpace* as)\n{\n\t\/\/ clone the Rule\n\tRule st_ver = *this;\n\tstd::map dict;\n\n\tHandle st_bindlink = standardize_helper(as, rule_handle_, dict);\n\tst_ver.set_handle(st_bindlink);\n\n\treturn st_ver;\n}\n\n\/**\n * Basic helper function to standardize apart the BindLink.\n *\n * @param as pointer to an atomspace where new atoms are added\n * @param h an input atom to standardize apart\n * @param dict a mapping of old VariableNode and new VariableNode\n * @return the new atom\n *\/\nHandle Rule::standardize_helper(AtomSpace* as, const Handle h, std::map& dict)\n{\n\tif (LinkCast(h))\n\t{\n\t\tHandleSeq old_outgoing = LinkCast(h)->getOutgoingSet();\n\t\tHandleSeq new_outgoing;\n\n\t\tfor (auto ho : old_outgoing)\n\t\t\tnew_outgoing.push_back(standardize_helper(as, ho, dict));\n\n\t\treturn as->add_atom(createLink(h->getType(), new_outgoing, h->getTruthValue()));\n\t}\n\n\t\/\/ normal node does not need to be changed\n\tif (h->getType() != VARIABLE_NODE)\n\t\treturn h;\n\n\t\/\/ use existing mapping if the VariableNode is already mapped\n\tif (dict.count(h) == 1)\n\t\treturn dict[h];\n\n\tstd::string new_name = NodeCast(h)->getName() + \"-standardize_apart-\" + to_string(boost::uuids::random_generator()());\n\n\tHandle hcpy = as->add_atom(createNode(h->getType(), new_name, h->getTruthValue()));\n\tdict[h] = hcpy;\n\n\treturn hcpy;\n}\nChanged standardized-apart variable to always be the same\/*\n * Rule.cc\n *\n * Copyright (C) 2015 Misgana Bayetta\n *\n * Author: Misgana Bayetta 2015\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program 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 General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"Rule.h\"\n\nusing namespace opencog;\n\nRule::Rule(Handle rule)\n{\n\tif (!rule->isType(MEMBER_LINK, true))\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t \"Rule '%s' is expected to be a MemberLink\",\n\t\t rule->toString().c_str());\n\n\tHandle name_h = LinkCast(rule)->getOutgoingAtom(0),\n\t\trbs_h = LinkCast(rule)->getOutgoingAtom(1);\n\n\trule_handle_ = DefineLink::get_definition(name_h);\n\tname_ = NodeCast(name_h)->getName();\n\tcategory_ = NodeCast(rbs_h)->getName();\n\tweight_ = rule->getTruthValue()->getMean();\n}\n\nfloat Rule::get_weight()\n{\n\treturn weight_;\n}\n\nvoid Rule::set_category(const string& name)\n{\n\tcategory_ = name;\n}\n\nstring& Rule::get_category()\n{\n\treturn category_;\n}\n\nconst string& Rule::get_category() const\n{\n\treturn category_;\n}\n\nvoid Rule::set_name(const string& name)\n{\n\tname_ = name;\n}\n\nstring& Rule::get_name()\n{\n\treturn name_;\n}\n\nconst string& Rule::get_name() const\n{\n\treturn name_;\n}\n\nvoid Rule::set_handle(Handle h) throw (InvalidParamException)\n{\n\trule_handle_ = h;\n}\n\nHandle Rule::get_handle()\n{\n\treturn rule_handle_;\n}\n\n\/**\n * Get the typed variable list of the Rule.\n *\n * @return the VariableList or the lone VariableNode\n *\/\nHandle Rule::get_vardecl()\n{\n\treturn LinkCast(rule_handle_)->getOutgoingAtom(0);\n}\n\n\/**\n * Get the implicant (input) of the rule defined in a BindLink.\n *\n * @return the Handle of the implicant\n *\/\nHandle Rule::get_implicant()\n{\n\t\/\/ if the rule's handle has not been set yet\n\tif (rule_handle_ == Handle::UNDEFINED)\n\t\treturn Handle::UNDEFINED;\n\n\treturn BindLinkCast(rule_handle_)->get_body();\n}\n\n\/**\n * Get the set of members of the implicant which are\n * connected by a root logical link.\n *\n * @return HandleSeq of members of the implicant\n *\/\nHandleSeq Rule::get_implicant_seq()\n{\n Handle implicant= get_implicant();\n Type t = implicant->getType();\n HandleSeq hs;\n\n if (t == AND_LINK or t == OR_LINK)\n hs = LinkCast(implicant)->getOutgoingSet();\n else\n hs.push_back(implicant);\n\n return hs;\n}\n\/**\n * Get the implicand (output) of the rule defined in a BindLink.\n *\n * @return the Handle of the implicand\n *\/\nHandle Rule::get_implicand()\n{\n\t\/\/ if the rule's handle has not been set yet\n\tif (rule_handle_ == Handle::UNDEFINED)\n\t\treturn Handle::UNDEFINED;\n\n\treturn BindLinkCast(rule_handle_)->get_implicand();\n}\n\n\/**\n * Get the implicand (output) of the rule defined in a BindLink.\n *\n * This function does extra processing to find the real output over an\n * ExecutionOutputLink. ie, skip to the ListLink under the ExLink.\n *\n * @return the HandleSeq of the implicand\n *\/\nHandleSeq Rule::get_implicand_seq()\n{\n\t\/\/ if the rule's handle has not been set yet\n\tif (rule_handle_ == Handle::UNDEFINED)\n\t\treturn HandleSeq();\n\n\tHandle implicand = BindLinkCast(rule_handle_)->get_implicand();\n\n\tstd::queue pre_output;\n\tHandleSeq final_output;\n\n\t\/\/ skip the top level ListLink\n\tif (implicand->getType() == LIST_LINK)\n\t{\n\t\tfor (Handle h : LinkCast(implicand)->getOutgoingSet())\n\t\t\tpre_output.push(h);\n\t}\n\telse\n\t{\n\t\tpre_output.push(implicand);\n\t}\n\n\t\/\/ check all output of ExecutionOutputLink\n\twhile (not pre_output.empty())\n\t{\n\t\tHandle hfront = pre_output.front();\n\t\tpre_output.pop();\n\n\t\tif (hfront->getType() == EXECUTION_OUTPUT_LINK)\n\t\t{\n\t\t\t\/\/ get the ListLink containing the arguments of the ExecutionOutputLink\n\t\t\tHandle harg = LinkCast(hfront)->getOutgoingSet()[1];\n\n\t\t\tfor (Handle h : LinkCast(harg)->getOutgoingSet())\n\t\t\t\tpre_output.push(h);\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ if not an ExecutionOutputLink, it is a final output\n\t\tfinal_output.push_back(hfront);\n\t}\n\n\treturn final_output;\n}\n\nvoid Rule::set_weight(float p)\n{\n\tweight_ = p;\n}\n\n\/**\n * Create a new rule where all variables are renamed.\n *\n * @param as pointer to the atomspace where the new BindLink will be added\n * @return a new Rule object with its own new BindLink\n *\/\nRule Rule::gen_standardize_apart(AtomSpace* as)\n{\n\t\/\/ clone the Rule\n\tRule st_ver = *this;\n\tstd::map dict;\n\n\tHandle st_bindlink = standardize_helper(as, rule_handle_, dict);\n\tst_ver.set_handle(st_bindlink);\n\n\treturn st_ver;\n}\n\n\/**\n * Basic helper function to standardize apart the BindLink.\n *\n * @param as pointer to an atomspace where new atoms are added\n * @param h an input atom to standardize apart\n * @param dict a mapping of old VariableNode and new VariableNode\n * @return the new atom\n *\/\nHandle Rule::standardize_helper(AtomSpace* as, const Handle h, std::map& dict)\n{\n\tif (LinkCast(h))\n\t{\n\t\tHandleSeq old_outgoing = LinkCast(h)->getOutgoingSet();\n\t\tHandleSeq new_outgoing;\n\n\t\tfor (auto ho : old_outgoing)\n\t\t\tnew_outgoing.push_back(standardize_helper(as, ho, dict));\n\n\t\treturn as->add_atom(createLink(h->getType(), new_outgoing, h->getTruthValue()));\n\t}\n\n\t\/\/ normal node does not need to be changed\n\tif (h->getType() != VARIABLE_NODE)\n\t\treturn h;\n\n\t\/\/ use existing mapping if the VariableNode is already mapped\n\tif (dict.count(h) == 1)\n\t\treturn dict[h];\n\n\tstd::stringstream ss;\n\tss << NodeCast(h)->getName() << \"-\" << rule_handle_ << \"-standardize_apart\";\n\n\tHandle hcpy = as->add_atom(createNode(h->getType(), ss.str(), h->getTruthValue()));\n\tdict[h] = hcpy;\n\n\treturn hcpy;\n}\n<|endoftext|>"} {"text":"\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2018, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program 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.\n * See the GNU Affero Public License for more details.\n *\n * You should have received a copy of the GNU Affero Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n\n\n\n * Author: David Keeney, April, 2018\n * ---------------------------------------------------------------------\n *\/\n\n\/*---------------------------------------------------------------------\n * This is a test of the backtrackingTMCpp C++ implimentation (no Python).\n *\n * For those not familiar with GTest:\n * ASSERT_TRUE(value) -- Fatal assertion that the value is true. Test\n * terminates if false.\n * ASSERT_FALSE(value) -- Fatal assertion that the value\n * is false. Test terminates if true.\n * ASSERT_STREQ(str1, str2) -- Fatal assertion that the strings are equal.\n * Test terminates if false.\n * EXPECT_TRUE(value) -- Nonfatal assertion that the value is true. Test\n * continues if false.\n * EXPECT_FALSE(value) -- Nonfatal assertion that the value is false.\n * Test continues if true.\n * EXPECT_STREQ(str1, str2) -- Nonfatal assertion that the strings are equal.\n * Test continues if false.\n * EXPECT_THROW(statement, exception_type) -- nonfatal exception, cought,\n * reported and continues.\n *---------------------------------------------------------------------\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\n#include \n\n#define VERBOSITY 0\n#define VERBOSE if (verbose) std::cerr << \"[ ] \"\nstatic bool verbose = true; \/\/ turn this on to print extra stuff for debugging the test.\n#define SEED 12\n\nusing namespace nupic;\nusing namespace nupic::algorithms::backtracking_tm;\nnamespace testing {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ helper routines\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntypedef shared_ptr Pattern_t;\n\n\n\/\/ Generate a single test pattern of random bits with given parameters.\n\/\/\n\/\/ Parameters :\n\/\/ @numCols -Number of columns in each pattern.\n\/\/ @minOnes -The minimum number of 1's in each pattern.\n\/\/ @maxOnes -The maximum number of 1's in each pattern.\n\nstatic Pattern_t generatePattern(Size numCols = 100, Size minOnes = 21,\n Size maxOnes = 25) {\n NTA_ASSERT(minOnes <= maxOnes);\n NTA_ASSERT(maxOnes < numCols);\n Pattern_t p(new Real32[numCols], std::default_delete());\n memset(p.get(), 0, numCols);\n\n int numOnes = (int)minOnes + std::rand() % (maxOnes - minOnes + 1);\n std::uniform_int_distribution<> distr(0, (int)numCols - 1); \/\/ define the range (requires C++11)\n for (int n = 0; n < numOnes; n++) {\n int idx = std::rand() % numCols;\n p.get()[idx] = 1.0f;\n }\n return p;\n}\n\n\/\/ Generates a sequence of n random patterns.\nstatic std::vector generateSequence(Size n = 10, Size numCols = 100,\n Size minOnes = 21,\n Size maxOnes = 25) {\n std::vector seq;\n Pattern_t p; \/\/ an empty pattern which means reset\n seq.push_back(p);\n\n for (Size i = 0; i < n; i++) {\n Pattern_t p = generatePattern(numCols, minOnes, maxOnes);\n seq.push_back(p);\n }\n return seq;\n}\n\n\nstruct param_t {\n UInt32 numberOfCols;\n UInt32 cellsPerColumn;\n Real32 initialPerm;\n Real32 connectedPerm;\n UInt32 minThreshold;\n UInt32 newSynapseCount;\n Real32 permanenceInc;\n Real32 permanenceDec;\n Real32 permanenceMax;\n Real32 globalDecay;\n UInt32 activationThreshold;\n bool doPooling;\n UInt32 segUpdateValidDuration;\n UInt32 burnIn;\n bool collectStats;\n Int32 seed;\n Int32 verbosity;\n bool checkSynapseConsistency;\n UInt32 pamLength;\n UInt32 maxInfBacktrack;\n UInt32 maxLrnBacktrack;\n UInt32 maxAge;\n UInt32 maxSeqLength;\n Int32 maxSegmentsPerCell;\n Int32 maxSynapsesPerSegment;\n char outputType[25];\n};\n\nvoid initializeParameters(struct param_t ¶m) {\n \/\/ same as default settings\n param.numberOfCols = 10;\n param.cellsPerColumn = 3;\n param.initialPerm = 0.11f;\n param.connectedPerm = 0.5f;\n param.minThreshold = 8;\n param.newSynapseCount = 15;\n param.permanenceInc = 0.1f;\n param.permanenceDec = 0.1f;\n param.permanenceMax = 1.0f;\n param.globalDecay = 0.1f;\n param.activationThreshold = 12;\n param.doPooling = false;\n param.segUpdateValidDuration = 5;\n param.burnIn = 2;\n param.collectStats = false;\n param.seed = 42;\n param.verbosity = VERBOSITY;\n param.checkSynapseConsistency = false;\n param.pamLength = 1;\n param.maxInfBacktrack = 10;\n param.maxLrnBacktrack = 5;\n param.maxAge = 100000;\n param.maxSeqLength = 32;\n param.maxSegmentsPerCell = -1;\n param.maxSynapsesPerSegment = -1;\n strcpy(param.outputType, \"normal\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Run a test of the basic TM class ported from backtracking_tm_test.py\nTEST(BacktrackingTMTest, testCheckpointLearned) {\n\n struct param_t param;\n initializeParameters(param);\n param.numberOfCols = 100;\n param.cellsPerColumn = 12;\n param.verbosity = VERBOSITY;\n\n try {\n \/\/ Create TM object\n BacktrackingTMCpp tm1(\n param.numberOfCols, param.cellsPerColumn, param.initialPerm,\n param.connectedPerm, param.minThreshold, param.newSynapseCount,\n param.permanenceInc, param.permanenceDec, param.permanenceMax,\n param.globalDecay, param.activationThreshold, param.doPooling,\n param.segUpdateValidDuration, param.burnIn, param.collectStats,\n param.seed, param.verbosity, param.checkSynapseConsistency,\n param.pamLength, param.maxInfBacktrack, param.maxLrnBacktrack,\n param.maxAge, param.maxSeqLength, param.maxSegmentsPerCell,\n param.maxSynapsesPerSegment, param.outputType);\n\n \/\/ generate 5 sets of sequences\n \/\/ The first pattern in each sequence is empty (a reset)\n std::vector> sequences;\n for (Size s = 0; s < 5; s++) {\n sequences.push_back(generateSequence());\n }\n \/\/ train with the first 3 sets of sequences.\n std::vector train;\n for (Size s = 0; s < 3; s++) {\n for (Size i = 0; i < sequences[s].size();i++) {\n train.push_back(sequences[s][i]);\n }\n }\n\n \/\/ process the patterns that are in the training set.\n for (Size t = 0; t < train.size(); t++) {\n if (!train[t]) {\n tm1.reset();\n } else {\n Real *bottomUpInput = train[t].get();\n tm1.compute(bottomUpInput, true, true);\n }\n }\n \/\/ Serialize and deserialized the TM.\n Directory::create(\"TestOutputDir\", false, true);\n std::string checkpointPath = \"TestOutputDir\/tm.save\";\n tm1.saveToFile(checkpointPath);\n\n BacktrackingTMCpp tm2;\n tm2.loadFromFile(checkpointPath);\n\n \/\/ Check that the TMs are the same.\n ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));\n\n \/\/ Feed remaining data into the models.\n train.clear();\n for (Size s = 3; s < sequences.size(); s++) {\n for (Size i = 0; i < sequences[s].size(); i++) {\n train.push_back(sequences[s][i]);\n }\n }\n\n for (Size t = 0; t < train.size(); t++) {\n if (!train[t]) {\n tm1.reset();\n tm2.reset();\n } else {\n Real *bottomUpInput = train[t].get();\n Real *result1 = tm1.compute(bottomUpInput, true, true);\n Real *result2 = tm2.compute(bottomUpInput, true, true);\n\n ASSERT_TRUE(tm1 == tm2);\n ASSERT_TRUE(tm1.getOutputBufferSize() == tm2.getOutputBufferSize());\n for (Size i = 0; i < tm1.getOutputBufferSize(); i++) {\n ASSERT_TRUE(result1[i] == result2[i]);\n }\n }\n }\n }\n catch (nupic::Exception &ex) {\n FAIL() << \"Failure: Exception: \" << ex.getFilename() << \"(\"\n << ex.getLineNumber() << \") \" << ex.getMessage() << \"\" << std::endl;\n }\n catch (std::exception &e) {\n FAIL() << \"Failure: Exception: \" << e.what() << \"\" << std::endl;\n }\n\n \/\/ cleanup .\n Directory::removeTree(\"TestOutputDir\");\n\n}\n\nTEST(BacktrackingTMTest, testCheckpointMiddleOfSequence)\n{\n \/\/ Create a model and give it some inputs to learn.\n BacktrackingTMCpp tm1(100, 12);\n tm1.setVerbosity((Int32)VERBOSITY);\n\n\n \/\/ generate 5 sets of sequences\n std::vector> sequences;\n for (Size s = 0; s < 5; s++) {\n sequences.push_back(generateSequence());\n }\n \/\/ separate train sets of sequences into halves\n std::vector firstHalf, secondHalf;\n const int HALF = 5*10 \/2;\n int idx = 0;\n for (auto seq: sequences) {\n for (auto pattern : seq) {\n\tif(idx++ < HALF) firstHalf.push_back(pattern);\n\telse secondHalf.push_back(pattern);\n }\n }\n\n \/\/ compute each of the patterns in train, learn\n for (auto p: firstHalf) {\n const auto pat = p.get();\n if (!pat) {\n tm1.reset();\n } else {\n tm1.compute(pat, true, true);\n }\n }\n\n \/\/ Serialize and TM.\n Directory::create(\"TestOutputDir\", false, true);\n std::string checkpointPath = \"TestOutputDir\/tm.save\";\n tm1.saveToFile(checkpointPath);\n\n \/\/ Restore the saved TM into tm2.\n \/\/ Note that this resets the random generator to the same\n \/\/ point that the first TM used when it processed that second set\n \/\/ of patterns.\n BacktrackingTMCpp tm2;\n tm2.loadFromFile(checkpointPath);\n\n ASSERT_EQ(tm1, tm2) << \"Deserialized TM is equal\";\n ASSERT_TRUE(tm1 == tm2);\n\n \/\/ process the remaining patterns in train with the first TM.\n for (auto p: secondHalf) {\n const auto pat = p.get();\n if (!pat) {\n tm1.reset();\n } else {\n Real *result1 = tm1.compute(pat, true, true);\n }\n }\n\n ASSERT_TRUE(tm1 != tm2) << \"TM1 moved, TM2 didn't\";\n\n\n \/\/ process the same remaining patterns in the train with the second TM.\n for (auto p: secondHalf) {\n const auto pat = p.get();\n if (!pat) {\n tm2.reset();\n } else {\n Real *result22= tm2.compute(pat, true, true);\n }\n }\n\n ASSERT_EQ(tm1, tm2) << \"Both TM trained\";\n ASSERT_TRUE(tm1 == tm2);\n\n \/\/ cleanup if successful.\n Directory::removeTree(\"TestOutputDir\");\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Run a test of the TM class ported from backtracking_tm_cpp2_test.py\nTEST(BacktrackingTMTest, basicTest) {\n \/\/ Create a model and give it some inputs to learn.\n BacktrackingTMCpp tm1(10, 3, 0.2f, 0.8f, 2, 5, 0.10f, 0.05f, 1.0f, 0.05f, 4,\n false, 5, 2, false, SEED, (Int32)VERBOSITY \/* rest are defaults *\/);\n tm1.setRetrieveLearningStates(true);\n Size nCols = tm1.getnumCol();\n\n \/\/ Serialize and deserialized the TM.\n Directory::create(\"TestOutputDir\", false, true);\n std::string checkpointPath = \"TestOutputDir\/tm.save\";\n tm1.saveToFile(checkpointPath);\n\n BacktrackingTMCpp tm2;\n tm2.loadFromFile(checkpointPath);\n\n \/\/ Check that the TMs are the same.\n ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));\n\n \/\/ generate some test data and NT patterns from it.\n std::vector data = generateSequence(10, nCols, 2, 2);\n std::vector> nzData;\n for (Size i = 0; i < data.size(); i++) {\n if (data[i]) { \/\/ skip reset patterns\n const auto indices = \n\t\tnupic::algorithms::backtracking_tm::nonzero(data[i].get(), nCols);\n nzData.push_back(indices);\n }\n }\n\n\n \/\/ Learn\n for (Size i = 0; i < 5; i++) {\n if (data[i])\n tm1.learn(data[i].get());\n }\n tm1.reset();\n\n \/\/ save and reload again after learning.\n tm1.saveToFile(checkpointPath);\n BacktrackingTMCpp tm3;\n tm3.loadFromFile(checkpointPath);\n \/\/ Check that the TMs are the same.\n ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm3, std::cout, 2));\n\n \/\/ Infer\n for (Size i = 0; i < 10; i++) {\n if (data[i]) {\n tm1.infer(data[i].get());\n if (i > 0)\n tm1._checkPrediction(nzData);\n }\n }\n\n \/\/ cleanup if successful.\n Directory::removeTree(\"TestOutputDir\");\n}\n\n} \/\/ namespace testing\nBackTM: test cleanup\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2018, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program 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.\n * See the GNU Affero Public License for more details.\n *\n * You should have received a copy of the GNU Affero Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n\n\n\n * Author: David Keeney, April, 2018\n * ---------------------------------------------------------------------\n *\/\n\n\/*---------------------------------------------------------------------\n * This is a test of the backtrackingTMCpp C++ implimentation (no Python).\n *\n * For those not familiar with GTest:\n * ASSERT_TRUE(value) -- Fatal assertion that the value is true. Test\n * terminates if false.\n * ASSERT_FALSE(value) -- Fatal assertion that the value\n * is false. Test terminates if true.\n * ASSERT_STREQ(str1, str2) -- Fatal assertion that the strings are equal.\n * Test terminates if false.\n * EXPECT_TRUE(value) -- Nonfatal assertion that the value is true. Test\n * continues if false.\n * EXPECT_FALSE(value) -- Nonfatal assertion that the value is false.\n * Test continues if true.\n * EXPECT_STREQ(str1, str2) -- Nonfatal assertion that the strings are equal.\n * Test continues if false.\n * EXPECT_THROW(statement, exception_type) -- nonfatal exception, cought,\n * reported and continues.\n *---------------------------------------------------------------------\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\n#include \n\n#define VERBOSITY 0\n#define VERBOSE if (verbose) std::cerr << \"[ ] \"\nstatic bool verbose = true; \/\/ turn this on to print extra stuff for debugging the test.\n#define SEED 12\n\nusing namespace nupic;\nusing namespace nupic::algorithms::backtracking_tm;\nnamespace testing {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ helper routines\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntypedef shared_ptr Pattern_t;\n\n\n\/\/ Generate a single test pattern of random bits with given parameters.\n\/\/\n\/\/ Parameters :\n\/\/ @numCols -Number of columns in each pattern.\n\/\/ @minOnes -The minimum number of 1's in each pattern.\n\/\/ @maxOnes -The maximum number of 1's in each pattern.\n\nstatic Pattern_t generatePattern(Size numCols = 100, Size minOnes = 21,\n Size maxOnes = 25) {\n NTA_ASSERT(minOnes <= maxOnes);\n NTA_ASSERT(maxOnes < numCols);\n Pattern_t p(new Real32[numCols], std::default_delete());\n memset(p.get(), 0, numCols);\n\n int numOnes = (int)minOnes + std::rand() % (maxOnes - minOnes + 1);\n std::uniform_int_distribution<> distr(0, (int)numCols - 1); \/\/ define the range (requires C++11)\n for (int n = 0; n < numOnes; n++) {\n int idx = std::rand() % numCols;\n p.get()[idx] = 1.0f;\n }\n return p;\n}\n\n\/\/ Generates a sequence of n random patterns.\nstatic std::vector generateSequence(Size n = 10, Size numCols = 100,\n Size minOnes = 21,\n Size maxOnes = 25) {\n std::vector seq;\n Pattern_t p; \/\/ an empty pattern which means reset\n seq.push_back(p);\n\n for (Size i = 0; i < n; i++) {\n Pattern_t p = generatePattern(numCols, minOnes, maxOnes);\n seq.push_back(p);\n }\n return seq;\n}\n\n\nstruct param_t {\n UInt32 numberOfCols;\n UInt32 cellsPerColumn;\n Real32 initialPerm;\n Real32 connectedPerm;\n UInt32 minThreshold;\n UInt32 newSynapseCount;\n Real32 permanenceInc;\n Real32 permanenceDec;\n Real32 permanenceMax;\n Real32 globalDecay;\n UInt32 activationThreshold;\n bool doPooling;\n UInt32 segUpdateValidDuration;\n UInt32 burnIn;\n bool collectStats;\n Int32 seed;\n Int32 verbosity;\n bool checkSynapseConsistency;\n UInt32 pamLength;\n UInt32 maxInfBacktrack;\n UInt32 maxLrnBacktrack;\n UInt32 maxAge;\n UInt32 maxSeqLength;\n Int32 maxSegmentsPerCell;\n Int32 maxSynapsesPerSegment;\n char outputType[25];\n};\n\nvoid initializeParameters(struct param_t ¶m) {\n \/\/ same as default settings\n param.numberOfCols = 10;\n param.cellsPerColumn = 3;\n param.initialPerm = 0.11f;\n param.connectedPerm = 0.5f;\n param.minThreshold = 8;\n param.newSynapseCount = 15;\n param.permanenceInc = 0.1f;\n param.permanenceDec = 0.1f;\n param.permanenceMax = 1.0f;\n param.globalDecay = 0.1f;\n param.activationThreshold = 12;\n param.doPooling = false;\n param.segUpdateValidDuration = 5;\n param.burnIn = 2;\n param.collectStats = false;\n param.seed = 42;\n param.verbosity = VERBOSITY;\n param.checkSynapseConsistency = false;\n param.pamLength = 1;\n param.maxInfBacktrack = 10;\n param.maxLrnBacktrack = 5;\n param.maxAge = 100000;\n param.maxSeqLength = 32;\n param.maxSegmentsPerCell = -1;\n param.maxSynapsesPerSegment = -1;\n strcpy(param.outputType, \"normal\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Run a test of the basic TM class ported from backtracking_tm_test.py\nTEST(BacktrackingTMTest, testCheckpointLearned) {\n\n struct param_t param;\n initializeParameters(param);\n param.numberOfCols = 100;\n param.cellsPerColumn = 12;\n param.verbosity = VERBOSITY;\n\n \/\/ Create TM object\n BacktrackingTMCpp tm1(\n param.numberOfCols, param.cellsPerColumn, param.initialPerm,\n param.connectedPerm, param.minThreshold, param.newSynapseCount,\n param.permanenceInc, param.permanenceDec, param.permanenceMax,\n param.globalDecay, param.activationThreshold, param.doPooling,\n param.segUpdateValidDuration, param.burnIn, param.collectStats,\n param.seed, param.verbosity, param.checkSynapseConsistency,\n param.pamLength, param.maxInfBacktrack, param.maxLrnBacktrack,\n param.maxAge, param.maxSeqLength, param.maxSegmentsPerCell,\n param.maxSynapsesPerSegment, param.outputType);\n\n \/\/ generate 5 sets of sequences\n \/\/ The first pattern in each sequence is empty (a reset)\n std::vector> sequences;\n for (Size s = 0; s < 5; s++) {\n sequences.push_back(generateSequence());\n }\n \/\/ train with the first 3 sets of sequences.\n std::vector train;\n for (Size s = 0; s < 3; s++) {\n for (Size i = 0; i < sequences[s].size();i++) {\n train.push_back(sequences[s][i]);\n }\n }\n\n \/\/ process the patterns that are in the training set.\n for (Size t = 0; t < train.size(); t++) {\n if (!train[t]) {\n tm1.reset();\n } else {\n Real *bottomUpInput = train[t].get();\n tm1.compute(bottomUpInput, true, true);\n }\n }\n \/\/ Serialize and deserialized the TM.\n Directory::create(\"TestOutputDir\", false, true);\n std::string checkpointPath = \"TestOutputDir\/tm.save\";\n tm1.saveToFile(checkpointPath);\n\n BacktrackingTMCpp tm2;\n tm2.loadFromFile(checkpointPath);\n\n \/\/ Check that the TMs are the same.\n ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));\n\n \/\/ Feed remaining data into the models.\n train.clear();\n for (Size s = 3; s < sequences.size(); s++) {\n for (Size i = 0; i < sequences[s].size(); i++) {\n train.push_back(sequences[s][i]);\n }\n }\n\n for (Size t = 0; t < train.size(); t++) {\n if (!train[t]) {\n tm1.reset();\n tm2.reset();\n } else {\n Real *bottomUpInput = train[t].get();\n Real *result1 = tm1.compute(bottomUpInput, true, true);\n Real *result2 = tm2.compute(bottomUpInput, true, true);\n\n ASSERT_TRUE(tm1 == tm2);\n ASSERT_TRUE(tm1.getOutputBufferSize() == tm2.getOutputBufferSize());\n\tASSERT_EQ(tm1, tm2);\n for (Size i = 0; i < tm1.getOutputBufferSize(); i++) {\n ASSERT_TRUE(result1[i] == result2[i]);\n }\n }\n }\n\n \/\/ cleanup .\n Directory::removeTree(\"TestOutputDir\");\n\n}\n\nTEST(BacktrackingTMTest, testCheckpointMiddleOfSequence)\n{\n \/\/ Create a model and give it some inputs to learn.\n BacktrackingTMCpp tm1(100, 12);\n tm1.setVerbosity((Int32)VERBOSITY);\n\n\n \/\/ generate 5 sets of sequences\n std::vector> sequences;\n for (Size s = 0; s < 5; s++) {\n sequences.push_back(generateSequence());\n }\n \/\/ separate train sets of sequences into halves\n std::vector firstHalf, secondHalf;\n const int HALF = 5*10 \/2;\n int idx = 0;\n for (auto seq: sequences) {\n for (auto pattern : seq) {\n\tif(idx++ < HALF) firstHalf.push_back(pattern);\n\telse secondHalf.push_back(pattern);\n }\n }\n\n \/\/ compute each of the patterns in train, learn\n for (auto p: firstHalf) {\n const auto pat = p.get();\n if (!pat) {\n tm1.reset();\n } else {\n tm1.compute(pat, true, true);\n }\n }\n\n \/\/ Serialize and TM.\n Directory::create(\"TestOutputDir\", false, true);\n std::string checkpointPath = \"TestOutputDir\/tm.save\";\n tm1.saveToFile(checkpointPath);\n\n \/\/ Restore the saved TM into tm2.\n \/\/ Note that this resets the random generator to the same\n \/\/ point that the first TM used when it processed that second set\n \/\/ of patterns.\n BacktrackingTMCpp tm2;\n tm2.loadFromFile(checkpointPath);\n\n ASSERT_EQ(tm1, tm2) << \"Deserialized TM is equal\";\n ASSERT_TRUE(tm1 == tm2);\n\n \/\/ process the remaining patterns in train with the first TM.\n for (auto p: secondHalf) {\n const auto pat = p.get();\n if (!pat) {\n tm1.reset();\n } else {\n Real *result1 = tm1.compute(pat, true, true);\n }\n }\n\n ASSERT_TRUE(tm1 != tm2) << \"TM1 moved, TM2 didn't\";\n\n\n \/\/ process the same remaining patterns in the train with the second TM.\n for (auto p: secondHalf) {\n const auto pat = p.get();\n if (!pat) {\n tm2.reset();\n } else {\n Real *result22= tm2.compute(pat, true, true);\n }\n }\n\n ASSERT_EQ(tm1, tm2) << \"Both TM trained\";\n ASSERT_TRUE(tm1 == tm2);\n\n \/\/ cleanup if successful.\n Directory::removeTree(\"TestOutputDir\");\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Run a test of the TM class ported from backtracking_tm_cpp2_test.py\nTEST(BacktrackingTMTest, basicTest) {\n \/\/ Create a model and give it some inputs to learn.\n BacktrackingTMCpp tm1(10, 3, 0.2f, 0.8f, 2, 5, 0.10f, 0.05f, 1.0f, 0.05f, 4,\n false, 5, 2, false, SEED, (Int32)VERBOSITY \/* rest are defaults *\/);\n tm1.setRetrieveLearningStates(true);\n Size nCols = tm1.getnumCol();\n\n \/\/ Serialize and deserialized the TM.\n Directory::create(\"TestOutputDir\", false, true);\n std::string checkpointPath = \"TestOutputDir\/tm.save\";\n tm1.saveToFile(checkpointPath);\n\n BacktrackingTMCpp tm2;\n tm2.loadFromFile(checkpointPath);\n\n \/\/ Check that the TMs are the same.\n ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));\n\n \/\/ generate some test data and NT patterns from it.\n std::vector data = generateSequence(10, nCols, 2, 2);\n std::vector> nzData;\n for (Size i = 0; i < data.size(); i++) {\n if (data[i]) { \/\/ skip reset patterns\n const auto indices = \n\t\tnupic::algorithms::backtracking_tm::nonzero(data[i].get(), nCols);\n nzData.push_back(indices);\n }\n }\n\n\n \/\/ Learn\n for (Size i = 0; i < 5; i++) {\n if (data[i])\n tm1.learn(data[i].get());\n }\n tm1.reset();\n\n \/\/ save and reload again after learning.\n tm1.saveToFile(checkpointPath);\n BacktrackingTMCpp tm3;\n tm3.loadFromFile(checkpointPath);\n \/\/ Check that the TMs are the same.\n ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm3, std::cout, 2));\n\n \/\/ Infer\n for (Size i = 0; i < 10; i++) {\n if (data[i]) {\n tm1.infer(data[i].get());\n if (i > 0)\n tm1._checkPrediction(nzData);\n }\n }\n\n \/\/ cleanup if successful.\n Directory::removeTree(\"TestOutputDir\");\n}\n\n} \/\/ namespace testing\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: bootstrapcontext.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2004-06-18 15:49:52 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_\n#define CONFIGMGR_BOOTSTRAPCONTEXT_HXX_\n\n#ifndef _CPPUHELPER_COMPBASE3_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n\n#ifndef _RTL_BOOTSTRAP_H_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_XCURRENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif \/\/ _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n\nnamespace com { namespace sun { namespace star { namespace uno {\n class XComponentContext;\n} } } }\n\n\/\/ -----------------------------------------------------------------------------\n#define SINGLETON_ \"\/singletons\/\"\n#define SINGLETON( NAME ) OUString( RTL_CONSTASCII_USTRINGPARAM( SINGLETON_ NAME ) )\n\/\/ -----------------------------------------------------------------------------\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace beans = ::com::sun::star::beans;\n using ::rtl::OUString;\n\/\/ -----------------------------------------------------------------------------\n typedef ::cppu::WeakComponentImplHelper3 <\n uno::XComponentContext,\n uno::XCurrentContext,\n lang::XServiceInfo\n > ComponentContext_Base;\n \/** Base class for customized ComponentContext using bootstrap data and overrides\n *\/\n class ComponentContext : public ComponentContext_Base\n {\n public:\n typedef uno::Reference< uno::XComponentContext > Context;\n typedef uno::Reference< lang::XMultiComponentFactory > ServiceManager;\n\n \/\/ creation and destruction\n public:\n \/** Constructs a ComponentContext based on the given overrides and context.\n Initially no bootstrap data will be used.\n\n @param _xContext\n The base context of this component context.\n Values from here take precedence over values from bootstrap data.\n\n @param _aOverrides\n The overrides used to create this component context.\n These values take precedence over values from the base context or bootstrap data.\n *\/\n explicit\n ComponentContext(Context const & _xContext);\n\n \/\/\/ Destroys this BootstrapContext\n ~ComponentContext();\n\n \/\/\/ changes the INI file to use for bootstrap data\n void changeBootstrapURL( const OUString& _aURL );\n\n \/\/ gets the INI in use for getting bootstrap data\n OUString getBootstrapURL() const;\n\n static sal_Bool isPassthrough(Context const & _xContext);\n\n static Context getBaseContext(Context const & _xContext);\n\n static beans::NamedValue makePassthroughMarker(sal_Bool bPassthrough = true);\n \/\/ interface implementations\n public:\n \/\/ XComponentContext & XCurrentContext\n \/** Retrieves a value from this context.\n Can be overridden in derived implementations\n\n @param Name\n The name of the value to retrieve.\n\n @returns\n The requested value, or if the value is not found.\n *\/\n virtual uno::Any SAL_CALL\n getValueByName( const OUString& Name )\n throw (uno::RuntimeException) = 0;\n\n \/\/ XComponentContext only\n virtual ServiceManager SAL_CALL\n getServiceManager( )\n throw (uno::RuntimeException);\n\n protected:\n \/\/ ComponentHelper\n virtual void SAL_CALL disposing();\n\n protected:\n \/\/ two phase construct - also initialized the bootstrap data\n void initialize(const OUString& _aBootstrapURL);\n\n bool lookupInContext ( uno::Any & _rValue, const OUString& _aName ) const;\n bool lookupInBootstrap( uno::Any & _rValue, const OUString& _aName ) const;\n\n osl::Mutex & mutex() const { return m_aMutex; }\n Context const & basecontext() const { osl::MutexGuard lock(mutex()); return m_xContext; }\n\n private:\n \/\/\/ The mutex protecting this component\n mutable osl::Mutex m_aMutex;\n \/\/\/ The context that most requests are delegated to\n Context m_xContext;\n \/\/\/ The bootstrap data consulted as fallback\n rtlBootstrapHandle m_hBootstrapData;\n };\n\/\/ -----------------------------------------------------------------------------\n\n class UnoContextTunnel\n {\n public:\n typedef uno::Reference< uno::XCurrentContext > CurrentContext;\n typedef uno::Reference< lang::XUnoTunnel > FailureTunnel;\n typedef uno::Reference< uno::XComponentContext > Context;\n public:\n UnoContextTunnel();\n ~UnoContextTunnel();\n void tunnel(Context const & xContext);\n void passthru(Context const & xContext);\n uno::Any recoverFailure(bool bRaise); \/\/ true, if there is a failure\n\n static Context recoverContext(Context const & xFallback = Context());\n static bool tunnelFailure(uno::Any const & aException, bool bRaise = false);\n private:\n CurrentContext m_xOldContext;\n FailureTunnel m_xActiveTunnel;\n class Tunnel;\n };\n\/\/ -----------------------------------------------------------------------------\n\n class DisposingForwarder : public cppu::WeakImplHelper1< lang::XEventListener >\n {\n uno::Reference< lang::XComponent > m_xTarget;\n\n DisposingForwarder( uno::Reference< lang::XComponent > const & xTarget ) SAL_THROW( () )\n : m_xTarget( xTarget )\n { OSL_ASSERT( m_xTarget.is() ); }\n\n virtual void SAL_CALL disposing( lang::EventObject const & rSource )\n throw (uno::RuntimeException);\n public:\n \/\/ listens at source for disposing, then disposes target\n static inline void forward(\n uno::Reference< lang::XComponent > const & xSource,\n uno::Reference< lang::XComponent > const & xTarget )\n SAL_THROW( (uno::RuntimeException) );\n };\n\/\/__________________________________________________________________________________________________\n inline void DisposingForwarder::forward(\n uno::Reference< lang::XComponent > const & xSource,\n uno::Reference< lang::XComponent > const & xTarget )\n SAL_THROW( (uno::RuntimeException) )\n {\n if (xSource.is())\n {\n xSource->addEventListener( new DisposingForwarder( xTarget ) );\n }\n }\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n#endif\n\n\nINTEGRATION: CWS cfglooseends (1.3.30); FILE MERGED 2004\/11\/02 16:57:22 jb 1.3.30.1: #109882# Use own servicemanager (-wrapper) for bootstrap context\/*************************************************************************\n *\n * $RCSfile: bootstrapcontext.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-11-15 13:36:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_\n#define CONFIGMGR_BOOTSTRAPCONTEXT_HXX_\n\n#ifndef _CPPUHELPER_COMPBASE3_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n\n#ifndef _RTL_BOOTSTRAP_H_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_XCURRENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif \/\/ _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n\nnamespace com { namespace sun { namespace star { namespace uno {\n class XComponentContext;\n} } } }\n\n\/\/ -----------------------------------------------------------------------------\n#define SINGLETON_ \"\/singletons\/\"\n#define SINGLETON( NAME ) OUString( RTL_CONSTASCII_USTRINGPARAM( SINGLETON_ NAME ) )\n\/\/ -----------------------------------------------------------------------------\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace beans = ::com::sun::star::beans;\n using ::rtl::OUString;\n\/\/ -----------------------------------------------------------------------------\n typedef ::cppu::WeakComponentImplHelper3 <\n uno::XComponentContext,\n uno::XCurrentContext,\n lang::XServiceInfo\n > ComponentContext_Base;\n \/** Base class for customized ComponentContext using bootstrap data and overrides\n *\/\n class ComponentContext : public ComponentContext_Base\n {\n public:\n typedef uno::Reference< uno::XComponentContext > Context;\n typedef uno::Reference< lang::XMultiComponentFactory > ServiceManager;\n\n \/\/ creation and destruction\n public:\n \/** Constructs a ComponentContext based on the given overrides and context.\n Initially no bootstrap data will be used.\n\n @param _xContext\n The base context of this component context.\n Values from here take precedence over values from bootstrap data.\n\n @param _aOverrides\n The overrides used to create this component context.\n These values take precedence over values from the base context or bootstrap data.\n *\/\n explicit\n ComponentContext(Context const & _xContext);\n\n \/\/\/ Destroys this BootstrapContext\n ~ComponentContext();\n\n \/\/\/ changes the INI file to use for bootstrap data\n void changeBootstrapURL( const OUString& _aURL );\n\n \/\/ gets the INI in use for getting bootstrap data\n OUString getBootstrapURL() const;\n\n static sal_Bool isPassthrough(Context const & _xContext);\n\n static Context getBaseContext(Context const & _xContext);\n\n static beans::NamedValue makePassthroughMarker(sal_Bool bPassthrough = true);\n \/\/ interface implementations\n public:\n \/\/ XComponentContext & XCurrentContext\n \/** Retrieves a value from this context.\n Can be overridden in derived implementations\n\n @param Name\n The name of the value to retrieve.\n\n @returns\n The requested value, or if the value is not found.\n *\/\n virtual uno::Any SAL_CALL\n getValueByName( const OUString& Name )\n throw (uno::RuntimeException) = 0;\n\n \/\/ XComponentContext only\n virtual ServiceManager SAL_CALL\n getServiceManager( )\n throw (uno::RuntimeException);\n\n protected:\n \/\/ ComponentHelper\n virtual void SAL_CALL disposing();\n\n protected:\n \/\/ two phase construct - also initialized the bootstrap data\n void initialize(const OUString& _aBootstrapURL);\n\n bool lookupInContext ( uno::Any & _rValue, const OUString& _aName ) const;\n bool lookupInBootstrap( uno::Any & _rValue, const OUString& _aName ) const;\n\n osl::Mutex & mutex() const { return m_aMutex; }\n Context const & basecontext() const { osl::MutexGuard lock(mutex()); return m_xContext; }\n\n private:\n \/\/\/ The mutex protecting this component\n mutable osl::Mutex m_aMutex;\n \/\/\/ The context that most requests are delegated to\n Context m_xContext;\n \/\/\/ The bootstrap data consulted as fallback\n rtlBootstrapHandle m_hBootstrapData;\n \/\/\/ The service manager associated with this context\n ServiceManager m_xServiceManager;\n };\n\/\/ -----------------------------------------------------------------------------\n\n class UnoContextTunnel\n {\n public:\n typedef uno::Reference< uno::XCurrentContext > CurrentContext;\n typedef uno::Reference< lang::XUnoTunnel > FailureTunnel;\n typedef uno::Reference< uno::XComponentContext > Context;\n public:\n UnoContextTunnel();\n ~UnoContextTunnel();\n void tunnel(Context const & xContext);\n void passthru(Context const & xContext);\n uno::Any recoverFailure(bool bRaise); \/\/ true, if there is a failure\n\n static Context recoverContext(Context const & xFallback = Context());\n static bool tunnelFailure(uno::Any const & aException, bool bRaise = false);\n private:\n CurrentContext m_xOldContext;\n FailureTunnel m_xActiveTunnel;\n class Tunnel;\n };\n\/\/ -----------------------------------------------------------------------------\n\n class DisposingForwarder : public cppu::WeakImplHelper1< lang::XEventListener >\n {\n uno::Reference< lang::XComponent > m_xTarget;\n\n DisposingForwarder( uno::Reference< lang::XComponent > const & xTarget ) SAL_THROW( () )\n : m_xTarget( xTarget )\n { OSL_ASSERT( m_xTarget.is() ); }\n\n virtual void SAL_CALL disposing( lang::EventObject const & rSource )\n throw (uno::RuntimeException);\n public:\n \/\/ listens at source for disposing, then disposes target\n static inline void forward(\n uno::Reference< lang::XComponent > const & xSource,\n uno::Reference< lang::XComponent > const & xTarget )\n SAL_THROW( (uno::RuntimeException) );\n };\n\/\/__________________________________________________________________________________________________\n inline void DisposingForwarder::forward(\n uno::Reference< lang::XComponent > const & xSource,\n uno::Reference< lang::XComponent > const & xTarget )\n SAL_THROW( (uno::RuntimeException) )\n {\n if (xSource.is())\n {\n xSource->addEventListener( new DisposingForwarder( xTarget ) );\n }\n }\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n#endif\n\n\n<|endoftext|>"} {"text":"\/\/\r\n\/\/#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 1000;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\tdouble t = time_to_complete;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tt -= 1;\r\n\t\t\t\/\/Pulse(out1, sin((2PI\/2) * abs(1\/t)));\r\n\t\t\t\/\/Wait(sin((PI\/2) * abs(1\/t)));\r\n\t\t\tPulse(out1, sin((2*PI) * abs(1\/t)));\r\n\t\t\tWait(sin((2*PI) * abs(1\/t)));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1 \/ resolution);\r\n\t\t\tWait(1\/resolution);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\nUpdate pwm.cpp\/\/\r\n\/\/#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 1000;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\tdouble t = time_to_complete;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tt -= 1;\r\n\t\t\t\/\/Pulse(out1, sin((2PI\/2) * abs(1\/t)));\r\n\t\t\t\/\/Wait(sin((PI\/2) * abs(1\/t)));\r\n\t\t\tPulse(out1, sin((2*PI) * abs(1\/t)));\r\n\t\t\tWait(sin((2*PI) * abs(1\/t)));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(2\/resolution);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<|endoftext|>"} {"text":"#include \"VulkanGraphicsInstance.hpp\"\n\n#if defined(PLATFORM_WINDOWS)\n#include \n#endif\n\nVulkanGraphicsInstance::VulkanGraphicsInstance()\n : m_alloc_info(reinterpret_cast(&m_allocs), allocs::pfnAllocation, allocs::pfnReallocation, allocs::pfnFree, allocs::pfnInternalAllocation, allocs::pfnInternalFree)\n\n , m_instance(new vk::Instance, [=](vk::Instance* ist)\n {\n (*ist).destroy(&m_alloc_info);\n })\n{\n}\n\nVKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(\n VkDebugReportFlagsEXT flags,\n VkDebugReportObjectTypeEXT \/*objectType*\/,\n uint64_t \/*object*\/,\n size_t \/*Location*\/,\n int32_t messageCode,\n const char* pLayerPrefix,\n const char* pMessage,\n void* \/*pUserData*\/)\n{\n\t\/\/ Supressing unnecessary log messages.\n\n std::string msgType = \"\";\n #if defined(PLATFORM_WINDOWS)\n bool breakOn = false;\n #endif\n if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)\n {\n msgType = \"ERROR:\";\n #if defined(PLATFORM_WINDOWS)\n breakOn = true;\n #endif\n }\n else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)\n {\n msgType = \"WARNING:\";\n #if defined(PLATFORM_WINDOWS)\n breakOn = true;\n #endif\n }\n else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)\n {\n msgType = \"PERFORMANCE WARNING:\";\n }\n else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)\n {\n msgType = \"INFO:\";\n }\n else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)\n {\n msgType = \"DEBUG:\";\n }\n\tif (std::string(pLayerPrefix) == \"loader\" || std::string(pLayerPrefix) == \"DebugReport\")\n\t\treturn false;\n F_ILOG(\"Vulkan\/DebugCallback\", \"%s %s {%d}: %s\", msgType.c_str(), pLayerPrefix, messageCode, pMessage);\n#if defined(PLATFORM_WINDOWS)\n if (breakOn && IsDebuggerPresent())\n __debugbreak();\n#endif\n return false;\n}\n\nbool VulkanGraphicsInstance::createInstance(const char* appName, unsigned appVersion, const char* engineName, unsigned engineVersion)\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ getting debug layers\n \/\/ TODO: These need to be saved for device creation also. which layers and extensions each use.\n auto layersInfos = vk::enumerateInstanceLayerProperties();\n\n std::vector layers;\n {\n \/\/ lunargvalidation list order\n GFX_ILOG(\"Enabled Vulkan debug layers:\");\n for (auto&& it : layerOrder)\n {\n auto found = std::find_if(layersInfos.begin(), layersInfos.end(), [&](const vk::LayerProperties& layer)\n {\n return it == layer.layerName;\n });\n if (found != layersInfos.end())\n {\n layers.push_back(it.c_str());\n m_layers.push_back(*found);\n GFX_ILOG(\"%s\", found->layerName);\n }\n else\n {\n GFX_ILOG(\"not enabled %s\", it.c_str());\n }\n }\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Getting extensions\n std::vector extInfos = vk::enumerateInstanceExtensionProperties();\n\n std::vector extensions;\n {\n \/\/ lunargvalidation list order\n GFX_ILOG(\"Enabled Vulkan extensions:\");\n\n for (auto&& it : extOrder)\n {\n auto found = std::find_if(extInfos.begin(), extInfos.end(), [&](const vk::ExtensionProperties& layer)\n {\n return it == layer.extensionName;\n });\n if (found != extInfos.end())\n {\n extensions.push_back(it.c_str());\n m_extensions.push_back(*found);\n GFX_ILOG(\"%s\", found->extensionName);\n }\n else\n {\n GFX_ILOG(\"not enabled %s\", it.c_str());\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ app instance\n app_info = vk::ApplicationInfo()\n .setPApplicationName(appName)\n .setApplicationVersion(appVersion)\n .setPEngineName(engineName)\n .setEngineVersion(engineVersion)\n .setApiVersion(VK_API_VERSION_1_0);\n\n instance_info = vk::InstanceCreateInfo()\n .setPApplicationInfo(&app_info)\n .setEnabledLayerCount(static_cast(layers.size()))\n .setPpEnabledLayerNames(layers.data())\n .setEnabledExtensionCount(static_cast(extensions.size()))\n .setPpEnabledExtensionNames(extensions.data());\n\n vk::Result res = vk::createInstance(&instance_info, &m_alloc_info, m_instance.get());\n\n if (res != vk::Result::eSuccess)\n {\n \/\/ quite hot shit baby yeah!\n auto error = vk::to_string(res);\n GFX_ILOG(\"Instance creation error: %s\", error.c_str());\n return false;\n }\n m_devices = m_instance->enumeratePhysicalDevices();\n\n \/\/ get addresses for few functions\n PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;\n PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;\n\n dbgCreateDebugReportCallback =\n (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(\n *m_instance, \"vkCreateDebugReportCallbackEXT\");\n if (!dbgCreateDebugReportCallback) {\n GFX_ILOG(\"GetInstanceProcAddr: Unable to find vkCreateDebugReportCallbackEXT function.\");;\n return true;\n }\n\n dbgDestroyDebugReportCallback =\n (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(\n *m_instance, \"vkDestroyDebugReportCallbackEXT\");\n if (!dbgDestroyDebugReportCallback) {\n GFX_ILOG(\"GetInstanceProcAddr: Unable to find vkDestroyDebugReportCallbackEXT function.\");;\n return true;\n }\n \/\/ the debug things\n auto flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::eDebug;\n vk::DebugReportCallbackCreateInfoEXT info = vk::DebugReportCallbackCreateInfoEXT(flags, debugCallback, nullptr);\n\n auto lol = m_instance; \/\/ callback needs to keep instance alive until its destroyed... so this works :DD\n auto allocInfo = m_alloc_info;\n m_debugcallback = std::shared_ptr(new vk::DebugReportCallbackEXT, [lol, allocInfo, dbgDestroyDebugReportCallback](vk::DebugReportCallbackEXT* ist)\n {\n dbgDestroyDebugReportCallback(*lol, *ist, reinterpret_cast(&allocInfo));\n });\n dbgCreateDebugReportCallback(*m_instance, reinterpret_cast(&info), reinterpret_cast(&m_alloc_info), reinterpret_cast(m_debugcallback.get()));\n return true;\n}\n\nVulkanGpuDevice VulkanGraphicsInstance::createGpuDevice(FileSystem& fs)\n{\n\n auto canPresent = [](vk::PhysicalDevice dev)\n {\n auto queueProperties = dev.getQueueFamilyProperties();\n for (auto&& queueProp : queueProperties)\n {\n for (uint32_t i = 0; i < queueProp.queueCount; ++i)\n {\n#if defined(PLATFORM_WINDOWS)\n if (dev.getWin32PresentationSupportKHR(i))\n#endif\n {\n return true;\n }\n }\n }\n return false;\n };\n int devId = 0;\n for (devId = 0; devId < static_cast(m_devices.size()); ++devId)\n {\n if (canPresent(m_devices[devId]))\n break;\n }\n auto&& physDev = m_devices[devId]; \/\/ assuming first device is best\n \n \/\/ extensions\n std::vector devExts = physDev.enumerateDeviceExtensionProperties();\n\n std::vector extensions;\n {\n GFX_ILOG(\"Available extensions for device:\");\n for (auto&& it : devExts)\n {\n GFX_ILOG(\"%s\", it.extensionName);\n }\n \/\/ lunargvalidation list order\n GFX_ILOG(\"Enabled Vulkan extensions for device:\");\n\n for (auto&& it : devExtOrder)\n {\n auto found = std::find_if(devExts.begin(), devExts.end(), [&](const vk::ExtensionProperties& layer)\n {\n return it == layer.extensionName;\n });\n if (found != devExts.end())\n {\n extensions.push_back(it.c_str());\n m_extensions.push_back(*found);\n GFX_ILOG(\"%s\", found->extensionName);\n }\n }\n }\n \/\/ queue\n\n\n \/\/auto queueProperties = vk::getPhysicalDeviceQueueFamilyProperties(physDev);\n auto queueProperties = physDev.getQueueFamilyProperties();\n std::vector queueInfos;\n uint32_t i = 0;\n std::vector> priorities;\n for (auto&& queueProp : queueProperties)\n {\n priorities.push_back(std::vector());\n for (size_t k = 0; k < queueProp.queueCount; ++k)\n {\n priorities[i].push_back(1.f);\n }\n vk::DeviceQueueCreateInfo queueInfo = vk::DeviceQueueCreateInfo()\n .setQueueFamilyIndex(i)\n .setQueueCount(queueProp.queueCount)\n .setPQueuePriorities(priorities[i].data());\n \/\/ queue priorities go here.\n queueInfos.push_back(queueInfo);\n ++i;\n }\n\n auto features = physDev.getFeatures(); \/\/ ALL OF THEM FEATURES.\n\n auto heapInfos = physDev.getMemoryProperties();\n\n auto device_info = vk::DeviceCreateInfo()\n .setQueueCreateInfoCount(static_cast(queueInfos.size()))\n .setPQueueCreateInfos(queueInfos.data())\n .setEnabledExtensionCount(static_cast(extensions.size()))\n .setPpEnabledExtensionNames(extensions.data())\n .setPEnabledFeatures(&features);\n\n\n vk::Device dev = physDev.createDevice(device_info, m_alloc_info);\n\n std::shared_ptr device(new vk::Device(dev), [=](vk::Device* ist)\n {\n ist->destroy(&m_alloc_info);\n\tdelete ist;\n });\n\n return VulkanGpuDevice(device,physDev, fs, m_alloc_info, queueProperties, heapInfos, false);\n}\n\n#if defined(PLATFORM_WINDOWS)\nVulkanSurface VulkanGraphicsInstance::createSurface(HWND hWnd, HINSTANCE instance)\n{\n\tvk::Win32SurfaceCreateInfoKHR createInfo = vk::Win32SurfaceCreateInfoKHR()\n\t\t.setHwnd(hWnd)\n\t\t.setHinstance(instance);\n\n\tVulkanSurface surface;\n\n\tvk::SurfaceKHR surfacekhr = m_instance->createWin32SurfaceKHR(createInfo);\n\n\tauto inst = m_instance;\n\n\tstd::shared_ptr khrSur(new vk::SurfaceKHR(surfacekhr), [inst](vk::SurfaceKHR* ist)\n\t{\n\t\tinst->destroySurfaceKHR(*ist);\n\t\tdelete ist;\n\t});\n\n\tsurface.surface = khrSur;\n\n\treturn surface;\n}\n#else\nVulkanSurface VulkanGraphicsInstance::createSurface()\n{\n\treturn VulkanSurface();\n}\n#endifadded device information output, prettified#include \"VulkanGraphicsInstance.hpp\"\n\n#if defined(PLATFORM_WINDOWS)\n#include \n#endif\n\nVulkanGraphicsInstance::VulkanGraphicsInstance()\n : m_alloc_info(reinterpret_cast(&m_allocs), allocs::pfnAllocation, allocs::pfnReallocation, allocs::pfnFree, allocs::pfnInternalAllocation, allocs::pfnInternalFree)\n\n , m_instance(new vk::Instance, [=](vk::Instance* ist)\n {\n (*ist).destroy(&m_alloc_info);\n })\n{\n}\n\nVKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(\n VkDebugReportFlagsEXT flags,\n VkDebugReportObjectTypeEXT \/*objectType*\/,\n uint64_t \/*object*\/,\n size_t \/*Location*\/,\n int32_t messageCode,\n const char* pLayerPrefix,\n const char* pMessage,\n void* \/*pUserData*\/)\n{\n\t\/\/ Supressing unnecessary log messages.\n\n std::string msgType = \"\";\n #if defined(PLATFORM_WINDOWS)\n bool breakOn = false;\n #endif\n if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)\n {\n msgType = \"ERROR:\";\n #if defined(PLATFORM_WINDOWS)\n breakOn = true;\n #endif\n }\n else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)\n {\n msgType = \"WARNING:\";\n #if defined(PLATFORM_WINDOWS)\n breakOn = true;\n #endif\n }\n else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)\n {\n msgType = \"PERFORMANCE WARNING:\";\n }\n else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)\n {\n msgType = \"INFO:\";\n }\n else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)\n {\n msgType = \"DEBUG:\";\n }\n\tif (std::string(pLayerPrefix) == \"loader\" || std::string(pLayerPrefix) == \"DebugReport\")\n\t\treturn false;\n F_ILOG(\"Vulkan\/DebugCallback\", \"%s %s {%d}: %s\", msgType.c_str(), pLayerPrefix, messageCode, pMessage);\n#if defined(PLATFORM_WINDOWS)\n if (breakOn && IsDebuggerPresent())\n __debugbreak();\n#endif\n return false;\n}\n\nbool VulkanGraphicsInstance::createInstance(const char* appName, unsigned appVersion, const char* engineName, unsigned engineVersion)\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ getting debug layers\n \/\/ TODO: These need to be saved for device creation also. which layers and extensions each use.\n auto layersInfos = vk::enumerateInstanceLayerProperties();\n\n std::vector layers;\n {\n \/\/ lunargvalidation list order\n GFX_ILOG(\"Enabled Vulkan debug layers:\");\n for (auto&& it : layerOrder)\n {\n auto found = std::find_if(layersInfos.begin(), layersInfos.end(), [&](const vk::LayerProperties& layer)\n {\n return it == layer.layerName;\n });\n if (found != layersInfos.end())\n {\n layers.push_back(it.c_str());\n m_layers.push_back(*found);\n GFX_ILOG(\"\\t\\t%s\", found->layerName);\n }\n else\n {\n GFX_ILOG(\"not enabled %s\", it.c_str());\n }\n }\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Getting extensions\n std::vector extInfos = vk::enumerateInstanceExtensionProperties();\n\n std::vector extensions;\n {\n \/\/ lunargvalidation list order\n GFX_ILOG(\"Enabled Vulkan extensions:\");\n\n for (auto&& it : extOrder)\n {\n auto found = std::find_if(extInfos.begin(), extInfos.end(), [&](const vk::ExtensionProperties& layer)\n {\n return it == layer.extensionName;\n });\n if (found != extInfos.end())\n {\n extensions.push_back(it.c_str());\n m_extensions.push_back(*found);\n GFX_ILOG(\"\\t\\t%s\", found->extensionName);\n }\n else\n {\n GFX_ILOG(\"not enabled %s\", it.c_str());\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ app instance\n app_info = vk::ApplicationInfo()\n .setPApplicationName(appName)\n .setApplicationVersion(appVersion)\n .setPEngineName(engineName)\n .setEngineVersion(engineVersion)\n .setApiVersion(VK_API_VERSION_1_0);\n\n instance_info = vk::InstanceCreateInfo()\n .setPApplicationInfo(&app_info)\n .setEnabledLayerCount(static_cast(layers.size()))\n .setPpEnabledLayerNames(layers.data())\n .setEnabledExtensionCount(static_cast(extensions.size()))\n .setPpEnabledExtensionNames(extensions.data());\n\n vk::Result res = vk::createInstance(&instance_info, &m_alloc_info, m_instance.get());\n\n if (res != vk::Result::eSuccess)\n {\n \/\/ quite hot shit baby yeah!\n auto error = vk::to_string(res);\n GFX_ILOG(\"Instance creation error: %s\", error.c_str());\n return false;\n }\n m_devices = m_instance->enumeratePhysicalDevices();\n\n \/\/ get addresses for few functions\n PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;\n PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;\n\n dbgCreateDebugReportCallback =\n (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(\n *m_instance, \"vkCreateDebugReportCallbackEXT\");\n if (!dbgCreateDebugReportCallback) {\n GFX_ILOG(\"GetInstanceProcAddr: Unable to find vkCreateDebugReportCallbackEXT function.\");;\n return true;\n }\n\n dbgDestroyDebugReportCallback =\n (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(\n *m_instance, \"vkDestroyDebugReportCallbackEXT\");\n if (!dbgDestroyDebugReportCallback) {\n GFX_ILOG(\"GetInstanceProcAddr: Unable to find vkDestroyDebugReportCallbackEXT function.\");;\n return true;\n }\n \/\/ the debug things\n auto flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::eDebug;\n vk::DebugReportCallbackCreateInfoEXT info = vk::DebugReportCallbackCreateInfoEXT(flags, debugCallback, nullptr);\n\n auto lol = m_instance; \/\/ callback needs to keep instance alive until its destroyed... so this works :DD\n auto allocInfo = m_alloc_info;\n m_debugcallback = std::shared_ptr(new vk::DebugReportCallbackEXT, [lol, allocInfo, dbgDestroyDebugReportCallback](vk::DebugReportCallbackEXT* ist)\n {\n dbgDestroyDebugReportCallback(*lol, *ist, reinterpret_cast(&allocInfo));\n });\n dbgCreateDebugReportCallback(*m_instance, reinterpret_cast(&info), reinterpret_cast(&m_alloc_info), reinterpret_cast(m_debugcallback.get()));\n return true;\n}\n\nVulkanGpuDevice VulkanGraphicsInstance::createGpuDevice(FileSystem& fs)\n{\n\n auto canPresent = [](vk::PhysicalDevice dev)\n {\n auto queueProperties = dev.getQueueFamilyProperties();\n for (auto&& queueProp : queueProperties)\n {\n for (uint32_t i = 0; i < queueProp.queueCount; ++i)\n {\n#if defined(PLATFORM_WINDOWS)\n if (dev.getWin32PresentationSupportKHR(i))\n#endif\n {\n return true;\n }\n }\n }\n return false;\n };\n int devId = 0;\n for (devId = 0; devId < static_cast(m_devices.size()); ++devId)\n {\n if (canPresent(m_devices[devId]))\n break;\n }\n auto&& physDev = m_devices[devId]; \/\/ assuming first device is best\n\n \/\/ some info\n auto stuff = physDev.getProperties();\n GFX_ILOG(\"Creating gpu device:\");\n GFX_ILOG(\"\\t\\tID: %u\", stuff.deviceID);\n GFX_ILOG(\"\\t\\tVendor: %u\", stuff.vendorID);\n GFX_ILOG(\"\\t\\tDevice: %s\", stuff.deviceName);\n GFX_ILOG(\"\\t\\tApi: %u\", stuff.apiVersion);\n GFX_ILOG(\"\\t\\tDriver: %u\", stuff.driverVersion);\n GFX_ILOG(\"\\t\\tType: %s\", vk::to_string(stuff.deviceType).c_str());\n \n \/\/ extensions\n std::vector devExts = physDev.enumerateDeviceExtensionProperties();\n\n std::vector extensions;\n {\n GFX_ILOG(\"Available extensions for device:\");\n for (auto&& it : devExts)\n {\n GFX_ILOG(\"\\t\\t%s\", it.extensionName);\n }\n \/\/ lunargvalidation list order\n GFX_ILOG(\"Enabled Vulkan extensions for device:\");\n\n for (auto&& it : devExtOrder)\n {\n auto found = std::find_if(devExts.begin(), devExts.end(), [&](const vk::ExtensionProperties& layer)\n {\n return it == layer.extensionName;\n });\n if (found != devExts.end())\n {\n extensions.push_back(it.c_str());\n m_extensions.push_back(*found);\n GFX_ILOG(\"\\t\\t%s\", found->extensionName);\n }\n }\n }\n\n \/\/ queue\n auto queueProperties = physDev.getQueueFamilyProperties();\n std::vector queueInfos;\n uint32_t i = 0;\n std::vector> priorities;\n for (auto&& queueProp : queueProperties)\n {\n priorities.push_back(std::vector());\n for (size_t k = 0; k < queueProp.queueCount; ++k)\n {\n priorities[i].push_back(1.f);\n }\n vk::DeviceQueueCreateInfo queueInfo = vk::DeviceQueueCreateInfo()\n .setQueueFamilyIndex(i)\n .setQueueCount(queueProp.queueCount)\n .setPQueuePriorities(priorities[i].data());\n \/\/ queue priorities go here.\n queueInfos.push_back(queueInfo);\n ++i;\n }\n\n auto features = physDev.getFeatures(); \/\/ ALL OF THEM FEATURES.\n\n auto heapInfos = physDev.getMemoryProperties();\n\n auto device_info = vk::DeviceCreateInfo()\n .setQueueCreateInfoCount(static_cast(queueInfos.size()))\n .setPQueueCreateInfos(queueInfos.data())\n .setEnabledExtensionCount(static_cast(extensions.size()))\n .setPpEnabledExtensionNames(extensions.data())\n .setPEnabledFeatures(&features);\n\n vk::Device dev = physDev.createDevice(device_info, m_alloc_info);\n\n std::shared_ptr device(new vk::Device(dev), [=](vk::Device* ist)\n {\n ist->destroy(&m_alloc_info);\n\tdelete ist;\n });\n\n return VulkanGpuDevice(device,physDev, fs, m_alloc_info, queueProperties, heapInfos, false);\n}\n\n#if defined(PLATFORM_WINDOWS)\nVulkanSurface VulkanGraphicsInstance::createSurface(HWND hWnd, HINSTANCE instance)\n{\n\tvk::Win32SurfaceCreateInfoKHR createInfo = vk::Win32SurfaceCreateInfoKHR()\n\t\t.setHwnd(hWnd)\n\t\t.setHinstance(instance);\n\n\tVulkanSurface surface;\n\n\tvk::SurfaceKHR surfacekhr = m_instance->createWin32SurfaceKHR(createInfo);\n\n\tauto inst = m_instance;\n\n\tstd::shared_ptr khrSur(new vk::SurfaceKHR(surfacekhr), [inst](vk::SurfaceKHR* ist)\n\t{\n\t\tinst->destroySurfaceKHR(*ist);\n\t\tdelete ist;\n\t});\n\n\tsurface.surface = khrSur;\n\n\treturn surface;\n}\n#else\nVulkanSurface VulkanGraphicsInstance::createSurface()\n{\n\treturn VulkanSurface();\n}\n#endif<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AKeys.cxx,v $\n *\n * $Revision: 1.18 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 02:14:39 $\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_connectivity.hxx\"\n\n#ifndef _CONNECTIVITY_ADO_KEYS_HXX_\n#include \"ado\/AKeys.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_INDEX_HXX_\n#include \"ado\/AKey.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include \n#endif\n#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_\n#include \"ado\/Awrapado.hxx\"\n#endif\n#ifndef _COMPHELPER_PROPERTY_HXX_\n#include \n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include \n#endif\n\nusing namespace ::comphelper;\nusing namespace connectivity;\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::sdbcx;\nusing namespace com::sun::star::container;\n\nsdbcx::ObjectType OKeys::createObject(const ::rtl::OUString& _rName)\n{\n return new OAdoKey(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));\n}\n\/\/ -------------------------------------------------------------------------\nvoid OKeys::impl_refresh() throw(RuntimeException)\n{\n m_aCollection.Refresh();\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > OKeys::createDescriptor()\n{\n return new OAdoKey(isCaseSensitive(),m_pConnection);\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XAppend\nsdbcx::ObjectType OKeys::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )\n{\n OAdoKey* pKey = NULL;\n if ( !getImplementation( pKey, descriptor ) || pKey == NULL)\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not create key: invalid object descriptor.\" ),\n static_cast(this)\n );\n\n \/\/ To pass as column parameter to Key's Apppend method\n OLEVariant vOptional;\n vOptional.setNoArg();\n\n#if OSL_DEBUG_LEVEL > 0\n KeyTypeEnum eKey =\n#endif\n OAdoKey::Map2KeyRule(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))));\n#if OSL_DEBUG_LEVEL > 0\n (void)eKey;\n#endif\n\n WpADOKey aKey = pKey->getImpl();\n ::rtl::OUString sName = aKey.get_Name();\n if(!sName.getLength())\n aKey.put_Name(::rtl::OUString::createFromAscii(\"PrimaryKey\") );\n\n ADOKeys* pKeys = m_aCollection;\n if ( FAILED(pKeys->Append(OLEVariant((ADOKey*)aKey),\n adKeyPrimary, \/\/ must be every time adKeyPrimary\n vOptional)) )\n {\n ADOS::ThrowException(*m_pConnection->getConnection(),static_cast(this));\n \/\/ just make sure that an SQLExceptionis thrown here\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not append key.\" ),\n static_cast(this)\n );\n }\n\n return new OAdoKey(isCaseSensitive(),m_pConnection,pKey->getImpl());\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XDrop\nvoid OKeys::dropObject(sal_Int32 \/*_nPos*\/,const ::rtl::OUString _sElementName)\n{\n if(!m_aCollection.Delete(OLEVariant(_sElementName)))\n ADOS::ThrowException(*m_pConnection->getConnection(),static_cast(this));\n}\n\/\/ -----------------------------------------------------------------------------\n\n\nINTEGRATION: CWS sb59 (1.17.28); FILE MERGED 2006\/08\/08 08:28:53 sb 1.17.28.1: #i67487# Made code warning-free (wntmsci10).\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AKeys.cxx,v $\n *\n * $Revision: 1.19 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 11:30:13 $\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_connectivity.hxx\"\n\n#ifndef _CONNECTIVITY_ADO_KEYS_HXX_\n#include \"ado\/AKeys.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_INDEX_HXX_\n#include \"ado\/AKey.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include \n#endif\n#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_\n#include \"ado\/Awrapado.hxx\"\n#endif\n#ifndef _COMPHELPER_PROPERTY_HXX_\n#include \n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include \n#endif\n\nusing namespace ::comphelper;\nusing namespace connectivity;\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::sdbcx;\nusing namespace com::sun::star::container;\n\nsdbcx::ObjectType OKeys::createObject(const ::rtl::OUString& _rName)\n{\n return new OAdoKey(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));\n}\n\/\/ -------------------------------------------------------------------------\nvoid OKeys::impl_refresh() throw(RuntimeException)\n{\n m_aCollection.Refresh();\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > OKeys::createDescriptor()\n{\n return new OAdoKey(isCaseSensitive(),m_pConnection);\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XAppend\nsdbcx::ObjectType OKeys::appendObject( const ::rtl::OUString&, const Reference< XPropertySet >& descriptor )\n{\n OAdoKey* pKey = NULL;\n if ( !getImplementation( pKey, descriptor ) || pKey == NULL)\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not create key: invalid object descriptor.\" ),\n static_cast(this)\n );\n\n \/\/ To pass as column parameter to Key's Apppend method\n OLEVariant vOptional;\n vOptional.setNoArg();\n\n#if OSL_DEBUG_LEVEL > 0\n KeyTypeEnum eKey =\n#endif\n OAdoKey::Map2KeyRule(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))));\n#if OSL_DEBUG_LEVEL > 0\n (void)eKey;\n#endif\n\n WpADOKey aKey = pKey->getImpl();\n ::rtl::OUString sName = aKey.get_Name();\n if(!sName.getLength())\n aKey.put_Name(::rtl::OUString::createFromAscii(\"PrimaryKey\") );\n\n ADOKeys* pKeys = m_aCollection;\n if ( FAILED(pKeys->Append(OLEVariant((ADOKey*)aKey),\n adKeyPrimary, \/\/ must be every time adKeyPrimary\n vOptional)) )\n {\n ADOS::ThrowException(*m_pConnection->getConnection(),static_cast(this));\n \/\/ just make sure that an SQLExceptionis thrown here\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not append key.\" ),\n static_cast(this)\n );\n }\n\n return new OAdoKey(isCaseSensitive(),m_pConnection,pKey->getImpl());\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XDrop\nvoid OKeys::dropObject(sal_Int32 \/*_nPos*\/,const ::rtl::OUString _sElementName)\n{\n if(!m_aCollection.Delete(OLEVariant(_sElementName)))\n ADOS::ThrowException(*m_pConnection->getConnection(),static_cast(this));\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"flow.h\"\n#include \"ofpbuf.h\"\n#include \"pcap-file.h\"\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {\n int retval;\n FILE *pcap;\n struct flow flow;\n struct ofpbuf *packet;\n uint8_t t[size+24];\n (unsigned int *)t[0] = 0xa1b2c3d4; \/* magic *\/\n (unsigned int *)t[1] = 0x00040002; \/* version *\/\n (unsigned int *)t[2] = 0; \/* thiszone *\/\n (unsigned int *)t[3] = 0; \/* sigfigs *\/\n (unsigned int *)t[4] = 65535; \/* snaplen *\/\n (unsigned int *)t[5] = 1; \/* eth *\/\n for (size_t i = 0 ; i < size; i++) {\n t[24+i] = data[i];\n }\n fwrite(t, 1, sizeof(t), \"test.pcap\");\n pcap = fopen(\"test.pcap\", \"rb\");\n if (!pcap) {\n ovs_fatal(errno, \"failed to open %s for reading\", \"test.pcap\");\n }\n\n retval = ovs_pcap_read_header(pcap);\n if (retval) {\n ovs_fatal(retval > 0 ? retval : 0, \"reading pcap header failed\");\n }\n\n retval = ovs_pcap_read(pcap, &packet, NULL);\n if (retval == EOF) {\n ovs_fatal(0, \"unexpected end of file reading pcap file\");\n } else if (retval) {\n ovs_fatal(retval, \"error reading pcap file\");\n }\n\n flow_extract(packet, NULL, &flow);\n unlink(\"test.pcap\"); \n return 0;\n}\nFixing clang errors#include \n#include \n#include \n#include \"flow.h\"\n#include \"ofpbuf.h\"\n#include \"pcap-file.h\"\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {\n int retval;\n FILE *pcap;\n struct flow flow;\n struct ofpbuf *packet;\n uint8_t t[size+24];\n (unsigned int *)t[0] = 0xa1b2c3d4; \/* magic *\/\n (unsigned int *)t[1] = 0x00040002; \/* version *\/\n (unsigned int *)t[2] = 0; \/* thiszone *\/\n (unsigned int *)t[3] = 0; \/* sigfigs *\/\n (unsigned int *)t[4] = 65535; \/* snaplen *\/\n (unsigned int *)t[5] = 1; \/* eth *\/\n for (size_t i = 0 ; i < size; i++) {\n t[24+i] = data[i];\n }\n pcap = fopen (\"test.pcap\", \"wb\");\n fwrite(t, 1, sizeof(t), pcap);\n fclose(pcap);\n pcap = fopen(\"test.pcap\", \"rb\");\n if (!pcap) {\n ovs_fatal(errno, \"failed to open %s for reading\", \"test.pcap\");\n }\n\n retval = ovs_pcap_read_header(pcap);\n if (retval) {\n ovs_fatal(retval > 0 ? retval : 0, \"reading pcap header failed\");\n }\n\n retval = ovs_pcap_read(pcap, &packet, NULL);\n if (retval == EOF) {\n ovs_fatal(0, \"unexpected end of file reading pcap file\");\n } else if (retval) {\n ovs_fatal(retval, \"error reading pcap file\");\n }\n\n flow_extract(packet, NULL, &flow);\n unlink(\"test.pcap\"); \n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#ifdef _DEBUG\n#pragma comment(lib, \"freeglut_staticd.lib\")\n#pragma comment(lib, \"glew32sd.lib\")\n#else \/\/ Release\n\/\/ FIXME: Static 'Release' version of the GLEW lib breaks the build\n\/\/ consider using dynamic linking for release\n#pragma comment(lib, \"freeglut_static.lib\")\n#pragma comment(lib, \"glew32sd.lib\")\n#endif\n\nnamespace uth\n{\n static int shaderTypes[SHADERTYPE_LAST] = {GL_VERTEX_SHADER,\n GL_FRAGMENT_SHADER};\n static int dataTypes[DATATYPE_LAST] = {GL_BYTE,\n GL_UNSIGNED_BYTE,\n GL_SHORT,\n GL_UNSIGNED_SHORT,\n GL_INT,\n GL_UNSIGNED_INT,\n GL_FLOAT,\n GL_DOUBLE};\n static int bufferTypes[BUFFERTYPE_LAST] = {GL_ARRAY_BUFFER,\n GL_READ_BUFFER,\n GL_COPY_WRITE_BUFFER,\n GL_ELEMENT_ARRAY_BUFFER,\n GL_PIXEL_PACK_BUFFER,\n GL_PIXEL_UNPACK_BUFFER,\n GL_TEXTURE_BUFFER,\n GL_TRANSFORM_FEEDBACK_BUFFER,\n GL_UNIFORM_BUFFER};\n static int usageTypes[USAGETYPE_LAST] = {GL_STREAM_DRAW,\n GL_STREAM_READ,\n GL_STREAM_COPY,\n GL_STATIC_DRAW,\n GL_STATIC_READ,\n GL_STATIC_COPY,\n GL_DYNAMIC_DRAW,\n GL_DYNAMIC_READ,\n GL_DYNAMIC_COPY};\n static int pixelStoreParams[PIXELSTOREPARAM_LAST] = {GL_PACK_SWAP_BYTES,\n GL_PACK_LSB_FIRST, \n GL_PACK_ROW_LENGTH, \n GL_PACK_IMAGE_HEIGHT, \n GL_PACK_SKIP_PIXELS, \n GL_PACK_SKIP_ROWS, \n GL_PACK_SKIP_IMAGES, \n GL_PACK_ALIGNMENT,\n GL_UNPACK_SWAP_BYTES, \n GL_UNPACK_LSB_FIRST, \n GL_UNPACK_ROW_LENGTH, \n GL_UNPACK_IMAGE_HEIGHT, \n GL_UNPACK_SKIP_PIXELS, \n GL_UNPACK_SKIP_ROWS, \n GL_UNPACK_SKIP_IMAGES, \n GL_UNPACK_ALIGNMENT};\n static int textureTypes[TEXTURETYPE_LAST] = {TEXTURE_1D, \n TEXTURE_2D, \n TEXTURE_3D, \n TEXTURE_1D_ARRAY, \n TEXTURE_2D_ARRAY, \n TEXTURE_RECTANGLE, \n TEXTURE_CUBE_MAP,\n TEXTURE_2D_MULTISAMPLE,\n TEXTURE_2D_MULTISAMPLE_ARRAY};\n static int imageFormats[IMAGEFORMAT_LAST] = {GL_RGB,\n GL_RGBA};\n static int textureParams[TEXTUREPARAM_LAST] = {GL_TEXTURE_BASE_LEVEL, \n GL_TEXTURE_COMPARE_FUNC, \n GL_TEXTURE_COMPARE_MODE, \n GL_TEXTURE_LOD_BIAS, \n GL_TEXTURE_MIN_FILTER, \n GL_TEXTURE_MAG_FILTER, \n GL_TEXTURE_MIN_LOD, \n GL_TEXTURE_MAX_LOD, \n GL_TEXTURE_MAX_LEVEL, \n GL_TEXTURE_SWIZZLE_R, \n GL_TEXTURE_SWIZZLE_G, \n GL_TEXTURE_SWIZZLE_B, \n GL_TEXTURE_SWIZZLE_A, \n GL_TEXTURE_WRAP_S, \n GL_TEXTURE_WRAP_T,\n GL_TEXTURE_WRAP_R};\n static int primitiveTypes[PRIMITIVETYPE_LAST] = {GL_POINTS, \n GL_LINE_STRIP, \n GL_LINE_LOOP, \n GL_LINES, \n GL_LINE_STRIP_ADJACENCY, \n GL_LINES_ADJACENCY, \n GL_TRIANGLE_STRIP, \n GL_TRIANGLE_FAN, \n GL_TRIANGLES, \n GL_TRIANGLE_STRIP_ADJACENCY,\n GL_TRIANGLES_ADJACENCY};\n static int depthFunctions[DEPTHFUNCTION_LAST] = {GL_NEVER, \n GL_LESS, \n GL_EQUAL, \n GL_LEQUAL,\n GL_GREATER, \n GL_NOTEQUAL, \n GL_GEQUAL, \n GL_ALWAYS};\n static int blendFunctions[BLENDFUNCTION_LAST] = {GL_ZERO, \n GL_ONE, \n GL_SRC_COLOR, \n GL_ONE_MINUS_SRC_COLOR, \n GL_DST_COLOR, \n GL_ONE_MINUS_DST_COLOR, \n GL_SRC_ALPHA, \n GL_ONE_MINUS_SRC_ALPHA, \n GL_DST_ALPHA, \n GL_ONE_MINUS_DST_ALPHA, \n GL_CONSTANT_COLOR, \n GL_ONE_MINUS_CONSTANT_COLOR, \n GL_CONSTANT_ALPHA, \n GL_ONE_MINUS_CONSTANT_ALPHA};\n static int faceCullings[FACECULLING_LAST] = {GL_FRONT, \n GL_BACK, \n GL_FRONT_AND_BACK};\n\n \n\n \/\/ Window functions\n bool Graphics::createWindow(const WindowSettings& settings)\n {\n if (m_windowHandle) destroyWindow();\n \n m_windowSettings = settings;\n\n \/\/ Context settings\n glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);\n glutInitContextProfile(GLUT_CORE_PROFILE);\n\n \/\/ Extra settings\n glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);\n\n \/\/ Position & size\n glutInitWindowPosition(settings.position.x, settings.position.y);\n glutInitWindowSize(settings.size.x, settings.size.y);\n\n \/\/ Display settings\n glutInitDisplayMode(settings.useBlending ? GLUT_RGBA : GLUT_RGB |\n settings.useDepthBuffer ? GLUT_DEPTH : 0x0 |\n settings.useStencilBuffer ? GLUT_STENCIL : 0x0 |\n settings.useDoubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE);\n\n\n int majorVer = settings.contextVersionMajor,\n minorVer = settings.contextVersionMinor;\n \n glutInitContextVersion(settings.contextVersionMajor, settings.contextVersionMinor);\n m_windowHandle = glutCreateWindow(\"Generic Window Title\");\n\n\t\tstd::cout << \"glew init might produces GL_INVALID_ENUM error. Just ignore it\" << std::endl;\n\t\tglewExperimental = GL_TRUE;\n oglCheck(glewInit());\n\n return true;\n }\n\n\n void Graphics::destroyWindow()\n {\n oglCheck(glutDestroyWindow(m_windowHandle));\n }\n\n\n void Graphics::clear(const float r, const float g, const float b, const float a)\n {\n oglCheck(glClear(GL_COLOR_BUFFER_BIT |\n GL_DEPTH_BUFFER_BIT |\n GL_STENCIL_BUFFER_BIT));\n\t\toglCheck(glClearColor(r, g, b, a));\n\n if (!m_windowSettings.useDepthBuffer) return;\n\n\t\t#ifdef UTH_SYSTEM_OPENGLES\n\t\t\toglCheck(glClearDepthf(1)); \n\t\t#else\n\t\t\toglCheck(glClearDepth(1)); \n\t\t#endif\n\n if (!m_windowSettings.useStencilBuffer) return;\n\n oglCheck(glClearStencil(1));\n }\n\n void Graphics::swapBuffers()\n {\n oglCheck(glutSwapBuffers());\n }\n\n void setViewport(const int x, const int y, const size_t width, const size_t height)\n {\n oglCheck(glViewport(x, y, width, height));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Shaders\n\n int Graphics::createShaderProgram()\n {\n return glCreateProgram();\n }\n\n bool Graphics::createShader(const ShaderType type, const int shaderProgram, const char* shaderCode)\n {\n if (!shaderCode) return false;\n\n unsigned int shader = glCreateShader(shaderTypes[type]);\n oglCheck(glShaderSource(shader, 1, &shaderCode, NULL));\n oglCheck(glCompileShader(shader));\n\n\t\tint infoLenght;\n\t\toglCheck(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLenght));\n\t\tif(infoLenght > 1)\n\t\t{\n\t\t\tchar* buf = new char[infoLenght];\n\t\t\toglCheck(glGetShaderInfoLog(shader, infoLenght, NULL, buf));\n\t\t\tstd::cout << buf << std::endl;\n\t\t\tdelete buf;\n\t\t}\n\n int success;\n\t\toglCheck(glGetShaderiv(shader, GL_COMPILE_STATUS, &success));\n\n\t\tif (!success)\n\t\t{\n glDeleteShader(shader);\n\n return false;\n }\n\n oglCheck(glAttachShader(shaderProgram, shader));\n oglCheck(glDeleteShader(shader));\n\n return true;\n }\n\n bool Graphics::linkShaderProgram(const int shaderProgram)\n {\n oglCheck(glLinkProgram(shaderProgram));\n\n int success;\n\t\toglCheck(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success));\n\n\t\tif (!success)\n\t\t{\n destroyShaderProgram(shaderProgram);\n\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n }\n\n void Graphics::bindProgram(const int shaderProgram)\n {\n if (shaderProgram)\n oglCheck(glUseProgram(shaderProgram));\n }\n\n void unbindProgram()\n {\n oglCheck(glUseProgram(0));\n }\n\n void Graphics::destroyShaderProgram(const int shaderProgram)\n {\n oglCheck(glDeleteProgram(shaderProgram));\n }\n\n int Graphics::getUniformLocation(const int shaderProgram, const char* name)\n {\n\t\treturn glGetUniformLocation(shaderProgram, name);\n }\n\n int Graphics::getAttributeLocation(const int shaderProgram, const char* name)\n {\n return glGetAttribLocation(shaderProgram, name);\n }\n\n void Graphics::setUniform(const int location, const float x)\n {\n oglCheck(glUniform1f(location, x));\n }\n\n void Graphics::setUniform(const int location, const float x, const float y)\n {\n oglCheck(glUniform2f(location, x, y));\n }\n\n void Graphics::setUniform(const int location, const float x, const float y, const float z)\n {\n oglCheck(glUniform3f(location, x, y, z));\n }\n\n void Graphics::setUniform(const int location, const float x, const float y, const float z, const float w)\n {\n oglCheck(glUniform4f(location, x, y, z, w));\n }\n\n void Graphics::setUniform(const int location, const umath::vector2& vector)\n {\n oglCheck(glUniform2fv(location, 1, &vector.x));\n }\n\n void Graphics::setUniform(const int location, const umath::vector3& vector)\n {\n oglCheck(glUniform3fv(location, 1, &vector.x));\n }\n\n void Graphics::setUniform(const int location, const umath::vector4& vector)\n {\n oglCheck(glUniform4fv(location, 1, &vector.x));\n }\n\n void Graphics::setUniform(const int location, const umath::matrix3& matrix)\n {\n oglCheck(glUniformMatrix3fv(location, 1, GL_FALSE, &matrix[0][0]));\n }\n\n void Graphics::setUniform(const int location, const umath::matrix4& matrix)\n {\n oglCheck(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]));\n }\n\n void Graphics::enableVertexAttribArray(const int location)\n {\n oglCheck(glEnableVertexAttribArray(location));\n }\n\n void Graphics::disableVertexAttribArray(const int location)\n {\n oglCheck(glDisableVertexAttribArray(location));\n }\n\n void Graphics::setVertexAttribPointer(const int location, const int size, DataType type, const int stride, const void* pointer)\n {\n oglCheck(glVertexAttribPointer(location, size, dataTypes[type], GL_FALSE, stride, pointer));\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Buffers\n\n void generateBuffers(const unsigned int amount, unsigned int* buffers)\n {\n oglCheck(glGenBuffers(amount, buffers));\n }\n\n void deleteBuffers(const unsigned int amount, unsigned int* buffers)\n {\n oglCheck(glDeleteBuffers(amount, buffers));\n }\n\n void bindBuffer(BufferType type, const unsigned int buffer)\n {\n oglCheck(glBindBuffer(bufferTypes[type], buffer));\n }\n\n void setBufferData(BufferType type, const unsigned int size, const void* data, UsageType usageType)\n {\n oglCheck(glBufferData(bufferTypes[type], size, data, usageTypes[usageType]));\n }\n\n void setBufferSubData(BufferType type, const unsigned int offset, const unsigned int size, const void* data)\n {\n oglCheck(glBufferSubData(bufferTypes[type], offset, size, data));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Texture functions\n \n void setPixelStore(PixelStoreParam param, const int value)\n {\n oglCheck(glPixelStorei(pixelStoreParams[param], value));\n }\n\n void generateTextures(const unsigned int amount, unsigned int* data)\n {\n oglCheck(glGenTextures(amount, data));\n }\n\n void setActiveTexUnit(TexUnit unit)\n {\n oglCheck(glActiveTexture(unit));\n }\n\n void bindTexture(TextureType type, const int texture)\n {\n oglCheck(glBindTexture(textureTypes[type], texture));\n }\n\n void setTextureImage1D(const int level, ImageFormat imageFormat, const size_t width, ImageFormat pixelFormat, DataType dataType, const void* pixels)\n {\n oglCheck(glTexImage1D(textureTypes[TEXTURE_1D], level, imageFormats[imageFormat], width, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));\n }\n\n void setTextureImage2D(TextureType type, const int level, ImageFormat imageFormat, const size_t width, const size_t height, ImageFormat pixelFormat, DataType dataType, const void* pixels)\n {\n oglCheck(glTexImage2D(textureTypes[TEXTURE_2D], level, imageFormats[imageFormat], width, height, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));\n }\n\n void setTextureParameter(TextureType type, TextureParam param, const int value)\n {\n oglCheck(glTexParameteri(textureTypes[type], textureParams[param], value));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Drawing functions\n void drawArrays(PrimitiveType type, const int first, const size_t count)\n {\n oglCheck(glDrawArrays(primitiveTypes[type], first, count));\n }\n\n void drawElements(PrimitiveType type, const size_t count, DataType dataType, const void* indices)\n {\n oglCheck(glDrawElements(primitiveTypes[type], count, dataTypes[dataType], indices));\n }\n\n void setPointSize(const float size)\n {\n oglCheck(glPointSize(size));\n }\n\n void setLineWidth(const float width)\n {\n oglCheck(glLineWidth(width));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Other\n void flush()\n {\n oglCheck(glFlush());\n }\n\n void setDepthFunction(const bool enable, DepthFunction func)\n {\n static bool enabled = false;\n\n if (enable != enabled)\n {\n if (enable)\n oglCheck(glEnable(GL_DEPTH_TEST));\n else\n oglCheck(glDisable(GL_DEPTH_TEST));\n\n enabled = !enabled;\n }\n\n oglCheck(glDepthFunc(depthFunctions[func]));\n }\n\n void setBlendFunction(const bool enable, BlendFunction sfunc, BlendFunction dfunc)\n {\n static bool enabled = false;\n\n if (enable != enabled)\n {\n if (enable)\n oglCheck(glEnable(GL_BLEND));\n else\n oglCheck(glDisable(GL_BLEND));\n\n enabled = !enabled;\n }\n\n oglCheck(glBlendFunc(blendFunctions[sfunc], blendFunctions[dfunc]));\n }\n\n void setFaceCulling(const bool enable, FaceCulling mode)\n {\n static bool enabled = false;\n\n if (enable != enabled)\n {\n if (enable)\n oglCheck(glEnable(GL_CULL_FACE));\n else\n oglCheck(glDisable(GL_CULL_FACE));\n\n enabled = !enabled;\n }\n\n oglCheck(glCullFace(faceCullings[mode]));\n }\n\n\n\n \/\/ Private\n\n Graphics::Graphics()\n : m_windowHandle(0),\n m_windowSettings()\n {\n char* myargv[1];\n int myargc = 1;\n myargv[0] = strdup(\"UtH Engine\");\n glutInit(&myargc, myargv);\n }\n\n Graphics::~Graphics()\n {\n destroyWindow();\n }\n}Made graphics.cpp functions actually be part of the graphics class.#include \n#include \n#include \n#include \n#include \n\n#ifdef _DEBUG\n#pragma comment(lib, \"freeglut_staticd.lib\")\n#pragma comment(lib, \"glew32sd.lib\")\n#else \/\/ Release\n\/\/ FIXME: Static 'Release' version of the GLEW lib breaks the build\n\/\/ consider using dynamic linking for release\n#pragma comment(lib, \"freeglut_static.lib\")\n#pragma comment(lib, \"glew32sd.lib\")\n#endif\n\nnamespace uth\n{\n static int shaderTypes[SHADERTYPE_LAST] = {GL_VERTEX_SHADER,\n GL_FRAGMENT_SHADER};\n static int dataTypes[DATATYPE_LAST] = {GL_BYTE,\n GL_UNSIGNED_BYTE,\n GL_SHORT,\n GL_UNSIGNED_SHORT,\n GL_INT,\n GL_UNSIGNED_INT,\n GL_FLOAT,\n GL_DOUBLE};\n static int bufferTypes[BUFFERTYPE_LAST] = {GL_ARRAY_BUFFER,\n GL_READ_BUFFER,\n GL_COPY_WRITE_BUFFER,\n GL_ELEMENT_ARRAY_BUFFER,\n GL_PIXEL_PACK_BUFFER,\n GL_PIXEL_UNPACK_BUFFER,\n GL_TEXTURE_BUFFER,\n GL_TRANSFORM_FEEDBACK_BUFFER,\n GL_UNIFORM_BUFFER};\n static int usageTypes[USAGETYPE_LAST] = {GL_STREAM_DRAW,\n GL_STREAM_READ,\n GL_STREAM_COPY,\n GL_STATIC_DRAW,\n GL_STATIC_READ,\n GL_STATIC_COPY,\n GL_DYNAMIC_DRAW,\n GL_DYNAMIC_READ,\n GL_DYNAMIC_COPY};\n static int pixelStoreParams[PIXELSTOREPARAM_LAST] = {GL_PACK_SWAP_BYTES,\n GL_PACK_LSB_FIRST, \n GL_PACK_ROW_LENGTH, \n GL_PACK_IMAGE_HEIGHT, \n GL_PACK_SKIP_PIXELS, \n GL_PACK_SKIP_ROWS, \n GL_PACK_SKIP_IMAGES, \n GL_PACK_ALIGNMENT,\n GL_UNPACK_SWAP_BYTES, \n GL_UNPACK_LSB_FIRST, \n GL_UNPACK_ROW_LENGTH, \n GL_UNPACK_IMAGE_HEIGHT, \n GL_UNPACK_SKIP_PIXELS, \n GL_UNPACK_SKIP_ROWS, \n GL_UNPACK_SKIP_IMAGES, \n GL_UNPACK_ALIGNMENT};\n static int textureTypes[TEXTURETYPE_LAST] = {TEXTURE_1D, \n TEXTURE_2D, \n TEXTURE_3D, \n TEXTURE_1D_ARRAY, \n TEXTURE_2D_ARRAY, \n TEXTURE_RECTANGLE, \n TEXTURE_CUBE_MAP,\n TEXTURE_2D_MULTISAMPLE,\n TEXTURE_2D_MULTISAMPLE_ARRAY};\n static int imageFormats[IMAGEFORMAT_LAST] = {GL_RGB,\n GL_RGBA};\n static int textureParams[TEXTUREPARAM_LAST] = {GL_TEXTURE_BASE_LEVEL, \n GL_TEXTURE_COMPARE_FUNC, \n GL_TEXTURE_COMPARE_MODE, \n GL_TEXTURE_LOD_BIAS, \n GL_TEXTURE_MIN_FILTER, \n GL_TEXTURE_MAG_FILTER, \n GL_TEXTURE_MIN_LOD, \n GL_TEXTURE_MAX_LOD, \n GL_TEXTURE_MAX_LEVEL, \n GL_TEXTURE_SWIZZLE_R, \n GL_TEXTURE_SWIZZLE_G, \n GL_TEXTURE_SWIZZLE_B, \n GL_TEXTURE_SWIZZLE_A, \n GL_TEXTURE_WRAP_S, \n GL_TEXTURE_WRAP_T,\n GL_TEXTURE_WRAP_R};\n static int primitiveTypes[PRIMITIVETYPE_LAST] = {GL_POINTS, \n GL_LINE_STRIP, \n GL_LINE_LOOP, \n GL_LINES, \n GL_LINE_STRIP_ADJACENCY, \n GL_LINES_ADJACENCY, \n GL_TRIANGLE_STRIP, \n GL_TRIANGLE_FAN, \n GL_TRIANGLES, \n GL_TRIANGLE_STRIP_ADJACENCY,\n GL_TRIANGLES_ADJACENCY};\n static int depthFunctions[DEPTHFUNCTION_LAST] = {GL_NEVER, \n GL_LESS, \n GL_EQUAL, \n GL_LEQUAL,\n GL_GREATER, \n GL_NOTEQUAL, \n GL_GEQUAL, \n GL_ALWAYS};\n static int blendFunctions[BLENDFUNCTION_LAST] = {GL_ZERO, \n GL_ONE, \n GL_SRC_COLOR, \n GL_ONE_MINUS_SRC_COLOR, \n GL_DST_COLOR, \n GL_ONE_MINUS_DST_COLOR, \n GL_SRC_ALPHA, \n GL_ONE_MINUS_SRC_ALPHA, \n GL_DST_ALPHA, \n GL_ONE_MINUS_DST_ALPHA, \n GL_CONSTANT_COLOR, \n GL_ONE_MINUS_CONSTANT_COLOR, \n GL_CONSTANT_ALPHA, \n GL_ONE_MINUS_CONSTANT_ALPHA};\n static int faceCullings[FACECULLING_LAST] = {GL_FRONT, \n GL_BACK, \n GL_FRONT_AND_BACK};\n\n \n\n \/\/ Window functions\n bool Graphics::createWindow(const WindowSettings& settings)\n {\n if (m_windowHandle) destroyWindow();\n \n m_windowSettings = settings;\n\n \/\/ Context settings\n glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);\n glutInitContextProfile(GLUT_CORE_PROFILE);\n\n \/\/ Extra settings\n glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);\n\n \/\/ Position & size\n glutInitWindowPosition(settings.position.x, settings.position.y);\n glutInitWindowSize(settings.size.x, settings.size.y);\n\n \/\/ Display settings\n glutInitDisplayMode(settings.useBlending ? GLUT_RGBA : GLUT_RGB |\n settings.useDepthBuffer ? GLUT_DEPTH : 0x0 |\n settings.useStencilBuffer ? GLUT_STENCIL : 0x0 |\n settings.useDoubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE);\n\n\n int majorVer = settings.contextVersionMajor,\n minorVer = settings.contextVersionMinor;\n \n glutInitContextVersion(settings.contextVersionMajor, settings.contextVersionMinor);\n m_windowHandle = glutCreateWindow(\"Generic Window Title\");\n\n\t\tstd::cout << \"glew init might produces GL_INVALID_ENUM error. Just ignore it\" << std::endl;\n\t\tglewExperimental = GL_TRUE;\n oglCheck(glewInit());\n\n return true;\n }\n\n\n void Graphics::destroyWindow()\n {\n oglCheck(glutDestroyWindow(m_windowHandle));\n }\n\n\n void Graphics::clear(const float r, const float g, const float b, const float a)\n {\n oglCheck(glClear(GL_COLOR_BUFFER_BIT |\n GL_DEPTH_BUFFER_BIT |\n GL_STENCIL_BUFFER_BIT));\n\t\toglCheck(glClearColor(r, g, b, a));\n\n if (!m_windowSettings.useDepthBuffer) return;\n\n\t\t#ifdef UTH_SYSTEM_OPENGLES\n\t\t\toglCheck(glClearDepthf(1)); \n\t\t#else\n\t\t\toglCheck(glClearDepth(1)); \n\t\t#endif\n\n if (!m_windowSettings.useStencilBuffer) return;\n\n oglCheck(glClearStencil(1));\n }\n\n void Graphics::swapBuffers()\n {\n oglCheck(glutSwapBuffers());\n }\n\n void setViewport(const int x, const int y, const size_t width, const size_t height)\n {\n oglCheck(glViewport(x, y, width, height));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Shaders\n\n int Graphics::createShaderProgram()\n {\n return glCreateProgram();\n }\n\n bool Graphics::createShader(const ShaderType type, const int shaderProgram, const char* shaderCode)\n {\n if (!shaderCode) return false;\n\n unsigned int shader = glCreateShader(shaderTypes[type]);\n oglCheck(glShaderSource(shader, 1, &shaderCode, NULL));\n oglCheck(glCompileShader(shader));\n\n\t\tint infoLenght;\n\t\toglCheck(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLenght));\n\t\tif(infoLenght > 1)\n\t\t{\n\t\t\tchar* buf = new char[infoLenght];\n\t\t\toglCheck(glGetShaderInfoLog(shader, infoLenght, NULL, buf));\n\t\t\tstd::cout << buf << std::endl;\n\t\t\tdelete buf;\n\t\t}\n\n int success;\n\t\toglCheck(glGetShaderiv(shader, GL_COMPILE_STATUS, &success));\n\n\t\tif (!success)\n\t\t{\n glDeleteShader(shader);\n\n return false;\n }\n\n oglCheck(glAttachShader(shaderProgram, shader));\n oglCheck(glDeleteShader(shader));\n\n return true;\n }\n\n bool Graphics::linkShaderProgram(const int shaderProgram)\n {\n oglCheck(glLinkProgram(shaderProgram));\n\n int success;\n\t\toglCheck(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success));\n\n\t\tif (!success)\n\t\t{\n destroyShaderProgram(shaderProgram);\n\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n }\n\n void Graphics::bindProgram(const int shaderProgram)\n {\n if (shaderProgram)\n oglCheck(glUseProgram(shaderProgram));\n }\n\n void unbindProgram()\n {\n oglCheck(glUseProgram(0));\n }\n\n void Graphics::destroyShaderProgram(const int shaderProgram)\n {\n oglCheck(glDeleteProgram(shaderProgram));\n }\n\n int Graphics::getUniformLocation(const int shaderProgram, const char* name)\n {\n\t\treturn glGetUniformLocation(shaderProgram, name);\n }\n\n int Graphics::getAttributeLocation(const int shaderProgram, const char* name)\n {\n return glGetAttribLocation(shaderProgram, name);\n }\n\n void Graphics::setUniform(const int location, const float x)\n {\n oglCheck(glUniform1f(location, x));\n }\n\n void Graphics::setUniform(const int location, const float x, const float y)\n {\n oglCheck(glUniform2f(location, x, y));\n }\n\n void Graphics::setUniform(const int location, const float x, const float y, const float z)\n {\n oglCheck(glUniform3f(location, x, y, z));\n }\n\n void Graphics::setUniform(const int location, const float x, const float y, const float z, const float w)\n {\n oglCheck(glUniform4f(location, x, y, z, w));\n }\n\n void Graphics::setUniform(const int location, const umath::vector2& vector)\n {\n oglCheck(glUniform2fv(location, 1, &vector.x));\n }\n\n void Graphics::setUniform(const int location, const umath::vector3& vector)\n {\n oglCheck(glUniform3fv(location, 1, &vector.x));\n }\n\n void Graphics::setUniform(const int location, const umath::vector4& vector)\n {\n oglCheck(glUniform4fv(location, 1, &vector.x));\n }\n\n void Graphics::setUniform(const int location, const umath::matrix3& matrix)\n {\n oglCheck(glUniformMatrix3fv(location, 1, GL_FALSE, &matrix[0][0]));\n }\n\n void Graphics::setUniform(const int location, const umath::matrix4& matrix)\n {\n oglCheck(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]));\n }\n\n void Graphics::enableVertexAttribArray(const int location)\n {\n oglCheck(glEnableVertexAttribArray(location));\n }\n\n void Graphics::disableVertexAttribArray(const int location)\n {\n oglCheck(glDisableVertexAttribArray(location));\n }\n\n void Graphics::setVertexAttribPointer(const int location, const int size, DataType type, const int stride, const void* pointer)\n {\n oglCheck(glVertexAttribPointer(location, size, dataTypes[type], GL_FALSE, stride, pointer));\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Buffers\n\n void Graphics::generateBuffers(const unsigned int amount, unsigned int* buffers)\n {\n oglCheck(glGenBuffers(amount, buffers));\n }\n\n void Graphics::deleteBuffers(const unsigned int amount, unsigned int* buffers)\n {\n oglCheck(glDeleteBuffers(amount, buffers));\n }\n\n void Graphics::bindBuffer(BufferType type, const unsigned int buffer)\n {\n oglCheck(glBindBuffer(bufferTypes[type], buffer));\n }\n\n void Graphics::setBufferData(BufferType type, const unsigned int size, const void* data, UsageType usageType)\n {\n oglCheck(glBufferData(bufferTypes[type], size, data, usageTypes[usageType]));\n }\n\n void Graphics::setBufferSubData(BufferType type, const unsigned int offset, const unsigned int size, const void* data)\n {\n oglCheck(glBufferSubData(bufferTypes[type], offset, size, data));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Texture functions\n \n void Graphics::setPixelStore(PixelStoreParam param, const int value)\n {\n oglCheck(glPixelStorei(pixelStoreParams[param], value));\n }\n\n void Graphics::generateTextures(const unsigned int amount, unsigned int* data)\n {\n oglCheck(glGenTextures(amount, data));\n }\n\n void Graphics::setActiveTexUnit(TexUnit unit)\n {\n oglCheck(glActiveTexture(unit));\n }\n\n void Graphics::bindTexture(TextureType type, const int texture)\n {\n oglCheck(glBindTexture(textureTypes[type], texture));\n }\n\n void Graphics::setTextureImage1D(const int level, ImageFormat imageFormat, const size_t width, ImageFormat pixelFormat, DataType dataType, const void* pixels)\n {\n oglCheck(glTexImage1D(textureTypes[TEXTURE_1D], level, imageFormats[imageFormat], width, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));\n }\n\n void Graphics::setTextureImage2D(TextureType type, const int level, ImageFormat imageFormat, const size_t width, const size_t height, ImageFormat pixelFormat, DataType dataType, const void* pixels)\n {\n oglCheck(glTexImage2D(textureTypes[TEXTURE_2D], level, imageFormats[imageFormat], width, height, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));\n }\n\n void Graphics::setTextureParameter(TextureType type, TextureParam param, const int value)\n {\n oglCheck(glTexParameteri(textureTypes[type], textureParams[param], value));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Drawing functions\n void Graphics::drawArrays(PrimitiveType type, const int first, const size_t count)\n {\n oglCheck(glDrawArrays(primitiveTypes[type], first, count));\n }\n\n void Graphics::drawElements(PrimitiveType type, const size_t count, DataType dataType, const void* indices)\n {\n oglCheck(glDrawElements(primitiveTypes[type], count, dataTypes[dataType], indices));\n }\n\n void Graphics::setPointSize(const float size)\n {\n oglCheck(glPointSize(size));\n }\n\n void Graphics::setLineWidth(const float width)\n {\n oglCheck(glLineWidth(width));\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Other\n void Graphics::flush()\n {\n oglCheck(glFlush());\n }\n\n void Graphics::setDepthFunction(const bool enable, DepthFunction func)\n {\n static bool enabled = false;\n\n if (enable != enabled)\n {\n if (enable)\n oglCheck(glEnable(GL_DEPTH_TEST));\n else\n oglCheck(glDisable(GL_DEPTH_TEST));\n\n enabled = !enabled;\n }\n\n oglCheck(glDepthFunc(depthFunctions[func]));\n }\n\n void Graphics::setBlendFunction(const bool enable, BlendFunction sfunc, BlendFunction dfunc)\n {\n static bool enabled = false;\n\n if (enable != enabled)\n {\n if (enable)\n oglCheck(glEnable(GL_BLEND));\n else\n oglCheck(glDisable(GL_BLEND));\n\n enabled = !enabled;\n }\n\n oglCheck(glBlendFunc(blendFunctions[sfunc], blendFunctions[dfunc]));\n }\n\n void Graphics::setFaceCulling(const bool enable, FaceCulling mode)\n {\n static bool enabled = false;\n\n if (enable != enabled)\n {\n if (enable)\n oglCheck(glEnable(GL_CULL_FACE));\n else\n oglCheck(glDisable(GL_CULL_FACE));\n\n enabled = !enabled;\n }\n\n oglCheck(glCullFace(faceCullings[mode]));\n }\n\n\n\n \/\/ Private\n\n Graphics::Graphics()\n : m_windowHandle(0),\n m_windowSettings()\n {\n char* myargv[1];\n int myargc = 1;\n myargv[0] = strdup(\"UtH Engine\");\n glutInit(&myargc, myargv);\n }\n\n Graphics::~Graphics()\n {\n destroyWindow();\n }\n}<|endoftext|>"} {"text":"\/* string_functions.cc\n Jeremy Barnes, 7 February 2005\n Copyright (c) 2005 Jeremy Barnes. All rights reserved.\n \n This file is part of \"Jeremy's Machine Learning Library\", copyright (c)\n 1999-2005 Jeremy Barnes.\n \n This program is available under the GNU General Public License, the terms\n of which are given by the file \"license.txt\" in the top level directory of\n the source code distribution. If this file is missing, you have no right\n to use the program; please contact the author.\n\n This program is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n for more details.\n\n ---\n \n String manipulation functions.\n*\/\n\n#include \"string_functions.h\"\n#include \n#include \n#include \"jml\/arch\/exception.h\"\n#include \n#include \n\nusing namespace std;\n\n\nnamespace ML {\n\nstruct va_ender {\n va_ender(va_list & ap)\n : ap(ap)\n {\n }\n\n ~va_ender()\n {\n va_end(ap);\n }\n\n va_list & ap;\n};\n\nstd::string format(const char * fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n try {\n string result = vformat(fmt, ap);\n va_end(ap);\n return result;\n }\n catch (...) {\n va_end(ap);\n throw;\n }\n}\n\nstd::string vformat(const char * fmt, va_list ap)\n{\n char * mem;\n string result;\n int res = vasprintf(&mem, fmt, ap);\n if (res < 0)\n throw Exception(errno, \"vasprintf\", \"format()\");\n\n try {\n result = mem;\n free(mem);\n return result;\n }\n catch (...) {\n free(mem);\n throw;\n }\n}\n\nstd::vector split(const std::string & str, char c)\n{\n vector result;\n size_t start = 0;\n size_t pos = 0;\n while (pos < str.size()) {\n if (str[pos] == c) {\n result.push_back(string(str, start, pos - start));\n start = pos + 1;\n }\n ++pos;\n }\n\n if (start < str.size())\n result.push_back(string(str, start, pos - start));\n\n return result;\n}\n\nstd::string lowercase(const std::string & str)\n{\n string result = str;\n for (unsigned i = 0; i < str.size(); ++i)\n result[i] = tolower(result[i]);\n return result;\n}\n\nstd::string remove_trailing_whitespace(const std::string & str)\n{\n int startOfSpace = -1;\n for (unsigned i = 0; i < str.length(); ++i) {\n if (isspace(str[i])) {\n if (startOfSpace == -1) startOfSpace = i;\n }\n else startOfSpace = -1;\n }\n\n if (startOfSpace == -1) return str;\n return string(str, 0, startOfSpace);\n}\n\nbool removeIfEndsWith(std::string & str, const std::string & ending)\n{\n if (str.rfind(ending) == str.size() - ending.length()) {\n str = string(str, 0, str.size() - ending.length());\n return true;\n }\n \n return false;\n}\n\nbool endsWith(const std::string & haystack, const std::string & needle)\n{\n string::size_type result = haystack.rfind(needle);\n return result != string::npos\n && result == haystack.size() - needle.size();\n}\n\nstd::string hexify_string(const std::string & str)\n{\n size_t i, len(str.size());\n std::string newString;\n newString.reserve(len * 3);\n\n for (i = 0; i < len; i++) {\n if (str[i] < 32 || str[i] > 127) {\n newString += format(\"\\\\x%.2x\", int(str[i] & 0xff));\n }\n else {\n newString += str[i];\n }\n }\n\n return newString;\n}\n\nint\nantoi(const char * start, const char * end, int base)\n{\n int result(0);\n bool neg = false;\n if (*start == '-') {\n if (base == 10) {\n neg = true;\n }\n else {\n throw ML::Exception(\"Cannot negate non base 10\");\n }\n }\n\n for (const char * ptr = start + neg; ptr < end; ptr++) {\n int digit;\n if (*ptr >= '0' and *ptr <= '9') {\n digit = *ptr - '0';\n }\n else if (*ptr >= 'A' and *ptr <= 'F') {\n digit = *ptr - 'A' + 10;\n }\n else if (*ptr >= 'a' and *ptr <= 'f') {\n digit = *ptr - 'a' + 10;\n }\n else {\n throw ML::Exception(\"expected digit\");\n }\n if (digit > base) {\n intptr_t offset = ptr - start;\n throw ML::Exception(\"digit '%c' (%d) exceeds base '%d'\"\n \" at offset '%d'\",\n *ptr, digit, base, offset);\n }\n result = result * base + digit;\n }\n\n if (neg) {\n return result * -1;\n } \n return result;\n}\n\n} \/\/ namespace ML\nantoi: accept numbers starting with \"+\"\/* string_functions.cc\n Jeremy Barnes, 7 February 2005\n Copyright (c) 2005 Jeremy Barnes. All rights reserved.\n \n This file is part of \"Jeremy's Machine Learning Library\", copyright (c)\n 1999-2005 Jeremy Barnes.\n \n This program is available under the GNU General Public License, the terms\n of which are given by the file \"license.txt\" in the top level directory of\n the source code distribution. If this file is missing, you have no right\n to use the program; please contact the author.\n\n This program is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n for more details.\n\n ---\n \n String manipulation functions.\n*\/\n\n#include \"string_functions.h\"\n#include \n#include \n#include \"jml\/arch\/exception.h\"\n#include \n#include \n\nusing namespace std;\n\n\nnamespace ML {\n\nstruct va_ender {\n va_ender(va_list & ap)\n : ap(ap)\n {\n }\n\n ~va_ender()\n {\n va_end(ap);\n }\n\n va_list & ap;\n};\n\nstd::string format(const char * fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n try {\n string result = vformat(fmt, ap);\n va_end(ap);\n return result;\n }\n catch (...) {\n va_end(ap);\n throw;\n }\n}\n\nstd::string vformat(const char * fmt, va_list ap)\n{\n char * mem;\n string result;\n int res = vasprintf(&mem, fmt, ap);\n if (res < 0)\n throw Exception(errno, \"vasprintf\", \"format()\");\n\n try {\n result = mem;\n free(mem);\n return result;\n }\n catch (...) {\n free(mem);\n throw;\n }\n}\n\nstd::vector split(const std::string & str, char c)\n{\n vector result;\n size_t start = 0;\n size_t pos = 0;\n while (pos < str.size()) {\n if (str[pos] == c) {\n result.push_back(string(str, start, pos - start));\n start = pos + 1;\n }\n ++pos;\n }\n\n if (start < str.size())\n result.push_back(string(str, start, pos - start));\n\n return result;\n}\n\nstd::string lowercase(const std::string & str)\n{\n string result = str;\n for (unsigned i = 0; i < str.size(); ++i)\n result[i] = tolower(result[i]);\n return result;\n}\n\nstd::string remove_trailing_whitespace(const std::string & str)\n{\n int startOfSpace = -1;\n for (unsigned i = 0; i < str.length(); ++i) {\n if (isspace(str[i])) {\n if (startOfSpace == -1) startOfSpace = i;\n }\n else startOfSpace = -1;\n }\n\n if (startOfSpace == -1) return str;\n return string(str, 0, startOfSpace);\n}\n\nbool removeIfEndsWith(std::string & str, const std::string & ending)\n{\n if (str.rfind(ending) == str.size() - ending.length()) {\n str = string(str, 0, str.size() - ending.length());\n return true;\n }\n \n return false;\n}\n\nbool endsWith(const std::string & haystack, const std::string & needle)\n{\n string::size_type result = haystack.rfind(needle);\n return result != string::npos\n && result == haystack.size() - needle.size();\n}\n\nstd::string hexify_string(const std::string & str)\n{\n size_t i, len(str.size());\n std::string newString;\n newString.reserve(len * 3);\n\n for (i = 0; i < len; i++) {\n if (str[i] < 32 || str[i] > 127) {\n newString += format(\"\\\\x%.2x\", int(str[i] & 0xff));\n }\n else {\n newString += str[i];\n }\n }\n\n return newString;\n}\n\nint\nantoi(const char * start, const char * end, int base)\n{\n int result(0);\n bool neg = false;\n if (*start == '-') {\n if (base == 10) {\n neg = true;\n }\n else {\n throw ML::Exception(\"Cannot negate non base 10\");\n }\n start++;\n }\n else if (*start == '+') {\n start++;\n }\n\n for (const char * ptr = start; ptr < end; ptr++) {\n int digit;\n if (*ptr >= '0' and *ptr <= '9') {\n digit = *ptr - '0';\n }\n else if (*ptr >= 'A' and *ptr <= 'F') {\n digit = *ptr - 'A' + 10;\n }\n else if (*ptr >= 'a' and *ptr <= 'f') {\n digit = *ptr - 'a' + 10;\n }\n else {\n throw ML::Exception(\"expected digit\");\n }\n if (digit > base) {\n intptr_t offset = ptr - start;\n throw ML::Exception(\"digit '%c' (%d) exceeds base '%d'\"\n \" at offset '%d'\",\n *ptr, digit, base, offset);\n }\n result = result * base + digit;\n }\n\n if (neg) {\n return result * -1;\n }\n\n return result;\n}\n\n} \/\/ namespace ML\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\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.txt\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\n#include \n\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkNumericTraits.h\"\n\n\ntemplate \nclass itkImageIteratorWithIndexTestIteratorTester\n{\n\n public:\n typedef TPixelType PixelType;\n\n typedef itk::Image< PixelType, 3 > ImageType;\n\n typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;\n\n typedef itk::ImageRegionConstIteratorWithIndex< ImageType > ConstIteratorType;\n\n itkImageIteratorWithIndexTestIteratorTester( const PixelType & value )\n {\n m_Image = ImageType::New();\n\n typename ImageType::SizeType size;\n size.Fill(100);\n\n typename ImageType::IndexType start;\n start.Fill(0);\n\n typename ImageType::RegionType region;\n region.SetSize( size );\n region.SetIndex( start );\n\n m_Image->SetRegions( region );\n m_Image->Allocate();\n\n m_Image->FillBuffer( value );\n }\n\n bool TestIterator()\n {\n IteratorType it( m_Image, m_Image->GetBufferedRegion() );\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n PixelType value = it.Get();\n PixelType testValue = value * static_cast::ValueType>( 2 );\n it.Set( testValue);\n if( it.Get() != testValue )\n {\n std::cerr << \"TestIterator failed!\" << std::endl;\n return false;\n }\n ++it;\n }\n return true;\n }\n\n bool TestConstIterator()\n {\n ConstIteratorType it( m_Image, m_Image->GetBufferedRegion() );\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n PixelType value = it.Get();\n if( value != it.Get() ) \/\/ check repeatibility\n {\n std::cerr << \"TestConstIterator failed!\" << std::endl;\n return false;\n }\n ++it;\n }\n return true;\n }\n\n private:\n\n typename ImageType::Pointer m_Image;\n\n};\n\nint itkImageIteratorWithIndexTest(int, char* [] )\n{\n\n bool testPassed = true; \/\/ let's be optimistic\n\n \/\/ Instantiate image of various types and\n \/\/ test the iterators on them\n\n std::cout << \"Testing with Image< char, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< char > TesterC( 10 );\n if( TesterC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< unsigned char, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< unsigned char > TesterUC( 10 );\n if( TesterUC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< short, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< short > TesterS( 10 );\n if( TesterS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< unsigned short, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< unsigned short > TesterUS( 10 );\n if( TesterUS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< int, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< int > TesterI( 10 );\n if( TesterI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< unsigned int, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< unsigned int > TesterUI( 10 );\n if( TesterUI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< float, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< float > TesterF( 10.0 );\n if( TesterF.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterF.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< double, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< double > TesterD( 10.0 );\n if( TesterD.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterD.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VC;\n VC vc;\n vc.Fill( 127 );\n itkImageIteratorWithIndexTestIteratorTester< VC > TesterVC( vc );\n if( TesterVC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VUC;\n VUC vuc;\n vuc.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VUC > TesterVUC( vuc );\n if( TesterVUC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VS;\n VS vs;\n vs.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VS > TesterVS( vs );\n if( TesterVS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VUS;\n VUS vus;\n vus.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VUS > TesterVUS( vus );\n if( TesterVUS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VI;\n VI vi;\n vi.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VI > TesterVI( vi );\n if( TesterVI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VUI;\n VUI vui;\n vui.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VUI > TesterVUI( vui );\n if( TesterVUI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VF;\n VF vf;\n vf.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VF > TesterVF( vf );\n if( TesterVF.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVF.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VD;\n VD vd;\n vd.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VD > TesterVD( vd );\n if( TesterVD.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVD.TestConstIterator() == false )\n {\n testPassed = false;\n }\n\n if ( !testPassed )\n {\n std::cout << \"Failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Success\" << std::endl;\n return EXIT_SUCCESS;\n\n}\nENH: adding reverse iteration test\/*=========================================================================\n *\n * Copyright Insight Software Consortium\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.txt\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\n#include \n\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkNumericTraits.h\"\n\n\ntemplate \nclass itkImageIteratorWithIndexTestIteratorTester\n{\n\n public:\n typedef TPixelType PixelType;\n\n typedef itk::Image< PixelType, 3 > ImageType;\n\n typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;\n\n typedef itk::ImageRegionConstIteratorWithIndex< ImageType > ConstIteratorType;\n\n itkImageIteratorWithIndexTestIteratorTester( const PixelType & value )\n {\n m_Image = ImageType::New();\n\n typename ImageType::SizeType size;\n size.Fill(100);\n\n typename ImageType::IndexType start;\n start.Fill(0);\n\n typename ImageType::RegionType region;\n region.SetSize( size );\n region.SetIndex( start );\n\n m_Image->SetRegions( region );\n m_Image->Allocate();\n\n m_Image->FillBuffer( value );\n }\n\n bool TestIterator()\n {\n IteratorType it( m_Image, m_Image->GetBufferedRegion() );\n itk::SizeValueType i = 0;\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n PixelType value = it.Get();\n PixelType testValue = value * static_cast::ValueType>( 2 );\n it.Set( testValue);\n if( it.Get() != testValue )\n {\n std::cerr << \"TestIterator failed!\" << std::endl;\n return false;\n }\n ++it;\n i++;\n }\n if (i != m_Image->GetBufferedRegion().GetNumberOfPixels())\n {\n std::cerr << \"TestConstIterator failed (NumberOfPixels)!\" << std::endl;\n return false;\n }\n return true;\n }\n\n bool TestConstIterator()\n {\n ConstIteratorType it( m_Image, m_Image->GetBufferedRegion() );\n itk::SizeValueType i = 0;\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n PixelType value = it.Get();\n if( value != it.Get() ) \/\/ check repeatibility\n {\n std::cerr << \"TestConstIterator failed!\" << std::endl;\n return false;\n }\n ++it;\n i++;\n }\n if (i != m_Image->GetBufferedRegion().GetNumberOfPixels())\n {\n std::cerr << \"TestConstIterator failed (NumberOfPixels)!\" << std::endl;\n return false;\n }\n return true;\n }\n\n bool TestReverseIteration()\n {\n ConstIteratorType it( m_Image, m_Image->GetBufferedRegion() );\n itk::SizeValueType i = 0;\n it.GoToReverseBegin();\n while( !it.IsAtReverseEnd() )\n {\n PixelType value = it.Get();\n if( value != it.Get() ) \/\/ check repeatibility\n {\n std::cerr << \"TestReverseIteration failed!\" << std::endl;\n return false;\n }\n --it;\n i++;\n }\n if (i != m_Image->GetBufferedRegion().GetNumberOfPixels())\n {\n std::cerr << \"TestConstIterator failed (NumberOfPixels)!\" << std::endl;\n return false;\n }\n return true;\n }\n\n private:\n\n typename ImageType::Pointer m_Image;\n\n};\n\nint itkImageIteratorWithIndexTest(int, char* [] )\n{\n\n bool testPassed = true; \/\/ let's be optimistic\n\n \/\/ Instantiate image of various types and\n \/\/ test the iterators on them\n\n std::cout << \"Testing with Image< char, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< char > TesterC( 10 );\n if( TesterC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterC.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< unsigned char, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< unsigned char > TesterUC( 10 );\n if( TesterUC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUC.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< short, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< short > TesterS( 10 );\n if( TesterS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterS.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< unsigned short, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< unsigned short > TesterUS( 10 );\n if( TesterUS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUS.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< int, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< int > TesterI( 10 );\n if( TesterI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterI.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< unsigned int, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< unsigned int > TesterUI( 10 );\n if( TesterUI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterUI.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< float, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< float > TesterF( 10.0 );\n if( TesterF.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterF.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterF.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< double, 3 > \" << std::endl;\n itkImageIteratorWithIndexTestIteratorTester< double > TesterD( 10.0 );\n if( TesterD.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterD.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterD.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VC;\n VC vc;\n vc.Fill( 127 );\n itkImageIteratorWithIndexTestIteratorTester< VC > TesterVC( vc );\n if( TesterVC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVC.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VUC;\n VUC vuc;\n vuc.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VUC > TesterVUC( vuc );\n if( TesterVUC.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUC.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUC.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VS;\n VS vs;\n vs.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VS > TesterVS( vs );\n if( TesterVS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVS.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VUS;\n VUS vus;\n vus.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VUS > TesterVUS( vus );\n if( TesterVUS.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUS.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUS.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VI;\n VI vi;\n vi.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VI > TesterVI( vi );\n if( TesterVI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVI.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VUI;\n VUI vui;\n vui.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VUI > TesterVUI( vui );\n if( TesterVUI.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUI.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVUI.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VF;\n VF vf;\n vf.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VF > TesterVF( vf );\n if( TesterVF.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVF.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVF.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n std::cout << \"Testing with Image< itk::Vector, 3 > \" << std::endl;\n typedef itk::Vector VD;\n VD vd;\n vd.Fill( 10 );\n itkImageIteratorWithIndexTestIteratorTester< VD > TesterVD( vd );\n if( TesterVD.TestIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVD.TestConstIterator() == false )\n {\n testPassed = false;\n }\n if( TesterVD.TestReverseIteration() == false )\n {\n testPassed = false;\n }\n\n if ( !testPassed )\n {\n std::cout << \"Failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Success\" << std::endl;\n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n\n#include \n\n\/\/ us\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nclass mitkMCThreadHandlerTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkMCThreadHandlerTestSuite);\n MITK_TEST(testConstructorBehavior);\n MITK_TEST(testCorrectNumberOfPhotons);\n MITK_TEST(testCorrectNumberOfPhotonsWithUnevenPackageSize);\n MITK_TEST(testCorrectNumberOfPhotonsWithTooLargePackageSize);\n MITK_TEST(testCorrectTimeMeasure);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n mitk::pa::MonteCarloThreadHandler::Pointer m_MonteCarloThreadHandler;\n long m_NumberOrTime = 500;\n\npublic:\n\n void setUp() override\n {\n }\n\n void testConstructorBehavior()\n {\n auto threadHandler1 = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, true, true);\n auto threadHandler2 = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, true);\n\n CPPUNIT_ASSERT(mitk::pa::Equal(threadHandler1, threadHandler2, 1e-6, true));\n }\n\n void testCorrectTimeMeasure()\n {\n for (int i = 0; i < 10; i++)\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, true, false);\n auto timeBefore = std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count();\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\/\/Do nothing\n }\n auto timeAfter = std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count();\n\n \/\/Assert that the time error is less than 10% in a 500ms sample size\n \/\/This test might not be stable when on different machines.\n CPPUNIT_ASSERT(std::abs((timeAfter - timeBefore) - m_NumberOrTime) <= 50);\n }\n }\n\n void testCorrectNumberOfPhotons()\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, false, false);\n m_MonteCarloThreadHandler->SetPackageSize(100);\n long numberOfPhotonsSimulated = 0;\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\n numberOfPhotonsSimulated += nextWorkPackage;\n }\n CPPUNIT_ASSERT(numberOfPhotonsSimulated == m_NumberOrTime);\n }\n\n void testCorrectNumberOfPhotonsWithUnevenPackageSize()\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, false, false);\n m_MonteCarloThreadHandler->SetPackageSize(77);\n long numberOfPhotonsSimulated = 0;\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\n numberOfPhotonsSimulated += nextWorkPackage;\n }\n CPPUNIT_ASSERT(numberOfPhotonsSimulated == m_NumberOrTime);\n }\n\n void testCorrectNumberOfPhotonsWithTooLargePackageSize()\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, false, false);\n m_MonteCarloThreadHandler->SetPackageSize(10000);\n long numberOfPhotonsSimulated = 0;\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\n numberOfPhotonsSimulated += nextWorkPackage;\n }\n CPPUNIT_ASSERT(numberOfPhotonsSimulated == m_NumberOrTime);\n }\n\n void tearDown() override\n {\n m_MonteCarloThreadHandler = nullptr;\n }\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkMCThreadHandler)\nFixed some warnings\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n\n#include \n\n\/\/ us\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nclass mitkMCThreadHandlerTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkMCThreadHandlerTestSuite);\n MITK_TEST(testConstructorBehavior);\n MITK_TEST(testCorrectNumberOfPhotons);\n MITK_TEST(testCorrectNumberOfPhotonsWithUnevenPackageSize);\n MITK_TEST(testCorrectNumberOfPhotonsWithTooLargePackageSize);\n MITK_TEST(testCorrectTimeMeasure);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n mitk::pa::MonteCarloThreadHandler::Pointer m_MonteCarloThreadHandler;\n long m_NumberOrTime = 500;\n\npublic:\n\n void setUp() override\n {\n }\n\n void testConstructorBehavior()\n {\n auto threadHandler1 = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, true, true);\n auto threadHandler2 = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, true);\n\n CPPUNIT_ASSERT(mitk::pa::Equal(threadHandler1, threadHandler2, 1e-6, true));\n }\n\n void testCorrectTimeMeasure()\n {\n for (int i = 0; i < 10; i++)\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, true, false);\n auto timeBefore = std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count();\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\/\/Do nothing\n }\n auto timeAfter = std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count();\n\n \/\/Assert that the time error is less than 10% in a 500ms sample size\n \/\/This test might not be stable when on different machines.\n CPPUNIT_ASSERT(std::labs((timeAfter - timeBefore) - m_NumberOrTime) <= 50);\n }\n }\n\n void testCorrectNumberOfPhotons()\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, false, false);\n m_MonteCarloThreadHandler->SetPackageSize(100);\n long numberOfPhotonsSimulated = 0;\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\n numberOfPhotonsSimulated += nextWorkPackage;\n }\n CPPUNIT_ASSERT(numberOfPhotonsSimulated == m_NumberOrTime);\n }\n\n void testCorrectNumberOfPhotonsWithUnevenPackageSize()\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, false, false);\n m_MonteCarloThreadHandler->SetPackageSize(77);\n long numberOfPhotonsSimulated = 0;\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\n numberOfPhotonsSimulated += nextWorkPackage;\n }\n CPPUNIT_ASSERT(numberOfPhotonsSimulated == m_NumberOrTime);\n }\n\n void testCorrectNumberOfPhotonsWithTooLargePackageSize()\n {\n m_MonteCarloThreadHandler = mitk::pa::MonteCarloThreadHandler::New(m_NumberOrTime, false, false);\n m_MonteCarloThreadHandler->SetPackageSize(10000);\n long numberOfPhotonsSimulated = 0;\n long nextWorkPackage = 0;\n while ((nextWorkPackage = m_MonteCarloThreadHandler->GetNextWorkPackage()) > 0)\n {\n numberOfPhotonsSimulated += nextWorkPackage;\n }\n CPPUNIT_ASSERT(numberOfPhotonsSimulated == m_NumberOrTime);\n }\n\n void tearDown() override\n {\n m_MonteCarloThreadHandler = nullptr;\n }\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkMCThreadHandler)\n<|endoftext|>"} {"text":"cppcheck: variableScope<|endoftext|>"} {"text":"\/\/_____________________________________________________________________\nAliAnalysisTask *AddTaskJFFlucMapMaster(TString taskName=\"JFFlucMaster\", UInt_t period = 0, double ptmin = 0.5){\n\t\/\/ Load Custom Configuration and parameters\n\tenum { lhc15o=0, lhc18q=1, lhc18r=2 };\n\tcout << \"AddTaskJFFlucMapMaster:: period=\" << period <<\"\\t ptmin=\"<< ptmin << endl;\n\tAliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\t\/\/-------- Correction Maps ----------\n\t\n\n\tif(period == lhc18q) {\n\t\tAliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask(\"JCorrectionMapTask\"); \n \tcmaptask->EnableCentFlattening(\"alien:\/\/\/alice\/cern.ch\/user\/j\/jparkkil\/legotrain\/Cent\/CentWeights_LHC18q_pass13.root\");\n \tcmaptask->EnableEffCorrection(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC18q-LHC18l8-0-Lists.root\"); \/\/ needed but not used!\n \tmgr->AddTask((AliAnalysisTask*) cmaptask);\n\t\t\n } else if(period == lhc18r) {\n \tAliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask(\"JCorrectionMapTask\"); \n \tcmaptask->EnableCentFlattening(\"alien:\/\/\/alice\/cern.ch\/user\/j\/jparkkil\/legotrain\/Cent\/CentWeights_LHC18r_pass13.root\");\n \tcmaptask->EnableEffCorrection(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC18q-LHC18l8-0-Lists.root\"); \/\/ needed but not used!\n \tmgr->AddTask((AliAnalysisTask*) cmaptask);\n }\n \n \/\/-------- JFlucWagons -------\n const int Nsets = 7; \/\/ number of configurations\n \tAliJFFlucTask *myTask[Nsets];\n\tTString configNames[Nsets] = {\n\t\t\"hybrid\", \/\/ 0\n\t\t\"global\",\n\t\t\"nqq\", \/\/ 2\n\t\t\"subA\",\n\t\t\"SPD\", \/\/ 4\n\t\t\"zvtx\",\n\t\t\"pileup\" \/\/ 6\n\t};\n \tInt_t hybridCut = 768;\n Int_t globalCut = 96;\n UInt_t selEvt;\n\tif(period == lhc15o) selEvt = AliVEvent::kINT7;\n\telse if(period == lhc18q || period == lhc18r) selEvt = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral;\n\t\/\/ --- track related common configurations -----\n\tfor(int i=0;iAddFlags(AliJFFlucTask::FLUC_EBE_WEIGHTING|AliJFFlucTask::FLUC_CUT_OUTLIERS);\n\t\t\tif(period == lhc18q || period == lhc18r) myTask[i]->AddFlags(AliJFFlucTask::FLUC_CENT_FLATTENING);\n\t\t}\n\t\tmyTask[i]->SelectCollisionCandidates( selEvt );\n\t\tmyTask[i]->SetCentDetName(\"V0M\");\n\t\tmyTask[i]->SelectSubevents(AliJFFlucTask::SUBEVENT_A|AliJFFlucTask::SUBEVENT_B);\n\t\tmyTask[i]->SetTestFilterBit(hybridCut);\n\t\tmyTask[i]->SetEtaRange(0.4, 0.8);\n\t\tmyTask[i]->SetPtRange(ptmin, 5.0);\n\t\tmyTask[i]->SetEffConfig(0,hybridCut);\n\t}\n\t\/\/ s_global\n\tint iS = 1;\n\tmyTask[iS]->SetTestFilterBit(globalCut);\n\tmyTask[iS]->SetEffConfig(0,globalCut);\n\t\/\/ s_nqq\n\tiS = 2;\n\tmyTask[iS]->SetParticleCharge(-1);\n \/\/ s_subA\n iS = 3;\n\tmyTask[iS]->SelectSubevents(AliJFFlucTask::SUBEVENT_A); \/\/ subA\n\t\/\/\n\t\/\/----------- Event related Check -------------\n\t\/\/ s_SPD\n\tiS = 4;\n\tmyTask[iS]->SetCentDetName(\"CL1\");\n\t\/\/ s_zvtx\n\tiS = 5;\n\tmyTask[iS]->SetZVertexCut(8);\n\t\/\/ s_pileup\n\tiS = 6;\n\tif(period==lhc18q || period==lhc18r) {\n\t\tmyTask[iS]->AddFlags(AliJFFlucTask::FLUC_EBE_WEIGHTING|AliJFFlucTask::FLUC_CENT_FLATTENING); \/\/ CAN|T overwrite Flags!!!\n\t} else if(period==lhc15o) {\n\t\tmyTask[iS]->AddFlags(AliJFFlucTask::FLUC_EBE_WEIGHTING); \/\/ CAN|T overwrite Flags!!! no weightening for 15o\n\t}\n\t\n\t\/\/ Must add the tasks\n\tfor(int i=0;iAddTask((AliAnalysisTask*) myTask[i]);\n\t\/\/ Create containers for input\/output\n\tAliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n\n\t\/\/ Connect input\/output\n\tfor(int i=0;iConnectInput(myTask[i], 0, cinput);\n\t\tAliAnalysisDataContainer *jHist = mgr->CreateContainer(Form(\"%scontainer\",myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:%s\",AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));\n\t\tmgr->ConnectOutput(myTask[i], 1, jHist );\n\t}\n\n\treturn myTask[0];\n}\n\nusing task name for subwagons\/\/_____________________________________________________________________\nAliAnalysisTask *AddTaskJFFlucMapMaster(TString taskName=\"JFFlucMaster\", UInt_t period = 0, double ptmin = 0.5){\n\t\/\/ Load Custom Configuration and parameters\n\tenum { lhc15o=0, lhc18q=1, lhc18r=2 };\n\tcout << \"AddTaskJFFlucMapMaster:: period=\" << period <<\"\\t ptmin=\"<< ptmin << endl;\n\tAliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\t\/\/-------- Correction Maps ----------\n\t\n\n\tif(period == lhc18q) {\n\t\tAliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask(\"JCorrectionMapTask\"); \n \tcmaptask->EnableCentFlattening(\"alien:\/\/\/alice\/cern.ch\/user\/j\/jparkkil\/legotrain\/Cent\/CentWeights_LHC18q_pass13.root\");\n \tcmaptask->EnableEffCorrection(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC18q-LHC18l8-0-Lists.root\"); \/\/ needed but not used!\n \tmgr->AddTask((AliAnalysisTask*) cmaptask);\n\t\t\n } else if(period == lhc18r) {\n \tAliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask(\"JCorrectionMapTask\"); \n \tcmaptask->EnableCentFlattening(\"alien:\/\/\/alice\/cern.ch\/user\/j\/jparkkil\/legotrain\/Cent\/CentWeights_LHC18r_pass13.root\");\n \tcmaptask->EnableEffCorrection(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC18q-LHC18l8-0-Lists.root\"); \/\/ needed but not used!\n \tmgr->AddTask((AliAnalysisTask*) cmaptask);\n }\n \n \/\/-------- JFlucWagons -------\n const int Nsets = 7; \/\/ number of configurations\n \tAliJFFlucTask *myTask[Nsets];\n\tTString configNames[Nsets] = {\n\t\t\"hybrid\", \/\/ 0\n\t\t\"global\",\n\t\t\"nqq\", \/\/ 2\n\t\t\"subA\",\n\t\t\"SPD\", \/\/ 4\n\t\t\"zvtx\",\n\t\t\"pileup\" \/\/ 6\n\t};\n \tInt_t hybridCut = 768;\n Int_t globalCut = 96;\n UInt_t selEvt;\n\tif(period == lhc15o) selEvt = AliVEvent::kINT7;\n\telse if(period == lhc18q || period == lhc18r) selEvt = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral;\n\t\/\/ --- track related common configurations -----\n\tfor(int i=0;iAddFlags(AliJFFlucTask::FLUC_EBE_WEIGHTING|AliJFFlucTask::FLUC_CUT_OUTLIERS);\n\t\t\tif(period == lhc18q || period == lhc18r) myTask[i]->AddFlags(AliJFFlucTask::FLUC_CENT_FLATTENING);\n\t\t}\n\t\tmyTask[i]->SelectCollisionCandidates( selEvt );\n\t\tmyTask[i]->SetCentDetName(\"V0M\");\n\t\tmyTask[i]->SelectSubevents(AliJFFlucTask::SUBEVENT_A|AliJFFlucTask::SUBEVENT_B);\n\t\tmyTask[i]->SetTestFilterBit(hybridCut);\n\t\tmyTask[i]->SetEtaRange(0.4, 0.8);\n\t\tmyTask[i]->SetPtRange(ptmin, 5.0);\n\t\tmyTask[i]->SetEffConfig(0,hybridCut);\n\t}\n\t\/\/ s_global\n\tint iS = 1;\n\tmyTask[iS]->SetTestFilterBit(globalCut);\n\tmyTask[iS]->SetEffConfig(0,globalCut);\n\t\/\/ s_nqq\n\tiS = 2;\n\tmyTask[iS]->SetParticleCharge(-1);\n \/\/ s_subA\n iS = 3;\n\tmyTask[iS]->SelectSubevents(AliJFFlucTask::SUBEVENT_A); \/\/ subA\n\t\/\/\n\t\/\/----------- Event related Check -------------\n\t\/\/ s_SPD\n\tiS = 4;\n\tmyTask[iS]->SetCentDetName(\"CL1\");\n\t\/\/ s_zvtx\n\tiS = 5;\n\tmyTask[iS]->SetZVertexCut(8);\n\t\/\/ s_pileup\n\tiS = 6;\n\tif(period==lhc18q || period==lhc18r) {\n\t\tmyTask[iS]->AddFlags(AliJFFlucTask::FLUC_EBE_WEIGHTING|AliJFFlucTask::FLUC_CENT_FLATTENING); \/\/ CAN|T overwrite Flags!!!\n\t} else if(period==lhc15o) {\n\t\tmyTask[iS]->AddFlags(AliJFFlucTask::FLUC_EBE_WEIGHTING); \/\/ CAN|T overwrite Flags!!! no weightening for 15o\n\t}\n\t\n\t\/\/ Must add the tasks\n\tfor(int i=0;iAddTask((AliAnalysisTask*) myTask[i]);\n\t\/\/ Create containers for input\/output\n\tAliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n\n\t\/\/ Connect input\/output\n\tfor(int i=0;iConnectInput(myTask[i], 0, cinput);\n\t\tAliAnalysisDataContainer *jHist = mgr->CreateContainer(Form(\"%scontainer\",myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:%s\",AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));\n\t\tmgr->ConnectOutput(myTask[i], 1, jHist );\n\t}\n\n\treturn myTask[0];\n}\n\n<|endoftext|>"} {"text":"#ifndef _SMRH_\n#define _SMRH_\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace DNFC\n{\n\ntypedef void *data_pointer;\n\n\/**\n * HazardPointerManager\n * \n * This class should not be used through HazardPointer template class.\n * This singleton private class providea central managment point for safe memory reclamation. \n * It provide memory managment for system wide hazard pointers.\n *\/\nclass HazardPointerManager\n{\nprivate:\n template \n friend class HazardPointer;\n\n \/**\n * HazardPointerRecord\n * \n * An object that hold informations about allocated hazard pointers in a Hazard pointer manager. \n *\/\n class HazardPointerRecord\n {\n public:\n std::unique_ptr[]> hp;\n int hpSize;\n std::list rlist;\n std::atomic active;\n HazardPointerRecord *next;\n\n std::atomic &operator[](std::size_t index)\n {\n assert(index >= hpSize);\n return hp[index];\n }\n\n HazardPointerRecord &operator=(HazardPointerRecord &&other) = delete;\n HazardPointerRecord &operator=(const HazardPointerRecord &) = delete;\n\n HazardPointerRecord(std::size_t nbHp, HazardPointerRecord *head, bool active) : next(head),\n hpSize(nbHp)\n {\n this->active.store(active, std::memory_order_relaxed);\n }\n ~HazardPointerRecord(){};\n\n private:\n void resetHp(std::size_t nbHp)\n {\n if (nbHp > hpSize)\n {\n }\n }\n };\n\n static HazardPointerManager &get()\n {\n static HazardPointerManager m;\n return m;\n }\n\n \/\/ Does not allow to copy or move the manager\n HazardPointerManager &operator=(HazardPointerManager &&) = delete;\n HazardPointerManager &operator=(const HazardPointerManager &) = delete;\n\n \/\/ Does not allow to copy construct or move construct the manager\n HazardPointerManager(const HazardPointerManager &) = delete;\n HazardPointerManager(HazardPointerManager &&) = delete;\n HazardPointerManager() : nbhp(0){};\n ~HazardPointerManager(){};\n\n std::atomic> head;\n std::atomic nbhp;\n\n \/**\n * Subscribe a thread to the manager. During the time the thread is subscribed, it is\n * given a HazardPointerRecord object that allow it to protect 'nbHp' number of pointers.\n * *\/\n static void subscribe(std::size_t nbHp)\n {\n \/\/ First try to reuse a retire HP record\n boost::thread_specific_ptr &myhp = getMyhp();\n bool expected = false;\n for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next)\n {\n if (i->active.load(std::memory_order_relaxed) ||\n !i->active.compare_exchange_strong(expected, true,\n std::memory_order_acquire, std::memory_order_relaxed))\n continue;\n\n \/\/ Sucessfully locked one record to use\n myhp.reset(i);\n return;\n }\n\n \/\/ No HP records available for reuse so we add new ones\n nbhp.fetch_add(nbPointers, std::memory_order_relaxed);\n\n \/\/ Allocate and push a new record\n myhp.reset(new HazardPointerRecord(\n nbHp,\n head.load(std::memory_order_relaxed),\n true));\n\n \/\/ Add the new record to the list\n while (!head.compare_exchange_weak(myhp->next, myhp.get(),\n std::memory_order_release,\n std::memory_order_relaxed))\n ;\n }\n\n \/**\n * \n *\/\n static void unsubscribe()\n {\n boost::thread_specific_ptr &myhp = getMyhp();\n if (!myhp.get())\n return;\n \/\/ Clear hp\n for (int i = 0; i < nbPointers; i++)\n myhp->hp[i].store(nullptr, atomics::memory_order_release);\n myhp->active.store(false, std::memory_order_relaxed);\n myhp.release();\n }\n\n unsigned int getBatchSize()\n {\n return (nbhp.load(std::memory_order_relaxed) * nbPointers * 2) + nbhp.load(std::memory_order_relaxed);\n }\n\n \/**\n * \n *\/\n void scan()\n {\n \/\/ Stage 1\n boost::thread_specific_ptr &myhp = getMyhp();\n std::vector plist;\n for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next)\n {\n for (int j = 0; j < nbPointers; j++)\n {\n T hp = i->hp[j].load(std::memory_order_relaxed);\n if (hp.get())\n plist.push_back(hp);\n }\n }\n if (plist.size() <= 0)\n return;\n\n \/\/ Stage 2\n std::sort(plist.begin(), plist.end());\n std::list localRList = myhp->rlist;\n myhp->rlist.clear();\n\n \/\/ Stage 3\n for (auto &&e : localRList)\n {\n if (std::binary_search(plist.begin(), plist.end(), e))\n myhp->rlist.push_front(e);\n else\n delete e;\n }\n }\n\n void help_scan()\n {\n boost::thread_specific_ptr &myhp = getMyhp();\n bool expected = false;\n for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next)\n {\n \/\/ Trying to lock the next non-used hazard pointer record\n if (i->active.load(std::memory_order_relaxed) ||\n !i->active.compare_exchange_strong(expected, true,\n std::memory_order_acquire, std::memory_order_relaxed))\n continue;\n\n \/\/ Inserting the rlist of the node in myhp\n for (auto &&e : i->rlist)\n {\n myhp->rlist.push_front(e);\n\n \/\/ scan if we reached the threshold\n if (myhp->rlist.size() >= getBatchSize())\n scan();\n }\n \/\/ Release the record\n i->rlist.clear();\n i->active.store(false, std::memory_order_relaxed);\n }\n }\n};\n\n\/**\n * HazardPointer\n * \n *\/\ntemplate \nclass HazardPointer\n{\npublic:\n \/**\n * \n *\/\n static constexpr const std::size_t capacity = NbPtr;\n\n \/**\n * \n * @param index \n *\/\n std::atomic &operator[](std::size_t index)\n {\n boost::thread_specific_ptr &myhp = getMyhp();\n assert(index >= myhp->hp.size());\n return myhp->hp[index];\n }\n\n \/**\n * \n * @param node \n *\/\n template \n void deleteNode(T &&node)\n {\n boost::thread_specific_ptr &myhp = getMyhp();\n if (!myhp.get())\n return;\n myhp->rlist.push_front(std::forward(node));\n if (myhp->rlist.size() >= getBatchSize())\n {\n scan();\n help_scan();\n }\n }\n\n \/**\n * \n *\/\n HazardPointer()\n {\n HazardPointerManager::get()->subscribe(capacity);\n };\n\n \/**\n * \n *\/\n ~HazardPointer()\n {\n HazardPointerManager::get()->unsubscribe();\n };\n\nprivate:\n static boost::thread_specific_ptr &getMyhp()\n {\n static boost::thread_specific_ptr myhp;\n return myhp;\n }\n};\n} \/\/ namespace DNFC\n\n#endif\n[WIP] HazardPointer KO: improsving memory footprint and structure#ifndef _SMRH_\n#define _SMRH_\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace DNFC\n{\n\n\/\/ Verbose typedef\ntypedef void *data_pointer;\n\n\/**\n * HazardPointer\n * \n *\/\ntemplate \nclass HazardPointer\n{\npublic:\n \/**\n * Access a HazardPointer through the HazardPointerRecord assigned\n * @param index \n *\/\n std::atomic &operator[](std::size_t index)\n {\n HazardPointerRecord &myhp = getMyhp();\n assert(myhp == nullptr && index >= myhp->hp.size());\n return myhp->hp[index];\n }\n\n \/**\n * Safely delete a node.\n * @param node \n *\/\n template \n void deleteNode(T &&node)\n {\n HazardPointerRecord &myhp = getMyhp();\n if (!myhp.get())\n return;\n myhp->rlist.push_front(std::forward(node));\n if (myhp->rlist.size() >= getBatchSize())\n {\n scan();\n help_scan();\n }\n }\n\n \/**\n * Subscribe and get a HazarPointerRecord set with the right amount of pointers.\n *\/\n HazardPointer()\n {\n HazardPointerManager::get().subscribe();\n };\n\n \/**\n * Unsubscribe and release the HazardPointerRecord.\n *\/\n ~HazardPointer()\n {\n HazardPointerManager::get().unsubscribe();\n };\n\nprivate:\n \/**\n * Thread local storage hazard pointer\n *\/\n HazardPointerRecord *getMyhp()\n {\n thread_local HazardPointerRecord *myhp;\n return myhp;\n }\n\n \/**\n * HazardPointerRecord\n * \n * An object that hold informations about allocated hazard pointers in a Hazard pointer manager. \n *\/\n class HazardPointerRecord\n {\n public:\n std::atomic hp[NbPtr];\n std::list rlist;\n std::atomic active;\n HazardPointerRecord *next;\n\n HazardPointerRecord &operator=(HazardPointerRecord &&other) = delete;\n HazardPointerRecord &operator=(const HazardPointerRecord &) = delete;\n\n HazardPointerRecord(HazardPointerRecord *head, bool active) : next(head)\n {\n this->active.store(active, std::memory_order_relaxed);\n }\n ~HazardPointerRecord(){};\n\n private:\n void resetHp()\n {\n if (nbHp > hpSize)\n {\n \/\/ TODO\n }\n }\n };\n\n \/**\n * HazardPointerManager\n * \n * This class should not be used through HazardPointer template class.\n * This singleton private class providea central managment point for safe memory reclamation. \n * It provide memory managment for system wide hazard pointers.\n *\/\n template \n friend class HazardPointerManager;\n\n template \n class HazardPointerManager\n {\n private:\n static HazardPointerManager &get()\n {\n static HazardPointerManager m;\n return m;\n }\n\n \/\/ Does not allow to copy or move the manager\n HazardPointerManager &operator=(HazardPointerManager &&) = delete;\n HazardPointerManager &operator=(const HazardPointerManager &) = delete;\n\n \/\/ Does not allow to copy construct or move construct the manager\n HazardPointerManager(const HazardPointerManager &) = delete;\n HazardPointerManager(HazardPointerManager &&) = delete;\n HazardPointerManager() : nbhp(0){};\n ~HazardPointerManager(){};\n\n std::atomic head;\n std::atomic nbhp;\n\n \/**\n * Subscribe a thread to the manager. During the time the thread is subscribed, it is\n * given a HazardPointerRecord object that allow it to protect 'nbPtr' number of pointers.\n *\/\n static void subscribe()\n {\n \/\/ First try to reuse a retire HP record\n HazardPointerRecord &myhp = getMyhp();\n bool expected = false;\n for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next)\n {\n if (i->active.load(std::memory_order_relaxed) ||\n !i->active.compare_exchange_strong(expected, true,\n std::memory_order_acquire, std::memory_order_relaxed))\n continue;\n\n \/\/ Sucessfully locked one record to use\n myhp.reset(i);\n return;\n }\n\n \/\/ No HP records available for reuse so we add new ones\n nbhp.fetch_add(nbPointers, std::memory_order_relaxed);\n\n \/\/ Allocate and push a new record\n myhp.reset(new HazardPointerRecord(\n nbPtr,\n head.load(std::memory_order_relaxed),\n true));\n\n \/\/ Add the new record to the list\n while (!head.compare_exchange_weak(myhp->next, myhp.get(),\n std::memory_order_release,\n std::memory_order_relaxed))\n ;\n }\n\n \/**\n * Unsubscribe the current thread from the manager. Its HazarPointerRecord is put back into the store\n * for reuse.\n *\/\n static void unsubscribe()\n {\n HazardPointerRecord &myhp = getMyhp();\n if (!myhp.get())\n return;\n \/\/ Clear hp\n for (int i = 0; i < nbPointers; i++)\n myhp->hp[i].store(nullptr, atomics::memory_order_release);\n myhp->active.store(false, std::memory_order_relaxed);\n myhp.release();\n }\n\n unsigned int getBatchSize()\n {\n return (nbhp.load(std::memory_order_relaxed) * nbPointers * 2) + nbhp.load(std::memory_order_relaxed);\n }\n\n \/**\n * Scan function that is called to garbage collect the memory.\n *\/\n void scan()\n {\n \/\/ Stage 1\n HazardPointerRecord &myhp = getMyhp();\n std::vector plist;\n for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next)\n {\n for (int j = 0; j < nbPointers; j++)\n {\n T hp = i->hp[j].load(std::memory_order_relaxed);\n if (hp.get())\n plist.push_back(hp);\n }\n }\n if (plist.size() <= 0)\n return;\n\n \/\/ Stage 2\n std::sort(plist.begin(), plist.end());\n std::list localRList = myhp->rlist;\n myhp->rlist.clear();\n\n \/\/ Stage 3\n for (auto &&e : localRList)\n {\n if (std::binary_search(plist.begin(), plist.end(), e))\n myhp->rlist.push_front(e);\n else\n delete e;\n }\n }\n\n void help_scan()\n {\n HazardPointerRecord &myhp = getMyhp();\n bool expected = false;\n for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next)\n {\n \/\/ Trying to lock the next non-used hazard pointer record\n if (i->active.load(std::memory_order_relaxed) ||\n !i->active.compare_exchange_strong(expected, true,\n std::memory_order_acquire, std::memory_order_relaxed))\n continue;\n\n \/\/ Inserting the rlist of the node in myhp\n for (auto &&e : i->rlist)\n {\n myhp->rlist.push_front(e);\n\n \/\/ scan if we reached the threshold\n if (myhp->rlist.size() >= getBatchSize())\n scan();\n }\n \/\/ Release the record\n i->rlist.clear();\n i->active.store(false, std::memory_order_relaxed);\n }\n }\n };\n};\n} \/\/ namespace DNFC\n\n#endif\n<|endoftext|>"} {"text":"\/\/\n\/\/ SerializeSourcemap.cc\n\/\/ drafter\n\/\/\n\/\/ Created by Pavan Kumar Sunkara on 18\/01\/15.\n\/\/ Copyright (c) 2015 Apiary Inc. All rights reserved.\n\/\/\n\n#include \"SerializeSourcemap.h\"\n\nusing namespace drafter;\n\nusing snowcrash::SourceMapBase;\nusing snowcrash::SourceMap;\nusing snowcrash::Collection;\n\nusing snowcrash::DataStructure;\nusing snowcrash::Asset;\nusing snowcrash::Payload;\nusing snowcrash::Header;\nusing snowcrash::Parameters;\nusing snowcrash::Parameter;\nusing snowcrash::Value;\nusing snowcrash::TransactionExample;\nusing snowcrash::Request;\nusing snowcrash::Response;\nusing snowcrash::Action;\nusing snowcrash::Resource;\nusing snowcrash::Element;\nusing snowcrash::Description;\nusing snowcrash::Blueprint;\nusing snowcrash::Metadata;\n\nsos::Array WrapSourcemap(const SourceMapBase& value)\n{\n sos::Array sourceMap;\n\n for (mdp::RangeSet::const_iterator it = value.sourceMap.begin();\n it != value.sourceMap.end();\n ++it) {\n\n sos::Array sourceMapRow;\n\n sourceMapRow.push(sos::Number(it->location));\n sourceMapRow.push(sos::Number(it->length));\n\n sourceMap.push(sourceMapRow);\n }\n\n return sourceMap;\n}\n\n\/\/ Forward declarations\nsos::Array WrapTypeSectionsSourcemap(const SourceMap& typeSections);\nsos::Array WrapElementsSourcemap(const SourceMap& elements);\n\nsos::Object WrapPropertyMemberSourcemap(const SourceMap& propertyMember)\n{\n sos::Object propertyMemberObject;\n\n \/\/ Name\n propertyMemberObject.set(SerializeKey::Name, WrapSourcemap(propertyMember.name));\n\n \/\/ Description\n propertyMemberObject.set(SerializeKey::Description, WrapSourcemap(propertyMember.description));\n\n \/\/ Value Definition\n propertyMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(propertyMember.valueDefinition));\n\n \/\/ Type Sections\n propertyMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(propertyMember.sections));\n\n return propertyMemberObject;\n}\n\nsos::Object WrapValueMemberSourcemap(const SourceMap& valueMember)\n{\n sos::Object valueMemberObject;\n\n \/\/ Description\n valueMemberObject.set(SerializeKey::Description, WrapSourcemap(valueMember.description));\n\n \/\/ Value Definition\n valueMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(valueMember.valueDefinition));\n\n \/\/ Type Sections\n valueMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(valueMember.sections));\n\n return valueMemberObject;\n}\n\nsos::Array WrapMixinSourcemap(const SourceMap& mixin)\n{\n return WrapSourcemap(mixin);\n}\n\nsos::Base WrapElementSourcemapBase(const SourceMap& element)\n{\n if (!element.elements().collection.empty()) {\n \/\/ Same for oneOf\n return WrapElementsSourcemap(element.elements()); \/\/ return sos::Array\n }\n else if (!element.mixin.sourceMap.empty()) {\n return WrapMixinSourcemap(element.mixin); \/\/ return sos::Array\n }\n else if (!element.value.empty()) {\n return WrapValueMemberSourcemap(element.value); \/\/ return sos::Object\n }\n else if (!element.property.empty()) {\n return WrapPropertyMemberSourcemap(element.property); \/\/ return sos::Object\n }\n\n return sos::Null(); \/\/ return sos::Null\n}\n\nsos::Array WrapElementsSourcemap(const SourceMap& elements)\n{\n return WrapCollection()(elements.collection, WrapElementSourcemapBase);\n}\n\nsos::Array WrapTypeSectionsSourcemap(const SourceMap& sections)\n{\n sos::Array sectionsArray;\n\n for (Collection >::const_iterator it = sections.collection.begin();\n it != sections.collection.end();\n ++it) {\n\n if (!it->description.sourceMap.empty()) {\n sectionsArray.push(WrapSourcemap(it->description));\n }\n else if (!it->value.sourceMap.empty()) {\n sectionsArray.push(WrapSourcemap(it->value));\n }\n else if (!it->elements().collection.empty()) {\n sectionsArray.push(WrapElementsSourcemap(it->elements()));\n }\n }\n\n return sectionsArray;\n}\n\nsos::Object WrapNamedTypeSourcemap(const SourceMap& namedType)\n{\n sos::Object namedTypeObject;\n\n \/\/ Name\n namedTypeObject.set(SerializeKey::Name, WrapSourcemap(namedType.name));\n\n \/\/ Type Definition\n namedTypeObject.set(SerializeKey::TypeDefinition, WrapSourcemap(namedType.typeDefinition));\n\n \/\/ Type Sections\n namedTypeObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(namedType.sections));\n\n return namedTypeObject;\n}\n\nsos::Object WrapDataStructureSourcemap(const SourceMap& dataStructure)\n{\n sos::Object dataStructureObject;\n\n \/\/ Name\n dataStructureObject.set(SerializeKey::Name, WrapSourcemap(dataStructure.name));\n\n \/\/ Type Definition\n dataStructureObject.set(SerializeKey::TypeDefinition, WrapSourcemap(dataStructure.typeDefinition));\n\n \/\/ Type Sections\n dataStructureObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(dataStructure.sections));\n\n return dataStructureObject;\n}\n\nsos::Object WrapAssetSourcemap(const SourceMap& asset)\n{\n sos::Object assetObject;\n\n \/\/ Content\n assetObject.set(SerializeKey::Content, WrapSourcemap(asset));\n\n return assetObject;\n}\n\nsos::Object WrapPayloadSourcemap(const SourceMap& payload)\n{\n sos::Object payloadObject;\n\n \/\/ Reference\n if (!payload.reference.sourceMap.empty()) {\n payloadObject.set(SerializeKey::Reference, WrapSourcemap(payload.reference));\n }\n\n \/\/ Name\n payloadObject.set(SerializeKey::Name, WrapSourcemap(payload.name));\n\n \/\/ Description\n payloadObject.set(SerializeKey::Description, WrapSourcemap(payload.description));\n\n \/\/ Headers\n payloadObject.set(SerializeKey::Headers, \n WrapCollection
()(payload.headers.collection, WrapSourcemap));\n\n \/\/ Body\n payloadObject.set(SerializeKey::Body, WrapSourcemap(payload.body));\n\n \/\/ Schema\n payloadObject.set(SerializeKey::Schema, WrapSourcemap(payload.schema));\n\n \/\/ Content\n sos::Array content;\n\n \/\/\/ Attributes\n if (!payload.attributes.empty()) {\n content.push(WrapDataStructureSourcemap(payload.attributes));\n }\n\n \/\/\/ Asset 'bodyExample'\n if (!payload.body.sourceMap.empty()) {\n content.push(WrapAssetSourcemap(payload.body));\n }\n\n \/\/\/ Asset 'bodySchema'\n if (!payload.schema.sourceMap.empty()) {\n content.push(WrapAssetSourcemap(payload.schema));\n }\n\n payloadObject.set(SerializeKey::Content, content);\n\n return payloadObject;\n}\n\nsos::Array WrapParametersSourcemap(const SourceMap& parameters)\n{\n sos::Array parametersArray;\n\n for (Collection >::const_iterator it = parameters.collection.begin();\n it != parameters.collection.end();\n ++it) {\n\n sos::Object parameter;\n\n \/\/ Name\n parameter.set(SerializeKey::Name, WrapSourcemap(it->name));\n\n \/\/ Description\n parameter.set(SerializeKey::Description, WrapSourcemap(it->description));\n\n \/\/ Type\n parameter.set(SerializeKey::Type, WrapSourcemap(it->type));\n\n \/\/ Use\n parameter.set(SerializeKey::Required, WrapSourcemap(it->use));\n\n \/\/ Example Value\n parameter.set(SerializeKey::Example, WrapSourcemap(it->exampleValue));\n\n \/\/ Default Value\n parameter.set(SerializeKey::Default, WrapSourcemap(it->defaultValue));\n\n \/\/ Values\n sos::Array values;\n\n for (Collection >::const_iterator valIt = it->values.collection.begin();\n valIt != it->values.collection.end();\n ++valIt) {\n\n sos::Object value;\n\n value.set(SerializeKey::Value, WrapSourcemap(*valIt));\n\n values.push(value);\n }\n\n parameter.set(SerializeKey::Values, values);\n }\n\n return parametersArray;\n}\n\nsos::Object WrapTransactionExampleSourcemap(const SourceMap& example)\n{\n sos::Object exampleObject;\n\n \/\/ Name\n exampleObject.set(SerializeKey::Name, WrapSourcemap(example.name));\n\n \/\/ Description\n exampleObject.set(SerializeKey::Description, WrapSourcemap(example.description));\n\n \/\/ Requests\n exampleObject.set(SerializeKey::Requests, \n WrapCollection()(example.requests.collection, WrapPayloadSourcemap));\n\n \/\/ Responses\n exampleObject.set(SerializeKey::Responses, \n WrapCollection()(example.responses.collection, WrapPayloadSourcemap));\n\n return exampleObject;\n}\n\nsos::Object WrapActionSourcemap(const SourceMap& action)\n{\n sos::Object actionObject;\n\n \/\/ Name\n actionObject.set(SerializeKey::Name, WrapSourcemap(action.name));\n\n \/\/ Description\n actionObject.set(SerializeKey::Description, WrapSourcemap(action.description));\n\n \/\/ HTTP Method\n actionObject.set(SerializeKey::Method, WrapSourcemap(action.method));\n\n \/\/ Parameters\n actionObject.set(SerializeKey::Parameters, WrapParametersSourcemap(action.parameters));\n\n \/\/ Transaction Examples\n actionObject.set(SerializeKey::Examples, \n WrapCollection()(action.examples.collection, WrapTransactionExampleSourcemap));\n\n \/\/ Content\n sos::Array content;\n\n \/\/\/ Attributes\n if (!action.attributes.empty()) {\n content.push(WrapDataStructureSourcemap(action.attributes));\n }\n\n actionObject.set(SerializeKey::Content, content);\n\n return actionObject;\n}\n\nsos::Object WrapResourceSourcemap(const SourceMap& resource)\n{\n sos::Object resourceObject;\n\n \/\/ Name\n resourceObject.set(SerializeKey::Name, WrapSourcemap(resource.name));\n\n \/\/ Description\n resourceObject.set(SerializeKey::Description, WrapSourcemap(resource.description));\n\n \/\/ URI Template\n resourceObject.set(SerializeKey::URITemplate, WrapSourcemap(resource.uriTemplate));\n\n \/\/ Model\n sos::Object model = (resource.model.name.sourceMap.empty() ? sos::Object() : WrapPayloadSourcemap(resource.model));\n resourceObject.set(SerializeKey::Model, model);\n\n \/\/ Parameters\n resourceObject.set(SerializeKey::Parameters, WrapParametersSourcemap(resource.parameters));\n\n \/\/ Actions\n resourceObject.set(SerializeKey::Actions, \n WrapCollection()(resource.actions.collection, WrapActionSourcemap));\n\n \/\/ Content\n sos::Array content;\n\n \/\/\/ Attributes\n if (!resource.attributes.empty()) {\n content.push(WrapDataStructureSourcemap(resource.attributes));\n }\n\n resourceObject.set(SerializeKey::Content, content);\n\n return resourceObject;\n}\n\nsos::Object WrapResourceGroupSourcemap(const SourceMap& resourceGroup)\n{\n sos::Object resourceGroupObject;\n\n \/\/ Name\n resourceGroupObject.set(SerializeKey::Name, WrapSourcemap(resourceGroup.attributes.name));\n\n \/\/ Description & Resources\n SourceMap description;\n sos::Array resources;\n\n for (Collection >::const_iterator it = resourceGroup.content.elements().collection.begin();\n it != resourceGroup.content.elements().collection.end();\n ++it) {\n\n if (it->element == Element::ResourceElement) {\n resources.push(WrapResourceSourcemap(it->content.resource));\n }\n else if (it->element == Element::CopyElement) {\n description.sourceMap.append(it->content.copy.sourceMap);\n }\n }\n\n resourceGroupObject.set(SerializeKey::Description, WrapSourcemap(description));\n resourceGroupObject.set(SerializeKey::Resources, resources);\n\n return resourceGroupObject;\n}\n\n\nsos::Object WrapDataStructureContent(const SourceMap& dataStructure)\n{\n sos::Object dataStructureObject;\n\n \/\/ Source\n dataStructureObject.set(SerializeKey::Source, WrapNamedTypeSourcemap(dataStructure));\n\n return dataStructureObject;\n}\n\nsos::Object WrapElementSourcemap(const SourceMap& element)\n{\n sos::Object elementObject;\n\n if (!element.attributes.name.sourceMap.empty()) {\n\n sos::Object attributes;\n\n attributes.set(SerializeKey::Name, WrapSourcemap(element.attributes.name));\n elementObject.set(SerializeKey::Attributes, attributes);\n }\n\n switch (element.element) {\n case Element::CopyElement:\n {\n elementObject.set(SerializeKey::Content, WrapSourcemap(element.content.copy));\n break;\n }\n\n case Element::DataStructureElement:\n {\n return WrapDataStructureSourcemap(element.content.dataStructure);\n }\n\n case Element::ResourceElement:\n {\n return WrapResourceSourcemap(element.content.resource);\n }\n\n case Element::CategoryElement:\n {\n elementObject.set(SerializeKey::Content, \n WrapCollection()(element.content.elements().collection, WrapElementSourcemap));\n break;\n }\n\n default:\n break;\n }\n\n return elementObject;\n}\n\nsos::Object drafter::WrapBlueprintSourcemap(const SourceMap& blueprint)\n{\n sos::Object blueprintObject;\n\n \/\/ Metadata\n blueprintObject.set(SerializeKey::Metadata, \n WrapCollection()(blueprint.metadata.collection, WrapSourcemap));\n\n \/\/ Name\n blueprintObject.set(SerializeKey::Name, WrapSourcemap(blueprint.name));\n\n \/\/ Description\n blueprintObject.set(SerializeKey::Description, WrapSourcemap(blueprint.description));\n\n \/\/ Resource Groups\n sos::Array resourceGroups;\n\n for (Collection >::const_iterator it = blueprint.content.elements().collection.begin();\n it != blueprint.content.elements().collection.end();\n ++it) {\n\n if (it->element == Element::CategoryElement &&\n it->category == Element::ResourceGroupCategory) {\n\n resourceGroups.push(WrapResourceGroupSourcemap(*it));\n }\n }\n\n blueprintObject.set(SerializeKey::ResourceGroups, resourceGroups);\n\n \/\/ Content\n blueprintObject.set(SerializeKey::Content, \n WrapCollection()(blueprint.content.elements().collection, WrapElementSourcemap));\n return blueprintObject;\n}\n* refactoring WrapTypeSectionsSourcemap\/\/\n\/\/ SerializeSourcemap.cc\n\/\/ drafter\n\/\/\n\/\/ Created by Pavan Kumar Sunkara on 18\/01\/15.\n\/\/ Copyright (c) 2015 Apiary Inc. All rights reserved.\n\/\/\n\n#include \"SerializeSourcemap.h\"\n\nusing namespace drafter;\n\nusing snowcrash::SourceMapBase;\nusing snowcrash::SourceMap;\nusing snowcrash::Collection;\n\nusing snowcrash::DataStructure;\nusing snowcrash::Asset;\nusing snowcrash::Payload;\nusing snowcrash::Header;\nusing snowcrash::Parameters;\nusing snowcrash::Parameter;\nusing snowcrash::Value;\nusing snowcrash::TransactionExample;\nusing snowcrash::Request;\nusing snowcrash::Response;\nusing snowcrash::Action;\nusing snowcrash::Resource;\nusing snowcrash::Element;\nusing snowcrash::Description;\nusing snowcrash::Blueprint;\nusing snowcrash::Metadata;\n\nsos::Array WrapSourcemap(const SourceMapBase& value)\n{\n sos::Array sourceMap;\n\n for (mdp::RangeSet::const_iterator it = value.sourceMap.begin();\n it != value.sourceMap.end();\n ++it) {\n\n sos::Array sourceMapRow;\n\n sourceMapRow.push(sos::Number(it->location));\n sourceMapRow.push(sos::Number(it->length));\n\n sourceMap.push(sourceMapRow);\n }\n\n return sourceMap;\n}\n\n\/\/ Forward declarations\nsos::Array WrapTypeSectionsSourcemap(const SourceMap& typeSections);\nsos::Array WrapElementsSourcemap(const SourceMap& elements);\n\nsos::Object WrapPropertyMemberSourcemap(const SourceMap& propertyMember)\n{\n sos::Object propertyMemberObject;\n\n \/\/ Name\n propertyMemberObject.set(SerializeKey::Name, WrapSourcemap(propertyMember.name));\n\n \/\/ Description\n propertyMemberObject.set(SerializeKey::Description, WrapSourcemap(propertyMember.description));\n\n \/\/ Value Definition\n propertyMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(propertyMember.valueDefinition));\n\n \/\/ Type Sections\n propertyMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(propertyMember.sections));\n\n return propertyMemberObject;\n}\n\nsos::Object WrapValueMemberSourcemap(const SourceMap& valueMember)\n{\n sos::Object valueMemberObject;\n\n \/\/ Description\n valueMemberObject.set(SerializeKey::Description, WrapSourcemap(valueMember.description));\n\n \/\/ Value Definition\n valueMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(valueMember.valueDefinition));\n\n \/\/ Type Sections\n valueMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(valueMember.sections));\n\n return valueMemberObject;\n}\n\nsos::Array WrapMixinSourcemap(const SourceMap& mixin)\n{\n return WrapSourcemap(mixin);\n}\n\nsos::Base WrapElementSourcemapBase(const SourceMap& element)\n{\n if (!element.elements().collection.empty()) {\n \/\/ Same for oneOf\n return WrapElementsSourcemap(element.elements()); \/\/ return sos::Array\n }\n else if (!element.mixin.sourceMap.empty()) {\n return WrapMixinSourcemap(element.mixin); \/\/ return sos::Array\n }\n else if (!element.value.empty()) {\n return WrapValueMemberSourcemap(element.value); \/\/ return sos::Object\n }\n else if (!element.property.empty()) {\n return WrapPropertyMemberSourcemap(element.property); \/\/ return sos::Object\n }\n\n return sos::Null(); \/\/ return sos::Null\n}\n\nsos::Array WrapElementsSourcemap(const SourceMap& elements)\n{\n return WrapCollection()(elements.collection, WrapElementSourcemapBase);\n}\n\nsos::Array WrapTypeSectionSourcemap(const SourceMap& section)\n{\n if (!section.description.sourceMap.empty()) {\n return WrapSourcemap(section.description);\n }\n else if (!section.value.sourceMap.empty()) {\n return WrapSourcemap(section.value);\n }\n else if (!section.elements().collection.empty()) {\n return WrapElementsSourcemap(section.elements());\n }\n}\n\nsos::Array WrapTypeSectionsSourcemap(const SourceMap& sections)\n{\n return WrapCollection()(sections.collection, WrapTypeSectionSourcemap);\n}\n\nsos::Object WrapNamedTypeSourcemap(const SourceMap& namedType)\n{\n sos::Object namedTypeObject;\n\n \/\/ Name\n namedTypeObject.set(SerializeKey::Name, WrapSourcemap(namedType.name));\n\n \/\/ Type Definition\n namedTypeObject.set(SerializeKey::TypeDefinition, WrapSourcemap(namedType.typeDefinition));\n\n \/\/ Type Sections\n namedTypeObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(namedType.sections));\n\n return namedTypeObject;\n}\n\nsos::Object WrapDataStructureSourcemap(const SourceMap& dataStructure)\n{\n sos::Object dataStructureObject;\n\n \/\/ Name\n dataStructureObject.set(SerializeKey::Name, WrapSourcemap(dataStructure.name));\n\n \/\/ Type Definition\n dataStructureObject.set(SerializeKey::TypeDefinition, WrapSourcemap(dataStructure.typeDefinition));\n\n \/\/ Type Sections\n dataStructureObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(dataStructure.sections));\n\n return dataStructureObject;\n}\n\nsos::Object WrapAssetSourcemap(const SourceMap& asset)\n{\n sos::Object assetObject;\n\n \/\/ Content\n assetObject.set(SerializeKey::Content, WrapSourcemap(asset));\n\n return assetObject;\n}\n\nsos::Object WrapPayloadSourcemap(const SourceMap& payload)\n{\n sos::Object payloadObject;\n\n \/\/ Reference\n if (!payload.reference.sourceMap.empty()) {\n payloadObject.set(SerializeKey::Reference, WrapSourcemap(payload.reference));\n }\n\n \/\/ Name\n payloadObject.set(SerializeKey::Name, WrapSourcemap(payload.name));\n\n \/\/ Description\n payloadObject.set(SerializeKey::Description, WrapSourcemap(payload.description));\n\n \/\/ Headers\n payloadObject.set(SerializeKey::Headers, \n WrapCollection
()(payload.headers.collection, WrapSourcemap));\n\n \/\/ Body\n payloadObject.set(SerializeKey::Body, WrapSourcemap(payload.body));\n\n \/\/ Schema\n payloadObject.set(SerializeKey::Schema, WrapSourcemap(payload.schema));\n\n \/\/ Content\n sos::Array content;\n\n \/\/\/ Attributes\n if (!payload.attributes.empty()) {\n content.push(WrapDataStructureSourcemap(payload.attributes));\n }\n\n \/\/\/ Asset 'bodyExample'\n if (!payload.body.sourceMap.empty()) {\n content.push(WrapAssetSourcemap(payload.body));\n }\n\n \/\/\/ Asset 'bodySchema'\n if (!payload.schema.sourceMap.empty()) {\n content.push(WrapAssetSourcemap(payload.schema));\n }\n\n payloadObject.set(SerializeKey::Content, content);\n\n return payloadObject;\n}\n\nsos::Array WrapParametersSourcemap(const SourceMap& parameters)\n{\n sos::Array parametersArray;\n\n for (Collection >::const_iterator it = parameters.collection.begin();\n it != parameters.collection.end();\n ++it) {\n\n sos::Object parameter;\n\n \/\/ Name\n parameter.set(SerializeKey::Name, WrapSourcemap(it->name));\n\n \/\/ Description\n parameter.set(SerializeKey::Description, WrapSourcemap(it->description));\n\n \/\/ Type\n parameter.set(SerializeKey::Type, WrapSourcemap(it->type));\n\n \/\/ Use\n parameter.set(SerializeKey::Required, WrapSourcemap(it->use));\n\n \/\/ Example Value\n parameter.set(SerializeKey::Example, WrapSourcemap(it->exampleValue));\n\n \/\/ Default Value\n parameter.set(SerializeKey::Default, WrapSourcemap(it->defaultValue));\n\n \/\/ Values\n sos::Array values;\n\n for (Collection >::const_iterator valIt = it->values.collection.begin();\n valIt != it->values.collection.end();\n ++valIt) {\n\n sos::Object value;\n\n value.set(SerializeKey::Value, WrapSourcemap(*valIt));\n\n values.push(value);\n }\n\n parameter.set(SerializeKey::Values, values);\n }\n\n return parametersArray;\n}\n\nsos::Object WrapTransactionExampleSourcemap(const SourceMap& example)\n{\n sos::Object exampleObject;\n\n \/\/ Name\n exampleObject.set(SerializeKey::Name, WrapSourcemap(example.name));\n\n \/\/ Description\n exampleObject.set(SerializeKey::Description, WrapSourcemap(example.description));\n\n \/\/ Requests\n exampleObject.set(SerializeKey::Requests, \n WrapCollection()(example.requests.collection, WrapPayloadSourcemap));\n\n \/\/ Responses\n exampleObject.set(SerializeKey::Responses, \n WrapCollection()(example.responses.collection, WrapPayloadSourcemap));\n\n return exampleObject;\n}\n\nsos::Object WrapActionSourcemap(const SourceMap& action)\n{\n sos::Object actionObject;\n\n \/\/ Name\n actionObject.set(SerializeKey::Name, WrapSourcemap(action.name));\n\n \/\/ Description\n actionObject.set(SerializeKey::Description, WrapSourcemap(action.description));\n\n \/\/ HTTP Method\n actionObject.set(SerializeKey::Method, WrapSourcemap(action.method));\n\n \/\/ Parameters\n actionObject.set(SerializeKey::Parameters, WrapParametersSourcemap(action.parameters));\n\n \/\/ Transaction Examples\n actionObject.set(SerializeKey::Examples, \n WrapCollection()(action.examples.collection, WrapTransactionExampleSourcemap));\n\n \/\/ Content\n sos::Array content;\n\n \/\/\/ Attributes\n if (!action.attributes.empty()) {\n content.push(WrapDataStructureSourcemap(action.attributes));\n }\n\n actionObject.set(SerializeKey::Content, content);\n\n return actionObject;\n}\n\nsos::Object WrapResourceSourcemap(const SourceMap& resource)\n{\n sos::Object resourceObject;\n\n \/\/ Name\n resourceObject.set(SerializeKey::Name, WrapSourcemap(resource.name));\n\n \/\/ Description\n resourceObject.set(SerializeKey::Description, WrapSourcemap(resource.description));\n\n \/\/ URI Template\n resourceObject.set(SerializeKey::URITemplate, WrapSourcemap(resource.uriTemplate));\n\n \/\/ Model\n sos::Object model = (resource.model.name.sourceMap.empty() ? sos::Object() : WrapPayloadSourcemap(resource.model));\n resourceObject.set(SerializeKey::Model, model);\n\n \/\/ Parameters\n resourceObject.set(SerializeKey::Parameters, WrapParametersSourcemap(resource.parameters));\n\n \/\/ Actions\n resourceObject.set(SerializeKey::Actions, \n WrapCollection()(resource.actions.collection, WrapActionSourcemap));\n\n \/\/ Content\n sos::Array content;\n\n \/\/\/ Attributes\n if (!resource.attributes.empty()) {\n content.push(WrapDataStructureSourcemap(resource.attributes));\n }\n\n resourceObject.set(SerializeKey::Content, content);\n\n return resourceObject;\n}\n\nsos::Object WrapResourceGroupSourcemap(const SourceMap& resourceGroup)\n{\n sos::Object resourceGroupObject;\n\n \/\/ Name\n resourceGroupObject.set(SerializeKey::Name, WrapSourcemap(resourceGroup.attributes.name));\n\n \/\/ Description & Resources\n SourceMap description;\n sos::Array resources;\n\n for (Collection >::const_iterator it = resourceGroup.content.elements().collection.begin();\n it != resourceGroup.content.elements().collection.end();\n ++it) {\n\n if (it->element == Element::ResourceElement) {\n resources.push(WrapResourceSourcemap(it->content.resource));\n }\n else if (it->element == Element::CopyElement) {\n description.sourceMap.append(it->content.copy.sourceMap);\n }\n }\n\n resourceGroupObject.set(SerializeKey::Description, WrapSourcemap(description));\n resourceGroupObject.set(SerializeKey::Resources, resources);\n\n return resourceGroupObject;\n}\n\n\nsos::Object WrapDataStructureContent(const SourceMap& dataStructure)\n{\n sos::Object dataStructureObject;\n\n \/\/ Source\n dataStructureObject.set(SerializeKey::Source, WrapNamedTypeSourcemap(dataStructure));\n\n return dataStructureObject;\n}\n\nsos::Object WrapElementSourcemap(const SourceMap& element)\n{\n sos::Object elementObject;\n\n if (!element.attributes.name.sourceMap.empty()) {\n\n sos::Object attributes;\n\n attributes.set(SerializeKey::Name, WrapSourcemap(element.attributes.name));\n elementObject.set(SerializeKey::Attributes, attributes);\n }\n\n switch (element.element) {\n case Element::CopyElement:\n {\n elementObject.set(SerializeKey::Content, WrapSourcemap(element.content.copy));\n break;\n }\n\n case Element::DataStructureElement:\n {\n return WrapDataStructureSourcemap(element.content.dataStructure);\n }\n\n case Element::ResourceElement:\n {\n return WrapResourceSourcemap(element.content.resource);\n }\n\n case Element::CategoryElement:\n {\n elementObject.set(SerializeKey::Content, \n WrapCollection()(element.content.elements().collection, WrapElementSourcemap));\n break;\n }\n\n default:\n break;\n }\n\n return elementObject;\n}\n\nsos::Object drafter::WrapBlueprintSourcemap(const SourceMap& blueprint)\n{\n sos::Object blueprintObject;\n\n \/\/ Metadata\n blueprintObject.set(SerializeKey::Metadata, \n WrapCollection()(blueprint.metadata.collection, WrapSourcemap));\n\n \/\/ Name\n blueprintObject.set(SerializeKey::Name, WrapSourcemap(blueprint.name));\n\n \/\/ Description\n blueprintObject.set(SerializeKey::Description, WrapSourcemap(blueprint.description));\n\n \/\/ Resource Groups\n sos::Array resourceGroups;\n\n for (Collection >::const_iterator it = blueprint.content.elements().collection.begin();\n it != blueprint.content.elements().collection.end();\n ++it) {\n\n if (it->element == Element::CategoryElement &&\n it->category == Element::ResourceGroupCategory) {\n\n resourceGroups.push(WrapResourceGroupSourcemap(*it));\n }\n }\n\n blueprintObject.set(SerializeKey::ResourceGroups, resourceGroups);\n\n \/\/ Content\n blueprintObject.set(SerializeKey::Content, \n WrapCollection()(blueprint.content.elements().collection, WrapElementSourcemap));\n return blueprintObject;\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep15\/host_establish_ex_chiplet.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/From Hostboot Directory\n\/\/\/\/Error handling and traces\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/HWP Invoker\n#include \n\n\/\/Targeting Support\n#include \n#include \n\n\/\/From Import Directory (EKB Repository)\n#include \n\n\/\/Namespaces\nusing namespace ERRORLOG;\nusing namespace TARGETING;\nusing namespace fapi2;\n\nnamespace ISTEP_15\n{\nvoid* host_establish_ex_chiplet (void *io_pArgs)\n{\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"host_establish_ex_chiplet entry\" );\n ISTEP_ERROR::IStepError l_StepError;\n errlHndl_t l_errl = NULL;\n do {\n \/\/Use targeting code to get a list of all processors\n TARGETING::TargetHandleList l_procChips;\n getAllChips( l_procChips, TARGETING::TYPE_PROC );\n\n for (const auto & l_procChip: l_procChips)\n {\n const fapi2::Target\n l_fapi_cpu_target(l_procChip);\n \/\/ call p9_update_ec_eq_state.C HWP\n FAPI_INVOKE_HWP( l_errl,\n p9_update_ec_eq_state,\n l_fapi_cpu_target);\n\n if(l_errl)\n {\n ErrlUserDetailsTarget(l_procChip).addToLog(l_errl);\n l_StepError.addErrorDetails( l_errl );\n errlCommit( l_errl, HWPF_COMP_ID );\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"host_establish_ex_chiplet:: failed on proc with HUID : %d\",TARGETING::get_huid(l_procChip) );\n }\n }\n }while(0);\n\n \/\/ end task, returning any errorlogs to IStepDisp\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"host_establish_ex_chiplet exit\" );\n return l_StepError.getErrorHandle();\n}\n};\nSkip establish ex chiplet step (15.3) during Axone for now\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep15\/host_establish_ex_chiplet.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/From Hostboot Directory\n\/\/\/\/Error handling and traces\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/HWP Invoker\n#include \n\n\/\/Targeting Support\n#include \n#include \n\n\/\/From Import Directory (EKB Repository)\n#include \n\n\/\/Namespaces\nusing namespace ERRORLOG;\nusing namespace TARGETING;\nusing namespace fapi2;\n\nnamespace ISTEP_15\n{\nvoid* host_establish_ex_chiplet (void *io_pArgs)\n{\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"host_establish_ex_chiplet entry\" );\n ISTEP_ERROR::IStepError l_StepError;\n #ifndef CONFIG_AXONE_BRING_UP\n errlHndl_t l_errl = NULL;\n do {\n \/\/Use targeting code to get a list of all processors\n TARGETING::TargetHandleList l_procChips;\n getAllChips( l_procChips, TARGETING::TYPE_PROC );\n\n for (const auto & l_procChip: l_procChips)\n {\n const fapi2::Target\n l_fapi_cpu_target(l_procChip);\n \/\/ call p9_update_ec_eq_state.C HWP\n FAPI_INVOKE_HWP( l_errl,\n p9_update_ec_eq_state,\n l_fapi_cpu_target);\n\n if(l_errl)\n {\n ErrlUserDetailsTarget(l_procChip).addToLog(l_errl);\n l_StepError.addErrorDetails( l_errl );\n errlCommit( l_errl, HWPF_COMP_ID );\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"host_establish_ex_chiplet:: failed on proc with HUID : %d\",TARGETING::get_huid(l_procChip) );\n }\n }\n }while(0);\n #endif\n\n \/\/ end task, returning any errorlogs to IStepDisp\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"host_establish_ex_chiplet exit\" );\n return l_StepError.getErrorHandle();\n}\n};\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \"rev.hpp\"\n\nint main(int, char*[])\n{\n for (auto& i: gnr::rev({1, 2, 3, 4}))\n {\n std::cout << i << std::endl;\n }\n\n auto r(std::vector{1, 2, 3, 4});\n\n for (auto& i: gnr::rev(r))\n {\n std::cout << i << std::endl;\n i = 0;\n }\n}\nsome fixes#include \n\n#include \n\n#include \"rev.hpp\"\n\nint main(int, char*[])\n{\n for (auto& i: gnr::rev({1, 2, 3, 4}))\n {\n std::cout << i << std::endl;\n }\n\n std::vector r{1, 2, 3, 4};\n\n for (auto& i: gnr::rev(r))\n {\n std::cout << i << std::endl;\n i = 0;\n }\n}\n<|endoftext|>"} {"text":"#ifndef GENERIC_REV_HPP\n# define GENERIC_REV_HPP\n# pragma once\n\n#include \n\n#include \n\nnamespace gnr\n{\n\nnamespace detail\n{\n\ntemplate \nclass rev_impl\n{\n T ref_;\n\npublic:\n explicit rev_impl(T&& r) noexcept(noexcept(T(std::forward(r)))) :\n ref_(std::forward(r))\n {\n };\n\n auto begin() noexcept(noexcept(std::rbegin(ref_)))\n {\n return std::rbegin(ref_);\n }\n\n auto end() noexcept(noexcept(std::rend(ref_)))\n {\n return std::rend(ref_);\n }\n};\n\n}\n\ntemplate \nauto rev(T&& r) noexcept(noexcept(detail::rev_impl(std::forward(r))))\n{\n return detail::rev_impl(std::forward(r));\n}\n\n}\n\n#endif \/\/ GENERIC_REV_HPP\nsome fixes#ifndef GENERIC_REV_HPP\n# define GENERIC_REV_HPP\n# pragma once\n\n#include \n\n#include \n\nnamespace gnr\n{\n\nnamespace detail\n{\n\ntemplate \nclass rev_impl\n{\n T ref_;\n\npublic:\n explicit rev_impl(T&& r) noexcept(noexcept(T(std::forward(r)))) :\n ref_(std::forward(r))\n {\n }\n\n auto begin() noexcept(noexcept(std::rbegin(ref_)))\n {\n return std::rbegin(ref_);\n }\n\n auto end() noexcept(noexcept(std::rend(ref_)))\n {\n return std::rend(ref_);\n }\n};\n\n}\n\ntemplate \nauto rev(T&& r) noexcept(noexcept(detail::rev_impl(std::forward(r))))\n{\n return detail::rev_impl(std::forward(r));\n}\n\n}\n\n#endif \/\/ GENERIC_REV_HPP\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Debug\/Demangle.h\"\n#include \"..\/Execution\/Exceptions.h\"\n\n#include \"String_Constant.h\"\n\n#include \"ToString.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\n\n\/*\n ********************************************************************************\n ************************************* ToString *********************************\n ********************************************************************************\n *\/\nnamespace Stroika::Foundation::Characters {\n template <>\n String ToString (const exception_ptr& e)\n {\n static const String kExceptPefix_{L\"Exception: \"sv};\n static const String kUnknown_{L\"Unknown Exception\"sv};\n try {\n rethrow_exception (e);\n }\n catch (const Execution::ExceptionStringHelper& e) {\n \/\/saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.\n \/\/return kExceptPefix_ + e.As ();\n return e.As ();\n }\n catch (const exception& e) {\n return kExceptPefix_ + String::FromNarrowSDKString (e.what ());\n }\n catch (...) {\n \/\/ fall through\n }\n return kUnknown_;\n }\n template <>\n String ToString (const type_info& t)\n {\n \/\/nb: demangle needed for gcc, but not msvc (but harmless there)\n return Debug::Demangle (String::FromNarrowSDKString (t.name ()));\n }\n template <>\n String ToString (const type_index& t)\n {\n \/\/nb: demangle needed for gcc, but not msvc (but harmless there)\n return Debug::Demangle (String::FromNarrowSDKString (t.name ()));\n }\n\n String ToString (const char* t)\n {\n \/\/ No way to know the 'right' characterset in this case, but as this is mostly used for debugging, no biggie. The caller\n \/\/ can be more careful if he cares about charset. This should be safe, and mostly helpful\n return String::FromISOLatin1 (t);\n }\n\n template <>\n String ToString (const bool& t)\n {\n static const String kTrue_{L\"true\"sv};\n static const String kFalse{L\"false\"sv};\n return t ? kTrue_ : kFalse;\n }\n\n namespace {\n template \n inline String num2Str_ (T t, std::ios_base::fmtflags flags)\n {\n static_assert (sizeof (t) <= sizeof (int));\n wchar_t buf[1024];\n switch (flags) {\n case std::ios_base::dec:\n (void)::swprintf (buf, NEltsOf (buf), L\"%d\", t);\n break;\n case std::ios_base::hex:\n (void)::swprintf (buf, NEltsOf (buf), L\"0x%x\", t);\n break;\n default:\n AssertNotReached (); \/\/ @todo support octal\n }\n return buf;\n }\n template \n inline String num2Strl_ (T t, std::ios_base::fmtflags flags)\n {\n wchar_t buf[1024];\n static_assert (sizeof (t) == sizeof (long int));\n switch (flags) {\n case std::ios_base::dec:\n (void)::swprintf (buf, NEltsOf (buf), L\"%ld\", t);\n break;\n case std::ios_base::hex:\n (void)::swprintf (buf, NEltsOf (buf), L\"0x%lx\", t);\n break;\n default:\n AssertNotReached (); \/\/ @todo support octal\n }\n return buf;\n }\n template \n inline String num2Strll_ (T t, std::ios_base::fmtflags flags)\n {\n wchar_t buf[1024];\n static_assert (sizeof (t) == sizeof (long long int));\n switch (flags) {\n case std::ios_base::dec:\n (void)::swprintf (buf, NEltsOf (buf), L\"%lld\", t);\n break;\n case std::ios_base::hex:\n (void)::swprintf (buf, NEltsOf (buf), L\"0x%llx\", t);\n break;\n default:\n AssertNotReached (); \/\/ @todo support octal\n }\n return buf;\n }\n }\n\n template <>\n String ToString (const signed char t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const short int t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const int t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const long int t, std::ios_base::fmtflags flags)\n {\n return num2Strl_ (t, flags);\n }\n template <>\n String ToString (const long long int t, std::ios_base::fmtflags flags)\n {\n return num2Strll_ (t, flags);\n }\n template <>\n String ToString (const unsigned char t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const unsigned short t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const unsigned int t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const unsigned long t, std::ios_base::fmtflags flags)\n {\n return num2Strl_ (t, flags);\n }\n template <>\n String ToString (const unsigned long long t, std::ios_base::fmtflags flags)\n {\n return num2Strll_ (t, flags);\n }\n\n namespace Private_ {\n String ToString_ex_ (const std::exception& t)\n {\n if (auto p = dynamic_cast (&t)) {\n return p->As ();\n }\n \/\/saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.\n \/\/return String_Constant {L\"Exception: \" } + String::FromNarrowSDKString (t.what ()) + String_Constant {L\"}\" };\n return String::FromNarrowSDKString (t.what ());\n }\n }\n}\nToString (integer-like-type) support for std::ios_base::oct argument\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Debug\/Demangle.h\"\n#include \"..\/Execution\/Exceptions.h\"\n\n#include \"String_Constant.h\"\n\n#include \"ToString.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\n\n\/*\n ********************************************************************************\n ************************************* ToString *********************************\n ********************************************************************************\n *\/\nnamespace Stroika::Foundation::Characters {\n template <>\n String ToString (const exception_ptr& e)\n {\n static const String kExceptPefix_{L\"Exception: \"sv};\n static const String kUnknown_{L\"Unknown Exception\"sv};\n try {\n rethrow_exception (e);\n }\n catch (const Execution::ExceptionStringHelper& e) {\n \/\/saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.\n \/\/return kExceptPefix_ + e.As ();\n return e.As ();\n }\n catch (const exception& e) {\n return kExceptPefix_ + String::FromNarrowSDKString (e.what ());\n }\n catch (...) {\n \/\/ fall through\n }\n return kUnknown_;\n }\n template <>\n String ToString (const type_info& t)\n {\n \/\/nb: demangle needed for gcc, but not msvc (but harmless there)\n return Debug::Demangle (String::FromNarrowSDKString (t.name ()));\n }\n template <>\n String ToString (const type_index& t)\n {\n \/\/nb: demangle needed for gcc, but not msvc (but harmless there)\n return Debug::Demangle (String::FromNarrowSDKString (t.name ()));\n }\n\n String ToString (const char* t)\n {\n \/\/ No way to know the 'right' characterset in this case, but as this is mostly used for debugging, no biggie. The caller\n \/\/ can be more careful if he cares about charset. This should be safe, and mostly helpful\n return String::FromISOLatin1 (t);\n }\n\n template <>\n String ToString (const bool& t)\n {\n static const String kTrue_{L\"true\"sv};\n static const String kFalse{L\"false\"sv};\n return t ? kTrue_ : kFalse;\n }\n\n namespace {\n template \n inline String num2Str_ (T t, std::ios_base::fmtflags flags)\n {\n static_assert (sizeof (t) <= sizeof (int));\n wchar_t buf[1024];\n switch (flags) {\n case std::ios_base::oct:\n (void)::swprintf (buf, NEltsOf (buf), L\"%o\", t);\n break;\n case std::ios_base::dec:\n (void)::swprintf (buf, NEltsOf (buf), L\"%d\", t);\n break;\n case std::ios_base::hex:\n (void)::swprintf (buf, NEltsOf (buf), L\"0x%x\", t);\n break;\n default:\n AssertNotReached (); \/\/ @todo support octal\n }\n return buf;\n }\n template \n inline String num2Strl_ (T t, std::ios_base::fmtflags flags)\n {\n wchar_t buf[1024];\n static_assert (sizeof (t) == sizeof (long int));\n switch (flags) {\n case std::ios_base::oct:\n (void)::swprintf (buf, NEltsOf (buf), L\"%lo\", t);\n break;\n case std::ios_base::dec:\n (void)::swprintf (buf, NEltsOf (buf), L\"%ld\", t);\n break;\n case std::ios_base::hex:\n (void)::swprintf (buf, NEltsOf (buf), L\"0x%lx\", t);\n break;\n default:\n AssertNotReached (); \/\/ @todo support octal\n }\n return buf;\n }\n template \n inline String num2Strll_ (T t, std::ios_base::fmtflags flags)\n {\n wchar_t buf[1024];\n static_assert (sizeof (t) == sizeof (long long int));\n switch (flags) {\n case std::ios_base::oct:\n (void)::swprintf (buf, NEltsOf (buf), L\"%llo\", t);\n break;\n case std::ios_base::dec:\n (void)::swprintf (buf, NEltsOf (buf), L\"%lld\", t);\n break;\n case std::ios_base::hex:\n (void)::swprintf (buf, NEltsOf (buf), L\"0x%llx\", t);\n break;\n default:\n AssertNotReached (); \/\/ @todo support octal\n }\n return buf;\n }\n }\n\n template <>\n String ToString (const signed char t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const short int t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const int t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const long int t, std::ios_base::fmtflags flags)\n {\n return num2Strl_ (t, flags);\n }\n template <>\n String ToString (const long long int t, std::ios_base::fmtflags flags)\n {\n return num2Strll_ (t, flags);\n }\n template <>\n String ToString (const unsigned char t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const unsigned short t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const unsigned int t, std::ios_base::fmtflags flags)\n {\n return num2Str_ (t, flags);\n }\n template <>\n String ToString (const unsigned long t, std::ios_base::fmtflags flags)\n {\n return num2Strl_ (t, flags);\n }\n template <>\n String ToString (const unsigned long long t, std::ios_base::fmtflags flags)\n {\n return num2Strll_ (t, flags);\n }\n\n namespace Private_ {\n String ToString_ex_ (const std::exception& t)\n {\n if (auto p = dynamic_cast (&t)) {\n return p->As ();\n }\n \/\/saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.\n \/\/return String_Constant {L\"Exception: \" } + String::FromNarrowSDKString (t.what ()) + String_Constant {L\"}\" };\n return String::FromNarrowSDKString (t.what ());\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n Q Light Controller\n efxpreviewarea.cpp\n\n Copyright (c) Heikki Junnila\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.txt\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 \n#include \n#include \n#include \n\n#include \"efxpreviewarea.h\"\n#include \"qlcmacros.h\"\n#include \"gradient.h\"\n\nEFXPreviewArea::EFXPreviewArea(QWidget* parent)\n : QWidget(parent)\n , m_timer(this)\n , m_iter(0)\n , m_gradientBg(false)\n , m_bgAlpha(255)\n{\n QPalette p = palette();\n p.setColor(QPalette::Window, p.color(QPalette::Base));\n setPalette(p);\n\n connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));\n}\n\nEFXPreviewArea::~EFXPreviewArea()\n{\n}\n\nvoid EFXPreviewArea::setPolygon(const QPolygonF& polygon)\n{\n m_original = polygon;\n m_scaled = scale(m_original, size());\n}\n\nint EFXPreviewArea::polygonsCount() const\n{\n return m_original.size();\n}\n\nvoid EFXPreviewArea::setFixturePolygons(const QVector &fixturePoints)\n{\n m_originalFixturePoints.resize(fixturePoints.size());\n m_fixturePoints.resize(fixturePoints.size());\n\n for(int i = 0; i < m_fixturePoints.size(); ++i)\n {\n m_originalFixturePoints[i] = QPolygonF(fixturePoints[i]);\n m_fixturePoints[i] = scale(m_originalFixturePoints[i], size());\n }\n}\n\nvoid EFXPreviewArea::draw(int timerInterval)\n{\n m_timer.stop();\n\n m_iter = 0;\n m_timer.start(timerInterval);\n}\n\nvoid EFXPreviewArea::slotTimeout()\n{\n repaint();\n}\n\nQPolygonF EFXPreviewArea::scale(const QPolygonF& poly, const QSize& target)\n{\n QPolygonF scaled;\n for (int i = 0; i < poly.size(); i++)\n {\n QPointF pt = poly.at(i);\n pt.setX((int) SCALE(qreal(pt.x()), qreal(0), qreal(255), qreal(0), qreal(target.width())));\n pt.setY((int) SCALE(qreal(pt.y()), qreal(0), qreal(255), qreal(0), qreal(target.height())));\n scaled << pt;\n }\n\n return scaled;\n}\n\nvoid EFXPreviewArea::resizeEvent(QResizeEvent* e)\n{\n m_scaled = scale(m_original, e->size());\n\n for (int i = 0; i < m_fixturePoints.size(); ++i)\n m_fixturePoints[i] = scale(m_originalFixturePoints[i], e->size());\n\n QWidget::resizeEvent(e);\n}\n\nvoid EFXPreviewArea::paintEvent(QPaintEvent* e)\n{\n QWidget::paintEvent(e);\n\n QPainter painter(this);\n QPen pen;\n QPointF point;\n QColor color = Qt::white;\n\n if (m_gradientBg)\n painter.drawImage(painter.window(), Gradient::getRGBGradient(256, 256));\n else\n {\n color.setAlpha(m_bgAlpha);\n painter.fillRect(rect(), color);\n }\n\n \/* Crosshairs *\/\n color = palette().color(QPalette::Mid);\n painter.setPen(color);\n \/\/ Do division by two instead with a bitshift to prevent rounding\n painter.drawLine(width() >> 1, 0, width() >> 1, height());\n painter.drawLine(0, height() >> 1, width(), height() >> 1);\n\n if (m_iter < m_scaled.size())\n m_iter++;\n\n \/* Plain points with text color *\/\n color = palette().color(QPalette::Text);\n pen.setColor(color);\n painter.setPen(pen);\n painter.drawPolygon(m_scaled);\n\n \/\/ Draw the points from the point array\n if (m_iter < m_scaled.size() && m_iter >= 0)\n {\n \/*\n \/\/ draw origin\n color = color.lighter(100 + (m_points.size() \/ 100));\n pen.setColor(color);\n painter.setPen(pen);\n point = m_points.point(m_iter);\n painter.drawEllipse(point.x() - 4, point.y() - 4, 8, 8);\n *\/\n\n painter.setBrush(Qt::white);\n pen.setColor(Qt::black);\n\n \/\/ draw fixture positions\n\n \/\/ drawing from the end -- so that lower numbers are on top\n for (int i = m_fixturePoints.size() - 1; i >= 0; --i)\n {\n point = m_fixturePoints.at(i).at(m_iter);\n painter.drawEllipse(point, 8, 8);\n painter.drawText(point.x() - 4, point.y() + 5, QString::number(i+1));\n }\n }\n else\n {\n \/\/m_timer.stop();\n\n \/\/Change old behaviour from stop to restart\n restart();\n }\n}\n\nvoid EFXPreviewArea::restart ()\n{\n m_iter = 0;\n}\n\nvoid EFXPreviewArea::showGradientBackground(bool enable)\n{\n m_gradientBg = enable;\n repaint();\n}\n\nvoid EFXPreviewArea::setBackgroundAlpha(int alpha)\n{\n m_bgAlpha = alpha;\n}\nui: fixed EFX preview area not respecting the requested speed\/*\n Q Light Controller\n efxpreviewarea.cpp\n\n Copyright (c) Heikki Junnila\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.txt\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 \n#include \n#include \n#include \n\n#include \"efxpreviewarea.h\"\n#include \"qlcmacros.h\"\n#include \"gradient.h\"\n\nEFXPreviewArea::EFXPreviewArea(QWidget* parent)\n : QWidget(parent)\n , m_timer(this)\n , m_iter(0)\n , m_gradientBg(false)\n , m_bgAlpha(255)\n{\n QPalette p = palette();\n p.setColor(QPalette::Window, p.color(QPalette::Base));\n setPalette(p);\n\n connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));\n}\n\nEFXPreviewArea::~EFXPreviewArea()\n{\n}\n\nvoid EFXPreviewArea::setPolygon(const QPolygonF& polygon)\n{\n m_original = polygon;\n m_scaled = scale(m_original, size());\n}\n\nint EFXPreviewArea::polygonsCount() const\n{\n return m_original.size();\n}\n\nvoid EFXPreviewArea::setFixturePolygons(const QVector &fixturePoints)\n{\n m_originalFixturePoints.resize(fixturePoints.size());\n m_fixturePoints.resize(fixturePoints.size());\n\n for(int i = 0; i < m_fixturePoints.size(); ++i)\n {\n m_originalFixturePoints[i] = QPolygonF(fixturePoints[i]);\n m_fixturePoints[i] = scale(m_originalFixturePoints[i], size());\n }\n}\n\nvoid EFXPreviewArea::draw(int timerInterval)\n{\n m_timer.stop();\n\n m_iter = 0;\n m_timer.start(timerInterval);\n}\n\nvoid EFXPreviewArea::slotTimeout()\n{\n if (m_iter < m_scaled.size())\n m_iter++;\n\n repaint();\n}\n\nQPolygonF EFXPreviewArea::scale(const QPolygonF& poly, const QSize& target)\n{\n QPolygonF scaled;\n for (int i = 0; i < poly.size(); i++)\n {\n QPointF pt = poly.at(i);\n pt.setX((int) SCALE(qreal(pt.x()), qreal(0), qreal(255), qreal(0), qreal(target.width())));\n pt.setY((int) SCALE(qreal(pt.y()), qreal(0), qreal(255), qreal(0), qreal(target.height())));\n scaled << pt;\n }\n\n return scaled;\n}\n\nvoid EFXPreviewArea::resizeEvent(QResizeEvent* e)\n{\n m_scaled = scale(m_original, e->size());\n\n for (int i = 0; i < m_fixturePoints.size(); ++i)\n m_fixturePoints[i] = scale(m_originalFixturePoints[i], e->size());\n\n QWidget::resizeEvent(e);\n}\n\nvoid EFXPreviewArea::paintEvent(QPaintEvent* e)\n{\n QWidget::paintEvent(e);\n\n QPainter painter(this);\n QPen pen;\n QPointF point;\n QColor color = Qt::white;\n\n if (m_gradientBg)\n painter.drawImage(painter.window(), Gradient::getRGBGradient(256, 256));\n else\n {\n color.setAlpha(m_bgAlpha);\n painter.fillRect(rect(), color);\n }\n\n \/* Crosshairs *\/\n color = palette().color(QPalette::Mid);\n painter.setPen(color);\n \/\/ Do division by two instead with a bitshift to prevent rounding\n painter.drawLine(width() >> 1, 0, width() >> 1, height());\n painter.drawLine(0, height() >> 1, width(), height() >> 1);\n\n \/* Plain points with text color *\/\n color = palette().color(QPalette::Text);\n pen.setColor(color);\n painter.setPen(pen);\n painter.drawPolygon(m_scaled);\n\n \/\/ Draw the points from the point array\n if (m_iter < m_scaled.size() && m_iter >= 0)\n {\n painter.setBrush(Qt::white);\n pen.setColor(Qt::black);\n\n \/\/ drawing fixture positions from the end,\n \/\/ so that lower numbers are on top\n for (int i = m_fixturePoints.size() - 1; i >= 0; --i)\n {\n point = m_fixturePoints.at(i).at(m_iter);\n painter.drawEllipse(point, 8, 8);\n painter.drawText(point.x() - 4, point.y() + 5, QString::number(i+1));\n }\n }\n else\n {\n \/\/Change old behaviour from stop to restart\n restart();\n }\n}\n\nvoid EFXPreviewArea::restart()\n{\n m_iter = 0;\n}\n\nvoid EFXPreviewArea::showGradientBackground(bool enable)\n{\n m_gradientBg = enable;\n repaint();\n}\n\nvoid EFXPreviewArea::setBackgroundAlpha(int alpha)\n{\n m_bgAlpha = alpha;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \n#include \"AudioDevice.hpp\"\n#include \"math\/MathUtils.hpp\"\n\nnamespace ouzel\n{\n namespace audio\n {\n AudioDevice::AudioDevice(Audio::Driver aDriver):\n driver(aDriver)\n {\n }\n\n AudioDevice::~AudioDevice()\n {\n }\n\n bool AudioDevice::init(bool)\n {\n return true;\n }\n\n bool AudioDevice::process()\n {\n executeAll();\n\n return true;\n }\n\n void AudioDevice::setRenderCommands(const std::vector& newRenderCommands)\n {\n std::lock_guard renderQueueLock(renderQueueMutex);\n\n renderQueue = newRenderCommands;\n }\n\n bool AudioDevice::processRenderCommands(uint32_t frames, std::vector& result)\n {\n std::vector renderCommands;\n\n {\n std::lock_guard renderQueueLock(renderQueueMutex);\n\n renderCommands = renderQueue;\n }\n\n uint32_t buffer = currentBuffer++;\n if (currentBuffer > buffers.size()) buffers.resize(currentBuffer);\n\n for (const RenderCommand& renderCommand : renderCommands)\n {\n if (!processRenderCommand(renderCommand,\n frames,\n Vector3(), \/\/ listener position\n Quaternion(), \/\/ listener rotation\n 1.0f, \/\/ pitch\n 1.0f, \/\/ gain\n 1.0f, \/\/ rolloff factor\n buffers[buffer])) return false;\n\n if (buffers[buffer].size() > buffers[buffer].size()) result.resize(buffers[buffer].size(), 0.0f);\n\n for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)\n {\n \/\/ mix the sound into the buffer\n result[i] += buffers[buffer][i];\n }\n }\n\n return true;\n }\n\n bool AudioDevice::processRenderCommand(const RenderCommand& renderCommand,\n uint32_t frames,\n Vector3 listenerPosition,\n Quaternion listenerRotation,\n float pitch,\n float gain,\n float rolloffFactor,\n std::vector& result)\n {\n uint32_t buffer = currentBuffer++;\n if (currentBuffer > buffers.size()) buffers.resize(currentBuffer);\n\n if (renderCommand.attributeCallback)\n {\n renderCommand.attributeCallback(listenerPosition,\n listenerRotation,\n pitch,\n gain,\n rolloffFactor);\n }\n\n for (const RenderCommand& command : renderCommand.renderCommands)\n {\n processRenderCommand(command,\n frames,\n listenerPosition,\n listenerRotation,\n pitch,\n gain,\n rolloffFactor,\n buffers[buffer]);\n\n if (buffers[buffer].size() > result.size()) result.resize(buffers[buffer].size(), 0.0f);\n\n for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)\n {\n \/\/ mix the sound into the buffer\n result[i] += buffers[buffer][i];\n }\n }\n\n if (renderCommand.renderCallback)\n {\n if (!renderCommand.renderCallback(frames,\n channels,\n sampleRate,\n listenerPosition,\n listenerRotation,\n pitch,\n gain,\n rolloffFactor,\n result)) return false;\n }\n\n return true;\n }\n\n bool AudioDevice::getData(uint32_t frames, std::vector& result)\n {\n currentBuffer = 0;\n uint32_t buffer = currentBuffer++;\n if (currentBuffer > buffers.size()) buffers.resize(currentBuffer);\n\n buffers[buffer].resize(frames * channels);\n std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);\n\n if (!processRenderCommands(frames, buffers[buffer])) return false;\n\n for (float& f : buffers[buffer])\n {\n f = clamp(f, -1.0f, 1.0f);\n }\n\n switch (format)\n {\n case Audio::Format::SINT16:\n {\n result.resize(frames * channels * sizeof(int16_t));\n int16_t* resultPtr = reinterpret_cast(result.data());\n\n for (uint32_t i = 0; i < buffers[buffer].size(); ++i)\n {\n *resultPtr = static_cast(buffers[buffer][i] * 32767.0f);\n ++resultPtr;\n }\n break;\n }\n case Audio::Format::FLOAT32:\n {\n result.reserve(frames * channels * sizeof(float));\n result.assign(reinterpret_cast(buffers[buffer].data()),\n reinterpret_cast(buffers[buffer].data()) + buffers[buffer].size() * sizeof(float));\n break;\n }\n }\n\n return true;\n }\n\n void AudioDevice::executeOnAudioThread(const std::function& func)\n {\n std::lock_guard lock(executeMutex);\n\n executeQueue.push(func);\n }\n\n void AudioDevice::executeAll()\n {\n std::function func;\n\n for (;;)\n {\n {\n std::lock_guard lock(executeMutex);\n\n if (executeQueue.empty())\n {\n break;\n }\n \n func = std::move(executeQueue.front());\n executeQueue.pop();\n }\n \n if (func)\n {\n func();\n }\n }\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\nno message\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \n#include \"AudioDevice.hpp\"\n#include \"math\/MathUtils.hpp\"\n\nnamespace ouzel\n{\n namespace audio\n {\n AudioDevice::AudioDevice(Audio::Driver aDriver):\n driver(aDriver)\n {\n buffers.resize(1000);\n }\n\n AudioDevice::~AudioDevice()\n {\n }\n\n bool AudioDevice::init(bool)\n {\n return true;\n }\n\n bool AudioDevice::process()\n {\n executeAll();\n\n return true;\n }\n\n void AudioDevice::setRenderCommands(const std::vector& newRenderCommands)\n {\n std::lock_guard renderQueueLock(renderQueueMutex);\n\n renderQueue = newRenderCommands;\n }\n\n bool AudioDevice::processRenderCommands(uint32_t frames, std::vector& result)\n {\n std::vector renderCommands;\n\n {\n std::lock_guard renderQueueLock(renderQueueMutex);\n\n renderCommands = renderQueue;\n }\n\n uint32_t buffer = currentBuffer++;\n if (currentBuffer > buffers.size()) return true; \/\/ out of buffers\n\n buffers[buffer].resize(frames * channels);\n std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);\n\n for (const RenderCommand& renderCommand : renderCommands)\n {\n if (!processRenderCommand(renderCommand,\n frames,\n Vector3(), \/\/ listener position\n Quaternion(), \/\/ listener rotation\n 1.0f, \/\/ pitch\n 1.0f, \/\/ gain\n 1.0f, \/\/ rolloff factor\n buffers[buffer])) return false;\n\n if (buffers[buffer].size() > buffers[buffer].size()) result.resize(buffers[buffer].size(), 0.0f);\n\n for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)\n {\n \/\/ mix the sound into the buffer\n result[i] += buffers[buffer][i];\n }\n }\n\n return true;\n }\n\n bool AudioDevice::processRenderCommand(const RenderCommand& renderCommand,\n uint32_t frames,\n Vector3 listenerPosition,\n Quaternion listenerRotation,\n float pitch,\n float gain,\n float rolloffFactor,\n std::vector& result)\n {\n uint32_t buffer = currentBuffer++;\n if (currentBuffer > buffers.size()) return true; \/\/ out of buffers\n\n buffers[buffer].resize(frames * channels);\n std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);\n\n if (renderCommand.attributeCallback)\n {\n renderCommand.attributeCallback(listenerPosition,\n listenerRotation,\n pitch,\n gain,\n rolloffFactor);\n }\n\n for (const RenderCommand& command : renderCommand.renderCommands)\n {\n processRenderCommand(command,\n frames,\n listenerPosition,\n listenerRotation,\n pitch,\n gain,\n rolloffFactor,\n buffers[buffer]);\n\n if (buffers[buffer].size() > result.size()) result.resize(buffers[buffer].size());\n\n for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)\n {\n \/\/ mix the sound into the buffer\n result[i] += buffers[buffer][i];\n }\n }\n\n if (renderCommand.renderCallback)\n {\n if (!renderCommand.renderCallback(frames,\n channels,\n sampleRate,\n listenerPosition,\n listenerRotation,\n pitch,\n gain,\n rolloffFactor,\n result)) return false;\n }\n\n return true;\n }\n\n bool AudioDevice::getData(uint32_t frames, std::vector& result)\n {\n currentBuffer = 0;\n uint32_t buffer = currentBuffer++;\n if (currentBuffer > buffers.size()) return true; \/\/ out of buffers\n\n buffers[buffer].resize(frames * channels);\n std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);\n\n if (!processRenderCommands(frames, buffers[buffer])) return false;\n\n for (float& f : buffers[buffer])\n {\n f = clamp(f, -1.0f, 1.0f);\n }\n\n switch (format)\n {\n case Audio::Format::SINT16:\n {\n result.resize(frames * channels * sizeof(int16_t));\n int16_t* resultPtr = reinterpret_cast(result.data());\n\n for (uint32_t i = 0; i < buffers[buffer].size(); ++i)\n {\n *resultPtr = static_cast(buffers[buffer][i] * 32767.0f);\n ++resultPtr;\n }\n break;\n }\n case Audio::Format::FLOAT32:\n {\n result.reserve(frames * channels * sizeof(float));\n result.assign(reinterpret_cast(buffers[buffer].data()),\n reinterpret_cast(buffers[buffer].data()) + buffers[buffer].size() * sizeof(float));\n break;\n }\n }\n\n return true;\n }\n\n void AudioDevice::executeOnAudioThread(const std::function& func)\n {\n std::lock_guard lock(executeMutex);\n\n executeQueue.push(func);\n }\n\n void AudioDevice::executeAll()\n {\n std::function func;\n\n for (;;)\n {\n {\n std::lock_guard lock(executeMutex);\n\n if (executeQueue.empty())\n {\n break;\n }\n \n func = std::move(executeQueue.front());\n executeQueue.pop();\n }\n \n if (func)\n {\n func();\n }\n }\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH\n#define DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n#include \"cmake_config.h\"\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include \n#include \n\n#include \n\nnamespace Dune {\nnamespace GDT {\nnamespace DiscreteFunction {\n\n\ntemplate \nclass BasisVisualization : public Dune::VTKFunction\n{\npublic:\n typedef SpaceImp SpaceType;\n typedef typename SpaceType::EntityType EntityType;\n typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;\n\nprivate:\n typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;\n\npublic:\n BasisVisualization(const SpaceType& sp, const size_t ind, const std::string nm = \"basis\")\n : space_(sp)\n , index_(ind)\n , values_(space_.mapper().maxNumDofs(), RangeType(0))\n , name_(nm)\n {\n if (index_ >= space_.mapper().maxNumDofs())\n DUNE_THROW(Dune::RangeError,\n \"index has to be smaller than \" << space_.mapper().maxNumDofs() << \"(is \" << index_ << \")!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n const auto baseFunctionSet = space_.baseFunctionSet(entity);\n assert(component >= 0 && \"Really?\");\n if (component < baseFunctionSet.size()) {\n baseFunctionSet.evaluate(x, values_);\n assert(component < values_.size() && \"This should not happen!\");\n return values_[index_][component];\n } else if (component < space_.mapper().maxNumDofs())\n return 0.0;\n else\n DUNE_THROW(Dune::RangeError,\n \"component has to be smaller than \" << space_.mapper().maxNumDofs() << \"(is \" << component << \")!\");\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const size_t index_;\n mutable std::vector values_;\n const std::string name_;\n}; \/\/ class BasisVisualization\n\n\ntemplate \nclass VisualizationAdapter : public Dune::VTKFunction\n{\npublic:\n typedef SpaceImp SpaceType;\n typedef VectorImp VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;\n typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;\n\n VisualizationAdapter(const SpaceType& sp, const VectorType& vec, const std::string nm = \"discrete_function\")\n : space_(sp)\n , name_(nm)\n , vector_(vec)\n , indices_(space_.mapper().maxNumDofs(), 0)\n , basis_values_(space_.mapper().maxNumDofs(), RangeType(0))\n {\n assert(vector_.size() == space_.mapper().size() && \"Given vector has wrong size!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n assert(component >= 0 && \"Really?\");\n RangeType value(0);\n assert(component < int(value.size()) && \"Really?\");\n const auto baseFunctionSet = space_.baseFunctionSet(entity);\n space_.mapper().globalIndices(entity, indices_);\n baseFunctionSet.evaluate(x, basis_values_);\n for (size_t ii = 0; ii < baseFunctionSet.size(); ++ii) {\n basis_values_[ii] *= vector_.get(indices_[ii]);\n value += basis_values_[ii];\n }\n return value[component];\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const std::string name_;\n const VectorType& vector_;\n mutable Dune::DynamicVector indices_;\n mutable std::vector basis_values_;\n}; \/\/ class VisualizationAdapter\n\n\n} \/\/ namespace DiscreteFunction\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH\n[discretefunction.visualize] replaced assertions by exceptions\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH\n#define DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n#include \"cmake_config.h\"\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace Dune {\nnamespace GDT {\nnamespace DiscreteFunction {\n\n\ntemplate \nclass BasisVisualization : public Dune::VTKFunction\n{\npublic:\n typedef SpaceImp SpaceType;\n typedef typename SpaceType::EntityType EntityType;\n typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;\n\nprivate:\n typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;\n\npublic:\n BasisVisualization(const SpaceType& sp, const size_t ind, const std::string nm = \"basis\")\n : space_(sp)\n , index_(ind)\n , values_(space_.mapper().maxNumDofs(), RangeType(0))\n , name_(nm)\n {\n if (index_ >= space_.mapper().maxNumDofs())\n DUNE_THROW(Dune::RangeError,\n \"index has to be smaller than \" << space_.mapper().maxNumDofs() << \"(is \" << index_ << \")!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n const auto baseFunctionSet = space_.baseFunctionSet(entity);\n if (component < 0)\n DUNE_THROW(Dune::RangeError, \"component must not be negative (is \" << component << \")!\");\n if (component < baseFunctionSet.size()) {\n baseFunctionSet.evaluate(x, values_);\n assert(component < values_.size() && \"This should not happen!\");\n return values_[index_][component];\n } else if (component < space_.mapper().maxNumDofs())\n return 0.0;\n else\n DUNE_THROW(Dune::RangeError,\n \"component has to be smaller than \" << space_.mapper().maxNumDofs() << \"(is \" << component << \")!\");\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const size_t index_;\n mutable std::vector values_;\n const std::string name_;\n}; \/\/ class BasisVisualization\n\n\ntemplate \nclass VisualizationAdapter : public Dune::VTKFunction\n{\npublic:\n typedef SpaceImp SpaceType;\n typedef VectorImp VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;\n typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;\n\n VisualizationAdapter(const SpaceType& sp, const VectorType& vec, const std::string nm = \"discrete_function\")\n : space_(sp)\n , name_(nm)\n , vector_(vec)\n , indices_(space_.mapper().maxNumDofs(), 0)\n , basis_values_(space_.mapper().maxNumDofs(), RangeType(0))\n {\n if (vector_.size() != space_.mapper().size())\n DUNE_PYMOR_THROW(Pymor::Exception::sizes_do_not_match,\n \"The sice of vec (\" << vec.size() << \") does not match the size of the space (\"\n << space_.mapper().size()\n << \")!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& xx) const\n {\n if (component < 0)\n DUNE_THROW(Dune::RangeError, \"component must not be negative (is \" << component << \")!\");\n RangeType value(0);\n if (component >= ncomps())\n DUNE_THROW(Dune::RangeError,\n \"component has to be smaller than ncomps() = \" << ncomps() << \" (is \" << component << \")!\");\n const auto baseFunctionSet = space_.baseFunctionSet(entity);\n space_.mapper().globalIndices(entity, indices_);\n baseFunctionSet.evaluate(xx, basis_values_);\n for (size_t ii = 0; ii < baseFunctionSet.size(); ++ii) {\n basis_values_[ii] *= vector_.get(indices_[ii]);\n value += basis_values_[ii];\n }\n return value[component];\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const std::string name_;\n const VectorType& vector_;\n mutable Dune::DynamicVector indices_;\n mutable std::vector basis_values_;\n}; \/\/ class VisualizationAdapter\n\n\n} \/\/ namespace DiscreteFunction\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH\n<|endoftext|>"} {"text":"\n#ifndef DUNE_GRID_PART_INTERSECTION_WRAPPER_HH\n#define DUNE_GRID_PART_INTERSECTION_WRAPPER_HH\n\n\/\/ dune-geometry\n#include \n\n\/\/ dune-grid\n#include \n\nnamespace Dune {\n\nnamespace grid {\n\nnamespace Part {\n\nnamespace Intersection {\n\nnamespace Wrapper {\n\ntemplate< class IntersectionIteratorImp, class WrappedIntersectionImp >\nclass FakeDomainBoundary\n{\npublic:\n typedef IntersectionIteratorImp IntersectionIteratorType;\n\n typedef WrappedIntersectionImp WrappedIntersectionType;\n\n typedef FakeDomainBoundary< IntersectionIteratorType, WrappedIntersectionType > ThisType;\n\n static const int dimension = WrappedIntersectionType::dimension;\n\n static const int dimensionworld = WrappedIntersectionType::dimensionworld;\n\n typedef typename WrappedIntersectionType::Entity Entity;\n\n typedef typename WrappedIntersectionType::EntityPointer EntityPointer;\n\n typedef typename WrappedIntersectionType::Geometry Geometry;\n\n typedef typename WrappedIntersectionType::LocalCoordinate LocalCoordinate;\n\n typedef typename WrappedIntersectionType::GlobalCoordinate GlobalCoordinate;\n\n typedef typename WrappedIntersectionType::LocalGeometry LocalGeometry;\n\n\/\/ typedef Dune::Intersection Intersection;\n\n typedef typename WrappedIntersectionType::ctype ctype;\n\n FakeDomainBoundary(const IntersectionIteratorType& intersectionIterator)\n : intersectionIterator_(intersectionIterator),\n passThrough_(true)\n {\n }\n\n\/\/ void bind(Dune::shared_ptr< const WrappedIntersectionType > wrappedIntersection)\n\/\/ {\n\/\/ wrappedIntersection_ = wrappedIntersection;\n\/\/ bound_ = true;\n\/\/ }\n\n bool boundary() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().boundary();\n }\n\n int boundaryId() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().boundaryId();\n }\n\n size_t boundarySegmentIndex() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().boundarySegmentIndex();\n }\n\n bool neighbor() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().neighbor();\n }\n\n EntityPointer inside() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().inside();\n }\n\n EntityPointer outside() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().outside();\n }\n\n bool conforming() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().conforming();\n }\n\n LocalGeometry geometryInInside() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().geometryInInside();\n }\n\n LocalGeometry geometryInOutside() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().geometryInOutside();\n }\n\n Geometry geometry() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().geometry();\n }\n\n Dune::GeometryType type() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().type();\n }\n\n int indexInInside() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().indexInInside();\n }\n\n int indexInOutside() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().indexInOutside();\n }\n\n GlobalCoordinate outerNormal(const LocalCoordinate& local) const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().outerNormal(local);\n }\n\n GlobalCoordinate integrationOuterNormal(const LocalCoordinate& local) const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().integrationOuterNormal(local);\n }\n\n GlobalCoordinate unitOuterNormal(const LocalCoordinate& local) const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().unitOuterNormal(local);\n }\n\n GlobalCoordinate centerUnitOuterNormal() const\n {\n \/\/if (passThrough_)\n return intersectionIterator_.getBaseIntersection().centerUnitOuterNormal();\n }\n\nprivate:\n const IntersectionIteratorType& intersectionIterator_;\n bool passThrough_;\n}; \/\/ class FakeDomainBoundary\n\n} \/\/ namespace Wrapper\n\n} \/\/ namespace Intersection\n\n} \/\/ namespace Part\n\n} \/\/ namespace grid\n\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GRID_PART_INTERSECTION_WRAPPER_HH\n[grid.part.intersection.wrapper] finished so far\n#ifndef DUNE_GRID_PART_INTERSECTION_WRAPPER_HH\n#define DUNE_GRID_PART_INTERSECTION_WRAPPER_HH\n\n\/\/ dune-geometry\n#include \n\n\/\/ dune-grid\n#include \n\nnamespace Dune {\n\nnamespace grid {\n\nnamespace Part {\n\nnamespace Intersection {\n\nnamespace Wrapper {\n\ntemplate< class IntersectionIteratorImp, class WrappedIntersectionImp >\nclass FakeDomainBoundary\n{\npublic:\n typedef IntersectionIteratorImp IntersectionIteratorType;\n\n typedef WrappedIntersectionImp WrappedIntersectionType;\n\n typedef FakeDomainBoundary< IntersectionIteratorType, WrappedIntersectionType > ThisType;\n\n static const int dimension = WrappedIntersectionType::dimension;\n\n static const int dimensionworld = WrappedIntersectionType::dimensionworld;\n\n typedef typename WrappedIntersectionType::Entity Entity;\n\n typedef typename WrappedIntersectionType::EntityPointer EntityPointer;\n\n typedef typename WrappedIntersectionType::Geometry Geometry;\n\n typedef typename WrappedIntersectionType::LocalCoordinate LocalCoordinate;\n\n typedef typename WrappedIntersectionType::GlobalCoordinate GlobalCoordinate;\n\n typedef typename WrappedIntersectionType::LocalGeometry LocalGeometry;\n\n\/\/ typedef Dune::Intersection Intersection;\n\n typedef typename WrappedIntersectionType::ctype ctype;\n\n FakeDomainBoundary(const IntersectionIteratorType& intersectionIterator)\n : intersectionIterator_(intersectionIterator),\n passThrough_(true),\n boundaryId_(-1)\n {\n }\n\n void setPassThrough(const bool passThrough)\n {\n passThrough_ = passThrough;\n }\n\n void setBoundaryId(const int boundaryId)\n {\n boundaryId_ = boundaryId;\n }\n\n bool neighbor() const\n {\n if (passThrough_)\n return intersectionIterator_.getBaseIntersection().neighbor();\n else\n return false;\n }\n\n bool boundary() const\n {\n if (passThrough_)\n return intersectionIterator_.getBaseIntersection().boundary();\n else\n return true;\n }\n\n int boundaryId() const\n {\n if (passThrough_)\n return intersectionIterator_.getBaseIntersection().boundaryId();\n else\n return boundaryId_;\n }\n\n size_t boundarySegmentIndex() const\n {\n return intersectionIterator_.getBaseIntersection().boundarySegmentIndex();\n }\n\n EntityPointer inside() const\n {\n return intersectionIterator_.getBaseIntersection().inside();\n }\n\n EntityPointer outside() const\n {\n return intersectionIterator_.getBaseIntersection().outside();\n }\n\n bool conforming() const\n {\n return intersectionIterator_.getBaseIntersection().conforming();\n }\n\n LocalGeometry geometryInInside() const\n {\n return intersectionIterator_.getBaseIntersection().geometryInInside();\n }\n\n LocalGeometry geometryInOutside() const\n {\n return intersectionIterator_.getBaseIntersection().geometryInOutside();\n }\n\n Geometry geometry() const\n {\n return intersectionIterator_.getBaseIntersection().geometry();\n }\n\n Dune::GeometryType type() const\n {\n return intersectionIterator_.getBaseIntersection().type();\n }\n\n int indexInInside() const\n {\n return intersectionIterator_.getBaseIntersection().indexInInside();\n }\n\n int indexInOutside() const\n {\n return intersectionIterator_.getBaseIntersection().indexInOutside();\n }\n\n GlobalCoordinate outerNormal(const LocalCoordinate& local) const\n {\n return intersectionIterator_.getBaseIntersection().outerNormal(local);\n }\n\n GlobalCoordinate integrationOuterNormal(const LocalCoordinate& local) const\n {\n return intersectionIterator_.getBaseIntersection().integrationOuterNormal(local);\n }\n\n GlobalCoordinate unitOuterNormal(const LocalCoordinate& local) const\n {\n return intersectionIterator_.getBaseIntersection().unitOuterNormal(local);\n }\n\n GlobalCoordinate centerUnitOuterNormal() const\n {\n return intersectionIterator_.getBaseIntersection().centerUnitOuterNormal();\n }\n\nprivate:\n const IntersectionIteratorType& intersectionIterator_;\n bool passThrough_;\n int boundaryId_;\n}; \/\/ class FakeDomainBoundary\n\n} \/\/ namespace Wrapper\n\n} \/\/ namespace Intersection\n\n} \/\/ namespace Part\n\n} \/\/ namespace grid\n\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GRID_PART_INTERSECTION_WRAPPER_HH\n<|endoftext|>"} {"text":"\/\/ ConverterMarket.cpp\n\/\/ Implements the ConverterMarket class\n\n#include \n#include \n\n#include \"ConverterMarket.h\"\n\n#include \"ConverterModel.h\"\n#include \"IsoVector.h\"\n#include \"Logger.h\"\n#include \"CycException.h\"\n#include \"InputXML.h\"\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::init(xmlNodePtr cur) { \n MarketModel::init(cur); \/\/\/ get facility list\n xmlNodeSetPtr nodes = XMLinput->get_xpath_elements(cur,\"model\/ConverterMarket\/converter\");\n \n \/\/ Find out what convertermodel matches the name given\n xmlNodePtr conv_node = nodes->nodeTab[0];\n conv_name_ = XMLinput->get_xpath_content(conv_node,\"type\");\n Model* converter = Model::getModelByName(conv_name_);\n\n \/\/ make one\n Model* new_converter = Model::create(converter);\n\n \/\/ move XML pointer to current model\n cur = XMLinput->get_xpath_element(cur,\"model\/ConverterMarket\");\n\n \/\/ The commodity initialized as the mktcommodity is the request commodity.\n offer_commod_ = XMLinput->get_xpath_content(cur,\"offercommodity\");\n req_commod_ = XMLinput->get_xpath_content(cur,\"reqcommodity\");\n\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::copy(ConverterMarket* src)\n{ \n MarketModel::copy(src);\n offer_commod_ = src->offer_commod_;\n req_commod_ = src->req_commod_;\n conv_name_ = src->conv_name_;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::copyFreshModel(Model* src)\n{ \n copy(dynamic_cast(src));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nstd::string ConverterMarket::str() { \n std::string s = MarketModel::str()\n + \"with offer commodity '\"\n + offer_commod_\n + \"' and request commodity '\"\n + req_commod_\n + \"'. \";\n return s;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nConverterModel* ConverterMarket::getConverter() {\n Model* converter;\n converter = Model::getModelByName(conv_name_);\n\n return dynamic_cast(converter);\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::receiveMessage(msg_ptr msg)\n{\n messages_.insert(msg);\n\n if (msg->isOffer()){\n offers_.insert(indexedMsg(msg->resource()->quantity(),msg));\n }\n else if (!msg->isOffer()) {\n requests_.insert(indexedMsg(msg->resource()->quantity(),msg));\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::reject_request(sortedMsgList::iterator request)\n{\n\n \/\/ delete the tentative orders\n while ( orders_.size() > firmOrders_) {\n orders_.pop_back();\n }\n\n \/\/ put all matched offers back in the sorted list\n while (matchedOffers_.size() > 0) {\n msg_ptr msg = *(matchedOffers_.begin());\n offers_.insert(indexedMsg(msg->resource()->quantity(),msg));\n matchedOffers_.erase(msg);\n }\n\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::process_request()\n{\n \/\/ update pointer to firm orders\n firmOrders_ = orders_.size();\n\n while (matchedOffers_.size() > 0)\n {\n msg_ptr msg = *(matchedOffers_.begin());\n messages_.erase(msg);\n matchedOffers_.erase(msg);\n }\n}\n \n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool ConverterMarket::match_request(sortedMsgList::iterator request)\n{\n sortedMsgList::iterator offer;\n double requestAmt,offerAmt;\n msg_ptr offerMsg;\n msg_ptr requestMsg;\n\n requestAmt = (*request).first;\n requestMsg = (*request).second;\n \n \/\/ if this request is not yet satisfied &&\n \/\/ there are more offers_ left\n while ( requestAmt > 0 && offers_.size() > 0)\n {\n \/\/ get a new offer\n offer = offers_.end();\n offer--;\n \/\/ convert it\n offerMsg = (this->getConverter())->convert((*offer).second, requestMsg);\n offerAmt = offerMsg->resource()->quantity();\n\n \/\/ pop off this offer\n offers_.erase(offer);\n if (requestMsg->resource()->checkQuality(offerMsg->resource())){\n if (requestAmt > offerAmt) { \n \/\/ put a new message in the order stack\n \/\/ it goes down to supplier\n offerMsg->setRequester(requestMsg->requester());\n\n \/\/ tenatively queue a new order (don't execute yet)\n matchedOffers_.insert(offerMsg);\n\n orders_.push_back(offerMsg);\n\n LOG(LEV_DEBUG2, \"none!\") << \"ConverterMarket has resolved a match from \"\n << offerMsg->supplier()->ID()\n << \" to \"\n << offerMsg->requester()->ID()\n << \" for the amount: \" \n << offerMsg->resource()->quantity();\n\n requestAmt -= offerAmt;\n } \n else {\n \/\/ split offer\n\n \/\/ queue a new order\n msg_ptr maybe_offer = offerMsg->clone();\n\n maybe_offer->resource()->setQuantity(requestAmt);\n maybe_offer->setRequester(requestMsg->requester());\n\n matchedOffers_.insert(offerMsg);\n\n orders_.push_back(maybe_offer);\n\n LOG(LEV_DEBUG2, \"none!\") << \"ConverterMarket has resolved a partial match from \"\n << maybe_offer->supplier()->ID()\n << \" to \"\n << maybe_offer->requester()->ID()\n << \" for the amount: \" \n << maybe_offer->resource()->quantity();\n\n \/\/ reduce the offer amount\n offerAmt -= requestAmt;\n\n \/\/ if the residual is above threshold,\n \/\/ make a new offer with reduced amount\n\n if(offerAmt > EPS_KG) {\n msg_ptr new_offer = offerMsg->clone();\n new_offer->resource()->setQuantity(offerAmt);\n \/\/ call this method for consistency\n receiveMessage(new_offer);\n }\n\n \/\/ zero out request\n requestAmt = 0;\n }\n }\n }\n\n return (0 == requestAmt);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::resolve()\n{\n sortedMsgList::iterator request;\n\n firmOrders_ = 0;\n\n \/\/\/ while requests_ remain and there is at least one offer left\n while (requests_.size() > 0)\n {\n request = requests_.end();\n request--;\n \n if(match_request(request)) {\n process_request();\n } \n else {\n LOG(LEV_DEBUG2, \"none!\") << \"The request from Requester \"<< \n (*request).second->requester()->ID()\n << \" for the amount \" << (*request).first \n << \" rejected by the ConverterMarket. \";\n reject_request(request);\n }\n \/\/ remove this request\n messages_.erase((*request).second);\n requests_.erase(request);\n }\n\n for (int i = 0; i < orders_.size(); i++) {\n msg_ptr msg = orders_.at(i);\n msg->setDir(DOWN_MSG);\n msg->sendOn();\n }\n orders_.clear();\n}\n\n\/* --------------------\n * all MODEL classes have these members\n * --------------------\n *\/\nextern \"C\" Model* constructConverterMarket() {\n return new ConverterMarket();\n}\n\n\/* -------------------- *\/\n\nConverterMarket passes tests\/\/ ConverterMarket.cpp\n\/\/ Implements the ConverterMarket class\n\n#include \n#include \n\n#include \"ConverterMarket.h\"\n\n#include \"ConverterModel.h\"\n#include \"Resource.h\"\n#include \"Logger.h\"\n#include \"CycException.h\"\n#include \"InputXML.h\"\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::init(xmlNodePtr cur) { \n MarketModel::init(cur); \/\/\/ get facility list\n xmlNodeSetPtr nodes = XMLinput->get_xpath_elements(cur,\"model\/ConverterMarket\/converter\");\n \n \/\/ Find out what convertermodel matches the name given\n xmlNodePtr conv_node = nodes->nodeTab[0];\n conv_name_ = XMLinput->get_xpath_content(conv_node,\"type\");\n Model* converter = Model::getModelByName(conv_name_);\n\n \/\/ make one\n Model* new_converter = Model::create(converter);\n\n \/\/ move XML pointer to current model\n cur = XMLinput->get_xpath_element(cur,\"model\/ConverterMarket\");\n\n \/\/ The commodity initialized as the mktcommodity is the request commodity.\n offer_commod_ = XMLinput->get_xpath_content(cur,\"offercommodity\");\n req_commod_ = XMLinput->get_xpath_content(cur,\"reqcommodity\");\n\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::copy(ConverterMarket* src)\n{ \n MarketModel::copy(src);\n offer_commod_ = src->offer_commod_;\n req_commod_ = src->req_commod_;\n conv_name_ = src->conv_name_;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::copyFreshModel(Model* src)\n{ \n copy(dynamic_cast(src));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nstd::string ConverterMarket::str() { \n std::string s = MarketModel::str()\n + \"with offer commodity '\"\n + offer_commod_\n + \"' and request commodity '\"\n + req_commod_\n + \"'. \";\n return s;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nConverterModel* ConverterMarket::getConverter() {\n Model* converter;\n converter = Model::getModelByName(conv_name_);\n\n return dynamic_cast(converter);\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::receiveMessage(msg_ptr msg)\n{\n messages_.insert(msg);\n\n if (msg->isOffer()){\n offers_.insert(indexedMsg(msg->resource()->quantity(),msg));\n }\n else if (!msg->isOffer()) {\n requests_.insert(indexedMsg(msg->resource()->quantity(),msg));\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::reject_request(sortedMsgList::iterator request)\n{\n\n \/\/ delete the tentative orders\n while ( orders_.size() > firmOrders_) {\n orders_.pop_back();\n }\n\n \/\/ put all matched offers back in the sorted list\n while (matchedOffers_.size() > 0) {\n msg_ptr msg = *(matchedOffers_.begin());\n offers_.insert(indexedMsg(msg->resource()->quantity(),msg));\n matchedOffers_.erase(msg);\n }\n\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::process_request()\n{\n \/\/ update pointer to firm orders\n firmOrders_ = orders_.size();\n\n while (matchedOffers_.size() > 0)\n {\n msg_ptr msg = *(matchedOffers_.begin());\n messages_.erase(msg);\n matchedOffers_.erase(msg);\n }\n}\n \n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool ConverterMarket::match_request(sortedMsgList::iterator request)\n{\n sortedMsgList::iterator offer;\n double requestAmt,offerAmt;\n msg_ptr offerMsg;\n msg_ptr requestMsg;\n\n requestAmt = (*request).first;\n requestMsg = (*request).second;\n \n \/\/ if this request is not yet satisfied &&\n \/\/ there are more offers_ left\n while ( requestAmt > 0 && offers_.size() > 0)\n {\n \/\/ get a new offer\n offer = offers_.end();\n offer--;\n \/\/ convert it\n offerMsg = (this->getConverter())->convert((*offer).second, requestMsg);\n offerAmt = offerMsg->resource()->quantity();\n\n \/\/ pop off this offer\n offers_.erase(offer);\n if (requestMsg->resource()->checkQuality(offerMsg->resource())){\n if (requestAmt > offerAmt) { \n \/\/ put a new message in the order stack\n \/\/ it goes down to supplier\n offerMsg->setRequester(requestMsg->requester());\n\n \/\/ tenatively queue a new order (don't execute yet)\n matchedOffers_.insert(offerMsg);\n\n orders_.push_back(offerMsg);\n\n LOG(LEV_DEBUG2, \"none!\") << \"ConverterMarket has resolved a match from \"\n << offerMsg->supplier()->ID()\n << \" to \"\n << offerMsg->requester()->ID()\n << \" for the amount: \" \n << offerMsg->resource()->quantity();\n\n requestAmt -= offerAmt;\n } \n else {\n \/\/ split offer\n\n \/\/ queue a new order\n msg_ptr maybe_offer = offerMsg->clone();\n\n maybe_offer->resource()->setQuantity(requestAmt);\n maybe_offer->setRequester(requestMsg->requester());\n\n matchedOffers_.insert(offerMsg);\n\n orders_.push_back(maybe_offer);\n\n LOG(LEV_DEBUG2, \"none!\") << \"ConverterMarket has resolved a partial match from \"\n << maybe_offer->supplier()->ID()\n << \" to \"\n << maybe_offer->requester()->ID()\n << \" for the amount: \" \n << maybe_offer->resource()->quantity();\n\n \/\/ reduce the offer amount\n offerAmt -= requestAmt;\n\n \/\/ if the residual is above threshold,\n \/\/ make a new offer with reduced amount\n\n if(offerAmt > EPS_RSRC) {\n msg_ptr new_offer = offerMsg->clone();\n new_offer->resource()->setQuantity(offerAmt);\n \/\/ call this method for consistency\n receiveMessage(new_offer);\n }\n\n \/\/ zero out request\n requestAmt = 0;\n }\n }\n }\n\n return (0 == requestAmt);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid ConverterMarket::resolve()\n{\n sortedMsgList::iterator request;\n\n firmOrders_ = 0;\n\n \/\/\/ while requests_ remain and there is at least one offer left\n while (requests_.size() > 0)\n {\n request = requests_.end();\n request--;\n \n if(match_request(request)) {\n process_request();\n } \n else {\n LOG(LEV_DEBUG2, \"none!\") << \"The request from Requester \"<< \n (*request).second->requester()->ID()\n << \" for the amount \" << (*request).first \n << \" rejected by the ConverterMarket. \";\n reject_request(request);\n }\n \/\/ remove this request\n messages_.erase((*request).second);\n requests_.erase(request);\n }\n\n for (int i = 0; i < orders_.size(); i++) {\n msg_ptr msg = orders_.at(i);\n msg->setDir(DOWN_MSG);\n msg->sendOn();\n }\n orders_.clear();\n}\n\n\/* --------------------\n * all MODEL classes have these members\n * --------------------\n *\/\nextern \"C\" Model* constructConverterMarket() {\n return new ConverterMarket();\n}\n\n\/* -------------------- *\/\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2002,2004 The Apache Software Foundation.\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\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static data\n\/\/ ---------------------------------------------------------------------------\nstatic XMLMsgLoader* gErrMsgLoader = 0;\nstatic XMLMsgLoader* gValidMsgLoader = 0;\nstatic XMLMutex* sErrRprtrMutex = 0;\nstatic XMLRegisterCleanup errRprtrMutexCleanup;\nstatic XMLRegisterCleanup cleanupErrMsgLoader;\nstatic XMLRegisterCleanup cleanupValidMsgLoader;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local, static functions\n\/\/ ---------------------------------------------------------------------------\nstatic void reinitErrRprtrMutex()\n{\n delete sErrRprtrMutex;\n sErrRprtrMutex = 0;\n}\n\nstatic XMLMutex& getErrRprtrMutex()\n{\n if (!sErrRprtrMutex)\n {\n XMLMutexLock lockInit(XMLPlatformUtils::fgAtomicMutex);\n\n if (!sErrRprtrMutex)\n {\n sErrRprtrMutex = new XMLMutex(XMLPlatformUtils::fgMemoryManager);\n errRprtrMutexCleanup.registerCleanup(reinitErrRprtrMutex);\n }\n }\n\n return *sErrRprtrMutex;\n}\n\nstatic void reinitErrMsgLoader()\n{\n\tdelete gErrMsgLoader;\n\tgErrMsgLoader = 0;\n}\n\nstatic void reinitValidMsgLoader()\n{\n\tdelete gValidMsgLoader;\n\tgValidMsgLoader = 0;\n}\n\nstatic XMLMsgLoader* getErrMsgLoader()\n{\n if (!gErrMsgLoader)\n {\n XMLMutexLock lock(&getErrRprtrMutex());\n\n if (!gErrMsgLoader)\n {\n gErrMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);\n\n if (!gErrMsgLoader)\n XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);\n else\n cleanupErrMsgLoader.registerCleanup(reinitErrMsgLoader);\n }\n }\n\n return gErrMsgLoader;\n}\n\n\nstatic XMLMsgLoader* getValidMsgLoader()\n{\n if (!gValidMsgLoader)\n {\n XMLMutexLock lock(&getErrRprtrMutex());\n\n if (!gValidMsgLoader)\n {\n gValidMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgValidityDomain);\n\n if (!gValidMsgLoader)\n XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);\n else\n cleanupValidMsgLoader.registerCleanup(reinitValidMsgLoader);\n }\n }\n return gValidMsgLoader;\n}\n\nvoid XMLInitializer::initializeXSDErrReporterMsgLoader()\n{\n gErrMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);\n if (gErrMsgLoader) {\n cleanupErrMsgLoader.registerCleanup(reinitErrMsgLoader);\n }\n\n gValidMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgValidityDomain);\n if (gValidMsgLoader) {\n cleanupValidMsgLoader.registerCleanup(reinitValidMsgLoader);\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSDErrorReporter: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXSDErrorReporter::XSDErrorReporter(XMLErrorReporter* const errorReporter) :\n fExitOnFirstFatal(false)\n , fErrorReporter(errorReporter)\n{\n\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSDErrorReporter: Error reporting\n\/\/ ---------------------------------------------------------------------------\nvoid XSDErrorReporter::emitError(const unsigned int toEmit,\n const XMLCh* const msgDomain,\n const Locator* const aLocator)\n{\n \/\/ Bump the error count if it is not a warning\n\/\/ if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)\n\/\/ incrementErrorCount();\n\n \/\/\n \/\/ Load the message into alocal and replace any tokens found in\n \/\/ the text.\n \/\/\n const unsigned int msgSize = 1023;\n XMLCh errText[msgSize + 1];\n XMLMsgLoader* msgLoader = getErrMsgLoader();\n XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);\n\n if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {\n\n errType = XMLValid::errorType((XMLValid::Codes) toEmit);\n msgLoader = getValidMsgLoader();\n }\n\n if (!msgLoader->loadMsg(toEmit, errText, msgSize))\n {\n \/\/ Should probably load a default message here\n }\n\n if (fErrorReporter)\n fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),\n aLocator->getPublicId(), aLocator->getLineNumber(),\n aLocator->getColumnNumber());\n\n \/\/ Bail out if its fatal an we are to give up on the first fatal error\n if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)\n throw (XMLErrs::Codes) toEmit;\n}\n\nvoid XSDErrorReporter::emitError(const unsigned int toEmit,\n const XMLCh* const msgDomain,\n const Locator* const aLocator,\n const XMLCh* const text1,\n const XMLCh* const text2,\n const XMLCh* const text3,\n const XMLCh* const text4,\n MemoryManager* const manager)\n{\n \/\/ Bump the error count if it is not a warning\n\/\/ if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)\n\/\/ incrementErrorCount();\n\n \/\/\n \/\/ Load the message into alocal and replace any tokens found in\n \/\/ the text.\n \/\/\n const unsigned int maxChars = 2047;\n XMLCh errText[maxChars + 1];\n XMLMsgLoader* msgLoader = getErrMsgLoader();\n XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);\n\n if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {\n\n errType = XMLValid::errorType((XMLValid::Codes) toEmit);\n msgLoader = getValidMsgLoader();\n }\n\n if (!msgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, manager))\n {\n \/\/ Should probably load a default message here\n }\n\n if (fErrorReporter)\n fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),\n aLocator->getPublicId(), aLocator->getLineNumber(),\n aLocator->getColumnNumber());\n\n \/\/ Bail out if its fatal an we are to give up on the first fatal error\n if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)\n throw (XMLErrs::Codes) toEmit;\n}\n\nvoid XSDErrorReporter::emitError(const XMLException& except,\n const Locator* const aLocator)\n{\n const XMLCh* const errText = except.getMessage();\n const unsigned int toEmit = except.getCode();\n XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);\n\n if (fErrorReporter)\n fErrorReporter->error(toEmit, XMLUni::fgExceptDomain, errType, errText, aLocator->getSystemId(),\n aLocator->getPublicId(), aLocator->getLineNumber(),\n aLocator->getColumnNumber());\n\n \/\/ Bail out if its fatal an we are to give up on the first fatal error\n if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)\n throw (XMLErrs::Codes) toEmit;\n}\n\nXERCES_CPP_NAMESPACE_END\nUse errType of Error to be consistent with previous behaviour.\/*\n * Copyright 2002,2004 The Apache Software Foundation.\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\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static data\n\/\/ ---------------------------------------------------------------------------\nstatic XMLMsgLoader* gErrMsgLoader = 0;\nstatic XMLMsgLoader* gValidMsgLoader = 0;\nstatic XMLMutex* sErrRprtrMutex = 0;\nstatic XMLRegisterCleanup errRprtrMutexCleanup;\nstatic XMLRegisterCleanup cleanupErrMsgLoader;\nstatic XMLRegisterCleanup cleanupValidMsgLoader;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local, static functions\n\/\/ ---------------------------------------------------------------------------\nstatic void reinitErrRprtrMutex()\n{\n delete sErrRprtrMutex;\n sErrRprtrMutex = 0;\n}\n\nstatic XMLMutex& getErrRprtrMutex()\n{\n if (!sErrRprtrMutex)\n {\n XMLMutexLock lockInit(XMLPlatformUtils::fgAtomicMutex);\n\n if (!sErrRprtrMutex)\n {\n sErrRprtrMutex = new XMLMutex(XMLPlatformUtils::fgMemoryManager);\n errRprtrMutexCleanup.registerCleanup(reinitErrRprtrMutex);\n }\n }\n\n return *sErrRprtrMutex;\n}\n\nstatic void reinitErrMsgLoader()\n{\n\tdelete gErrMsgLoader;\n\tgErrMsgLoader = 0;\n}\n\nstatic void reinitValidMsgLoader()\n{\n\tdelete gValidMsgLoader;\n\tgValidMsgLoader = 0;\n}\n\nstatic XMLMsgLoader* getErrMsgLoader()\n{\n if (!gErrMsgLoader)\n {\n XMLMutexLock lock(&getErrRprtrMutex());\n\n if (!gErrMsgLoader)\n {\n gErrMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);\n\n if (!gErrMsgLoader)\n XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);\n else\n cleanupErrMsgLoader.registerCleanup(reinitErrMsgLoader);\n }\n }\n\n return gErrMsgLoader;\n}\n\n\nstatic XMLMsgLoader* getValidMsgLoader()\n{\n if (!gValidMsgLoader)\n {\n XMLMutexLock lock(&getErrRprtrMutex());\n\n if (!gValidMsgLoader)\n {\n gValidMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgValidityDomain);\n\n if (!gValidMsgLoader)\n XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);\n else\n cleanupValidMsgLoader.registerCleanup(reinitValidMsgLoader);\n }\n }\n return gValidMsgLoader;\n}\n\nvoid XMLInitializer::initializeXSDErrReporterMsgLoader()\n{\n gErrMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);\n if (gErrMsgLoader) {\n cleanupErrMsgLoader.registerCleanup(reinitErrMsgLoader);\n }\n\n gValidMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgValidityDomain);\n if (gValidMsgLoader) {\n cleanupValidMsgLoader.registerCleanup(reinitValidMsgLoader);\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSDErrorReporter: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXSDErrorReporter::XSDErrorReporter(XMLErrorReporter* const errorReporter) :\n fExitOnFirstFatal(false)\n , fErrorReporter(errorReporter)\n{\n\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSDErrorReporter: Error reporting\n\/\/ ---------------------------------------------------------------------------\nvoid XSDErrorReporter::emitError(const unsigned int toEmit,\n const XMLCh* const msgDomain,\n const Locator* const aLocator)\n{\n \/\/ Bump the error count if it is not a warning\n\/\/ if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)\n\/\/ incrementErrorCount();\n\n \/\/\n \/\/ Load the message into alocal and replace any tokens found in\n \/\/ the text.\n \/\/\n const unsigned int msgSize = 1023;\n XMLCh errText[msgSize + 1];\n XMLMsgLoader* msgLoader = getErrMsgLoader();\n XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);\n\n if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {\n\n errType = XMLValid::errorType((XMLValid::Codes) toEmit);\n msgLoader = getValidMsgLoader();\n }\n\n if (!msgLoader->loadMsg(toEmit, errText, msgSize))\n {\n \/\/ Should probably load a default message here\n }\n\n if (fErrorReporter)\n fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),\n aLocator->getPublicId(), aLocator->getLineNumber(),\n aLocator->getColumnNumber());\n\n \/\/ Bail out if its fatal an we are to give up on the first fatal error\n if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)\n throw (XMLErrs::Codes) toEmit;\n}\n\nvoid XSDErrorReporter::emitError(const unsigned int toEmit,\n const XMLCh* const msgDomain,\n const Locator* const aLocator,\n const XMLCh* const text1,\n const XMLCh* const text2,\n const XMLCh* const text3,\n const XMLCh* const text4,\n MemoryManager* const manager)\n{\n \/\/ Bump the error count if it is not a warning\n\/\/ if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)\n\/\/ incrementErrorCount();\n\n \/\/\n \/\/ Load the message into alocal and replace any tokens found in\n \/\/ the text.\n \/\/\n const unsigned int maxChars = 2047;\n XMLCh errText[maxChars + 1];\n XMLMsgLoader* msgLoader = getErrMsgLoader();\n XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);\n\n if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {\n\n errType = XMLValid::errorType((XMLValid::Codes) toEmit);\n msgLoader = getValidMsgLoader();\n }\n\n if (!msgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, manager))\n {\n \/\/ Should probably load a default message here\n }\n\n if (fErrorReporter)\n fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),\n aLocator->getPublicId(), aLocator->getLineNumber(),\n aLocator->getColumnNumber());\n\n \/\/ Bail out if its fatal an we are to give up on the first fatal error\n if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)\n throw (XMLErrs::Codes) toEmit;\n}\n\nvoid XSDErrorReporter::emitError(const XMLException& except,\n const Locator* const aLocator)\n{\n const XMLCh* const errText = except.getMessage();\n const unsigned int toEmit = except.getCode();\n \/\/Before the code was modified to call this routine it used to use\n \/\/the XMLErrs::DisplayErrorMessage error message, which is just {'0'}\n \/\/and that error message has errType of Error. So to be consistent\n \/\/with previous behaviour set the errType to be Error instead of\n \/\/getting the error type off of the exception.\n \/\/XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);\n XMLErrorReporter::ErrTypes errType = XMLErrorReporter::ErrType_Error;\n\n if (fErrorReporter)\n fErrorReporter->error(toEmit, XMLUni::fgExceptDomain, errType, errText, aLocator->getSystemId(),\n aLocator->getPublicId(), aLocator->getLineNumber(),\n aLocator->getColumnNumber());\n\n \/\/ Bail out if its fatal an we are to give up on the first fatal error\n \/\/if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)\n \/\/ throw (XMLErrs::Codes) toEmit;\n}\n\nXERCES_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: iso8601_converter.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 01:46:43 $\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_shell.hxx\"\n\n#ifndef ISO8601_CONVERTER_HXX_INCLUDED\n#include \"internal\/iso8601_converter.hxx\"\n#endif\n\n#ifndef UTILITIES_HXX_INCLUDED\n#include \"internal\/utilities.hxx\"\n#endif\n\n#include \n#include \n\n\/\/-----------------------------------\n\/* Converts ISO 8601 conform date\/time\n represenation to the representation\n conforming to the current locale\n*\/\nstd::wstring iso8601_date_to_local_date(const std::wstring& isoDate )\n{\n const std::wstring CONST_SPACE(L\" \");\n ::std::wstring ws8601DateTime(isoDate);\n\n if ( ws8601DateTime.length() == 19 )\n {\n \/\/fill in the SYSTEMTIME structure;\n std::string asDateTime = WStringToString( ws8601DateTime );\n SYSTEMTIME DateTime;\n DateTime.wYear = ( unsigned short )strtol( asDateTime.substr( 0, 4 ).c_str(), NULL, 10 );\n DateTime.wMonth = ( unsigned short )strtol( asDateTime.substr( 5, 2 ).c_str(), NULL, 10 );\n DateTime.wDayOfWeek = 0;\n DateTime.wDay = ( unsigned short )strtol( asDateTime.substr( 8, 2 ).c_str(), NULL, 10 );\n DateTime.wHour = ( unsigned short )strtol( asDateTime.substr( 11,2 ).c_str(), NULL, 10 );\n DateTime.wMinute = ( unsigned short )strtol( asDateTime.substr( 14,2 ).c_str(), NULL, 10 );\n DateTime.wSecond = ( unsigned short )strtol( asDateTime.substr( 17,2 ).c_str(), NULL, 10 );\n DateTime.wMilliseconds = 0;\n\n \/\/get Date info from structure\n WCHAR DateBuffer[ MAX_PATH ];\n int DateSize = GetDateFormatW(\n LOCALE_SYSTEM_DEFAULT,\n 0,\n &DateTime,\n NULL,\n DateBuffer,\n MAX_PATH );\n\n if ( DateSize )\n ws8601DateTime.assign(DateBuffer);\n else\n ws8601DateTime = StringToWString( asDateTime );\n\n \/\/get Time info from structure\n WCHAR TimeBuffer[ MAX_PATH ];\n\n int TimeSize = GetTimeFormatW(\n LOCALE_SYSTEM_DEFAULT,\n 0,\n &DateTime,\n NULL,\n TimeBuffer,\n MAX_PATH );\n\n if ( TimeSize )\n {\n ws8601DateTime.append(L\" \");\n ws8601DateTime.append(TimeBuffer);\n }\n else\n ws8601DateTime = StringToWString( asDateTime );\n }\n\n return ws8601DateTime;\n}\n\n\/\/------------------------------------\n\/* Converts ISO 8601 conform duration\n representation to the representation\n conforming to the current locale\n\n Expect format PTnHnMnS according to\n ISO 8601 where n is abitrary number\n of digits\n*\/\n\nstd::wstring iso8601_duration_to_local_duration(const std::wstring& iso8601duration)\n{\n std::wstring days;\n std::wstring hours;\n std::wstring minutes;\n std::wstring seconds;\n\n std::wstring::const_iterator iter = iso8601duration.begin();\n std::wstring::const_iterator iter_end = iso8601duration.end();\n\n std::wstring num;\n\n for (\/**\/; iter != iter_end; ++iter)\n {\n if (isdigit(*iter))\n {\n num += *iter;\n }\n else\n {\n if (*iter == L'D' || *iter == L'd')\n days = num;\n else if (*iter == L'H' || *iter == L'h')\n hours = num;\n else if (*iter == L'M' || *iter == L'm')\n minutes = num;\n else if (*iter == L'S' || *iter == L's')\n seconds = num;\n\n num.clear();\n }\n }\n\n if (days.length() > 0)\n {\n int h = ((_wtoi(days.c_str()) * 24) + _wtoi(hours.c_str()));\n wchar_t buff[10];\n _itow(h, buff, 10);\n hours = buff;\n }\n\n std::wostringstream oss;\n\n oss << std::setw(2) << std::setfill('0') << hours << L\":\" <<\n std::setw(2) << std::setfill('0') << minutes << L\":\" <<\n std::setw(2) << std::setfill('0') << seconds;\n\n return oss.str();\n}\n\nINTEGRATION: CWS obo24 (1.5.120); FILE MERGED 2008\/03\/13 15:26:36 obo 1.5.120.1: #i75046# additional build for 64 bit shell extension (Windows Vista)\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: iso8601_converter.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2008-04-02 09:45:13 $\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_shell.hxx\"\n\n#ifndef ISO8601_CONVERTER_HXX_INCLUDED\n#include \"internal\/iso8601_converter.hxx\"\n#endif\n\n#ifndef UTILITIES_HXX_INCLUDED\n#include \"internal\/utilities.hxx\"\n#endif\n\n#include \n#include \n\n\/\/-----------------------------------\n\/* Converts ISO 8601 conform date\/time\n represenation to the representation\n conforming to the current locale\n*\/\nstd::wstring iso8601_date_to_local_date(const std::wstring& isoDate )\n{\n const std::wstring CONST_SPACE(L\" \");\n ::std::wstring ws8601DateTime(isoDate);\n\n if ( ws8601DateTime.length() == 19 )\n {\n \/\/fill in the SYSTEMTIME structure;\n std::string asDateTime = WStringToString( ws8601DateTime );\n SYSTEMTIME DateTime;\n DateTime.wYear = ( unsigned short )strtol( asDateTime.substr( 0, 4 ).c_str(), NULL, 10 );\n DateTime.wMonth = ( unsigned short )strtol( asDateTime.substr( 5, 2 ).c_str(), NULL, 10 );\n DateTime.wDayOfWeek = 0;\n DateTime.wDay = ( unsigned short )strtol( asDateTime.substr( 8, 2 ).c_str(), NULL, 10 );\n DateTime.wHour = ( unsigned short )strtol( asDateTime.substr( 11,2 ).c_str(), NULL, 10 );\n DateTime.wMinute = ( unsigned short )strtol( asDateTime.substr( 14,2 ).c_str(), NULL, 10 );\n DateTime.wSecond = ( unsigned short )strtol( asDateTime.substr( 17,2 ).c_str(), NULL, 10 );\n DateTime.wMilliseconds = 0;\n\n \/\/get Date info from structure\n WCHAR DateBuffer[ MAX_PATH ];\n int DateSize = GetDateFormatW(\n LOCALE_SYSTEM_DEFAULT,\n 0,\n &DateTime,\n NULL,\n DateBuffer,\n MAX_PATH );\n\n if ( DateSize )\n ws8601DateTime.assign(DateBuffer);\n else\n ws8601DateTime = StringToWString( asDateTime );\n\n \/\/get Time info from structure\n WCHAR TimeBuffer[ MAX_PATH ];\n\n int TimeSize = GetTimeFormatW(\n LOCALE_SYSTEM_DEFAULT,\n 0,\n &DateTime,\n NULL,\n TimeBuffer,\n MAX_PATH );\n\n if ( TimeSize )\n {\n ws8601DateTime.append(L\" \");\n ws8601DateTime.append(TimeBuffer);\n }\n else\n ws8601DateTime = StringToWString( asDateTime );\n }\n\n return ws8601DateTime;\n}\n\n\/\/------------------------------------\n\/* Converts ISO 8601 conform duration\n representation to the representation\n conforming to the current locale\n\n Expect format PTnHnMnS according to\n ISO 8601 where n is abitrary number\n of digits\n*\/\n\nstd::wstring iso8601_duration_to_local_duration(const std::wstring& iso8601duration)\n{\n std::wstring days;\n std::wstring hours;\n std::wstring minutes;\n std::wstring seconds;\n\n std::wstring::const_iterator iter = iso8601duration.begin();\n std::wstring::const_iterator iter_end = iso8601duration.end();\n\n std::wstring num;\n\n for (\/**\/; iter != iter_end; ++iter)\n {\n if (isdigit(*iter))\n {\n num += *iter;\n }\n else\n {\n if (*iter == L'D' || *iter == L'd')\n days = num;\n else if (*iter == L'H' || *iter == L'h')\n hours = num;\n else if (*iter == L'M' || *iter == L'm')\n minutes = num;\n else if (*iter == L'S' || *iter == L's')\n seconds = num;\n\n num.clear();\n }\n }\n\n if (days.length() > 0)\n {\n int h = ((_wtoi(days.c_str()) * 24) + _wtoi(hours.c_str()));\n wchar_t buff[10];\n _itow(h, buff, 10);\n hours = buff;\n }\n\n std::wostringstream oss;\n\n#if defined(_MSC_VER) && defined(_M_X64)\n oss << std::setw(2) << std::setfill(wchar_t('0')) << hours << L\":\" <<\n std::setw(2) << std::setfill(wchar_t('0')) << minutes << L\":\" <<\n std::setw(2) << std::setfill(wchar_t('0')) << seconds;\n#else\n oss << std::setw(2) << std::setfill('0') << hours << L\":\" <<\n std::setw(2) << std::setfill('0') << minutes << L\":\" <<\n std::setw(2) << std::setfill('0') << seconds;\n#endif\n return oss.str();\n}\n\n<|endoftext|>"} {"text":"\/*******************************\nCopyright (c) 2016-2019 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n\n#include \"componentwidgets.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace editor {\nnamespace detail {\n\nstatic ComponentWidgetData* first_component = nullptr;\n\nvoid register_component_widget(ComponentWidgetData* data) {\n\tdata->next = first_component;\n\tfirst_component = data;\n}\n\n}\n\nvoid draw_component_widgets(ContextPtr ctx, ecs::EntityId id) {\n\tfor(detail::ComponentWidgetData* data = detail::first_component; data; data = data->next) {\n\t\ty_debug_assert(data->func);\n\t\tdata->func(ctx, id);\n\t}\n}\n\n\n\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tLights\n**************************************************************************\/\n\ntemplate\nstatic void light_widget(T* light) {\n\tconst int color_flags = ImGuiColorEditFlags_NoSidePreview |\n\t\t\t\t\t \/\/ ImGuiColorEditFlags_NoSmallPreview |\n\t\t\t\t\t ImGuiColorEditFlags_NoAlpha |\n\t\t\t\t\t ImGuiColorEditFlags_Float |\n\t\t\t\t\t ImGuiColorEditFlags_InputRGB;\n\n\tconst math::Vec4 color(light->color(), 1.0f);\n\tif(ImGui::ColorButton(\"Color\", color, color_flags)) {\n\t\tImGui::OpenPopup(\"Color\");\n\t}\n\tImGui::SameLine();\n\tImGui::Text(\"Light color\");\n\n\tif(ImGui::BeginPopup(\"Color\")) {\n\t\tImGui::ColorPicker3(\"##lightpicker\", light->color().begin(), color_flags);\n\n\t\tfloat kelvin = std::clamp(rgb_to_k(light->color()), 1000.0f, 12000.0f);\n\t\tif(ImGui::SliderFloat(\"\", &kelvin, 1000.0f, 12000.0f, \"%.0f°K\")) {\n\t\t\tlight->color() = k_to_rbg(kelvin);\n\t\t}\n\n\t\tImGui::EndPopup();\n\t}\n\n\tImGui::DragFloat(\"Intensity\", &light->intensity(), 1.0f, 0.0f, std::numeric_limits::max());\n}\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tPointLightComponent* light = ctx->world().component(id);\n\tif(!light) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Point light\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\n\tlight_widget(light);\n\n\tImGui::DragFloat(\"Radius\", &light->radius(), 1.0f, 0.0f, std::numeric_limits::max(), \"%.2f\");\n\tImGui::DragFloat(\"Falloff\", &light->falloff(), 0.1f, 0.0f, std::numeric_limits::max(), \"%.2f\", 2.0f);\n}\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tDirectionalLightComponent* light = ctx->world().component(id);\n\tif(!light) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Directional light\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\tlight_widget(light);\n\n\tImGui::InputFloat3(\"Direction\", light->direction().data(), \"%.2f\");\n}\n\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tSkyComponent* sky = ctx->world().component(id);\n\tif(!sky) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Sky\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\tlight_widget(&sky->sun());\n\n\tmath::Vec3 beta = sky->beta_rayleight() * 1e6f;\n\tif(ImGui::InputFloat3(\"Beta\", beta.data(), \"%.2f\")) {\n\t\tsky->beta_rayleight() = beta * 1e-6f;\n\t}\n\n\tImGui::SameLine();\n\n\tif(ImGui::Button(ICON_FA_GLOBE_AFRICA)) {\n\t\tsky->beta_rayleight() = SkyComponent::earth_beta;\n\t}\n}\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tMeshes\n**************************************************************************\/\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tif(!ctx->world().component(id)) {\n\t\treturn;\n\t}\n\tif(!ImGui::CollapsingHeader(\"Static mesh\")) {\n\t\treturn;\n\t}\n\n\tconst auto static_mesh = [ctx, id]() -> StaticMeshComponent* { return ctx->world().component(id); };\n\t{\n\t\t\/\/ material\n\t\tif(imgui::asset_selector(ctx, static_mesh()->material().id(), AssetType::Material, \"Material\")) {\n\t\t\tctx->ui().add(AssetType::Material)->set_selected_callback(\n\t\t\t\t[=](AssetId asset) {\n\t\t\t\t\tif(const auto material = ctx->loader().load(asset)) {\n\t\t\t\t\t\tif(StaticMeshComponent* comp = static_mesh()) {\n\t\t\t\t\t\t\tcomp->material() = material.unwrap();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t}\n\n\t\t\/\/ mesh\n\t\tif(imgui::asset_selector(ctx, static_mesh()->mesh().id(), AssetType::Mesh, \"Mesh\")) {\n\t\t\tctx->ui().add(AssetType::Mesh)->set_selected_callback(\n\t\t\t\t[=](AssetId asset) {\n\t\t\t\t\tif(const auto mesh = ctx->loader().load(asset)) {\n\t\t\t\t\t\tif(StaticMeshComponent* comp = static_mesh()) {\n\t\t\t\t\t\t\tcomp->mesh() = mesh.unwrap();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t}\n\t}\n}\n\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tEditor\n**************************************************************************\/\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tEditorComponent* component = ctx->world().component(id);\n\tif(!component) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Entity\")) {\n\t\treturn;\n\t}\n\n\tconst core::String& name = component->name();\n\n\tstd::array name_buffer;\n\tstd::fill(name_buffer.begin(), name_buffer.end(), 0);\n\tstd::copy(name.begin(), name.end(), name_buffer.begin());\n\n\tif(ImGui::InputText(\"Name\", name_buffer.begin(), name_buffer.size())) {\n\t\tcomponent->set_name(name_buffer.begin());\n\t}\n}\n\n}\nAdded transformable editor back\/*******************************\nCopyright (c) 2016-2019 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n\n#include \"componentwidgets.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace editor {\nnamespace detail {\n\nstatic ComponentWidgetData* first_component = nullptr;\n\nvoid register_component_widget(ComponentWidgetData* data) {\n\tdata->next = first_component;\n\tfirst_component = data;\n}\n\n}\n\nvoid draw_component_widgets(ContextPtr ctx, ecs::EntityId id) {\n\tfor(detail::ComponentWidgetData* data = detail::first_component; data; data = data->next) {\n\t\ty_debug_assert(data->func);\n\t\tdata->func(ctx, id);\n\t}\n}\n\n\n\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tLights\n**************************************************************************\/\n\ntemplate\nstatic void light_widget(T* light) {\n\tconst int color_flags = ImGuiColorEditFlags_NoSidePreview |\n\t\t\t\t\t \/\/ ImGuiColorEditFlags_NoSmallPreview |\n\t\t\t\t\t ImGuiColorEditFlags_NoAlpha |\n\t\t\t\t\t ImGuiColorEditFlags_Float |\n\t\t\t\t\t ImGuiColorEditFlags_InputRGB;\n\n\tconst math::Vec4 color(light->color(), 1.0f);\n\tif(ImGui::ColorButton(\"Color\", color, color_flags)) {\n\t\tImGui::OpenPopup(\"Color\");\n\t}\n\tImGui::SameLine();\n\tImGui::Text(\"Light color\");\n\n\tif(ImGui::BeginPopup(\"Color\")) {\n\t\tImGui::ColorPicker3(\"##lightpicker\", light->color().begin(), color_flags);\n\n\t\tfloat kelvin = std::clamp(rgb_to_k(light->color()), 1000.0f, 12000.0f);\n\t\tif(ImGui::SliderFloat(\"\", &kelvin, 1000.0f, 12000.0f, \"%.0f°K\")) {\n\t\t\tlight->color() = k_to_rbg(kelvin);\n\t\t}\n\n\t\tImGui::EndPopup();\n\t}\n\n\tImGui::DragFloat(\"Intensity\", &light->intensity(), 1.0f, 0.0f, std::numeric_limits::max());\n}\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tPointLightComponent* light = ctx->world().component(id);\n\tif(!light) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Point light\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\n\tlight_widget(light);\n\n\tImGui::DragFloat(\"Radius\", &light->radius(), 1.0f, 0.0f, std::numeric_limits::max(), \"%.2f\");\n\tImGui::DragFloat(\"Falloff\", &light->falloff(), 0.1f, 0.0f, std::numeric_limits::max(), \"%.2f\", 2.0f);\n}\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tDirectionalLightComponent* light = ctx->world().component(id);\n\tif(!light) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Directional light\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\tlight_widget(light);\n\n\tImGui::InputFloat3(\"Direction\", light->direction().data(), \"%.2f\");\n}\n\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tSkyComponent* sky = ctx->world().component(id);\n\tif(!sky) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Sky\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\tlight_widget(&sky->sun());\n\n\tImGui::InputFloat3(\"Direction\", sky->sun().direction().data(), \"%.2f\");\n\n\tmath::Vec3 beta = sky->beta_rayleight() * 1e6f;\n\tif(ImGui::InputFloat3(\"Beta\", beta.data(), \"%.2f\")) {\n\t\tsky->beta_rayleight() = beta * 1e-6f;\n\t}\n\n\tImGui::SameLine();\n\n\tif(ImGui::Button(ICON_FA_GLOBE_AFRICA)) {\n\t\tsky->beta_rayleight() = SkyComponent::earth_beta;\n\t}\n}\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tMeshes\n**************************************************************************\/\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tif(!ctx->world().component(id)) {\n\t\treturn;\n\t}\n\tif(!ImGui::CollapsingHeader(\"Static mesh\")) {\n\t\treturn;\n\t}\n\n\tconst auto static_mesh = [ctx, id]() -> StaticMeshComponent* { return ctx->world().component(id); };\n\t{\n\t\t\/\/ material\n\t\tif(imgui::asset_selector(ctx, static_mesh()->material().id(), AssetType::Material, \"Material\")) {\n\t\t\tctx->ui().add(AssetType::Material)->set_selected_callback(\n\t\t\t\t[=](AssetId asset) {\n\t\t\t\t\tif(const auto material = ctx->loader().load(asset)) {\n\t\t\t\t\t\tif(StaticMeshComponent* comp = static_mesh()) {\n\t\t\t\t\t\t\tcomp->material() = material.unwrap();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t}\n\n\t\t\/\/ mesh\n\t\tif(imgui::asset_selector(ctx, static_mesh()->mesh().id(), AssetType::Mesh, \"Mesh\")) {\n\t\t\tctx->ui().add(AssetType::Mesh)->set_selected_callback(\n\t\t\t\t[=](AssetId asset) {\n\t\t\t\t\tif(const auto mesh = ctx->loader().load(asset)) {\n\t\t\t\t\t\tif(StaticMeshComponent* comp = static_mesh()) {\n\t\t\t\t\t\t\tcomp->mesh() = mesh.unwrap();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t}\n\t}\n}\n\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tTransformable\n**************************************************************************\/\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tTransformableComponent* component = ctx->world().component(id);\n\tif(!component) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Transform\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\t\treturn;\n\t}\n\n\t{\n\t\tmath::Vec3 prev_euler; \/\/ this should be stable\n\t\tauto [pos, rot, scale] = component->transform().decompose();\n\n\t\t\/\/ position\n\t\t{\n\t\t\tImGui::BeginGroup();\n\t\t\tImGui::InputFloat3(\"Position\", pos.data(), \"%.2f\");\n\t\t\tImGui::EndGroup();\n\t\t}\n\n\t\t\/\/ rotation\n\t\t{\n\t\t\tauto dedouble_quat = [](math::Quaternion<> q) {\n\t\t\t\treturn q.x() < 0.0f ? -q.as_vec() : q.as_vec();\n\t\t\t};\n\t\t\tauto is_same_angle = [&](math::Vec3 a, math::Vec3 b) {\n\t\t\t\tauto qa = math::Quaternion<>::from_euler(a * math::to_rad(1.0f));\n\t\t\t\tauto qb = math::Quaternion<>::from_euler(b * math::to_rad(1.0f));\n\t\t\t\treturn (dedouble_quat(qa) - dedouble_quat(qb)).length2() < 0.0001f;\n\t\t\t};\n\n\t\t\tmath::Vec3 euler = rot.to_euler() * math::to_deg(1.0f);\n\t\t\tif(is_same_angle(euler, prev_euler)) {\n\t\t\t\teuler = prev_euler;\n\t\t\t}\n\n\t\t\tfloat speed = 1.0f;\n\t\t\tImGui::BeginGroup();\n\t\t\tImGui::DragFloat(\"Yaw\", &euler[math::Quaternion<>::YawIndex], speed, -180.0f, 180.0f, \"%.2f\");\n\t\t\tImGui::DragFloat(\"Pitch\", &euler[math::Quaternion<>::PitchIndex], speed, -180.0f, 180.0f, \"%.2f\");\n\t\t\tImGui::DragFloat(\"Roll\", &euler[math::Quaternion<>::RollIndex], speed, -180.0f, 180.0f, \"%.2f\");\n\t\t\tImGui::EndGroup();\n\n\t\t\tif(!is_same_angle(euler, prev_euler)) {\n\t\t\t\tprev_euler = euler;\n\t\t\t\trot = math::Quaternion<>::from_euler(euler * math::to_rad(1.0f));\n\t\t\t}\n\t\t}\n\n\t\tcomponent->transform() = math::Transform<>(pos, rot, scale);\n\t}\n}\n\n\n\n\/**************************************************************************\n*\t\t\t\t\t\t\t\tEditor\n**************************************************************************\/\n\neditor_widget_draw_func(ContextPtr ctx, ecs::EntityId id) {\n\tEditorComponent* component = ctx->world().component(id);\n\tif(!component) {\n\t\treturn;\n\t}\n\n\tif(!ImGui::CollapsingHeader(\"Entity\")) {\n\t\treturn;\n\t}\n\n\tconst core::String& name = component->name();\n\n\tstd::array name_buffer;\n\tstd::fill(name_buffer.begin(), name_buffer.end(), 0);\n\tstd::copy(name.begin(), name.end(), name_buffer.begin());\n\n\tif(ImGui::InputText(\"Name\", name_buffer.begin(), name_buffer.size())) {\n\t\tcomponent->set_name(name_buffer.begin());\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Test the behavior of malloc\/calloc\/realloc when the allocation size is huge.\n\/\/ By default (allocator_may_return_null=0) the process shoudl crash.\n\/\/ With allocator_may_return_null=1 the allocator should return 0.\n\/\/\n\/\/ RUN: %clangxx_asan -O0 %s -o %t\n\/\/ RUN: not %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t calloc 2>&1 | FileCheck %s --check-prefix=CHECK-cCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t calloc 2>&1 | FileCheck %s --check-prefix=CHECK-cNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t calloc-overflow 2>&1 | FileCheck %s --check-prefix=CHECK-coCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t calloc-overflow 2>&1 | FileCheck %s --check-prefix=CHECK-coNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t realloc 2>&1 | FileCheck %s --check-prefix=CHECK-rCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t realloc 2>&1 | FileCheck %s --check-prefix=CHECK-rNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t realloc-after-malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mrCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t realloc-after-malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mrNULL\n\n#include \n#include \n#include \n#include \n#include \n#include \nint main(int argc, char **argv) {\n volatile size_t size = std::numeric_limits::max() - 10000;\n assert(argc == 2);\n char *x = 0;\n if (!strcmp(argv[1], \"malloc\")) {\n fprintf(stderr, \"malloc:\\n\");\n x = (char*)malloc(size);\n }\n if (!strcmp(argv[1], \"calloc\")) {\n fprintf(stderr, \"calloc:\\n\");\n x = (char*)calloc(size \/ 4, 4);\n }\n\n if (!strcmp(argv[1], \"calloc-overflow\")) {\n fprintf(stderr, \"calloc-overflow:\\n\");\n volatile size_t kMaxSizeT = std::numeric_limits::max();\n size_t kArraySize = 4096;\n volatile size_t kArraySize2 = kMaxSizeT \/ kArraySize + 10;\n x = (char*)calloc(kArraySize, kArraySize2);\n }\n\n if (!strcmp(argv[1], \"realloc\")) {\n fprintf(stderr, \"realloc:\\n\");\n x = (char*)realloc(0, size);\n }\n if (!strcmp(argv[1], \"realloc-after-malloc\")) {\n fprintf(stderr, \"realloc-after-malloc:\\n\");\n char *t = (char*)malloc(100);\n *t = 42;\n x = (char*)realloc(t, size);\n assert(*t == 42);\n }\n fprintf(stderr, \"x: %p\\n\", x);\n return x != 0;\n}\n\/\/ CHECK-mCRASH: malloc:\n\/\/ CHECK-mCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-cCRASH: calloc:\n\/\/ CHECK-cCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-coCRASH: calloc-overflow:\n\/\/ CHECK-coCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-rCRASH: realloc:\n\/\/ CHECK-rCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-mrCRASH: realloc-after-malloc:\n\/\/ CHECK-mrCRASH: AddressSanitizer's allocator is terminating the process\n\n\/\/ CHECK-mNULL: malloc:\n\/\/ CHECK-mNULL: x: (nil)\n\/\/ CHECK-cNULL: calloc:\n\/\/ CHECK-cNULL: x: (nil)\n\/\/ CHECK-coNULL: calloc-overflow:\n\/\/ CHECK-coNULL: x: (nil)\n\/\/ CHECK-rNULL: realloc:\n\/\/ CHECK-rNULL: x: (nil)\n\/\/ CHECK-mrNULL: realloc-after-malloc:\n\/\/ CHECK-mrNULL: x: (nil)\n[ASan] make the check for NULL more portable.\/\/ Test the behavior of malloc\/calloc\/realloc when the allocation size is huge.\n\/\/ By default (allocator_may_return_null=0) the process shoudl crash.\n\/\/ With allocator_may_return_null=1 the allocator should return 0.\n\/\/\n\/\/ RUN: %clangxx_asan -O0 %s -o %t\n\/\/ RUN: not %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t calloc 2>&1 | FileCheck %s --check-prefix=CHECK-cCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t calloc 2>&1 | FileCheck %s --check-prefix=CHECK-cNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t calloc-overflow 2>&1 | FileCheck %s --check-prefix=CHECK-coCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t calloc-overflow 2>&1 | FileCheck %s --check-prefix=CHECK-coNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t realloc 2>&1 | FileCheck %s --check-prefix=CHECK-rCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t realloc 2>&1 | FileCheck %s --check-prefix=CHECK-rNULL\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=0 not %t realloc-after-malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mrCRASH\n\/\/ RUN: ASAN_OPTIONS=allocator_may_return_null=1 %t realloc-after-malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mrNULL\n\n#include \n#include \n#include \n#include \n#include \n#include \nint main(int argc, char **argv) {\n volatile size_t size = std::numeric_limits::max() - 10000;\n assert(argc == 2);\n char *x = 0;\n if (!strcmp(argv[1], \"malloc\")) {\n fprintf(stderr, \"malloc:\\n\");\n x = (char*)malloc(size);\n }\n if (!strcmp(argv[1], \"calloc\")) {\n fprintf(stderr, \"calloc:\\n\");\n x = (char*)calloc(size \/ 4, 4);\n }\n\n if (!strcmp(argv[1], \"calloc-overflow\")) {\n fprintf(stderr, \"calloc-overflow:\\n\");\n volatile size_t kMaxSizeT = std::numeric_limits::max();\n size_t kArraySize = 4096;\n volatile size_t kArraySize2 = kMaxSizeT \/ kArraySize + 10;\n x = (char*)calloc(kArraySize, kArraySize2);\n }\n\n if (!strcmp(argv[1], \"realloc\")) {\n fprintf(stderr, \"realloc:\\n\");\n x = (char*)realloc(0, size);\n }\n if (!strcmp(argv[1], \"realloc-after-malloc\")) {\n fprintf(stderr, \"realloc-after-malloc:\\n\");\n char *t = (char*)malloc(100);\n *t = 42;\n x = (char*)realloc(t, size);\n assert(*t == 42);\n }\n \/\/ The NULL pointer is printed differently on different systems, while (long)0\n \/\/ is always the same.\n fprintf(stderr, \"x: %lx\\n\", (long)x);\n return x != 0;\n}\n\/\/ CHECK-mCRASH: malloc:\n\/\/ CHECK-mCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-cCRASH: calloc:\n\/\/ CHECK-cCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-coCRASH: calloc-overflow:\n\/\/ CHECK-coCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-rCRASH: realloc:\n\/\/ CHECK-rCRASH: AddressSanitizer's allocator is terminating the process\n\/\/ CHECK-mrCRASH: realloc-after-malloc:\n\/\/ CHECK-mrCRASH: AddressSanitizer's allocator is terminating the process\n\n\/\/ CHECK-mNULL: malloc:\n\/\/ CHECK-mNULL: x: 0\n\/\/ CHECK-cNULL: calloc:\n\/\/ CHECK-cNULL: x: 0\n\/\/ CHECK-coNULL: calloc-overflow:\n\/\/ CHECK-coNULL: x: 0\n\/\/ CHECK-rNULL: realloc:\n\/\/ CHECK-rNULL: x: 0\n\/\/ CHECK-mrNULL: realloc-after-malloc:\n\/\/ CHECK-mrNULL: x: 0\n<|endoftext|>"} {"text":"#include \"common\/RhodesApp.h\"\n#include \"common\/RhoStd.h\"\n#include \"common\/RhoConf.h\"\n#include \"common\/RhoFile.h\"\n#include \"common\/RhoDefs.h\"\n#include \"common\/Tokenizer.h\"\n#include \"logging\/RhoLogConf.h\"\n#include \"generated\/cpp\/LogCaptureBase.h\"\n\nnamespace rho {\n \n using namespace apiGenerator;\n using namespace common;\n \n class CLogCaptureImpl: public CLogCaptureSingletonBase, public ILogSink\n {\n public:\n \n CLogCaptureImpl(): CLogCaptureSingletonBase(), mMaxLines(1024), mTotalSize(0) {}\n \n \/\/ ILogSink\n virtual void writeLogMessage( String& strMsg )\n {\n if ( mMaxLines > 0 )\n {\n if (mCapturedLog.size() > mMaxLines)\n {\n mCapturedLog.clear();\n mTotalSize = 0;\n }\n \n if (mExcludeCategories.size()>0)\n {\n for(Vector::const_iterator it = mExcludeCategories.begin(); it != mExcludeCategories.end(); ++it)\n {\n if (strMsg.find(*it)!=String::npos)\n {\n return;\n }\n }\n }\n mCapturedLog.push_back(strMsg);\n mTotalSize += strMsg.size() + 2;\n }\n }\n \n virtual int getCurPos()\n {\n return mCapturedLog.size();\n }\n \n virtual void clear()\n {\n \n }\n \n \/\/ ILogCaptureSingleto\n virtual void getExcludeCategories(rho::apiGenerator::CMethodResult& oResult)\n {\n const Vector& log_attr = mExcludeCategories;\n \n size_t len = 0;\n for(Vector::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++)\n {\n len += (*iter).length() + 1; \/\/ including separator\n }\n \n rho::String str;\n str.reserve(len);\n \n for(Vector::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++)\n {\n if (iter != log_attr.begin())\n {\n str += \",\";\n }\n str += *iter;\n }\n \n oResult.set( str );\n }\n \n virtual void setExcludeCategories( const rho::String& excludeCategories, rho::apiGenerator::CMethodResult& oResult)\n {\n if ( excludeCategories.length() > 0 )\n {\n rho::common::CTokenizer oTokenizer( excludeCategories, \",\" );\n while (oTokenizer.hasMoreTokens())\n {\n String tok = rho::String_trim(oTokenizer.nextToken());\n if (tok.length() == 0)\n continue;\n\n mExcludeCategories.addElement( tok );\n } \n }\n else\n mExcludeCategories.removeAllElements();\n }\n \n virtual void getMaxLines(rho::apiGenerator::CMethodResult& oResult)\n {\n oResult.set(mMaxLines);\n }\n \n virtual void setMaxLines( int maxLines, rho::apiGenerator::CMethodResult& oResult)\n {\n mMaxLines = maxLines;\n }\n \n virtual void start(rho::apiGenerator::CMethodResult& oResult)\n {\n LOGCONF().addAuxSink(this);\n }\n \n virtual void stop(rho::apiGenerator::CMethodResult& oResult)\n {\n LOGCONF().removeAuxSink(this);\n }\n \n virtual void clear(rho::apiGenerator::CMethodResult& oResult)\n {\n mCapturedLog.clear();\n mTotalSize = 0;\n }\n \n virtual void numLines(rho::apiGenerator::CMethodResult& oResult)\n {\n oResult.set( static_cast(mCapturedLog.size()) );\n }\n \n virtual void read(rho::apiGenerator::CMethodResult& oResult)\n {\n String str;\n\n str.reserve(mTotalSize);\n for (Vector::iterator it = mCapturedLog.begin(); it != mCapturedLog.end(); ++it )\n {\n str += *it;\n str += '\\n';\n }\n \n oResult.set(str);\n }\n \n private:\n Vector mCapturedLog;\n Vector mExcludeCategories;\n int mMaxLines;\n size_t mTotalSize;\n };\n \n class CLogCaptureFactory: public CLogCaptureFactoryBase\n {\n public:\n ~CLogCaptureFactory(){}\n \n ILogCaptureSingleton* createModuleSingleton()\n { \n return new CLogCaptureImpl(); \n }\n };\n}\n\nextern \"C\" void Init_LogCapture_extension()\n{\n rho::CLogCaptureFactory::setInstance( new rho::CLogCaptureFactory() );\n rho::Init_LogCapture_API();\n}\nAdd proper LogCapture destructor#include \"common\/RhodesApp.h\"\n#include \"common\/RhoStd.h\"\n#include \"common\/RhoConf.h\"\n#include \"common\/RhoFile.h\"\n#include \"common\/RhoDefs.h\"\n#include \"common\/Tokenizer.h\"\n#include \"logging\/RhoLogConf.h\"\n#include \"generated\/cpp\/LogCaptureBase.h\"\n\nnamespace rho {\n \n using namespace apiGenerator;\n using namespace common;\n \n class CLogCaptureImpl: public CLogCaptureSingletonBase, public ILogSink\n {\n public:\n \n CLogCaptureImpl(): CLogCaptureSingletonBase(), mMaxLines(1024), mTotalSize(0) {}\n virtual ~CLogCaptureImpl()\n {\n LOGCONF().removeAuxSink(this);\n }\n \n \/\/ ILogSink\n virtual void writeLogMessage( String& strMsg )\n {\n if ( mMaxLines > 0 )\n {\n if (mCapturedLog.size() > mMaxLines)\n {\n mCapturedLog.clear();\n mTotalSize = 0;\n }\n \n if (mExcludeCategories.size()>0)\n {\n for(Vector::const_iterator it = mExcludeCategories.begin(); it != mExcludeCategories.end(); ++it)\n {\n if (strMsg.find(*it)!=String::npos)\n {\n return;\n }\n }\n }\n mCapturedLog.push_back(strMsg);\n mTotalSize += strMsg.size() + 2;\n }\n }\n \n virtual int getCurPos()\n {\n return mCapturedLog.size();\n }\n \n virtual void clear()\n {\n \n }\n \n \/\/ ILogCaptureSingleto\n virtual void getExcludeCategories(rho::apiGenerator::CMethodResult& oResult)\n {\n const Vector& log_attr = mExcludeCategories;\n \n size_t len = 0;\n for(Vector::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++)\n {\n len += (*iter).length() + 1; \/\/ including separator\n }\n \n rho::String str;\n str.reserve(len);\n \n for(Vector::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++)\n {\n if (iter != log_attr.begin())\n {\n str += \",\";\n }\n str += *iter;\n }\n \n oResult.set( str );\n }\n \n virtual void setExcludeCategories( const rho::String& excludeCategories, rho::apiGenerator::CMethodResult& oResult)\n {\n if ( excludeCategories.length() > 0 )\n {\n rho::common::CTokenizer oTokenizer( excludeCategories, \",\" );\n while (oTokenizer.hasMoreTokens())\n {\n String tok = rho::String_trim(oTokenizer.nextToken());\n if (tok.length() == 0)\n continue;\n\n mExcludeCategories.addElement( tok );\n } \n }\n else\n mExcludeCategories.removeAllElements();\n }\n \n virtual void getMaxLines(rho::apiGenerator::CMethodResult& oResult)\n {\n oResult.set(mMaxLines);\n }\n \n virtual void setMaxLines( int maxLines, rho::apiGenerator::CMethodResult& oResult)\n {\n mMaxLines = maxLines;\n }\n \n virtual void start(rho::apiGenerator::CMethodResult& oResult)\n {\n LOGCONF().addAuxSink(this);\n }\n \n virtual void stop(rho::apiGenerator::CMethodResult& oResult)\n {\n LOGCONF().removeAuxSink(this);\n }\n \n virtual void clear(rho::apiGenerator::CMethodResult& oResult)\n {\n mCapturedLog.clear();\n mTotalSize = 0;\n }\n \n virtual void numLines(rho::apiGenerator::CMethodResult& oResult)\n {\n oResult.set( static_cast(mCapturedLog.size()) );\n }\n \n virtual void read(rho::apiGenerator::CMethodResult& oResult)\n {\n String str;\n\n str.reserve(mTotalSize);\n for (Vector::iterator it = mCapturedLog.begin(); it != mCapturedLog.end(); ++it )\n {\n str += *it;\n str += '\\n';\n }\n \n oResult.set(str);\n }\n \n private:\n Vector mCapturedLog;\n Vector mExcludeCategories;\n int mMaxLines;\n size_t mTotalSize;\n };\n \n class CLogCaptureFactory: public CLogCaptureFactoryBase\n {\n public:\n ~CLogCaptureFactory(){}\n \n ILogCaptureSingleton* createModuleSingleton()\n { \n return new CLogCaptureImpl(); \n }\n };\n}\n\nextern \"C\" void Init_LogCapture_extension()\n{\n rho::CLogCaptureFactory::setInstance( new rho::CLogCaptureFactory() );\n rho::Init_LogCapture_API();\n}\n<|endoftext|>"} {"text":"#include \n\/\/ -- (textra first)\n#include \"ceres_subspace_functor.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace tools::finite::opt;\nusing namespace tools::finite::opt::internal;\n\n\n\nvoid tools::finite::opt::internal::subspace::filter_candidates(std::vector &candidate_list, double maximum_subspace_error, size_t max_accept) {\n \/\/ Sort the candidate list in order of descending overlaps. If the overlaps are the same, compare instead the distance in energy to the\n \/\/ current energy\n std::sort(candidate_list.begin(),candidate_list.end(), std::greater<>());\n size_t initial_size = candidate_list.size();\n size_t min_accept = std::min(std::min(max_accept,32ul), candidate_list.size());\n max_accept = std::min(max_accept, candidate_list.size());\n double subspace_error = subspace::get_subspace_error(candidate_list); \/\/ This number is as low as it gets now, and will start growing\n while(true){\n if(candidate_list.size() <= max_accept){\n if(candidate_list.size() <= min_accept) break;\n subspace_error = subspace::get_subspace_error(candidate_list);\n if(subspace_error >= maximum_subspace_error) break;\n }\n candidate_list.pop_back();\n }\n size_t idx = 0;\n for(auto & candidate : candidate_list){\n candidate.set_name(fmt::format(\"eigenvector {}\", idx++));\n\/\/ tools::log->trace(\"Filtered {:<16}: overlap {:.16f} | energy {:>20.16f}\", candidate.get_name(), candidate.get_overlap(),\n\/\/ candidate.get_energy_per_site());\n }\n\n tools::log->trace(\"Filtered from {} down to {} states\", initial_size, candidate_list.size());\n tools::log->trace(\"Subspace error after filter = {}\", std::log10(subspace_error));\n if(candidate_list.size() < min_accept) throw std::runtime_error(\"Filtered too many candidates\");\n}\n\n\n\n\nstd::optional tools::finite::opt::internal::subspace::get_idx_to_candidate_with_highest_overlap(const std::vector &candidate_list,\n double energy_llim_per_site, double energy_ulim_per_site) {\n if(candidate_list.empty()) return std::nullopt;\n auto overlaps = get_overlaps(candidate_list);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n if(candidate.get_energy_per_site() > energy_ulim_per_site) overlaps(idx) = 0.0;\n if(candidate.get_energy_per_site() < energy_llim_per_site) overlaps(idx) = 0.0;\n idx++;\n }\n \/\/ Now we have a list of overlaps where nonzero elements correspond do candidates inside the energy window\n \/\/ Get the index to the highest overlapping element\n double max_overlap_val = overlaps.maxCoeff(&idx);\n if(max_overlap_val == 0.0) {\n tools::log->debug(\"No overlapping eigenstates in given energy window {} to {}.\", energy_llim_per_site, energy_ulim_per_site);\n return std::nullopt;\n }\n return idx;\n}\n\nstd::vector tools::finite::opt::internal::subspace::get_idx_to_candidates_with_highest_overlap(const std::vector &candidate_list, size_t max_candidates, double energy_llim_per_site,\n double energy_ulim_per_site) {\n if(candidate_list.empty()) return std::vector();\n auto overlaps = get_overlaps(candidate_list);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n if(candidate.get_energy_per_site() > energy_ulim_per_site) overlaps(idx) = 0.0;\n if(candidate.get_energy_per_site() < energy_llim_per_site) overlaps(idx) = 0.0;\n idx++;\n }\n \/\/ Now we have a list of overlaps where nonzero elements correspond do candidates inside the energy window\n \/\/ Get the index to the highest overlapping element\n double max_overlap_val = overlaps.maxCoeff();\n if(max_overlap_val == 0.0) {\n tools::log->debug(\"No overlapping eigenstates in given energy window {} to {}.\", energy_llim_per_site, energy_ulim_per_site);\n return std::vector();\n }\n\n std::vector best_idx;\n std::vector best_val;\n \/\/ We collect the best candidates from this list until the squared sum of their overlaps goes above a certain threshold.\n \/\/ Note that the squared sum overlap = 1 if the states in the list form a complete basis for the current state.\n while(true) {\n max_overlap_val = overlaps.maxCoeff(&idx);\n if(max_overlap_val == 0.0) break;\n best_idx.emplace_back(idx);\n const auto &candidate = *std::next(candidate_list.begin(), static_cast(idx));\n if(candidate.is_basis_vector) best_val.emplace_back(max_overlap_val);\n if(best_idx.size() > max_candidates) break;\n double sq_sum_overlap = overlaps.cwiseAbs2().sum();\n if(sq_sum_overlap > 0.6) break; \/\/ Half means cat state.\n overlaps(idx) = 0.0; \/\/ Zero out the current best so the next-best is found in the next iteration\n }\n tools::log->debug(\"Found {} candidates with good overlap in energy window\", best_idx.size());\n return best_idx;\n}\n\n\nEigen::MatrixXcd tools::finite::opt::internal::subspace::get_eigvecs(const std::vector &candidate_list) {\n long rows = candidate_list.front().get_tensor().size();\n long cols = static_cast(candidate_list.size());\n Eigen::MatrixXcd eigvecs(rows, cols);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n eigvecs.col(idx++) = Eigen::Map(candidate.get_tensor().data(), rows);\n }\n eigvecs.conservativeResize(rows, idx);\n return eigvecs;\n}\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_eigvals(const std::vector &candidate_list) {\n long size = static_cast(candidate_list.size());\n Eigen::VectorXd eigvals(size);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n eigvals(idx++) = candidate.get_eigval();\n }\n eigvals.conservativeResize(idx);\n return eigvals;\n}\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_energies(const std::vector &candidate_list) {\n Eigen::VectorXd energies(static_cast(candidate_list.size()));\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n energies(idx++) = candidate.get_energy();\n }\n energies.conservativeResize(idx);\n return energies;\n}\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_energies_per_site(const std::vector &candidate_list) {\n Eigen::VectorXd energies(static_cast(candidate_list.size()));\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n energies(idx++) = candidate.get_energy_per_site();\n }\n energies.conservativeResize(idx);\n return energies;\n}\n\n\ndouble tools::finite::opt::internal::subspace::get_subspace_error(const std::vector &candidate_list) {\n double eps = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n eps += std::pow(candidate.get_overlap(), 2);\n }\n return 1.0 - eps;\n}\n\n\ndouble tools::finite::opt::internal::subspace::get_subspace_error(const std::vector &overlaps) {\n double eps = 0;\n for(const auto &overlap : overlaps) {\n eps += std::pow(overlap, 2);\n }\n return 1.0 - eps;\n}\n\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_overlaps(const std::vector &candidate_list) {\n Eigen::VectorXd overlaps(static_cast(candidate_list.size()));\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n overlaps(idx++) = candidate.get_overlap();\n }\n overlaps.conservativeResize(idx);\n return overlaps;\n}\n\nstd::pair find_max_overlap(const std::vector &overlaps) {\n auto max_it = max_element(overlaps.begin(), overlaps.end());\n auto max_val = *max_it;\n auto max_idx = std::distance(overlaps.begin(), max_it);\n return {max_val, static_cast(max_idx)};\n}\n\nEigen::VectorXcd tools::finite::opt::internal::subspace::get_vector_in_subspace(const std::vector &candidate_list, size_t idx) {\n \/\/ In this function we project a vector to the subspace spanned by a small set of eigenvectors\n \/\/ Essentially this old computation\n \/\/ Eigen::VectorXcd subspace_vector = (eigvecs.adjoint() * fullspace_vector).normalized();\n\n auto fullspace_vector = std::next(candidate_list.begin(), static_cast(idx))->get_vector();\n long subspace_size = static_cast(candidate_list.size());\n Eigen::VectorXcd subspace_vector(subspace_size);\n long subspace_idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n subspace_vector(subspace_idx++) = candidate.get_vector().dot(fullspace_vector);\n }\n subspace_vector.conservativeResize(subspace_idx);\n return subspace_vector.normalized();\n}\n\nEigen::VectorXcd tools::finite::opt::internal::subspace::get_vector_in_subspace(const std::vector &candidate_list, const Eigen::VectorXcd & fullspace_vector) {\n \/\/ In this function we project a vector to the subspace spanned by a small set of eigenvectors\n \/\/ Essentially this old computation\n \/\/ Eigen::VectorXcd subspace_vector = (eigvecs.adjoint() * fullspace_vector).normalized();\n long subspace_size = static_cast(candidate_list.size());\n Eigen::VectorXcd subspace_vector(subspace_size);\n long subspace_idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n subspace_vector(subspace_idx++) = candidate.get_vector().adjoint() * fullspace_vector;\n }\n subspace_vector.conservativeResize(subspace_idx);\n return subspace_vector.normalized();\n}\n\n\nEigen::VectorXcd tools::finite::opt::internal::subspace::get_vector_in_fullspace(const std::vector &candidate_list,\n const Eigen::VectorXcd & subspace_vector) {\n \/\/ In this function we project a subspace vector back to the full space\n \/\/ Essentially this old computation\n \/\/ Eigen::VectorXcd fullspace_vector = (eigvecs * subspace_vector.asDiagonal()).rowwise().sum().normalized();\n \/\/\n \/\/ The subspace_vector is a list of weights corresponding to each eigenvector that we use to form a linear combination.\n \/\/ Therefore all we need to do to obtain the fullspace vector is to actually add up the linear combination with those weights.\n\n long fullspace_size = candidate_list.front().get_vector().size();\n Eigen::VectorXcd fullspace_vector(fullspace_size);\n fullspace_vector.setZero();\n long subspace_idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n fullspace_vector += candidate.get_vector() * subspace_vector(subspace_idx++);\n }\n return fullspace_vector.normalized();\n}\nUse dot product instead of adjoint. Some compilers don't seem to like the implicit conversion to double when using adjoint()#include \n\/\/ -- (textra first)\n#include \"ceres_subspace_functor.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace tools::finite::opt;\nusing namespace tools::finite::opt::internal;\n\n\n\nvoid tools::finite::opt::internal::subspace::filter_candidates(std::vector &candidate_list, double maximum_subspace_error, size_t max_accept) {\n \/\/ Sort the candidate list in order of descending overlaps. If the overlaps are the same, compare instead the distance in energy to the\n \/\/ current energy\n std::sort(candidate_list.begin(),candidate_list.end(), std::greater<>());\n size_t initial_size = candidate_list.size();\n size_t min_accept = std::min(std::min(max_accept,32ul), candidate_list.size());\n max_accept = std::min(max_accept, candidate_list.size());\n double subspace_error = subspace::get_subspace_error(candidate_list); \/\/ This number is as low as it gets now, and will start growing\n while(true){\n if(candidate_list.size() <= max_accept){\n if(candidate_list.size() <= min_accept) break;\n subspace_error = subspace::get_subspace_error(candidate_list);\n if(subspace_error >= maximum_subspace_error) break;\n }\n candidate_list.pop_back();\n }\n size_t idx = 0;\n for(auto & candidate : candidate_list){\n candidate.set_name(fmt::format(\"eigenvector {}\", idx++));\n\/\/ tools::log->trace(\"Filtered {:<16}: overlap {:.16f} | energy {:>20.16f}\", candidate.get_name(), candidate.get_overlap(),\n\/\/ candidate.get_energy_per_site());\n }\n\n tools::log->trace(\"Filtered from {} down to {} states\", initial_size, candidate_list.size());\n tools::log->trace(\"Subspace error after filter = {}\", std::log10(subspace_error));\n if(candidate_list.size() < min_accept) throw std::runtime_error(\"Filtered too many candidates\");\n}\n\n\n\n\nstd::optional tools::finite::opt::internal::subspace::get_idx_to_candidate_with_highest_overlap(const std::vector &candidate_list,\n double energy_llim_per_site, double energy_ulim_per_site) {\n if(candidate_list.empty()) return std::nullopt;\n auto overlaps = get_overlaps(candidate_list);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n if(candidate.get_energy_per_site() > energy_ulim_per_site) overlaps(idx) = 0.0;\n if(candidate.get_energy_per_site() < energy_llim_per_site) overlaps(idx) = 0.0;\n idx++;\n }\n \/\/ Now we have a list of overlaps where nonzero elements correspond do candidates inside the energy window\n \/\/ Get the index to the highest overlapping element\n double max_overlap_val = overlaps.maxCoeff(&idx);\n if(max_overlap_val == 0.0) {\n tools::log->debug(\"No overlapping eigenstates in given energy window {} to {}.\", energy_llim_per_site, energy_ulim_per_site);\n return std::nullopt;\n }\n return idx;\n}\n\nstd::vector tools::finite::opt::internal::subspace::get_idx_to_candidates_with_highest_overlap(const std::vector &candidate_list, size_t max_candidates, double energy_llim_per_site,\n double energy_ulim_per_site) {\n if(candidate_list.empty()) return std::vector();\n auto overlaps = get_overlaps(candidate_list);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n if(candidate.get_energy_per_site() > energy_ulim_per_site) overlaps(idx) = 0.0;\n if(candidate.get_energy_per_site() < energy_llim_per_site) overlaps(idx) = 0.0;\n idx++;\n }\n \/\/ Now we have a list of overlaps where nonzero elements correspond do candidates inside the energy window\n \/\/ Get the index to the highest overlapping element\n double max_overlap_val = overlaps.maxCoeff();\n if(max_overlap_val == 0.0) {\n tools::log->debug(\"No overlapping eigenstates in given energy window {} to {}.\", energy_llim_per_site, energy_ulim_per_site);\n return std::vector();\n }\n\n std::vector best_idx;\n std::vector best_val;\n \/\/ We collect the best candidates from this list until the squared sum of their overlaps goes above a certain threshold.\n \/\/ Note that the squared sum overlap = 1 if the states in the list form a complete basis for the current state.\n while(true) {\n max_overlap_val = overlaps.maxCoeff(&idx);\n if(max_overlap_val == 0.0) break;\n best_idx.emplace_back(idx);\n const auto &candidate = *std::next(candidate_list.begin(), static_cast(idx));\n if(candidate.is_basis_vector) best_val.emplace_back(max_overlap_val);\n if(best_idx.size() > max_candidates) break;\n double sq_sum_overlap = overlaps.cwiseAbs2().sum();\n if(sq_sum_overlap > 0.6) break; \/\/ Half means cat state.\n overlaps(idx) = 0.0; \/\/ Zero out the current best so the next-best is found in the next iteration\n }\n tools::log->debug(\"Found {} candidates with good overlap in energy window\", best_idx.size());\n return best_idx;\n}\n\n\nEigen::MatrixXcd tools::finite::opt::internal::subspace::get_eigvecs(const std::vector &candidate_list) {\n long rows = candidate_list.front().get_tensor().size();\n long cols = static_cast(candidate_list.size());\n Eigen::MatrixXcd eigvecs(rows, cols);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n eigvecs.col(idx++) = Eigen::Map(candidate.get_tensor().data(), rows);\n }\n eigvecs.conservativeResize(rows, idx);\n return eigvecs;\n}\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_eigvals(const std::vector &candidate_list) {\n long size = static_cast(candidate_list.size());\n Eigen::VectorXd eigvals(size);\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n eigvals(idx++) = candidate.get_eigval();\n }\n eigvals.conservativeResize(idx);\n return eigvals;\n}\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_energies(const std::vector &candidate_list) {\n Eigen::VectorXd energies(static_cast(candidate_list.size()));\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n energies(idx++) = candidate.get_energy();\n }\n energies.conservativeResize(idx);\n return energies;\n}\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_energies_per_site(const std::vector &candidate_list) {\n Eigen::VectorXd energies(static_cast(candidate_list.size()));\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n energies(idx++) = candidate.get_energy_per_site();\n }\n energies.conservativeResize(idx);\n return energies;\n}\n\n\ndouble tools::finite::opt::internal::subspace::get_subspace_error(const std::vector &candidate_list) {\n double eps = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n eps += std::pow(candidate.get_overlap(), 2);\n }\n return 1.0 - eps;\n}\n\n\ndouble tools::finite::opt::internal::subspace::get_subspace_error(const std::vector &overlaps) {\n double eps = 0;\n for(const auto &overlap : overlaps) {\n eps += std::pow(overlap, 2);\n }\n return 1.0 - eps;\n}\n\n\nEigen::VectorXd tools::finite::opt::internal::subspace::get_overlaps(const std::vector &candidate_list) {\n Eigen::VectorXd overlaps(static_cast(candidate_list.size()));\n long idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n overlaps(idx++) = candidate.get_overlap();\n }\n overlaps.conservativeResize(idx);\n return overlaps;\n}\n\nstd::pair find_max_overlap(const std::vector &overlaps) {\n auto max_it = max_element(overlaps.begin(), overlaps.end());\n auto max_val = *max_it;\n auto max_idx = std::distance(overlaps.begin(), max_it);\n return {max_val, static_cast(max_idx)};\n}\n\nEigen::VectorXcd tools::finite::opt::internal::subspace::get_vector_in_subspace(const std::vector &candidate_list, size_t idx) {\n \/\/ In this function we project a vector to the subspace spanned by a small set of eigenvectors\n \/\/ Essentially this old computation\n \/\/ Eigen::VectorXcd subspace_vector = (eigvecs.adjoint() * fullspace_vector).normalized();\n\n auto fullspace_vector = std::next(candidate_list.begin(), static_cast(idx))->get_vector();\n long subspace_size = static_cast(candidate_list.size());\n Eigen::VectorXcd subspace_vector(subspace_size);\n long subspace_idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n subspace_vector(subspace_idx++) = candidate.get_vector().dot(fullspace_vector);\n }\n subspace_vector.conservativeResize(subspace_idx);\n return subspace_vector.normalized();\n}\n\nEigen::VectorXcd tools::finite::opt::internal::subspace::get_vector_in_subspace(const std::vector &candidate_list, const Eigen::VectorXcd & fullspace_vector) {\n \/\/ In this function we project a vector to the subspace spanned by a small set of eigenvectors\n \/\/ Essentially this old computation\n \/\/ Eigen::VectorXcd subspace_vector = (eigvecs.adjoint() * fullspace_vector).normalized();\n long subspace_size = static_cast(candidate_list.size());\n Eigen::VectorXcd subspace_vector(subspace_size);\n long subspace_idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n subspace_vector(subspace_idx++) = candidate.get_vector().dot(fullspace_vector);\n }\n subspace_vector.conservativeResize(subspace_idx);\n return subspace_vector.normalized();\n}\n\n\nEigen::VectorXcd tools::finite::opt::internal::subspace::get_vector_in_fullspace(const std::vector &candidate_list,\n const Eigen::VectorXcd & subspace_vector) {\n \/\/ In this function we project a subspace vector back to the full space\n \/\/ Essentially this old computation\n \/\/ Eigen::VectorXcd fullspace_vector = (eigvecs * subspace_vector.asDiagonal()).rowwise().sum().normalized();\n \/\/\n \/\/ The subspace_vector is a list of weights corresponding to each eigenvector that we use to form a linear combination.\n \/\/ Therefore all we need to do to obtain the fullspace vector is to actually add up the linear combination with those weights.\n\n long fullspace_size = candidate_list.front().get_vector().size();\n Eigen::VectorXcd fullspace_vector(fullspace_size);\n fullspace_vector.setZero();\n long subspace_idx = 0;\n for(const auto &candidate : candidate_list) {\n if(not candidate.is_basis_vector) continue;\n fullspace_vector += candidate.get_vector() * subspace_vector(subspace_idx++);\n }\n return fullspace_vector.normalized();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"InteriorsExplorerController.h\"\n#include \"InteriorsExplorerModel.h\"\n#include \"InteriorsExplorerViewModel.h\"\n#include \"IInteriorsExplorerView.h\"\n#include \"IMenuViewModel.h\"\n#include \"IScreenControlViewModel.h\"\n#include \"IMyPinCreationInitiationViewModel.h\"\n#include \"InteriorsExplorerFloorSelectionDraggedMessage.h\"\n#include \"ApplyScreenControl.h\"\n#include \"WorldPinVisibility.h\"\n\nnamespace ExampleApp\n{\n namespace InteriorsExplorer\n {\n namespace View\n {\n InteriorsExplorerController::InteriorsExplorerController(SdkModel::InteriorsExplorerModel& model,\n IInteriorsExplorerView& view,\n InteriorsExplorerViewModel& viewModel,\n ExampleAppMessaging::TMessageBus& messageBus)\n : m_model(model)\n , m_view(view)\n , m_viewModel(viewModel)\n , m_replayTutorials(false)\n , m_messageBus(messageBus)\n , m_appMode(AppModes::SdkModel::WorldMode)\n , m_dismissedCallback(this, &InteriorsExplorerController::OnDismiss)\n , m_selectFloorCallback(this, &InteriorsExplorerController::OnSelectFloor)\n , m_stateChangedCallback(this, &InteriorsExplorerController::OnStateChanged)\n , m_floorSelectedCallback(this, &InteriorsExplorerController::OnFloorSelected)\n , m_draggingFloorSelectionCallback(this, &InteriorsExplorerController::OnFloorSelectionDragged)\n , m_viewStateCallback(this, &InteriorsExplorerController::OnViewStateChangeScreenControl)\n , m_appModeChangedCallback(this, &InteriorsExplorerController::OnAppModeChanged)\n , m_interiorsUINotificationCallback(this, &InteriorsExplorerController::OnInteriorsUINotificationRequired)\n {\n m_messageBus.SubscribeUi(m_stateChangedCallback);\n m_messageBus.SubscribeUi(m_floorSelectedCallback);\n m_messageBus.SubscribeUi(m_appModeChangedCallback);\n m_messageBus.SubscribeUi(m_interiorsUINotificationCallback);\n \n m_viewModel.InsertOnScreenStateChangedCallback(m_viewStateCallback);\n \n m_view.InsertDismissedCallback(m_dismissedCallback);\n m_view.InsertFloorSelectedCallback(m_selectFloorCallback);\n m_view.InsertFloorSelectionDraggedCallback(m_draggingFloorSelectionCallback);\n }\n \n InteriorsExplorerController::~InteriorsExplorerController()\n {\n m_view.RemoveFloorSelectionDraggedCallback(m_draggingFloorSelectionCallback);\n m_view.RemoveDismissedCallback(m_dismissedCallback);\n m_view.RemoveFloorSelectedCallback(m_selectFloorCallback);\n \n m_viewModel.RemoveOnScreenStateChangedCallback(m_viewStateCallback);\n \n m_messageBus.UnsubscribeUi(m_interiorsUINotificationCallback);\n m_messageBus.UnsubscribeUi(m_stateChangedCallback);\n m_messageBus.UnsubscribeUi(m_floorSelectedCallback);\n m_messageBus.UnsubscribeUi(m_appModeChangedCallback);\n }\n \n void InteriorsExplorerController::OnDismiss()\n {\n m_messageBus.Publish(InteriorsExplorerExitMessage());\n m_view.SetTouchEnabled(false);\n }\n \n void InteriorsExplorerController::OnSelectFloor(int& selected)\n {\n m_messageBus.Publish(InteriorsExplorerSelectFloorMessage(selected));\n }\n \n void InteriorsExplorerController::OnFloorSelectionDragged(float &dragParam)\n {\n m_messageBus.Publish(InteriorsExplorerFloorSelectionDraggedMessage(dragParam));\n }\n \n void InteriorsExplorerController::OnFloorSelected(const InteriorsExplorerFloorSelectedMessage& message)\n {\n m_view.SetFloorName(message.GetFloorName());\n \n if(m_viewModel.IsFullyOnScreen())\n {\n m_view.SetSelectedFloorIndex(message.GetFloorIndex());\n }\n }\n \n void InteriorsExplorerController::OnStateChanged(const InteriorsExplorerStateChangedMessage& message)\n {\n if(message.IsInteriorVisible())\n {\n m_view.UpdateFloors(message.GetFloorShortNames(), message.GetSelectedFloorIndex());\n m_view.SetTouchEnabled(true);\n\n OnFloorSelected(InteriorsExplorerFloorSelectedMessage(message.GetSelectedFloorIndex(), message.GetSelectedFloorName()));\n\n\t\t\t\t\tconst int maxTutorialViews = 2;\n\t\t\t\t\tbool showExitTutorial = m_replayTutorials || m_model.GetInteriorExitTutorialViewedCount() < maxTutorialViews;\n\t\t\t\t\tbool showChangeFloorTutorial = (m_replayTutorials || m_model.GetInteriorChangeFloorTutorialViewedCount() < maxTutorialViews) && m_view.GetCanShowChangeFloorTutorialDialog();\n\n\t\t\t\t\tif(showExitTutorial || showChangeFloorTutorial)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_view.AddTutorialDialogs(showExitTutorial, showChangeFloorTutorial);\n\n\t\t\t\t\t\tif(showExitTutorial)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_model.RecordHasViewedInteriorExitTutorial();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(showChangeFloorTutorial)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_model.RecordHasViewedInteriorChangeFloorTutorial();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n ReplayTutorials(false);\n\n m_viewModel.AddToScreen();\n }\n else\n {\n m_viewModel.RemoveFromScreen();\n }\n }\n \n void InteriorsExplorerController::OnViewStateChangeScreenControl(ScreenControl::View::IScreenControlViewModel &viewModel, float &state)\n {\n ScreenControl::View::Apply(m_viewModel, m_view);\n }\n \n void InteriorsExplorerController::OnAppModeChanged(const AppModes::AppModeChangedMessage& message)\n {\n m_appMode = message.GetAppMode();\n }\n\n void InteriorsExplorerController::OnInteriorsUINotificationRequired(const InteriorsExplorerUINotifyMessage & message)\n {\n m_view.PlaySliderAnim();\n }\n\n void InteriorsExplorerController::ReplayTutorials(const bool enableTutorials)\n {\n m_replayTutorials = enableTutorials;\n m_replayTutorialsCallbacks.ExecuteCallbacks(m_replayTutorials);\n }\n\n void InteriorsExplorerController::InsertReplayTutorialsChangedCallback(Eegeo::Helpers::ICallback1& callback)\n {\n m_replayTutorialsCallbacks.AddCallback(callback);\n }\n\n void InteriorsExplorerController::RemoveReplayTutorialsChangedCallback(Eegeo::Helpers::ICallback1& callback)\n {\n m_replayTutorialsCallbacks.RemoveCallback(callback);\n }\n }\n }\n}\nAlways show tutorial dialogs after attract mode ends. Buddy: Blair.\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"InteriorsExplorerController.h\"\n#include \"InteriorsExplorerModel.h\"\n#include \"InteriorsExplorerViewModel.h\"\n#include \"IInteriorsExplorerView.h\"\n#include \"IMenuViewModel.h\"\n#include \"IScreenControlViewModel.h\"\n#include \"IMyPinCreationInitiationViewModel.h\"\n#include \"InteriorsExplorerFloorSelectionDraggedMessage.h\"\n#include \"ApplyScreenControl.h\"\n#include \"WorldPinVisibility.h\"\n\nnamespace ExampleApp\n{\n namespace InteriorsExplorer\n {\n namespace View\n {\n InteriorsExplorerController::InteriorsExplorerController(SdkModel::InteriorsExplorerModel& model,\n IInteriorsExplorerView& view,\n InteriorsExplorerViewModel& viewModel,\n ExampleAppMessaging::TMessageBus& messageBus)\n : m_model(model)\n , m_view(view)\n , m_viewModel(viewModel)\n , m_replayTutorials(false)\n , m_messageBus(messageBus)\n , m_appMode(AppModes::SdkModel::WorldMode)\n , m_dismissedCallback(this, &InteriorsExplorerController::OnDismiss)\n , m_selectFloorCallback(this, &InteriorsExplorerController::OnSelectFloor)\n , m_stateChangedCallback(this, &InteriorsExplorerController::OnStateChanged)\n , m_floorSelectedCallback(this, &InteriorsExplorerController::OnFloorSelected)\n , m_draggingFloorSelectionCallback(this, &InteriorsExplorerController::OnFloorSelectionDragged)\n , m_viewStateCallback(this, &InteriorsExplorerController::OnViewStateChangeScreenControl)\n , m_appModeChangedCallback(this, &InteriorsExplorerController::OnAppModeChanged)\n , m_interiorsUINotificationCallback(this, &InteriorsExplorerController::OnInteriorsUINotificationRequired)\n {\n m_messageBus.SubscribeUi(m_stateChangedCallback);\n m_messageBus.SubscribeUi(m_floorSelectedCallback);\n m_messageBus.SubscribeUi(m_appModeChangedCallback);\n m_messageBus.SubscribeUi(m_interiorsUINotificationCallback);\n \n m_viewModel.InsertOnScreenStateChangedCallback(m_viewStateCallback);\n \n m_view.InsertDismissedCallback(m_dismissedCallback);\n m_view.InsertFloorSelectedCallback(m_selectFloorCallback);\n m_view.InsertFloorSelectionDraggedCallback(m_draggingFloorSelectionCallback);\n }\n \n InteriorsExplorerController::~InteriorsExplorerController()\n {\n m_view.RemoveFloorSelectionDraggedCallback(m_draggingFloorSelectionCallback);\n m_view.RemoveDismissedCallback(m_dismissedCallback);\n m_view.RemoveFloorSelectedCallback(m_selectFloorCallback);\n \n m_viewModel.RemoveOnScreenStateChangedCallback(m_viewStateCallback);\n \n m_messageBus.UnsubscribeUi(m_interiorsUINotificationCallback);\n m_messageBus.UnsubscribeUi(m_stateChangedCallback);\n m_messageBus.UnsubscribeUi(m_floorSelectedCallback);\n m_messageBus.UnsubscribeUi(m_appModeChangedCallback);\n }\n \n void InteriorsExplorerController::OnDismiss()\n {\n m_messageBus.Publish(InteriorsExplorerExitMessage());\n m_view.SetTouchEnabled(false);\n }\n \n void InteriorsExplorerController::OnSelectFloor(int& selected)\n {\n m_messageBus.Publish(InteriorsExplorerSelectFloorMessage(selected));\n }\n \n void InteriorsExplorerController::OnFloorSelectionDragged(float &dragParam)\n {\n m_messageBus.Publish(InteriorsExplorerFloorSelectionDraggedMessage(dragParam));\n }\n \n void InteriorsExplorerController::OnFloorSelected(const InteriorsExplorerFloorSelectedMessage& message)\n {\n m_view.SetFloorName(message.GetFloorName());\n \n if(m_viewModel.IsFullyOnScreen())\n {\n m_view.SetSelectedFloorIndex(message.GetFloorIndex());\n }\n }\n \n void InteriorsExplorerController::OnStateChanged(const InteriorsExplorerStateChangedMessage& message)\n {\n if(message.IsInteriorVisible())\n {\n m_view.UpdateFloors(message.GetFloorShortNames(), message.GetSelectedFloorIndex());\n m_view.SetTouchEnabled(true);\n\n OnFloorSelected(InteriorsExplorerFloorSelectedMessage(message.GetSelectedFloorIndex(), message.GetSelectedFloorName()));\n\n\t\t\t\t\tconst int maxTutorialViews = 2;\n\t\t\t\t\tbool showExitTutorial = m_replayTutorials || m_model.GetInteriorExitTutorialViewedCount() < maxTutorialViews;\n\t\t\t\t\tbool showChangeFloorTutorial = (m_replayTutorials || m_model.GetInteriorChangeFloorTutorialViewedCount() < maxTutorialViews) && m_view.GetCanShowChangeFloorTutorialDialog();\n\n\t\t\t\t\tif(showExitTutorial || showChangeFloorTutorial)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_view.AddTutorialDialogs(showExitTutorial, showChangeFloorTutorial);\n\n\t\t\t\t\t\tif(showExitTutorial)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_model.RecordHasViewedInteriorExitTutorial();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(showChangeFloorTutorial)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_model.RecordHasViewedInteriorChangeFloorTutorial();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n ReplayTutorials(false);\n\n m_viewModel.AddToScreen();\n }\n else\n {\n m_viewModel.RemoveFromScreen();\n }\n }\n \n void InteriorsExplorerController::OnViewStateChangeScreenControl(ScreenControl::View::IScreenControlViewModel &viewModel, float &state)\n {\n ScreenControl::View::Apply(m_viewModel, m_view);\n }\n \n void InteriorsExplorerController::OnAppModeChanged(const AppModes::AppModeChangedMessage& message)\n {\n m_appMode = message.GetAppMode();\n if (m_appMode == AppModes::SdkModel::AppMode::AttractMode)\n {\n ReplayTutorials(true);\n }\n }\n\n void InteriorsExplorerController::OnInteriorsUINotificationRequired(const InteriorsExplorerUINotifyMessage & message)\n {\n m_view.PlaySliderAnim();\n }\n\n void InteriorsExplorerController::ReplayTutorials(const bool enableTutorials)\n {\n m_replayTutorials = enableTutorials;\n m_replayTutorialsCallbacks.ExecuteCallbacks(m_replayTutorials);\n }\n\n void InteriorsExplorerController::InsertReplayTutorialsChangedCallback(Eegeo::Helpers::ICallback1& callback)\n {\n m_replayTutorialsCallbacks.AddCallback(callback);\n }\n\n void InteriorsExplorerController::RemoveReplayTutorialsChangedCallback(Eegeo::Helpers::ICallback1& callback)\n {\n m_replayTutorialsCallbacks.RemoveCallback(callback);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#include \"log_writer_file.h\"\n#include \"messages.h\"\n#include \n#include \n\n#include \n#include \n\nnamespace px4\n{\nnamespace logger\n{\nconstexpr size_t LogWriterFile::_min_write_chunk;\n\n\nLogWriterFile::LogWriterFile(size_t buffer_size) :\n\t\/\/We always write larger chunks (orb messages) to the buffer, so the buffer\n\t\/\/needs to be larger than the minimum write chunk (300 is somewhat arbitrary)\n\t_buffer_size(math::max(buffer_size, _min_write_chunk + 300))\n{\n\tpthread_mutex_init(&_mtx, nullptr);\n\tpthread_cond_init(&_cv, nullptr);\n\t\/* allocate write performance counters *\/\n\t_perf_write = perf_alloc(PC_ELAPSED, \"sd write\");\n\t_perf_fsync = perf_alloc(PC_ELAPSED, \"sd fsync\");\n}\n\nbool LogWriterFile::init()\n{\n\tif (_buffer) {\n\t\treturn true;\n\t}\n\n\t_buffer = new uint8_t[_buffer_size];\n\n\treturn _buffer;\n}\n\nLogWriterFile::~LogWriterFile()\n{\n\tpthread_mutex_destroy(&_mtx);\n\tpthread_cond_destroy(&_cv);\n\tperf_free(_perf_write);\n\tperf_free(_perf_fsync);\n\n\tif (_buffer) {\n\t\tdelete[] _buffer;\n\t}\n}\n\nvoid LogWriterFile::start_log(const char *filename)\n{\n\t_fd = ::open(filename, O_CREAT | O_WRONLY, PX4_O_MODE_666);\n\n\tif (_fd < 0) {\n\t\tPX4_ERR(\"Can't open log file %s\", filename);\n\t\t_should_run = false;\n\t\treturn;\n\n\t} else {\n\t\tPX4_INFO(\"Opened log file: %s\", filename);\n\t\t_should_run = true;\n\t\t_running = true;\n\t}\n\n\t\/\/ Clear buffer and counters\n\t_head = 0;\n\t_count = 0;\n\t_total_written = 0;\n\tnotify();\n}\n\nvoid LogWriterFile::stop_log()\n{\n\t_should_run = false;\n\tnotify();\n}\n\nint LogWriterFile::thread_start()\n{\n\tpthread_attr_t thr_attr;\n\tpthread_attr_init(&thr_attr);\n\n\tsched_param param;\n\t\/* low priority, as this is expensive disk I\/O *\/\n\tparam.sched_priority = SCHED_PRIORITY_DEFAULT - 40;\n\t(void)pthread_attr_setschedparam(&thr_attr, ¶m);\n\n\tpthread_attr_setstacksize(&thr_attr, PX4_STACK_ADJUSTED(1024));\n\n\tint ret = pthread_create(&_thread, &thr_attr, &LogWriterFile::run_helper, this);\n\tpthread_attr_destroy(&thr_attr);\n\n\treturn ret;\n}\n\nvoid LogWriterFile::thread_stop()\n{\n\t\/\/ this will terminate the main loop of the writer thread\n\t_exit_thread = true;\n\t_should_run = false;\n\n\tnotify();\n\n\t\/\/ wait for thread to complete\n\tint ret = pthread_join(_thread, NULL);\n\n\tif (ret) {\n\t\tPX4_WARN(\"join failed: %d\", ret);\n\t}\n\n}\n\nvoid *LogWriterFile::run_helper(void *context)\n{\n\tpx4_prctl(PR_SET_NAME, \"log_writer_file\", px4_getpid());\n\n\treinterpret_cast(context)->run();\n\treturn nullptr;\n}\n\nvoid LogWriterFile::run()\n{\n\twhile (!_exit_thread) {\n\t\t\/\/ Outer endless loop\n\t\t\/\/ Wait for _should_run flag\n\t\twhile (!_exit_thread) {\n\t\t\tbool start = false;\n\t\t\tpthread_mutex_lock(&_mtx);\n\t\t\tpthread_cond_wait(&_cv, &_mtx);\n\t\t\tstart = _should_run;\n\t\t\tpthread_mutex_unlock(&_mtx);\n\n\t\t\tif (start) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint poll_count = 0;\n\t\tint written = 0;\n\n\t\twhile (true) {\n\t\t\tsize_t available = 0;\n\t\t\tvoid *read_ptr = nullptr;\n\t\t\tbool is_part = false;\n\n\t\t\t\/* lock _buffer\n\t\t\t * wait for sufficient data, cycle on notify()\n\t\t\t *\/\n\t\t\tpthread_mutex_lock(&_mtx);\n\n\t\t\twhile (true) {\n\t\t\t\tavailable = get_read_ptr(&read_ptr, &is_part);\n\n\t\t\t\t\/* if sufficient data available or partial read or terminating, exit this wait loop *\/\n\t\t\t\tif ((available >= _min_write_chunk) || is_part || !_should_run) {\n\t\t\t\t\t\/* GOTO end of block *\/\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/* wait for a call to notify()\n\t\t\t\t * this call unlocks the mutex while waiting, and returns with the mutex locked\n\t\t\t\t *\/\n\t\t\t\tpthread_cond_wait(&_cv, &_mtx);\n\t\t\t}\n\n\t\t\tpthread_mutex_unlock(&_mtx);\n\t\t\twritten = 0;\n\n\t\t\tif (available > 0) {\n\t\t\t\tperf_begin(_perf_write);\n\t\t\t\twritten = ::write(_fd, read_ptr, available);\n\t\t\t\tperf_end(_perf_write);\n\n\t\t\t\t\/* call fsync periodically to minimize potential loss of data *\/\n\t\t\t\tif (++poll_count >= 100) {\n\t\t\t\t\tperf_begin(_perf_fsync);\n\t\t\t\t\t::fsync(_fd);\n\t\t\t\t\tperf_end(_perf_fsync);\n\t\t\t\t\tpoll_count = 0;\n\t\t\t\t}\n\n\t\t\t\tif (written < 0) {\n\t\t\t\t\tPX4_WARN(\"error writing log file\");\n\t\t\t\t\t_should_run = false;\n\t\t\t\t\t\/* GOTO end of block *\/\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tpthread_mutex_lock(&_mtx);\n\t\t\t\t\/* subtract bytes written from number in _buffer (_count -= written) *\/\n\t\t\t\tmark_read(written);\n\t\t\t\tpthread_mutex_unlock(&_mtx);\n\n\t\t\t\t_total_written += written;\n\t\t\t}\n\n\t\t\tif (!_should_run && written == static_cast(available) && !is_part) {\n\t\t\t\t\/\/ Stop only when all data written\n\t\t\t\t_running = false;\n\t\t\t\t_head = 0;\n\t\t\t\t_count = 0;\n\n\t\t\t\tif (_fd >= 0) {\n\t\t\t\t\tint res = ::close(_fd);\n\t\t\t\t\t_fd = -1;\n\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tPX4_WARN(\"error closing log file\");\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tPX4_INFO(\"closed logfile, bytes written: %zu\", _total_written);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint LogWriterFile::write_message(void *ptr, size_t size, uint64_t dropout_start)\n{\n\tif (_need_reliable_transfer) {\n\t\tint ret;\n\n\t\twhile ((ret = write(ptr, size, dropout_start)) == -1) {\n\t\t\tunlock();\n\t\t\tnotify();\n\t\t\tusleep(3000);\n\t\t\tlock();\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\treturn write(ptr, size, dropout_start);\n}\n\nint LogWriterFile::write(void *ptr, size_t size, uint64_t dropout_start)\n{\n\tif (!is_started()) {\n\t\treturn 0;\n\t}\n\n\t\/\/ Bytes available to write\n\tsize_t available = _buffer_size - _count;\n\tsize_t dropout_size = 0;\n\n\tif (dropout_start) {\n\t\tdropout_size = sizeof(ulog_message_dropout_s);\n\t}\n\n\tif (size + dropout_size > available) {\n\t\t\/\/ buffer overflow\n\t\treturn -1;\n\t}\n\n\tif (dropout_start) {\n\t\t\/\/write dropout msg\n\t\tulog_message_dropout_s dropout_msg;\n\t\tdropout_msg.duration = (uint16_t)(hrt_elapsed_time(&dropout_start) \/ 1000);\n\t\twrite_no_check(&dropout_msg, sizeof(dropout_msg));\n\t}\n\n\twrite_no_check(ptr, size);\n\treturn 0;\n}\n\nvoid LogWriterFile::write_no_check(void *ptr, size_t size)\n{\n\tsize_t n = _buffer_size - _head;\t\/\/ bytes to end of the buffer\n\n\tuint8_t *buffer_c = reinterpret_cast(ptr);\n\n\tif (size > n) {\n\t\t\/\/ Message goes over the end of the buffer\n\t\tmemcpy(&(_buffer[_head]), buffer_c, n);\n\t\t_head = 0;\n\n\t} else {\n\t\tn = 0;\n\t}\n\n\t\/\/ now: n = bytes already written\n\tsize_t p = size - n;\t\/\/ number of bytes to write\n\tmemcpy(&(_buffer[_head]), &(buffer_c[n]), p);\n\t_head = (_head + p) % _buffer_size;\n\t_count += size;\n}\n\nsize_t LogWriterFile::get_read_ptr(void **ptr, bool *is_part)\n{\n\t\/\/ bytes available to read\n\tint read_ptr = _head - _count;\n\n\tif (read_ptr < 0) {\n\t\tread_ptr += _buffer_size;\n\t\t*ptr = &_buffer[read_ptr];\n\t\t*is_part = true;\n\t\treturn _buffer_size - read_ptr;\n\n\t} else {\n\t\t*ptr = &_buffer[read_ptr];\n\t\t*is_part = false;\n\t\treturn _count;\n\t}\n}\n\n}\n}\nadd errno to error message\/****************************************************************************\n *\n * Copyright (c) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#include \"log_writer_file.h\"\n#include \"messages.h\"\n#include \n#include \n\n#include \n#include \n\nnamespace px4\n{\nnamespace logger\n{\nconstexpr size_t LogWriterFile::_min_write_chunk;\n\n\nLogWriterFile::LogWriterFile(size_t buffer_size) :\n\t\/\/We always write larger chunks (orb messages) to the buffer, so the buffer\n\t\/\/needs to be larger than the minimum write chunk (300 is somewhat arbitrary)\n\t_buffer_size(math::max(buffer_size, _min_write_chunk + 300))\n{\n\tpthread_mutex_init(&_mtx, nullptr);\n\tpthread_cond_init(&_cv, nullptr);\n\t\/* allocate write performance counters *\/\n\t_perf_write = perf_alloc(PC_ELAPSED, \"sd write\");\n\t_perf_fsync = perf_alloc(PC_ELAPSED, \"sd fsync\");\n}\n\nbool LogWriterFile::init()\n{\n\tif (_buffer) {\n\t\treturn true;\n\t}\n\n\t_buffer = new uint8_t[_buffer_size];\n\n\treturn _buffer;\n}\n\nLogWriterFile::~LogWriterFile()\n{\n\tpthread_mutex_destroy(&_mtx);\n\tpthread_cond_destroy(&_cv);\n\tperf_free(_perf_write);\n\tperf_free(_perf_fsync);\n\n\tif (_buffer) {\n\t\tdelete[] _buffer;\n\t}\n}\n\nvoid LogWriterFile::start_log(const char *filename)\n{\n\t_fd = ::open(filename, O_CREAT | O_WRONLY, PX4_O_MODE_666);\n\n\tif (_fd < 0) {\n\t\tPX4_ERR(\"Can't open log file %s, errno: %d\", filename, errno);\n\t\t_should_run = false;\n\t\treturn;\n\n\t} else {\n\t\tPX4_INFO(\"Opened log file: %s\", filename);\n\t\t_should_run = true;\n\t\t_running = true;\n\t}\n\n\t\/\/ Clear buffer and counters\n\t_head = 0;\n\t_count = 0;\n\t_total_written = 0;\n\tnotify();\n}\n\nvoid LogWriterFile::stop_log()\n{\n\t_should_run = false;\n\tnotify();\n}\n\nint LogWriterFile::thread_start()\n{\n\tpthread_attr_t thr_attr;\n\tpthread_attr_init(&thr_attr);\n\n\tsched_param param;\n\t\/* low priority, as this is expensive disk I\/O *\/\n\tparam.sched_priority = SCHED_PRIORITY_DEFAULT - 40;\n\t(void)pthread_attr_setschedparam(&thr_attr, ¶m);\n\n\tpthread_attr_setstacksize(&thr_attr, PX4_STACK_ADJUSTED(1024));\n\n\tint ret = pthread_create(&_thread, &thr_attr, &LogWriterFile::run_helper, this);\n\tpthread_attr_destroy(&thr_attr);\n\n\treturn ret;\n}\n\nvoid LogWriterFile::thread_stop()\n{\n\t\/\/ this will terminate the main loop of the writer thread\n\t_exit_thread = true;\n\t_should_run = false;\n\n\tnotify();\n\n\t\/\/ wait for thread to complete\n\tint ret = pthread_join(_thread, NULL);\n\n\tif (ret) {\n\t\tPX4_WARN(\"join failed: %d\", ret);\n\t}\n\n}\n\nvoid *LogWriterFile::run_helper(void *context)\n{\n\tpx4_prctl(PR_SET_NAME, \"log_writer_file\", px4_getpid());\n\n\treinterpret_cast(context)->run();\n\treturn nullptr;\n}\n\nvoid LogWriterFile::run()\n{\n\twhile (!_exit_thread) {\n\t\t\/\/ Outer endless loop\n\t\t\/\/ Wait for _should_run flag\n\t\twhile (!_exit_thread) {\n\t\t\tbool start = false;\n\t\t\tpthread_mutex_lock(&_mtx);\n\t\t\tpthread_cond_wait(&_cv, &_mtx);\n\t\t\tstart = _should_run;\n\t\t\tpthread_mutex_unlock(&_mtx);\n\n\t\t\tif (start) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint poll_count = 0;\n\t\tint written = 0;\n\n\t\twhile (true) {\n\t\t\tsize_t available = 0;\n\t\t\tvoid *read_ptr = nullptr;\n\t\t\tbool is_part = false;\n\n\t\t\t\/* lock _buffer\n\t\t\t * wait for sufficient data, cycle on notify()\n\t\t\t *\/\n\t\t\tpthread_mutex_lock(&_mtx);\n\n\t\t\twhile (true) {\n\t\t\t\tavailable = get_read_ptr(&read_ptr, &is_part);\n\n\t\t\t\t\/* if sufficient data available or partial read or terminating, exit this wait loop *\/\n\t\t\t\tif ((available >= _min_write_chunk) || is_part || !_should_run) {\n\t\t\t\t\t\/* GOTO end of block *\/\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/* wait for a call to notify()\n\t\t\t\t * this call unlocks the mutex while waiting, and returns with the mutex locked\n\t\t\t\t *\/\n\t\t\t\tpthread_cond_wait(&_cv, &_mtx);\n\t\t\t}\n\n\t\t\tpthread_mutex_unlock(&_mtx);\n\t\t\twritten = 0;\n\n\t\t\tif (available > 0) {\n\t\t\t\tperf_begin(_perf_write);\n\t\t\t\twritten = ::write(_fd, read_ptr, available);\n\t\t\t\tperf_end(_perf_write);\n\n\t\t\t\t\/* call fsync periodically to minimize potential loss of data *\/\n\t\t\t\tif (++poll_count >= 100) {\n\t\t\t\t\tperf_begin(_perf_fsync);\n\t\t\t\t\t::fsync(_fd);\n\t\t\t\t\tperf_end(_perf_fsync);\n\t\t\t\t\tpoll_count = 0;\n\t\t\t\t}\n\n\t\t\t\tif (written < 0) {\n\t\t\t\t\tPX4_WARN(\"error writing log file\");\n\t\t\t\t\t_should_run = false;\n\t\t\t\t\t\/* GOTO end of block *\/\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tpthread_mutex_lock(&_mtx);\n\t\t\t\t\/* subtract bytes written from number in _buffer (_count -= written) *\/\n\t\t\t\tmark_read(written);\n\t\t\t\tpthread_mutex_unlock(&_mtx);\n\n\t\t\t\t_total_written += written;\n\t\t\t}\n\n\t\t\tif (!_should_run && written == static_cast(available) && !is_part) {\n\t\t\t\t\/\/ Stop only when all data written\n\t\t\t\t_running = false;\n\t\t\t\t_head = 0;\n\t\t\t\t_count = 0;\n\n\t\t\t\tif (_fd >= 0) {\n\t\t\t\t\tint res = ::close(_fd);\n\t\t\t\t\t_fd = -1;\n\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tPX4_WARN(\"error closing log file\");\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tPX4_INFO(\"closed logfile, bytes written: %zu\", _total_written);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint LogWriterFile::write_message(void *ptr, size_t size, uint64_t dropout_start)\n{\n\tif (_need_reliable_transfer) {\n\t\tint ret;\n\n\t\twhile ((ret = write(ptr, size, dropout_start)) == -1) {\n\t\t\tunlock();\n\t\t\tnotify();\n\t\t\tusleep(3000);\n\t\t\tlock();\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\treturn write(ptr, size, dropout_start);\n}\n\nint LogWriterFile::write(void *ptr, size_t size, uint64_t dropout_start)\n{\n\tif (!is_started()) {\n\t\treturn 0;\n\t}\n\n\t\/\/ Bytes available to write\n\tsize_t available = _buffer_size - _count;\n\tsize_t dropout_size = 0;\n\n\tif (dropout_start) {\n\t\tdropout_size = sizeof(ulog_message_dropout_s);\n\t}\n\n\tif (size + dropout_size > available) {\n\t\t\/\/ buffer overflow\n\t\treturn -1;\n\t}\n\n\tif (dropout_start) {\n\t\t\/\/write dropout msg\n\t\tulog_message_dropout_s dropout_msg;\n\t\tdropout_msg.duration = (uint16_t)(hrt_elapsed_time(&dropout_start) \/ 1000);\n\t\twrite_no_check(&dropout_msg, sizeof(dropout_msg));\n\t}\n\n\twrite_no_check(ptr, size);\n\treturn 0;\n}\n\nvoid LogWriterFile::write_no_check(void *ptr, size_t size)\n{\n\tsize_t n = _buffer_size - _head;\t\/\/ bytes to end of the buffer\n\n\tuint8_t *buffer_c = reinterpret_cast(ptr);\n\n\tif (size > n) {\n\t\t\/\/ Message goes over the end of the buffer\n\t\tmemcpy(&(_buffer[_head]), buffer_c, n);\n\t\t_head = 0;\n\n\t} else {\n\t\tn = 0;\n\t}\n\n\t\/\/ now: n = bytes already written\n\tsize_t p = size - n;\t\/\/ number of bytes to write\n\tmemcpy(&(_buffer[_head]), &(buffer_c[n]), p);\n\t_head = (_head + p) % _buffer_size;\n\t_count += size;\n}\n\nsize_t LogWriterFile::get_read_ptr(void **ptr, bool *is_part)\n{\n\t\/\/ bytes available to read\n\tint read_ptr = _head - _count;\n\n\tif (read_ptr < 0) {\n\t\tread_ptr += _buffer_size;\n\t\t*ptr = &_buffer[read_ptr];\n\t\t*is_part = true;\n\t\treturn _buffer_size - read_ptr;\n\n\t} else {\n\t\t*ptr = &_buffer[read_ptr];\n\t\t*is_part = false;\n\t\treturn _count;\n\t}\n}\n\n}\n}\n<|endoftext|>"} {"text":"#ifndef __se3_sample_models_hpp__ \n#define __se3_sample_models_hpp__ \n\n#include \"pinocchio\/multibody\/model.hpp\"\n\nnamespace se3\n{\n namespace buildModels\n {\n\n void humanoid2d( Model& model)\n {\n model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"ff1\");\n model.addBody(model.getBodyId(\"ff1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"root\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg1\");\n model.addBody(model.getBodyId(\"lleg1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg2\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg1\");\n model.addBody(model.getBodyId(\"rleg1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg2\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"torso1\");\n model.addBody(model.getBodyId(\"torso1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"chest\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm1\");\n model.addBody(model.getBodyId(\"rarm1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm2\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm1\");\n model.addBody(model.getBodyId(\"larm1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm2\");\n }\n\n void humanoidSimple( Model& model, bool usingFF = true)\n { \n if(! usingFF ) \n\t{\n\t model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"ff1\");\n\t model.addBody(model.getBodyId(\"ff1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"ff2\");\n\t model.addBody(model.getBodyId(\"ff2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"ff3\");\n\t model.addBody(model.getBodyId(\"ff3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"ff4\");\n\t model.addBody(model.getBodyId(\"ff4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"ff5\");\n\t model.addBody(model.getBodyId(\"ff5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"root\");\n\t}\n else\n\tmodel.addBody(model.getBodyId(\"universe\"),JointModelFreeFlyer(),SE3::Random(),Inertia::Random(),\"root\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg1\");\n model.addBody(model.getBodyId(\"lleg1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg2\");\n model.addBody(model.getBodyId(\"lleg2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg3\");\n model.addBody(model.getBodyId(\"lleg3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg4\");\n model.addBody(model.getBodyId(\"lleg4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg5\");\n model.addBody(model.getBodyId(\"lleg5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg6\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg1\");\n model.addBody(model.getBodyId(\"rleg1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg2\");\n model.addBody(model.getBodyId(\"rleg2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg3\");\n model.addBody(model.getBodyId(\"rleg3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg4\");\n model.addBody(model.getBodyId(\"rleg4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg5\");\n model.addBody(model.getBodyId(\"rleg5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg6\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"torso1\");\n model.addBody(model.getBodyId(\"torso1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"chest\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm1\");\n model.addBody(model.getBodyId(\"rarm1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm2\");\n model.addBody(model.getBodyId(\"rarm2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm3\");\n model.addBody(model.getBodyId(\"rarm3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm4\");\n model.addBody(model.getBodyId(\"rarm4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm5\");\n model.addBody(model.getBodyId(\"rarm5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm6\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm1\");\n model.addBody(model.getBodyId(\"larm1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm2\");\n model.addBody(model.getBodyId(\"larm2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm3\");\n model.addBody(model.getBodyId(\"larm3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm4\");\n model.addBody(model.getBodyId(\"larm4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm5\");\n model.addBody(model.getBodyId(\"larm5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm6\");\n }\n\n } \/\/ namespace buildModels\n} \/\/ namespace se3 \n\n#endif \/\/ ifndef __se3_sample_models_hpp__ \nSet FF to SE3::Identity in model-sample.#ifndef __se3_sample_models_hpp__ \n#define __se3_sample_models_hpp__ \n\n#include \"pinocchio\/multibody\/model.hpp\"\n\nnamespace se3\n{\n namespace buildModels\n {\n\n void humanoid2d( Model& model)\n {\n model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\"ff1\");\n model.addBody(model.getBodyId(\"ff1\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\"root\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\"lleg1\");\n model.addBody(model.getBodyId(\"lleg1\"),JointModelRY(),SE3::Random(),Inertia::Random(),\"lleg2\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\"rleg1\");\n model.addBody(model.getBodyId(\"rleg1\"),JointModelRY(),SE3::Random(),Inertia::Random(),\"rleg2\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRY(),SE3::Random(),Inertia::Random(),\"torso1\");\n model.addBody(model.getBodyId(\"torso1\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\"chest\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm1\");\n model.addBody(model.getBodyId(\"rarm1\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\"rarm2\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm1\");\n model.addBody(model.getBodyId(\"larm1\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\"larm2\");\n }\n\n void humanoidSimple( Model& model, bool usingFF = true)\n { \n if(! usingFF ) \n\t{\n\t model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\"ff1\");\n\t model.addBody(model.getBodyId(\"ff1\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\"ff2\");\n\t model.addBody(model.getBodyId(\"ff2\"),JointModelRZ(),SE3::Identity(),Inertia::Random(),\"ff3\");\n\t model.addBody(model.getBodyId(\"ff3\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\"ff4\");\n\t model.addBody(model.getBodyId(\"ff4\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\"ff5\");\n\t model.addBody(model.getBodyId(\"ff5\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\"root\");\n\t}\n else\n\tmodel.addBody(model.getBodyId(\"universe\"),JointModelFreeFlyer(),SE3::Identity(),Inertia::Random(),\"root\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg1\");\n model.addBody(model.getBodyId(\"lleg1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg2\");\n model.addBody(model.getBodyId(\"lleg2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg3\");\n model.addBody(model.getBodyId(\"lleg3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg4\");\n model.addBody(model.getBodyId(\"lleg4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg5\");\n model.addBody(model.getBodyId(\"lleg5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"lleg6\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg1\");\n model.addBody(model.getBodyId(\"rleg1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg2\");\n model.addBody(model.getBodyId(\"rleg2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg3\");\n model.addBody(model.getBodyId(\"rleg3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg4\");\n model.addBody(model.getBodyId(\"rleg4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg5\");\n model.addBody(model.getBodyId(\"rleg5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rleg6\");\n\n model.addBody(model.getBodyId(\"root\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"torso1\");\n model.addBody(model.getBodyId(\"torso1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"chest\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm1\");\n model.addBody(model.getBodyId(\"rarm1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm2\");\n model.addBody(model.getBodyId(\"rarm2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm3\");\n model.addBody(model.getBodyId(\"rarm3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm4\");\n model.addBody(model.getBodyId(\"rarm4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm5\");\n model.addBody(model.getBodyId(\"rarm5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"rarm6\");\n\n model.addBody(model.getBodyId(\"chest\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm1\");\n model.addBody(model.getBodyId(\"larm1\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm2\");\n model.addBody(model.getBodyId(\"larm2\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm3\");\n model.addBody(model.getBodyId(\"larm3\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm4\");\n model.addBody(model.getBodyId(\"larm4\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm5\");\n model.addBody(model.getBodyId(\"larm5\"),JointModelRX(),SE3::Random(),Inertia::Random(),\"larm6\");\n }\n\n } \/\/ namespace buildModels\n} \/\/ namespace se3 \n\n#endif \/\/ ifndef __se3_sample_models_hpp__ \n<|endoftext|>"} {"text":"#include \"BoundingBox.hpp\"\n#include \"QuadKey.hpp\"\n#include \"entities\/Element.hpp\"\n#include \"entities\/Node.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"entities\/Area.hpp\"\n#include \"entities\/Relation.hpp\"\n#include \"index\/ElementStore.hpp\"\n#include \"index\/ElementGeometryClipper.hpp\"\n\nusing namespace utymap;\nusing namespace utymap::entities;\nusing namespace utymap::formats;\n\nusing namespace utymap::mapcss;\n\nnamespace {\n using PointLocation = utymap::index::ElementGeometryClipper::PointLocation;\n\n template\n inline PointLocation setPath(const BoundingBox& bbox, const T& t, ClipperLib::Path& shape) {\n shape.reserve(t.coordinates.size());\n bool allInside = true;\n bool allOutside = true;\n for (const GeoCoordinate& coord : t.coordinates) {\n bool contains = bbox.contains(coord);\n allInside &= contains;\n allOutside &= !contains;\n\n auto x = static_cast(coord.longitude * utymap::index::ElementGeometryClipper::Scale);\n auto y = static_cast(coord.latitude * utymap::index::ElementGeometryClipper::Scale);\n shape.push_back(ClipperLib::IntPoint(x, y));\n }\n\n return allInside ? PointLocation::AllInside :\n (allOutside ? PointLocation::AllOutside : PointLocation::Mixed);\n }\n}\n\nnamespace utymap { namespace index {\n\nconst double ElementGeometryClipper::Scale = 1E7;\n\nvoid ElementGeometryClipper::clipAndCall(const Element& element, const QuadKey& quadKey, const BoundingBox& quadKeyBbox)\n{\n quadKey_ = quadKey;\n quadKeyBbox_ = quadKeyBbox;\n element.accept(*this);\n}\n\nvoid ElementGeometryClipper:: visitNode(const Node& node)\n{\n \/\/ here, node should be always in tile\n callback_(node, quadKey_);\n}\n\nvoid ElementGeometryClipper::visitWay(const Way& way)\n{\n ClipperLib::Path wayShape;\n PointLocation pointLocation = setPath(quadKeyBbox_, way, wayShape);\n \/\/ 1. all geometry inside current quadkey: no need to truncate.\n if (pointLocation == PointLocation::AllInside) {\n callback_(way, quadKey_);\n return;\n }\n\n \/\/ 2. all geometry outside : way should be skipped\n if (pointLocation == PointLocation::AllOutside) {\n return;\n }\n\n ClipperLib::PolyTree solution;\n clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n clipper_.Execute(ClipperLib::ctIntersection, solution);\n clipper_.Clear();\n std::size_t count = static_cast(solution.Total());\n\n \/\/ 3. way intersects border only once: store a copy with clipped geometry\n if (count == 1) {\n Way clippedWay;\n setData(clippedWay, way, solution.GetFirst()->Contour);\n callback_(clippedWay, quadKey_);\n }\n \/\/ 4. in this case, result should be stored as relation (collection of ways)\n else {\n Relation relation;\n relation.id = way.id;\n relation.tags = way.tags;\n relation.elements.reserve(count);\n ClipperLib::PolyNode* polyNode = solution.GetFirst();\n while (polyNode) {\n auto clippedWay = std::make_shared();\n clippedWay->id = way.id;\n setCoordinates(*clippedWay, polyNode->Contour);\n relation.elements.push_back(clippedWay);\n polyNode = polyNode->GetNext();\n }\n callback_(relation, quadKey_);\n }\n}\n\nvoid ElementGeometryClipper::visitArea(const Area& area)\n{\n ClipperLib::Path areaShape;\n PointLocation pointLocation = setPath(quadKeyBbox_, area, areaShape);\n \/\/ 1. all geometry inside current quadkey: no need to truncate.\n if (pointLocation == PointLocation::AllInside) {\n callback_(area, quadKey_);\n return;\n }\n\n \/\/ 2. all geometry outside: skip\n if (pointLocation == PointLocation::AllOutside) {\n return;\n }\n\n ClipperLib::Paths solution;\n clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n clipper_.Execute(ClipperLib::ctIntersection, solution);\n clipper_.Clear();\n\n \/\/ 3. way intersects border only once: store a copy with clipped geometry\n if (solution.size() == 1) {\n Area clippedArea;\n setData(clippedArea, area, solution[0]);\n callback_(clippedArea, quadKey_);\n }\n \/\/ 4. in this case, result should be stored as relation (collection of areas)\n else {\n Relation relation;\n relation.id = area.id;\n relation.tags = area.tags;\n relation.elements.reserve(solution.size());\n for (auto it = solution.begin(); it != solution.end(); ++it) {\n auto clippedArea = std::make_shared ();\n clippedArea->id = area.id;\n setCoordinates(*clippedArea, *it);\n relation.elements.push_back(clippedArea);\n }\n callback_(relation, quadKey_);\n }\n}\n\nvoid ElementGeometryClipper::visitRelation(const Relation& relation)\n{\n struct RelationVisitor : public ElementVisitor\n {\n RelationVisitor(const BoundingBox& quadKeyBbox, ClipperLib::Clipper& clipper) :\n bbox_(quadKeyBbox), clipper_(clipper) { }\n\n void visitNode(const Node& node) \n {\n \/\/ TODO\n }\n\n void visitWay(const Way& way)\n {\n ClipperLib::Path wayShape;\n setPath(bbox_, way, wayShape);\n clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n }\n\n void visitArea(const Area& area)\n {\n ClipperLib::Path areaShape;\n setPath(bbox_, area, areaShape);\n clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n }\n\n void visitRelation(const Relation& relation)\n {\n for (const auto& element : relation.elements) {\n element->accept(*this);\n }\n }\n\n private:\n const BoundingBox& bbox_;\n ClipperLib::Clipper& clipper_;\n\n } visitor(quadKeyBbox_, clipper_);\n\n relation.accept(visitor);\n\n \/\/ Process results\n ClipperLib::PolyTree solution;\n clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n clipper_.Execute(ClipperLib::ctIntersection, solution);\n clipper_.Clear();\n\n std::size_t count = static_cast(solution.Total());\n \/\/ Do not store one result as relation\n if (count == 1) {\n ClipperLib::PolyNode* node = solution.GetFirst();\n if (node->IsOpen()) {\n Way way;\n setData(way, relation, node->Contour);\n callback_(way, quadKey_);\n }\n else {\n if (!node->IsHole()) {\n Area area;\n setData(area, relation, node->Contour);\n callback_(area, quadKey_);\n }\n }\n }\n else if (count > 1) {\n Relation newRelation;\n newRelation.id = relation.id;\n newRelation.tags = relation.tags;\n newRelation.elements.reserve(count);\n\n ClipperLib::PolyNode* polyNode = solution.GetFirst();\n while (polyNode) {\n if (polyNode->IsOpen()) {\n auto way = std::make_shared();\n setCoordinates(*way, polyNode->Contour);\n newRelation.elements.push_back(way);\n }\n else {\n auto area = std::make_shared();\n setCoordinates(*area, polyNode->Contour);\n newRelation.elements.push_back(area);\n }\n polyNode = polyNode->GetNext();\n }\n callback_(newRelation, quadKey_);\n }\n}\n\nClipperLib::Path ElementGeometryClipper::createPathFromBoundingBox()\n{\n double xMin = quadKeyBbox_.minPoint.longitude, yMin = quadKeyBbox_.minPoint.latitude,\n xMax = quadKeyBbox_.maxPoint.longitude, yMax = quadKeyBbox_.maxPoint.latitude;\n ClipperLib::Path rect;\n rect.push_back(ClipperLib::IntPoint(static_cast(xMin*Scale), \n static_cast(yMin*Scale)));\n\n rect.push_back(ClipperLib::IntPoint(static_cast(xMax*Scale), \n static_cast(yMin*Scale)));\n\n rect.push_back(ClipperLib::IntPoint(static_cast(xMax*Scale), \n static_cast(yMax*Scale)));\n\n rect.push_back(ClipperLib::IntPoint(static_cast(xMin*Scale),\n static_cast(yMax*Scale)));\n return std::move(rect);\n}\n\n}}\ncore: fix issue with missing terrain regions#include \"BoundingBox.hpp\"\n#include \"QuadKey.hpp\"\n#include \"entities\/Element.hpp\"\n#include \"entities\/Node.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"entities\/Area.hpp\"\n#include \"entities\/Relation.hpp\"\n#include \"index\/ElementStore.hpp\"\n#include \"index\/ElementGeometryClipper.hpp\"\n\nusing namespace utymap;\nusing namespace utymap::entities;\nusing namespace utymap::formats;\n\nusing namespace utymap::mapcss;\n\nnamespace {\n using PointLocation = utymap::index::ElementGeometryClipper::PointLocation;\n\n template\n inline PointLocation setPath(const BoundingBox& bbox, const T& t, ClipperLib::Path& shape) {\n shape.reserve(t.coordinates.size());\n bool allInside = true;\n bool allOutside = true;\n for (const GeoCoordinate& coord : t.coordinates) {\n bool contains = bbox.contains(coord);\n allInside &= contains;\n allOutside &= !contains;\n\n auto x = static_cast(coord.longitude * utymap::index::ElementGeometryClipper::Scale);\n auto y = static_cast(coord.latitude * utymap::index::ElementGeometryClipper::Scale);\n shape.push_back(ClipperLib::IntPoint(x, y));\n }\n\n return allInside ? PointLocation::AllInside :\n (allOutside ? PointLocation::AllOutside : PointLocation::Mixed);\n }\n}\n\nnamespace utymap { namespace index {\n\nconst double ElementGeometryClipper::Scale = 1E7;\n\nvoid ElementGeometryClipper::clipAndCall(const Element& element, const QuadKey& quadKey, const BoundingBox& quadKeyBbox)\n{\n quadKey_ = quadKey;\n quadKeyBbox_ = quadKeyBbox;\n element.accept(*this);\n}\n\nvoid ElementGeometryClipper:: visitNode(const Node& node)\n{\n \/\/ here, node should be always in tile\n callback_(node, quadKey_);\n}\n\nvoid ElementGeometryClipper::visitWay(const Way& way)\n{\n ClipperLib::Path wayShape;\n PointLocation pointLocation = setPath(quadKeyBbox_, way, wayShape);\n \/\/ 1. all geometry inside current quadkey: no need to truncate.\n if (pointLocation == PointLocation::AllInside) {\n callback_(way, quadKey_);\n return;\n }\n\n \/\/ 2. all geometry outside : way should be skipped\n if (pointLocation == PointLocation::AllOutside) {\n return;\n }\n\n ClipperLib::PolyTree solution;\n clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n clipper_.Execute(ClipperLib::ctIntersection, solution);\n clipper_.Clear();\n std::size_t count = static_cast(solution.Total());\n\n \/\/ 3. way intersects border only once: store a copy with clipped geometry\n if (count == 1) {\n Way clippedWay;\n setData(clippedWay, way, solution.GetFirst()->Contour);\n callback_(clippedWay, quadKey_);\n }\n \/\/ 4. in this case, result should be stored as relation (collection of ways)\n else {\n Relation relation;\n relation.id = way.id;\n relation.tags = way.tags;\n relation.elements.reserve(count);\n ClipperLib::PolyNode* polyNode = solution.GetFirst();\n while (polyNode) {\n auto clippedWay = std::make_shared();\n clippedWay->id = way.id;\n setCoordinates(*clippedWay, polyNode->Contour);\n relation.elements.push_back(clippedWay);\n polyNode = polyNode->GetNext();\n }\n callback_(relation, quadKey_);\n }\n}\n\nvoid ElementGeometryClipper::visitArea(const Area& area)\n{\n ClipperLib::Path areaShape;\n PointLocation pointLocation = setPath(quadKeyBbox_, area, areaShape);\n \/\/ 1. all geometry inside current quadkey: no need to truncate.\n if (pointLocation == PointLocation::AllInside) {\n callback_(area, quadKey_);\n return;\n }\n\n \/\/ 2. all geometry outside: use geometry of quadkey\n if (pointLocation == PointLocation::AllOutside) {\n Area newArea;\n newArea.id = area.id;\n newArea.tags = area.tags;\n\n newArea.coordinates.reserve(4);\n newArea.coordinates.push_back(quadKeyBbox_.minPoint);\n newArea.coordinates.push_back(GeoCoordinate(quadKeyBbox_.maxPoint.latitude, quadKeyBbox_.minPoint.longitude));\n newArea.coordinates.push_back(quadKeyBbox_.maxPoint);\n newArea.coordinates.push_back(GeoCoordinate(quadKeyBbox_.minPoint.latitude, quadKeyBbox_.maxPoint.longitude));\n\n callback_(newArea, quadKey_);\n return;\n }\n\n ClipperLib::Paths solution;\n clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n clipper_.Execute(ClipperLib::ctIntersection, solution);\n clipper_.Clear();\n\n \/\/ 3. way intersects border only once: store a copy with clipped geometry\n if (solution.size() == 1) {\n Area clippedArea;\n setData(clippedArea, area, solution[0]);\n callback_(clippedArea, quadKey_);\n }\n \/\/ 4. in this case, result should be stored as relation (collection of areas)\n else {\n Relation relation;\n relation.id = area.id;\n relation.tags = area.tags;\n relation.elements.reserve(solution.size());\n for (auto it = solution.begin(); it != solution.end(); ++it) {\n auto clippedArea = std::make_shared ();\n clippedArea->id = area.id;\n setCoordinates(*clippedArea, *it);\n relation.elements.push_back(clippedArea);\n }\n callback_(relation, quadKey_);\n }\n}\n\nvoid ElementGeometryClipper::visitRelation(const Relation& relation)\n{\n struct RelationVisitor : public ElementVisitor\n {\n RelationVisitor(const BoundingBox& quadKeyBbox, ClipperLib::Clipper& clipper) :\n bbox_(quadKeyBbox), clipper_(clipper) { }\n\n void visitNode(const Node& node) \n {\n \/\/ TODO\n }\n\n void visitWay(const Way& way)\n {\n ClipperLib::Path wayShape;\n setPath(bbox_, way, wayShape);\n clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n }\n\n void visitArea(const Area& area)\n {\n ClipperLib::Path areaShape;\n setPath(bbox_, area, areaShape);\n clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n }\n\n void visitRelation(const Relation& relation)\n {\n for (const auto& element : relation.elements) {\n element->accept(*this);\n }\n }\n\n private:\n const BoundingBox& bbox_;\n ClipperLib::Clipper& clipper_;\n\n } visitor(quadKeyBbox_, clipper_);\n\n relation.accept(visitor);\n\n \/\/ Process results\n ClipperLib::PolyTree solution;\n clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n clipper_.Execute(ClipperLib::ctIntersection, solution);\n clipper_.Clear();\n\n std::size_t count = static_cast(solution.Total());\n \/\/ Do not store one result as relation\n if (count == 1) {\n ClipperLib::PolyNode* node = solution.GetFirst();\n if (node->IsOpen()) {\n Way way;\n setData(way, relation, node->Contour);\n callback_(way, quadKey_);\n }\n else {\n if (!node->IsHole()) {\n Area area;\n setData(area, relation, node->Contour);\n callback_(area, quadKey_);\n }\n }\n }\n else if (count > 1) {\n Relation newRelation;\n newRelation.id = relation.id;\n newRelation.tags = relation.tags;\n newRelation.elements.reserve(count);\n\n ClipperLib::PolyNode* polyNode = solution.GetFirst();\n while (polyNode) {\n if (polyNode->IsOpen()) {\n auto way = std::make_shared();\n setCoordinates(*way, polyNode->Contour);\n newRelation.elements.push_back(way);\n }\n else {\n auto area = std::make_shared();\n setCoordinates(*area, polyNode->Contour);\n newRelation.elements.push_back(area);\n }\n polyNode = polyNode->GetNext();\n }\n callback_(newRelation, quadKey_);\n }\n}\n\nClipperLib::Path ElementGeometryClipper::createPathFromBoundingBox()\n{\n double xMin = quadKeyBbox_.minPoint.longitude, yMin = quadKeyBbox_.minPoint.latitude,\n xMax = quadKeyBbox_.maxPoint.longitude, yMax = quadKeyBbox_.maxPoint.latitude;\n ClipperLib::Path rect;\n rect.push_back(ClipperLib::IntPoint(static_cast(xMin*Scale), \n static_cast(yMin*Scale)));\n\n rect.push_back(ClipperLib::IntPoint(static_cast(xMax*Scale), \n static_cast(yMin*Scale)));\n\n rect.push_back(ClipperLib::IntPoint(static_cast(xMax*Scale), \n static_cast(yMax*Scale)));\n\n rect.push_back(ClipperLib::IntPoint(static_cast(xMin*Scale),\n static_cast(yMax*Scale)));\n return std::move(rect);\n}\n\n}}\n<|endoftext|>"} {"text":"\/* ******************************************************************************\n *\n *\n * This program and the accompanying materials are made available under the\n * terms of the Apache License, Version 2.0 which is available at\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n *\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n ******************************************************************************\/\n\n\/\/\n\/\/ @author raver119@gmail.com\n\/\/\n\n#include \n#if NOT_EXCLUDED(OP_shape_of)\n\n#include \n\nnamespace sd {\nnamespace ops {\nCUSTOM_OP_IMPL(shape_of, 1, 1, false, 0, 0) {\n auto x = INPUT_VARIABLE(0);\n auto z = OUTPUT_VARIABLE(0);\n\n for (int e = 0; e < x->rankOf(); e++) z->p(e, x->sizeAt(e));\n\n STORE_RESULT(z);\n\n return sd::Status::OK;\n};\nDECLARE_SYN(shape, shape_of);\n\nDECLARE_SHAPE_FN(shape_of) {\n auto inShape = inputShape->at(0);\n\n \/\/ LONG by default\n auto dtype = DataType::INT64;\n if (block.numI() > 0) dtype = DataTypeUtils::fromInt(INT_ARG(0));\n\n return SHAPELIST(ConstantShapeHelper::getInstance().vectorShapeInfo(shape::rank(inShape), dtype));\n};\n\nDECLARE_TYPES(shape_of) {\n getOpDescriptor()->setAllowedInputTypes(sd::DataType::ANY)->setAllowedOutputTypes({ALL_INTS});\n}\n#endif\n\n#if NOT_EXCLUDED(set_shape)\nCUSTOM_OP_IMPL(set_shape, 2, 1, true, 0, 0) {\n auto x = INPUT_VARIABLE(0);\n auto shape = INPUT_VARIABLE(1);\n auto z = OUTPUT_VARIABLE(0);\n REQUIRE_TRUE(shape->isVector() || shape->isScalar(), 0, \"Shape must be either a scalar or a vector\");\n auto newShapeInfo = ConstantShapeHelper::getInstance().createShapeInfo(x->dataType(), x->ordering(),\n shape->asVectorT());\n z->setShapeInfo(newShapeInfo);\n \/\/ if x and z aren't the same reference ensure the elements are the same.\n \/\/ this op should almost always be used in place and in very specific circumstances.\n if (x != z) {\n z->assign(x, true);\n }\n return sd::Status::OK;\n};\n\nDECLARE_SHAPE_FN(set_shape) {\n auto inShape = INPUT_VARIABLE(1);\n return SHAPELIST(inShape->shapeInfo());\n};\n\nDECLARE_TYPES(set_shape) {\n getOpDescriptor()\n ->setAllowedInputTypes(0, sd::DataType::ANY)\n ->setAllowedInputTypes(1, sd::DataType::INT64)\n ->setAllowedOutputTypes({sd::DataType::ANY});\n}\n} \/\/ namespace ops\n} \/\/ namespace sd\n\n#endif\nUpdate shape.cpp\/* ******************************************************************************\n *\n *\n * This program and the accompanying materials are made available under the\n * terms of the Apache License, Version 2.0 which is available at\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n *\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n ******************************************************************************\/\n\n\/\/\n\/\/ @author raver119@gmail.com\n\/\/\n\n#include \n#if NOT_EXCLUDED(OP_shape_of)\n\n#include \n\nnamespace sd {\nnamespace ops {\nCUSTOM_OP_IMPL(shape_of, 1, 1, false, 0, 0) {\n auto x = INPUT_VARIABLE(0);\n auto z = OUTPUT_VARIABLE(0);\n\n for (int e = 0; e < x->rankOf(); e++) z->p(e, x->sizeAt(e));\n\n STORE_RESULT(z);\n\n return sd::Status::OK;\n};\nDECLARE_SYN(shape, shape_of);\n\nDECLARE_SHAPE_FN(shape_of) {\n auto inShape = inputShape->at(0);\n\n \/\/ LONG by default\n auto dtype = DataType::INT64;\n if (block.numI() > 0) dtype = DataTypeUtils::fromInt(INT_ARG(0));\n\n return SHAPELIST(ConstantShapeHelper::getInstance().vectorShapeInfo(shape::rank(inShape), dtype));\n};\n\nDECLARE_TYPES(shape_of) {\n getOpDescriptor()->setAllowedInputTypes(sd::DataType::ANY)->setAllowedOutputTypes({ALL_INTS});\n}\n#endif\n\n#if NOT_EXCLUDED(OP_set_shape)\nCUSTOM_OP_IMPL(set_shape, 2, 1, true, 0, 0) {\n auto x = INPUT_VARIABLE(0);\n auto shape = INPUT_VARIABLE(1);\n auto z = OUTPUT_VARIABLE(0);\n REQUIRE_TRUE(shape->isVector() || shape->isScalar(), 0, \"Shape must be either a scalar or a vector\");\n auto newShapeInfo = ConstantShapeHelper::getInstance().createShapeInfo(x->dataType(), x->ordering(),\n shape->asVectorT());\n z->setShapeInfo(newShapeInfo);\n \/\/ if x and z aren't the same reference ensure the elements are the same.\n \/\/ this op should almost always be used in place and in very specific circumstances.\n if (x != z) {\n z->assign(x, true);\n }\n return sd::Status::OK;\n};\n\nDECLARE_SHAPE_FN(set_shape) {\n auto inShape = INPUT_VARIABLE(1);\n return SHAPELIST(inShape->shapeInfo());\n};\n\nDECLARE_TYPES(set_shape) {\n getOpDescriptor()\n ->setAllowedInputTypes(0, sd::DataType::ANY)\n ->setAllowedInputTypes(1, sd::DataType::INT64)\n ->setAllowedOutputTypes({sd::DataType::ANY});\n}\n} \/\/ namespace ops\n} \/\/ namespace sd\n\n#endif\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File NektarUnivTypeDefs.hpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Scientific Computing and Imaging Institute,\n\/\/ University of Utah (USA) and Department of Aeronautics, Imperial\n\/\/ College London (UK).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Universal type defines in the Nektar Library \n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef NEKTARUNIVTYPEDEF_HPP\n#define NEKTARUNIVTYPEDEF_HPP\n\n#include \n#include \n#include \n\nnamespace Nektar\n{\n typedef double NekDouble;\n\n enum Dimension\n {\n OneD = 1,\n TwoD = 2,\n ThreeD = 3\n };\n\n} \/\/end of namespace \n\n#endif\n\n\/***\n$Log: NektarUnivTypeDefs.hpp,v $\nRevision 1.10 2007\/07\/20 00:39:54 bnelson\nReplaced boost::shared_ptr with Nektar::ptr\n\nRevision 1.9 2007\/05\/14 23:47:43 bnelson\nRemoved old SharedArray typedefs. Added new Dimension enumeration.\n\nRevision 1.8 2007\/04\/29 00:31:12 jfrazier\nContinued conversion to multi_arrays.\n\nRevision 1.7 2007\/04\/26 21:52:09 jfrazier\nConverted to new multi_array implementation.\n\nRevision 1.6 2007\/04\/10 14:00:44 sherwin\nUpdate to include SharedArray in all 2D element (including Nodal tris). Have also remvoed all new and double from 2D shapes in StdRegions\n\nRevision 1.5 2007\/03\/31 15:37:51 bnelson\nRemoved boost::shared_array.hpp\n\nRevision 1.4 2007\/03\/29 18:44:11 bnelson\nReplaced boost::shared_array with SharedArray\n\nRevision 1.3 2007\/03\/20 13:48:05 sherwin\nCompiling version\n\nRevision 1.2 2007\/03\/20 12:27:39 sherwin\nChanged shared_ptr to shared_array\n\nRevision 1.1 2007\/03\/20 11:56:25 sherwin\n.\n\n**\/\nAdded enumerations for the 3 principal directions. These are to be used in GetD(Direction).\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ File NektarUnivTypeDefs.hpp\r\n\/\/\r\n\/\/ For more information, please see: http:\/\/www.nektar.info\r\n\/\/\r\n\/\/ The MIT License\r\n\/\/\r\n\/\/ Copyright (c) 2006 Scientific Computing and Imaging Institute,\r\n\/\/ University of Utah (USA) and Department of Aeronautics, Imperial\r\n\/\/ College London (UK).\r\n\/\/\r\n\/\/ License for the specific language governing rights and limitations under\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\r\n\/\/ copy of this software and associated documentation files (the \"Software\"),\r\n\/\/ to deal in the Software without restriction, including without limitation\r\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\r\n\/\/ Software is furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included\r\n\/\/ in all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n\/\/ DEALINGS IN THE SOFTWARE.\r\n\/\/\r\n\/\/ Description: Universal type defines in the Nektar Library \r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n#ifndef NEKTARUNIVTYPEDEF_HPP\r\n#define NEKTARUNIVTYPEDEF_HPP\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace Nektar\r\n{\r\n typedef double NekDouble;\r\n\r\n enum Dimension\r\n {\r\n OneD = 1,\r\n TwoD = 2,\r\n ThreeD = 3\r\n };\r\n\r\n enum Direction\r\n {\r\n xDir = 0,\r\n yDir = 1,\r\n zDir = 2\r\n };\r\n\r\n\r\n} \/\/end of namespace \r\n\r\n#endif\r\n\r\n\/***\r\n$Log: NektarUnivTypeDefs.hpp,v $\r\nRevision 1.11 2007\/07\/22 23:03:24 bnelson\r\nBacked out Nektar::ptr.\r\n\r\nRevision 1.10 2007\/07\/20 00:39:54 bnelson\r\nReplaced boost::shared_ptr with Nektar::ptr\r\n\r\nRevision 1.9 2007\/05\/14 23:47:43 bnelson\r\nRemoved old SharedArray typedefs. Added new Dimension enumeration.\r\n\r\nRevision 1.8 2007\/04\/29 00:31:12 jfrazier\r\nContinued conversion to multi_arrays.\r\n\r\nRevision 1.7 2007\/04\/26 21:52:09 jfrazier\r\nConverted to new multi_array implementation.\r\n\r\nRevision 1.6 2007\/04\/10 14:00:44 sherwin\r\nUpdate to include SharedArray in all 2D element (including Nodal tris). Have also remvoed all new and double from 2D shapes in StdRegions\r\n\r\nRevision 1.5 2007\/03\/31 15:37:51 bnelson\r\nRemoved boost::shared_array.hpp\r\n\r\nRevision 1.4 2007\/03\/29 18:44:11 bnelson\r\nReplaced boost::shared_array with SharedArray\r\n\r\nRevision 1.3 2007\/03\/20 13:48:05 sherwin\r\nCompiling version\r\n\r\nRevision 1.2 2007\/03\/20 12:27:39 sherwin\r\nChanged shared_ptr to shared_array\r\n\r\nRevision 1.1 2007\/03\/20 11:56:25 sherwin\r\n.\r\n\r\n**\/\r\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n\nint main(int argc, char* argv[]) {\n CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);\n\n return 0;\n}\n:white_check_mark: tests(ConcurrencyCopy): add unittest for concurrency copying gc\/\/ Copyright (c) 2017 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \"concurrency_copy.h\"\n\nint main(int argc, char* argv[]) {\n CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);\n\n constexpr int kCount = 1000;\n constexpr int kReleaseCount = 20;\n constexpr int kCreateCount = kReleaseCount * 3;\n for (auto i = 0; i < kCount; ++i) {\n for (auto j = 0; j < kCreateCount; ++j) {\n if ((j + 1) % 3 == 0) {\n auto* second = gc::ConcurrencyCopy::get_instance().fetch_out();\n auto* first = gc::ConcurrencyCopy::get_instance().fetch_out();\n gc::ConcurrencyCopy::get_instance().put_in(first, second);\n }\n else {\n gc::ConcurrencyCopy::get_instance().put_in(i * j);\n }\n }\n\n for (auto j = 0; j < kReleaseCount; ++j)\n gc::ConcurrencyCopy::get_instance().fetch_out();\n }\n gc::ConcurrencyCopy::get_instance().collect();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2014 BMW Car IT GmbH\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 * #L%\n *\/\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include \"joynr\/PrivateCopyAssign.h\"\n\n#include \"joynr\/MessageQueue.h\"\n#include \"joynr\/Timer.h\"\n\n#include \n#include \n\nusing namespace joynr;\n\nclass MessageQueueTest : public ::testing::Test {\npublic:\n MessageQueueTest()\n : messageQueue(),\n cleanerTimer(),\n expiryDate(std::chrono::time_point_cast(std::chrono::system_clock::now()) + std::chrono::milliseconds(100))\n {\n }\n\n ~MessageQueueTest() = default;\n\n void SetUp()\n {\n cleanerTimer.addTimer(\n [this](joynr::Timer::TimerId) {\n this->messageQueue.removeOutdatedMessages();\n },\n [](Timer::TimerId) { },\n 50,\n true\n );\n }\n\n void TearDown()\n {\n cleanerTimer.shutdown();\n }\n\n\nprotected:\n MessageQueue messageQueue;\n Timer cleanerTimer;\n JoynrTimePoint expiryDate;\n\nprivate:\n DISALLOW_COPY_AND_ASSIGN(MessageQueueTest);\n};\n\nTEST_F(MessageQueueTest, initialQueueIsEmpty) {\n EXPECT_EQ(messageQueue.getQueueLength(), 0);\n}\n\nTEST_F(MessageQueueTest, addMultipleMessages) {\n JoynrMessage msg1;\n msg1.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg1), 1);\n JoynrMessage msg2;\n msg2.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg2), 2);\n JoynrMessage msg3;\n msg3.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg3), 3);\n JoynrMessage msg4;\n msg4.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg4), 4);\n}\n\nTEST_F(MessageQueueTest, queueDequeueMessages) {\n \/\/ add messages to the queue\n JoynrMessage msg1;\n msg1.setHeaderTo(\"TEST1\");\n msg1.setHeaderExpiryDate(expiryDate);\n messageQueue.queueMessage(msg1);\n\n JoynrMessage msg2;\n msg2.setHeaderTo(\"TEST2\");\n msg2.setHeaderExpiryDate(expiryDate);\n messageQueue.queueMessage(msg2);\n EXPECT_EQ(messageQueue.getQueueLength(), 2);\n\n \/\/ get messages from queue\n MessageQueueItem* item = messageQueue.getNextMessageForParticipant(\"TEST1\");\n EXPECT_EQ(item->getContent(), msg1);\n EXPECT_EQ(messageQueue.getQueueLength(), 1);\n\n item = messageQueue.getNextMessageForParticipant(\"TEST2\");\n EXPECT_EQ(item->getContent(), msg2);\n EXPECT_EQ(messageQueue.getQueueLength(), 0);\n}\n\nTEST_F(MessageQueueTest, queueDequeueMultipleMessagesForOneParticipant) {\n \/\/ add messages to the queue\n JoynrMessage msg;\n msg.setHeaderTo(\"TEST\");\n msg.setHeaderExpiryDate(expiryDate);\n messageQueue.queueMessage(msg);\n messageQueue.queueMessage(msg);\n EXPECT_EQ(messageQueue.getQueueLength(), 2);\n\n \/\/ get messages from queue\n MessageQueueItem* item = messageQueue.getNextMessageForParticipant(\"TEST\");\n EXPECT_EQ(item->getContent(), msg);\n EXPECT_EQ(messageQueue.getQueueLength(), 1);\n\n item = messageQueue.getNextMessageForParticipant(\"TEST\");\n EXPECT_EQ(item->getContent(), msg);\n EXPECT_EQ(messageQueue.getQueueLength(), 0);\n}\n\nTEST_F(MessageQueueTest, dequeueInvalidParticipantId) {\n EXPECT_FALSE(messageQueue.getNextMessageForParticipant(\"TEST\"));\n}\n[C++] Remove timer from MessageQueueTest\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2014 BMW Car IT GmbH\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 * #L%\n *\/\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include \"joynr\/PrivateCopyAssign.h\"\n\n#include \"joynr\/MessageQueue.h\"\n\n#include \n#include \n\nusing namespace joynr;\n\nclass MessageQueueTest : public ::testing::Test {\npublic:\n MessageQueueTest()\n : messageQueue(),\n expiryDate(std::chrono::time_point_cast(std::chrono::system_clock::now()) + std::chrono::milliseconds(100))\n {\n }\n\n ~MessageQueueTest() = default;\n\nprotected:\n MessageQueue messageQueue;\n JoynrTimePoint expiryDate;\n\nprivate:\n DISALLOW_COPY_AND_ASSIGN(MessageQueueTest);\n};\n\nTEST_F(MessageQueueTest, initialQueueIsEmpty) {\n EXPECT_EQ(messageQueue.getQueueLength(), 0);\n}\n\nTEST_F(MessageQueueTest, addMultipleMessages) {\n JoynrMessage msg1;\n msg1.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg1), 1);\n JoynrMessage msg2;\n msg2.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg2), 2);\n JoynrMessage msg3;\n msg3.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg3), 3);\n JoynrMessage msg4;\n msg4.setHeaderExpiryDate(expiryDate);\n EXPECT_EQ(messageQueue.queueMessage(msg4), 4);\n}\n\nTEST_F(MessageQueueTest, queueDequeueMessages) {\n \/\/ add messages to the queue\n JoynrMessage msg1;\n msg1.setHeaderTo(\"TEST1\");\n msg1.setHeaderExpiryDate(expiryDate);\n messageQueue.queueMessage(msg1);\n\n JoynrMessage msg2;\n msg2.setHeaderTo(\"TEST2\");\n msg2.setHeaderExpiryDate(expiryDate);\n messageQueue.queueMessage(msg2);\n EXPECT_EQ(messageQueue.getQueueLength(), 2);\n\n \/\/ get messages from queue\n MessageQueueItem* item = messageQueue.getNextMessageForParticipant(\"TEST1\");\n EXPECT_EQ(item->getContent(), msg1);\n EXPECT_EQ(messageQueue.getQueueLength(), 1);\n\n item = messageQueue.getNextMessageForParticipant(\"TEST2\");\n EXPECT_EQ(item->getContent(), msg2);\n EXPECT_EQ(messageQueue.getQueueLength(), 0);\n}\n\nTEST_F(MessageQueueTest, queueDequeueMultipleMessagesForOneParticipant) {\n \/\/ add messages to the queue\n JoynrMessage msg;\n msg.setHeaderTo(\"TEST\");\n msg.setHeaderExpiryDate(expiryDate);\n messageQueue.queueMessage(msg);\n messageQueue.queueMessage(msg);\n EXPECT_EQ(messageQueue.getQueueLength(), 2);\n\n \/\/ get messages from queue\n MessageQueueItem* item = messageQueue.getNextMessageForParticipant(\"TEST\");\n EXPECT_EQ(item->getContent(), msg);\n EXPECT_EQ(messageQueue.getQueueLength(), 1);\n\n item = messageQueue.getNextMessageForParticipant(\"TEST\");\n EXPECT_EQ(item->getContent(), msg);\n EXPECT_EQ(messageQueue.getQueueLength(), 0);\n}\n\nTEST_F(MessageQueueTest, dequeueInvalidParticipantId) {\n EXPECT_FALSE(messageQueue.getNextMessageForParticipant(\"TEST\"));\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n** Copyright (c) 2000-2003 Wayne Roth\n** Copyright (c) 2004-2007 Stefan Sander\n** Copyright (c) 2007 Michal Policht\n** Copyright (c) 2008 Brandon Fosdick\n** Copyright (c) 2009-2010 Liam Staskawicz\n** Copyright (c) 2011 Debao Zhang\n** Copyright (c) 2012 Doug Brown\n** All right reserved.\n** Web: http:\/\/code.google.com\/p\/qextserialport\/\n**\n** Permission is hereby granted, free of charge, to any person obtaining\n** a copy of this software and associated documentation files (the\n** \"Software\"), to deal in the Software without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and\/or sell copies of the Software, and to\n** permit persons to whom the Software is furnished to do so, subject to\n** the following conditions:\n**\n** The above copyright notice and this permission notice shall be\n** included in all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n**\n****************************************************************************\/\n\n#include \"qextserialenumerator.h\"\n#include \"qextserialenumerator_p.h\"\n#include \n#include \n#include \n\nvoid QextSerialEnumeratorPrivate::platformSpecificInit()\n{\n#ifndef QESP_NO_UDEV\n monitor = NULL;\n notifierFd = -1;\n notifier = NULL;\n\n udev = udev_new();\n if (!udev)\n qCritical() << \"Unable to initialize udev notifications\";\n#endif\n}\n\nvoid QextSerialEnumeratorPrivate::platformSpecificDestruct()\n{\n#ifndef QESP_NO_UDEV\n if (notifier) {\n notifier->setEnabled(false);\n delete notifier;\n }\n\n if (monitor)\n udev_monitor_unref(monitor);\n\n if (udev)\n udev_unref(udev);\n#endif\n}\n\n#ifndef QESP_NO_UDEV\nstatic QextPortInfo portInfoFromDevice(struct udev_device *dev)\n{\n QString vendor = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_VENDOR_ID\"));\n QString product = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_MODEL_ID\"));\n\n QextPortInfo pi;\n pi.vendorID = vendor.toInt(0, 16);\n pi.productID = product.toInt(0, 16);\n pi.portName = QString::fromLatin1(udev_device_get_devnode(dev));\n pi.physName = pi.portName;\n\n return pi;\n}\n#endif\n\nQList QextSerialEnumeratorPrivate::getPorts_sys()\n{\n QList infoList;\n#ifndef QESP_NO_UDEV\n struct udev *ud = udev_new();\n if (!ud) {\n qCritical() << \"Unable to enumerate ports because udev is not initialized.\";\n return infoList;\n }\n\n struct udev_enumerate *enumerate = udev_enumerate_new(ud);\n udev_enumerate_add_match_subsystem(enumerate, \"tty\");\n udev_enumerate_scan_devices(enumerate);\n struct udev_list_entry *list = udev_enumerate_get_list_entry(enumerate);\n struct udev_list_entry *entry;\n udev_list_entry_foreach(entry, list) {\n const char *path;\n struct udev_device *dev;\n\n \/\/ Have to grab the actual udev device here...\n path = udev_list_entry_get_name(entry);\n dev = udev_device_new_from_syspath(ud, path);\n\n infoList.append(portInfoFromDevice(dev));\n\n \/\/ Done with this device\n udev_device_unref(dev);\n }\n \/\/ Done with the list and this udev\n udev_enumerate_unref(enumerate);\n udev_unref(ud);\n#else\n QStringList portNamePrefixes, portNameList;\n portNamePrefixes << QLatin1String(\"ttyS*\"); \/\/ list normal serial ports first\n\n QDir dir(QLatin1String(\"\/dev\"));\n portNameList = dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n \/\/ remove the values which are not serial ports for e.g. \/dev\/ttysa\n for (int i = 0; i < portNameList.size(); i++) {\n bool ok;\n QString current = portNameList.at(i);\n \/\/ remove the ttyS part, and check, if the other part is a number\n current.remove(0,4).toInt(&ok, 10);\n if (!ok) {\n portNameList.removeAt(i);\n i--;\n }\n }\n\n \/\/ get the non standard serial ports names\n \/\/ (USB-serial, bluetooth-serial, 18F PICs, and so on)\n \/\/ if you know an other name prefix for serial ports please let us know\n portNamePrefixes.clear();\n portNamePrefixes << QLatin1String(\"ttyACM*\") << QLatin1String(\"ttyUSB*\") << QLatin1String(\"rfcomm*\");\n portNamePrefixes << QLatin1String(\"serial\/by-id\/usb-*\")\n portNameList += dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n foreach (QString str , portNameList) {\n QextPortInfo inf;\n inf.physName = QLatin1String(\"\/dev\/\")+str;\n inf.portName = str;\n\n if (str.contains(QLatin1String(\"ttyS\"))) {\n inf.friendName = QLatin1String(\"Serial port \")+str.remove(0, 4);\n }\n else if (str.contains(QLatin1String(\"ttyUSB\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"rfcomm\"))) {\n inf.friendName = QLatin1String(\"Bluetooth-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"serial\/by-id\/usb-\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 17);\n }\n inf.enumName = QLatin1String(\"\/dev\"); \/\/ is there a more helpful name for this?\n infoList.append(inf);\n }\n#endif\n\n return infoList;\n}\n\nbool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool setup)\n{\n Q_UNUSED(setup);\n#ifndef QESP_NO_UDEV\n Q_Q(QextSerialEnumerator);\n if (!udev) {\n qCritical() << \"Unable to initialize notifications because udev is not initialized.\";\n return false;\n }\n\n \/\/ Emit signals immediately for devices already connected (Windows version seems to behave\n \/\/ this way)\n foreach (QextPortInfo i, getPorts_sys())\n Q_EMIT q->deviceDiscovered(i);\n\n \/\/ Look for tty devices from udev.\n monitor = udev_monitor_new_from_netlink(udev, \"udev\");\n udev_monitor_filter_add_match_subsystem_devtype(monitor, \"tty\", NULL);\n udev_monitor_enable_receiving(monitor);\n notifierFd = udev_monitor_get_fd(monitor);\n notifier = new QSocketNotifier(notifierFd, QSocketNotifier::Read);\n q->connect(notifier, SIGNAL(activated(int)), q, SLOT(_q_deviceEvent()));\n notifier->setEnabled(true);\n\n return true;\n#else\n return false;\n#endif\n}\n\n#ifndef QESP_NO_UDEV\nvoid QextSerialEnumeratorPrivate::_q_deviceEvent()\n{\n Q_Q(QextSerialEnumerator);\n struct udev_device *dev = udev_monitor_receive_device(monitor);\n if (dev) {\n QextPortInfo pi = portInfoFromDevice(dev);\n QLatin1String action(udev_device_get_action(dev));\n\n if (action == QLatin1String(\"add\"))\n Q_EMIT q->deviceDiscovered(pi);\n else if (action == QLatin1String(\"remove\"))\n Q_EMIT q->deviceRemoved(pi);\n\n udev_device_unref(dev);\n }\n}\n#endif\nFixed typo\/****************************************************************************\n** Copyright (c) 2000-2003 Wayne Roth\n** Copyright (c) 2004-2007 Stefan Sander\n** Copyright (c) 2007 Michal Policht\n** Copyright (c) 2008 Brandon Fosdick\n** Copyright (c) 2009-2010 Liam Staskawicz\n** Copyright (c) 2011 Debao Zhang\n** Copyright (c) 2012 Doug Brown\n** All right reserved.\n** Web: http:\/\/code.google.com\/p\/qextserialport\/\n**\n** Permission is hereby granted, free of charge, to any person obtaining\n** a copy of this software and associated documentation files (the\n** \"Software\"), to deal in the Software without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and\/or sell copies of the Software, and to\n** permit persons to whom the Software is furnished to do so, subject to\n** the following conditions:\n**\n** The above copyright notice and this permission notice shall be\n** included in all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n**\n****************************************************************************\/\n\n#include \"qextserialenumerator.h\"\n#include \"qextserialenumerator_p.h\"\n#include \n#include \n#include \n\nvoid QextSerialEnumeratorPrivate::platformSpecificInit()\n{\n#ifndef QESP_NO_UDEV\n monitor = NULL;\n notifierFd = -1;\n notifier = NULL;\n\n udev = udev_new();\n if (!udev)\n qCritical() << \"Unable to initialize udev notifications\";\n#endif\n}\n\nvoid QextSerialEnumeratorPrivate::platformSpecificDestruct()\n{\n#ifndef QESP_NO_UDEV\n if (notifier) {\n notifier->setEnabled(false);\n delete notifier;\n }\n\n if (monitor)\n udev_monitor_unref(monitor);\n\n if (udev)\n udev_unref(udev);\n#endif\n}\n\n#ifndef QESP_NO_UDEV\nstatic QextPortInfo portInfoFromDevice(struct udev_device *dev)\n{\n QString vendor = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_VENDOR_ID\"));\n QString product = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_MODEL_ID\"));\n\n QextPortInfo pi;\n pi.vendorID = vendor.toInt(0, 16);\n pi.productID = product.toInt(0, 16);\n pi.portName = QString::fromLatin1(udev_device_get_devnode(dev));\n pi.physName = pi.portName;\n\n return pi;\n}\n#endif\n\nQList QextSerialEnumeratorPrivate::getPorts_sys()\n{\n QList infoList;\n#ifndef QESP_NO_UDEV\n struct udev *ud = udev_new();\n if (!ud) {\n qCritical() << \"Unable to enumerate ports because udev is not initialized.\";\n return infoList;\n }\n\n struct udev_enumerate *enumerate = udev_enumerate_new(ud);\n udev_enumerate_add_match_subsystem(enumerate, \"tty\");\n udev_enumerate_scan_devices(enumerate);\n struct udev_list_entry *list = udev_enumerate_get_list_entry(enumerate);\n struct udev_list_entry *entry;\n udev_list_entry_foreach(entry, list) {\n const char *path;\n struct udev_device *dev;\n\n \/\/ Have to grab the actual udev device here...\n path = udev_list_entry_get_name(entry);\n dev = udev_device_new_from_syspath(ud, path);\n\n infoList.append(portInfoFromDevice(dev));\n\n \/\/ Done with this device\n udev_device_unref(dev);\n }\n \/\/ Done with the list and this udev\n udev_enumerate_unref(enumerate);\n udev_unref(ud);\n#else\n QStringList portNamePrefixes, portNameList;\n portNamePrefixes << QLatin1String(\"ttyS*\"); \/\/ list normal serial ports first\n\n QDir dir(QLatin1String(\"\/dev\"));\n portNameList = dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n \/\/ remove the values which are not serial ports for e.g. \/dev\/ttysa\n for (int i = 0; i < portNameList.size(); i++) {\n bool ok;\n QString current = portNameList.at(i);\n \/\/ remove the ttyS part, and check, if the other part is a number\n current.remove(0,4).toInt(&ok, 10);\n if (!ok) {\n portNameList.removeAt(i);\n i--;\n }\n }\n\n \/\/ get the non standard serial ports names\n \/\/ (USB-serial, bluetooth-serial, 18F PICs, and so on)\n \/\/ if you know an other name prefix for serial ports please let us know\n portNamePrefixes.clear();\n portNamePrefixes << QLatin1String(\"ttyACM*\") << QLatin1String(\"ttyUSB*\") << QLatin1String(\"rfcomm*\");\n portNamePrefixes << QLatin1String(\"serial\/by-id\/usb-*\");\n portNameList += dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n foreach (QString str , portNameList) {\n QextPortInfo inf;\n inf.physName = QLatin1String(\"\/dev\/\")+str;\n inf.portName = str;\n\n if (str.contains(QLatin1String(\"ttyS\"))) {\n inf.friendName = QLatin1String(\"Serial port \")+str.remove(0, 4);\n }\n else if (str.contains(QLatin1String(\"ttyUSB\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"rfcomm\"))) {\n inf.friendName = QLatin1String(\"Bluetooth-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"serial\/by-id\/usb-\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 17);\n }\n inf.enumName = QLatin1String(\"\/dev\"); \/\/ is there a more helpful name for this?\n infoList.append(inf);\n }\n#endif\n\n return infoList;\n}\n\nbool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool setup)\n{\n Q_UNUSED(setup);\n#ifndef QESP_NO_UDEV\n Q_Q(QextSerialEnumerator);\n if (!udev) {\n qCritical() << \"Unable to initialize notifications because udev is not initialized.\";\n return false;\n }\n\n \/\/ Emit signals immediately for devices already connected (Windows version seems to behave\n \/\/ this way)\n foreach (QextPortInfo i, getPorts_sys())\n Q_EMIT q->deviceDiscovered(i);\n\n \/\/ Look for tty devices from udev.\n monitor = udev_monitor_new_from_netlink(udev, \"udev\");\n udev_monitor_filter_add_match_subsystem_devtype(monitor, \"tty\", NULL);\n udev_monitor_enable_receiving(monitor);\n notifierFd = udev_monitor_get_fd(monitor);\n notifier = new QSocketNotifier(notifierFd, QSocketNotifier::Read);\n q->connect(notifier, SIGNAL(activated(int)), q, SLOT(_q_deviceEvent()));\n notifier->setEnabled(true);\n\n return true;\n#else\n return false;\n#endif\n}\n\n#ifndef QESP_NO_UDEV\nvoid QextSerialEnumeratorPrivate::_q_deviceEvent()\n{\n Q_Q(QextSerialEnumerator);\n struct udev_device *dev = udev_monitor_receive_device(monitor);\n if (dev) {\n QextPortInfo pi = portInfoFromDevice(dev);\n QLatin1String action(udev_device_get_action(dev));\n\n if (action == QLatin1String(\"add\"))\n Q_EMIT q->deviceDiscovered(pi);\n else if (action == QLatin1String(\"remove\"))\n Q_EMIT q->deviceRemoved(pi);\n\n udev_device_unref(dev);\n }\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Pavel Kirienko \n *\/\n\n#pragma once\n\n#include \n#include \n#include \n\nnamespace uavcan\n{\n\ntemplate \nclass LazyConstructor\n{\n unsigned char data_[sizeof(T)] __attribute__((aligned(16))); \/\/ TODO: compiler-independent alignment\n T* ptr_;\n\n void failure() const\n {\n#if UAVCAN_EXCEPTIONS\n throw std::logic_error(typeid(*this).name());\n#else\n assert(0);\n std::abort();\n#endif\n }\n\n void ensureConstructed() const\n {\n if (!ptr_)\n failure();\n }\n\n void ensureNotConstructed() const\n {\n if (ptr_)\n failure();\n }\n\npublic:\n LazyConstructor()\n : ptr_(NULL)\n { }\n\n LazyConstructor(const LazyConstructor& rhs)\n : ptr_(NULL)\n {\n if (rhs)\n construct(*rhs); \/\/ Invoke copy constructor\n }\n\n ~LazyConstructor() { destroy(); }\n\n LazyConstructor& operator=(const LazyConstructor& rhs)\n {\n destroy();\n if (rhs)\n construct(*rhs); \/\/ Invoke copy constructor\n return *this;\n }\n\n bool isConstructed() const { return ptr_ != NULL; }\n\n operator T*() const { return ptr_; }\n\n const T* operator->() const { ensureConstructed(); return ptr_; }\n T* operator->() { ensureConstructed(); return ptr_; }\n\n const T& operator*() const { ensureConstructed(); return *ptr_; }\n T& operator*() { ensureConstructed(); return *ptr_; }\n\n void destroy()\n {\n if (ptr_)\n ptr_->~T();\n ptr_ = NULL;\n }\n\n void construct()\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T();\n }\n\n\/\/ MAX_ARGS = 6\n\/\/ TEMPLATE = '''\n\/\/ template <%s>\n\/\/ void construct(%s)\n\/\/ {\n\/\/ ensureNotConstructed();\n\/\/ ptr_ = new (static_cast(data_)) T(%s);\n\/\/ }'''\n\/\/ for nargs in range(1, MAX_ARGS + 1):\n\/\/ nums = [(x + 1) for x in range(nargs)]\n\/\/ l1 = ['typename P%d' % x for x in nums]\n\/\/ l2 = ['P%d p%d' % (x, x) for x in nums]\n\/\/ l3 = ['p%d' % x for x in nums]\n\/\/ print(TEMPLATE % (', '.join(l1), ', '.join(l2), ', '.join(l3)))\n\n template \n void construct(P1 p1)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1);\n }\n\n template \n void construct(P1 p1, P2 p2)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3, P4 p4)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3, p4);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3, p4, p5);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3, p4, p5, p6);\n }\n};\n\n}\nLazy constructor init fix\/*\n * Copyright (C) 2014 Pavel Kirienko \n *\/\n\n#pragma once\n\n#include \n#include \n#include \n\nnamespace uavcan\n{\n\ntemplate \nclass LazyConstructor\n{\n unsigned char data_[sizeof(T)] __attribute__((aligned(16))); \/\/ TODO: compiler-independent alignment\n T* ptr_;\n\n void failure() const\n {\n#if UAVCAN_EXCEPTIONS\n throw std::logic_error(typeid(*this).name());\n#else\n assert(0);\n std::abort();\n#endif\n }\n\n void ensureConstructed() const\n {\n if (!ptr_)\n failure();\n }\n\n void ensureNotConstructed() const\n {\n if (ptr_)\n failure();\n }\n\npublic:\n LazyConstructor()\n : ptr_(NULL)\n {\n std::fill(data_, data_ + sizeof(T), 0);\n }\n\n LazyConstructor(const LazyConstructor& rhs)\n : ptr_(NULL)\n {\n std::fill(data_, data_ + sizeof(T), 0);\n if (rhs)\n construct(*rhs); \/\/ Invoke copy constructor\n }\n\n ~LazyConstructor() { destroy(); }\n\n LazyConstructor& operator=(const LazyConstructor& rhs)\n {\n destroy();\n if (rhs)\n construct(*rhs); \/\/ Invoke copy constructor\n return *this;\n }\n\n bool isConstructed() const { return ptr_ != NULL; }\n\n operator T*() const { return ptr_; }\n\n const T* operator->() const { ensureConstructed(); return ptr_; }\n T* operator->() { ensureConstructed(); return ptr_; }\n\n const T& operator*() const { ensureConstructed(); return *ptr_; }\n T& operator*() { ensureConstructed(); return *ptr_; }\n\n void destroy()\n {\n if (ptr_)\n ptr_->~T();\n ptr_ = NULL;\n }\n\n void construct()\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T();\n }\n\n\/\/ MAX_ARGS = 6\n\/\/ TEMPLATE = '''\n\/\/ template <%s>\n\/\/ void construct(%s)\n\/\/ {\n\/\/ ensureNotConstructed();\n\/\/ ptr_ = new (static_cast(data_)) T(%s);\n\/\/ }'''\n\/\/ for nargs in range(1, MAX_ARGS + 1):\n\/\/ nums = [(x + 1) for x in range(nargs)]\n\/\/ l1 = ['typename P%d' % x for x in nums]\n\/\/ l2 = ['P%d p%d' % (x, x) for x in nums]\n\/\/ l3 = ['p%d' % x for x in nums]\n\/\/ print(TEMPLATE % (', '.join(l1), ', '.join(l2), ', '.join(l3)))\n\n template \n void construct(P1 p1)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1);\n }\n\n template \n void construct(P1 p1, P2 p2)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3, P4 p4)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3, p4);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3, p4, p5);\n }\n\n template \n void construct(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6)\n {\n ensureNotConstructed();\n ptr_ = new (static_cast(data_)) T(p1, p2, p3, p4, p5, p6);\n }\n};\n\n}\n<|endoftext|>"} {"text":"#ifndef SDR_H_\n#define SDR_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace sdr\n{\n\n\ntypedef std::size_t position_t;\ntypedef std::size_t width_t;\n\n\n\n\/\/ this holds all of the traits for a single concept\n\/\/ ie - if width is 1024, this could hold up to 1024 values between 0 and 1024\n\/\/ designed to be fast to create, pass around, and as util to compress sparse data\nstruct concept\n{\n std::vector data;\n\n \/\/ for vector of positions we assume the data has already been dealt with\n concept(const std::vector & input) : data(input)\n {}\n\n \/\/ otherwise we assume that is hasn't, thus we only add non zero fields\n template concept(const std::bitset & input) : data()\n {\n for(std::size_t i=0; i < input.size(); ++i) {\n if(input[i]) {\n data.push_back(i);\n }\n }\n }\n\n \/\/ store [amount] largest ones from input\n template concept(const std::array & input, const std::size_t amount) : data()\n {\n std::vector idx(input.size());\n std::iota(idx.begin(), idx.end(), 0);\n\n std::partial_sort(idx.begin(), idx.begin() + amount, idx.end(), [&](\n const T a,\n const T b\n ) {\n return input[a] > input[b];\n });\n\n for(std::size_t i=0; i < amount; ++i) {\n \/\/ end if value is 0\n if(! input[idx[i]]) {\n break;\n }\n\n data.push_back(idx[i]);\n }\n }\n};\n\n\n\/\/ represents a concept in storage\n\/\/ designed to be able to be quickly queried and modified\nstruct storage_concept\n{\n \/\/ store the positions of all set bits from 0 -> width\n std::unordered_set positions;\n\n storage_concept(const concept & concept) : positions(concept.data.begin(), concept.data.end())\n {}\n\n void fill(const concept & concept)\n {\n std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));\n }\n\n void clear()\n {\n positions.clear();\n }\n\n \/\/ conversion to concept via cast\n operator concept() const\n {\n return concept(std::vector(positions.begin(), positions.end()));\n }\n};\n\n\n\/\/ this is the memory bank for the sdr memory unit\ntemplate struct bank\n{\n \/\/ all inputs we have ever received, we store here compressed into storage\n std::vector storage;\n\n \/\/ this holds our sets of vectors for easy comparison of different objects in storage\n std::array, Width> bitmap;\n\n bank() : storage(), bitmap()\n {}\n\n position_t insert(const concept & concept)\n {\n storage.push_back(storage_concept(concept));\n\n const position_t last_pos = storage.size() - 1;\n\n for(position_t pos : concept.data) {\n bitmap[pos].insert(last_pos);\n }\n\n return last_pos;\n }\n\n void update(const position_t pos, const concept & concept)\n {\n storage_concept & storage_concept = storage[pos];\n\n for(position_t i : storage_concept.positions) {\n bitmap[i].erase(pos);\n }\n\n storage_concept.clear();\n\n storage_concept.fill(concept);\n\n for(position_t p : storage_concept.positions) {\n bitmap[p].insert(pos);\n }\n }\n\n \/\/ find amount of matching bits between two vectors\n std::size_t similarity(const position_t a, const position_t b) const\n {\n std::size_t result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b);\n }\n\n return result;\n }\n\n \/\/ find amount of matching bits between two vectors\n double weighted_similarity(const position_t a, const position_t b, const std::array & weights) const\n {\n double result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b) * weights[pos];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n std::size_t union_similarity(const position_t pos, const std::vector & positions) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n std::size_t result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n double weighted_union_similarity(const position_t pos, const std::vector & positions, const std::array & weights) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n double result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp] * weights[cmp];\n }\n\n return result;\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> closest(const position_t pos, const std::size_t amount) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(idx.begin(), idx.end(), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n ++v[bpos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i(v[m])));\n }\n\n return ret;\n }\n\n std::future>> async_closest(const position_t pos, const std::size_t amount) const\n {\n return std::async(std::launch::async, &bank::closest, this, pos, amount);\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> weighted_closest(const position_t pos, const std::size_t amount, const std::array & weights) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(idx.begin(), idx.end(), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n v[bpos] += weights[spos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0.0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i>> async_weighted_closest(const position_t pos, const std::size_t amount, const std::array & weights) const\n {\n return std::async(std::launch::async, &bank::weighted_closest, this, pos, amount, weights);\n }\n\n \/\/ return all items matching all in data\n std::vector matching(const concept & concept) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n for(const std::size_t m : concept.data) {\n if(bitmap[m].count(pos) == 0) {\n goto skip;\n }\n }\n\n matching.insert(pos);\n skip:;\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n\n \/\/ has to match amount in data\n std::vector matching(const concept & concept, const std::size_t amount) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n std::size_t amount_matching = 0;\n\n for(const std::size_t m : concept.data) {\n amount_matching += bitmap[m].count(pos);\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n\n \/\/ has to match amount in data\n std::vector weighted_matching(const std::vector & data, const double amount, const std::array & weights) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : data) {\n for(const std::size_t pos : bitmap[item]) {\n double amount_matching = 0;\n\n for(const std::size_t m : data) {\n amount_matching += bitmap[m].count(pos) * weights[m];\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n};\n\n} \/\/namespace sdr\n\n#endif\nuse std::begin\/end#ifndef SDR_H_\n#define SDR_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace sdr\n{\n\n\ntypedef std::size_t position_t;\ntypedef std::size_t width_t;\n\n\n\n\/\/ this holds all of the traits for a single concept\n\/\/ ie - if width is 1024, this could hold up to 1024 values between 0 and 1024\n\/\/ designed to be fast to create, pass around, and as util to compress sparse data\nstruct concept\n{\n std::vector data;\n\n \/\/ for vector of positions we assume the data has already been dealt with\n concept(const std::vector & input) : data(input)\n {}\n\n \/\/ otherwise we assume that is hasn't, thus we only add non zero fields\n template concept(const std::bitset & input) : data()\n {\n for(std::size_t i=0; i < input.size(); ++i) {\n if(input[i]) {\n data.push_back(i);\n }\n }\n }\n\n \/\/ store [amount] largest ones from input\n template concept(const std::array & input, const std::size_t amount) : data()\n {\n std::vector idx(input.size());\n std::iota(std::begin(idx), std::end(idx), 0);\n\n std::partial_sort(std::begin(idx), std::begin(idx) + amount, std::end(idx), [&](\n const T a,\n const T b\n ) {\n return input[a] > input[b];\n });\n\n for(std::size_t i=0; i < amount; ++i) {\n \/\/ end if value is 0\n if(! input[idx[i]]) {\n break;\n }\n\n data.push_back(idx[i]);\n }\n }\n};\n\n\n\/\/ represents a concept in storage\n\/\/ designed to be able to be quickly queried and modified\nstruct storage_concept\n{\n \/\/ store the positions of all set bits from 0 -> width\n std::unordered_set positions;\n\n storage_concept(const concept & concept) : positions(std::begin(concept.data), std::end(concept.data))\n {}\n\n void fill(const concept & concept)\n {\n std::copy(std::begin(concept.data), std::end(concept.data), std::inserter(positions, std::begin(positions)));\n }\n\n void clear()\n {\n positions.clear();\n }\n\n \/\/ conversion to concept via cast\n operator concept() const\n {\n return concept(std::vector(std::begin(positions), std::end(positions)));\n }\n};\n\n\n\/\/ this is the memory bank for the sdr memory unit\ntemplate struct bank\n{\n \/\/ all inputs we have ever received, we store here compressed into storage\n std::vector storage;\n\n \/\/ this holds our sets of vectors for easy comparison of different objects in storage\n std::array, Width> bitmap;\n\n bank() : storage(), bitmap()\n {}\n\n position_t insert(const concept & concept)\n {\n storage.push_back(storage_concept(concept));\n\n const position_t last_pos = storage.size() - 1;\n\n for(position_t pos : concept.data) {\n bitmap[pos].insert(last_pos);\n }\n\n return last_pos;\n }\n\n void update(const position_t pos, const concept & concept)\n {\n storage_concept & storage_concept = storage[pos];\n\n for(position_t i : storage_concept.positions) {\n bitmap[i].erase(pos);\n }\n\n storage_concept.clear();\n\n storage_concept.fill(concept);\n\n for(position_t p : storage_concept.positions) {\n bitmap[p].insert(pos);\n }\n }\n\n \/\/ find amount of matching bits between two vectors\n std::size_t similarity(const position_t a, const position_t b) const\n {\n std::size_t result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b);\n }\n\n return result;\n }\n\n \/\/ find amount of matching bits between two vectors\n double weighted_similarity(const position_t a, const position_t b, const std::array & weights) const\n {\n double result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b) * weights[pos];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n std::size_t union_similarity(const position_t pos, const std::vector & positions) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n std::size_t result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n double weighted_union_similarity(const position_t pos, const std::vector & positions, const std::array & weights) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n double result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp] * weights[cmp];\n }\n\n return result;\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> closest(const position_t pos, const std::size_t amount) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(std::begin(idx), std::end(idx), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n ++v[bpos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(std::begin(idx), std::begin(idx) + partial_amount, std::end(idx), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i(v[m])));\n }\n\n return ret;\n }\n\n std::future>> async_closest(const position_t pos, const std::size_t amount) const\n {\n return std::async(std::launch::async, &bank::closest, this, pos, amount);\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> weighted_closest(const position_t pos, const std::size_t amount, const std::array & weights) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(std::begin(idx), std::end(idx), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n v[bpos] += weights[spos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0.0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(std::begin(idx), std::begin(idx) + partial_amount, std::end(idx), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i>> async_weighted_closest(const position_t pos, const std::size_t amount, const std::array & weights) const\n {\n return std::async(std::launch::async, &bank::weighted_closest, this, pos, amount, weights);\n }\n\n \/\/ return all items matching all in data\n std::vector matching(const concept & concept) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n for(const std::size_t m : concept.data) {\n if(bitmap[m].count(pos) == 0) {\n goto skip;\n }\n }\n\n matching.insert(pos);\n skip:;\n }\n }\n\n return std::vector(std::begin(matching), std::end(matching));\n }\n\n \/\/ has to match amount in data\n std::vector matching(const concept & concept, const std::size_t amount) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n std::size_t amount_matching = 0;\n\n for(const std::size_t m : concept.data) {\n amount_matching += bitmap[m].count(pos);\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(std::begin(matching), std::begin(matching));\n }\n\n \/\/ has to match amount in data\n std::vector weighted_matching(const std::vector & data, const double amount, const std::array & weights) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : data) {\n for(const std::size_t pos : bitmap[item]) {\n double amount_matching = 0;\n\n for(const std::size_t m : data) {\n amount_matching += bitmap[m].count(pos) * weights[m];\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(std::begin(matching), std::end(matching));\n }\n};\n\n} \/\/namespace sdr\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#include \n#include \n\n#include \"test.hh\"\n\nnamespace pegtl\n{\n struct file_content : seq< pegtl_string_t( \"dummy content\" ), eol, discard > {};\n struct file_grammar : seq< rep_min_max< 11, 11, file_content >, eof > {};\n\n void unit_test()\n {\n TEST_ASSERT( parse_stdin< file_grammar >( 16 ) );\n }\n\n} \/\/ namespace pegtl\n\n#include \"main.hh\"\nRemove<|endoftext|>"} {"text":"\n#include \n#include \n#include \"dmaManager.h\"\n#include \"spikehw.h\"\n\nint verbose = 0;\n\nclass SpikeHwIndication : public SpikeHwIndicationWrapper\n{\n sem_t sem;\npublic:\n uint32_t buf[16];\n\n void irqChanged( const uint8_t irqLevel, const uint8_t intrSources ) {\n fprintf(stderr, \"irqLevel %d intr sources %x\\n\", irqLevel, intrSources);\n }\n virtual void resetDone() {\n\tfprintf(stderr, \"reset done\\n\");\n\tsem_post(&sem);\n }\n virtual void status ( const uint8_t mmcm_locked, const uint8_t irq, const uint8_t intrSources ) {\n\tfprintf(stderr, \"axi eth status mmcm_locked=%d irq=%d intr sources=%x\\n\", mmcm_locked, irq, intrSources);\n\tsem_post(&sem);\n }\n\n void wait() {\n\tsem_wait(&sem);\n }\n\n void readDone ( const uint32_t value ) {\n\tbuf[0] = value;\n\tif (verbose) fprintf(stderr, \"readDone value=%08x\\n\", value);\n\tsem_post(&sem);\n }\n\n void writeDone ( ) {\n\tif (verbose) fprintf(stderr, \"writeDone\\n\");\n\tsem_post(&sem);\n }\n\n void readFlashDone ( const uint32_t value ) {\n\tbuf[0] = value;\n\tif (verbose) fprintf(stderr, \"readFlashDone value=%08x\\n\", value);\n\tsem_post(&sem);\n }\n\n void writeFlashDone ( ) {\n\tif (verbose) fprintf(stderr, \"writeFlashDone\\n\");\n\tsem_post(&sem);\n }\n\n SpikeHwIndication(unsigned int id) : SpikeHwIndicationWrapper(id) {\n sem_init(&sem, 0, 0);\n }\n};\n\n\nSpikeHwRequestProxy *request;\nSpikeHwIndication *indication;\n\n#ifdef STANDALONE\nint main(int argc, const char **argv)\n{\n request = new SpikeHwRequestProxy(IfcNames_SpikeHwRequestS2H);\n indication = new SpikeHwIndication(IfcNames_SpikeHwIndicationH2S);\n fprintf(stderr, \"Reading ID register\\n\");\n request->read((1<<18) + 0x4f8);\n indication->wait();\n for (int i = 0; i < 16; i++) {\n fprintf(stderr, \"register %04x\\n\", i*4);\n request->read((1<<18) + i*4);\n indication->wait();\n fprintf(stderr, \"now writing ...\\n\");\n request->write((1<<18) + i*4, 0xbeef);\n indication->wait();\n request->read((1<<18) + i*4);\n indication->wait();\n }\n return 0;\n}\n\n#else\nSpikeHw::SpikeHw()\n : request(0), indication(0), dmaManager(0), didReset(false)\n{\n request = new SpikeHwRequestProxy(IfcNames_SpikeHwRequestS2H);\n indication = new SpikeHwIndication(IfcNames_SpikeHwIndicationH2S);\n dmaManager = platformInit();\n}\n\nSpikeHw::~SpikeHw()\n{\n \/\/delete request;\n \/\/delete indication;\n request = 0;\n indication = 0;\n}\n\nvoid SpikeHw::maybeReset()\n{\n if (0)\n if (!didReset) {\n\tfprintf(stderr, \"resetting flash\\n\");\n\trequest->reset();\n\tindication->wait();\n\t\/\/request->setParameters(50, 0);\n\tfprintf(stderr, \"done resetting flash\\n\");\n\tdidReset = true;\n }\n}\n\nvoid SpikeHw::status()\n{\n request->status();\n indication->wait();\n}\n\nvoid SpikeHw::setupDma(uint32_t memfd)\n{\n int memref = dmaManager->reference(memfd);\n request->setupDma(memref);\n}\n\nvoid SpikeHw::read(unsigned long offset, uint8_t *buf)\n{\n maybeReset();\n\n if (verbose) fprintf(stderr, \"SpikeHw::read offset=%lx\\n\", offset);\n request->read(offset);\n indication->wait();\n if (verbose) fprintf(stderr, \"SpikeHw::read offset=%lx value=%x\\n\", offset, *(uint32_t *)indication->buf);\n memcpy(buf, indication->buf, 4);\n}\n\nvoid SpikeHw::write(unsigned long offset, const uint8_t *buf)\n{\n maybeReset();\n\n if (1 || verbose) fprintf(stderr, \"SpikeHw::write offset=%lx value=%x\\n\", offset, *(uint32_t *)buf);\n request->write(offset, *(uint32_t *)buf);\n indication->wait();\n request->status();\n indication->wait();\n}\n\nvoid SpikeHw::setFlashParameters(unsigned long cycles)\n{\n request->setFlashParameters(cycles);\n}\n\nvoid SpikeHw::readFlash(unsigned long offset, uint8_t *buf)\n{\n maybeReset();\n\n if (verbose) fprintf(stderr, \"SpikeHw::readFlash offset=%lx\\n\", offset);\n request->readFlash(offset);\n indication->wait();\n if (verbose) fprintf(stderr, \"SpikeHw::readFlash offset=%lx value=%x\\n\", offset, *(uint32_t *)indication->buf);\n memcpy(buf, indication->buf, 4);\n}\n\nvoid SpikeHw::writeFlash(unsigned long offset, const uint8_t *buf)\n{\n maybeReset();\n\n if (1 || verbose) fprintf(stderr, \"SpikeHw::writeFlash offset=%lx value=%x\\n\", offset, *(uint32_t *)buf);\n request->writeFlash(offset, *(uint32_t *)buf);\n indication->wait();\n}\n#endif\nremoved STANDALONE from spikehw.cpp\n#include \n#include \n#include \"dmaManager.h\"\n#include \"spikehw.h\"\n\nint verbose = 0;\n\nclass SpikeHwIndication : public SpikeHwIndicationWrapper\n{\n sem_t sem;\npublic:\n uint32_t buf[16];\n\n void irqChanged( const uint8_t irqLevel, const uint8_t intrSources ) {\n fprintf(stderr, \"irqLevel %d intr sources %x\\n\", irqLevel, intrSources);\n }\n virtual void resetDone() {\n\tfprintf(stderr, \"reset done\\n\");\n\tsem_post(&sem);\n }\n virtual void status ( const uint8_t mmcm_locked, const uint8_t irq, const uint8_t intrSources ) {\n\tfprintf(stderr, \"axi eth status mmcm_locked=%d irq=%d intr sources=%x\\n\", mmcm_locked, irq, intrSources);\n\tsem_post(&sem);\n }\n\n void wait() {\n\tsem_wait(&sem);\n }\n\n void readDone ( const uint32_t value ) {\n\tbuf[0] = value;\n\tif (verbose) fprintf(stderr, \"readDone value=%08x\\n\", value);\n\tsem_post(&sem);\n }\n\n void writeDone ( ) {\n\tif (verbose) fprintf(stderr, \"writeDone\\n\");\n\tsem_post(&sem);\n }\n\n void readFlashDone ( const uint32_t value ) {\n\tbuf[0] = value;\n\tif (verbose) fprintf(stderr, \"readFlashDone value=%08x\\n\", value);\n\tsem_post(&sem);\n }\n\n void writeFlashDone ( ) {\n\tif (verbose) fprintf(stderr, \"writeFlashDone\\n\");\n\tsem_post(&sem);\n }\n\n SpikeHwIndication(unsigned int id) : SpikeHwIndicationWrapper(id) {\n sem_init(&sem, 0, 0);\n }\n};\n\n\nSpikeHwRequestProxy *request;\nSpikeHwIndication *indication;\n\nSpikeHw::SpikeHw()\n : request(0), indication(0), dmaManager(0), didReset(false)\n{\n request = new SpikeHwRequestProxy(IfcNames_SpikeHwRequestS2H);\n indication = new SpikeHwIndication(IfcNames_SpikeHwIndicationH2S);\n dmaManager = platformInit();\n}\n\nSpikeHw::~SpikeHw()\n{\n \/\/delete request;\n \/\/delete indication;\n request = 0;\n indication = 0;\n}\n\nvoid SpikeHw::maybeReset()\n{\n if (0)\n if (!didReset) {\n\tfprintf(stderr, \"resetting flash\\n\");\n\trequest->reset();\n\tindication->wait();\n\t\/\/request->setParameters(50, 0);\n\tfprintf(stderr, \"done resetting flash\\n\");\n\tdidReset = true;\n }\n}\n\nvoid SpikeHw::status()\n{\n request->status();\n indication->wait();\n}\n\nvoid SpikeHw::setupDma(uint32_t memfd)\n{\n int memref = dmaManager->reference(memfd);\n request->setupDma(memref);\n}\n\nvoid SpikeHw::read(unsigned long offset, uint8_t *buf)\n{\n maybeReset();\n\n if (verbose) fprintf(stderr, \"SpikeHw::read offset=%lx\\n\", offset);\n request->read(offset);\n indication->wait();\n if (verbose) fprintf(stderr, \"SpikeHw::read offset=%lx value=%x\\n\", offset, *(uint32_t *)indication->buf);\n memcpy(buf, indication->buf, 4);\n}\n\nvoid SpikeHw::write(unsigned long offset, const uint8_t *buf)\n{\n maybeReset();\n\n if (1 || verbose) fprintf(stderr, \"SpikeHw::write offset=%lx value=%x\\n\", offset, *(uint32_t *)buf);\n request->write(offset, *(uint32_t *)buf);\n indication->wait();\n request->status();\n indication->wait();\n}\n\nvoid SpikeHw::setFlashParameters(unsigned long cycles)\n{\n request->setFlashParameters(cycles);\n}\n\nvoid SpikeHw::readFlash(unsigned long offset, uint8_t *buf)\n{\n maybeReset();\n\n if (verbose) fprintf(stderr, \"SpikeHw::readFlash offset=%lx\\n\", offset);\n request->readFlash(offset);\n indication->wait();\n if (verbose) fprintf(stderr, \"SpikeHw::readFlash offset=%lx value=%x\\n\", offset, *(uint32_t *)indication->buf);\n memcpy(buf, indication->buf, 4);\n}\n\nvoid SpikeHw::writeFlash(unsigned long offset, const uint8_t *buf)\n{\n maybeReset();\n\n if (1 || verbose) fprintf(stderr, \"SpikeHw::writeFlash offset=%lx value=%x\\n\", offset, *(uint32_t *)buf);\n request->writeFlash(offset, *(uint32_t *)buf);\n indication->wait();\n}\n<|endoftext|>"} {"text":"\/*\n * Tests for the next hop computation (LFDB).\n *\n * Copyright (C) 2018 Vincenzo Maffione\n * Author: Vincenzo Maffione \n *\n * This file is part of rlite.\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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"uipcp-normal-lfdb.hpp\"\n\n\/* A type to represent a single routing table, excluding the default next\n * hop. *\/\nusing NextHops = std::unordered_map>;\n\n\/* A type to represent a collection of routing tables, one for each node\n * in a network. *\/\nusing RoutingTables =\n std::unordered_map>;\n\n\/* Representation of a list of reachability tests. See the description\n * below. *\/\nusing ReachabilityTests = std::vector>;\n\nstruct TestLFDB : public rlite::LFDB {\n using LinksList = std::vector>;\n LinksList links;\n\n \/* Populate rlite::LFDB::db from the list of links coming from\n * the test vector. *\/\n TestLFDB(const LinksList &links, bool lfa_enabled)\n : rlite::LFDB(lfa_enabled, \/*verbose=*\/false), links(links)\n {\n for (const auto &link : links) {\n gpb::LowerFlow lf1, lf2;\n\n lf1.set_local_node(std::to_string(link.first));\n lf1.set_remote_node(std::to_string(link.second));\n lf2.set_local_node(std::to_string(link.second));\n lf2.set_remote_node(std::to_string(link.first));\n lf1.set_cost(1);\n lf2.set_cost(1);\n lf1.set_seqnum(1);\n lf2.set_seqnum(1);\n lf1.set_state(true);\n lf2.set_state(true);\n lf1.set_age(0);\n lf2.set_age(0);\n\n db[lf1.local_node()][lf1.remote_node()] = lf1;\n db[lf2.local_node()][lf2.remote_node()] = lf2;\n }\n }\n};\n\n\/* Returns true if the routing tables are able to route a packet from\n * 'src_node' to 'dst_node' with exactly 'n' hops. *\/\nstatic bool\nreachable(const RoutingTables &rtables, int src_node, int dst_node,\n int expected_nhops, const bool verbose)\n{\n rlite::NodeId dst = std::to_string(dst_node);\n rlite::NodeId cur = std::to_string(src_node);\n\n if (verbose) {\n std::cout << \"---> Start from node \" << cur << std::endl;\n }\n for (; expected_nhops >= 0 && cur != dst; expected_nhops--) {\n const auto &rt = rtables.at(cur);\n NextHops::const_iterator nhops = rt.first.find(dst);\n\n if (nhops != rt.first.end()) {\n \/* Entry find in the routing table. *\/\n cur = nhops->second.front();\n } else {\n \/* Not found, use default next hop. *\/\n cur = rt.second;\n }\n if (verbose) {\n std::cout << \" hop to \" << cur << std::endl;\n }\n }\n return cur == dst && expected_nhops == 0;\n}\n\nint\nmain(int argc, char **argv)\n{\n auto usage = []() {\n std::cout << \"lfdb-test -n SIZE\\n\"\n \" -v be verbose\\n\"\n \" -h show this help and exit\\n\";\n };\n int verbosity = 0;\n int n = 100;\n int opt;\n\n while ((opt = getopt(argc, argv, \"hvn:\")) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n\n case 'v':\n verbosity++;\n break;\n\n case 'n':\n n = std::atoi(optarg);\n break;\n\n default:\n std::cout << \" Unrecognized option \" << static_cast(opt)\n << std::endl;\n usage();\n return -1;\n }\n }\n\n \/* Test vectors are stored in a list of pairs. Each pair is made of a list\n * of links and a list of reachability tests. A list of links describes\n * a network graph, where nodes are integer numbers; each link in the list\n * is a pair of integers, which represents a link between two nodes. An\n * item in list of reachability tests is a pair of integers; the first\n * integer refers to a destination node to be reached (from node 0), and\n * the second integer refers to the number of expected hops to reach the\n * destination node. *\/\n std::list> test_vectors =\n {{\/*links=*\/{{0, 1}, {0, 3}, {1, 2}, {2, 3}},\n \/*reachability_tests=*\/{{1, 1}, {2, 2}, {3, 1}}}};\n\n {\n \/* Generate a grid-shaped network of size 'sqn' x 'sqn'. *\/\n TestLFDB::LinksList links;\n ReachabilityTests reachability_tests;\n int sqn = static_cast(std::sqrt(n));\n\n if (sqn < 2) {\n sqn = 2;\n }\n\n auto coord = [sqn](int i, int j) { return i * sqn + j; };\n\n for (int i = 0; i < sqn; i++) {\n for (int j = 0; j < sqn - 1; j++) {\n links.push_back({coord(i, j), coord(i, j + 1)});\n links.push_back({coord(j, i), coord(j + 1, i)});\n }\n }\n\n \/* Get from node 0 (top left) to top right in sqn-1 steps. *\/\n reachability_tests.push_back({coord(0, sqn - 1), sqn - 1});\n\n \/* Get from node 0 (top left) to bottom left in sqn-1 steps. *\/\n reachability_tests.push_back({coord(sqn - 1, 0), sqn - 1});\n\n \/* Get from node 0 (top left) to bottom right. *\/\n reachability_tests.push_back({coord(sqn - 1, sqn - 1), 2 * (sqn - 1)});\n\n \/* Get from node 0 (top left) to one very close to the the\n * bottom left node. *\/\n reachability_tests.push_back({coord(sqn - 2, 1), sqn - 1});\n\n test_vectors.push_back(\n make_pair(std::move(links), std::move(reachability_tests)));\n }\n\n int counter = 1;\n for (const auto &p : test_vectors) {\n TestLFDB::LinksList links = p.first;\n ReachabilityTests reachability_tests = p.second;\n\n std::cout << \"Test vector #\" << counter << std::endl;\n\n \/* Build the lfdb object under test by populating it with the\n * links in the test vector. *\/\n TestLFDB lfdb(links, \/*lfa_enabled=*\/false);\n\n if (verbosity >= 2) {\n std::stringstream ss;\n lfdb.dump(ss);\n std::cout << ss.str();\n }\n assert(!links.empty());\n\n \/* Compute the routing tables for each node in the network and\n * store them into 'rtables'. *\/\n RoutingTables rtables;\n auto start = std::chrono::system_clock::now();\n\n for (const auto &kv : lfdb.db) {\n const rlite::NodeId &source = kv.first;\n\n lfdb.compute_next_hops(source);\n if (verbosity >= 2) {\n std::stringstream ss;\n lfdb.dump_routing(ss, source);\n std::cout << ss.str();\n }\n rtables[source] =\n make_pair(std::move(lfdb.next_hops), std::move(lfdb.dflt_nhop));\n }\n auto delta = std::chrono::duration_cast(\n std::chrono::system_clock::now() - start);\n\n \/* Use 'rtables' to carry out all the reachability tests defined for\n * this network. *\/\n for (const auto &rtest : reachability_tests) {\n const int src_node = 0;\n if (!reachable(rtables, \/*src_node=*\/src_node,\n \/*dst_node=*\/rtest.first,\n \/*expected_nhops=*\/rtest.second,\n \/*verbose=*\/verbosity >= 1)) {\n std::cerr << \"Cannot reach node \" << rtest.first\n << \" from node \" << src_node << \" in \" << rtest.second\n << \" steps\" << std::endl;\n std::cout << \"Test # \" << counter << \" failed\" << std::endl;\n return -1;\n }\n }\n\n std::cout << \"Test # \" << counter << \" completed in \" << delta.count()\n << \" ms\" << std::endl;\n counter++;\n }\n\n return 0;\n}\nuipcps: lfdb-test: add a 9-nodes handcrafted network\/*\n * Tests for the next hop computation (LFDB).\n *\n * Copyright (C) 2018 Vincenzo Maffione\n * Author: Vincenzo Maffione \n *\n * This file is part of rlite.\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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"uipcp-normal-lfdb.hpp\"\n\n\/* A type to represent a single routing table, excluding the default next\n * hop. *\/\nusing NextHops = std::unordered_map>;\n\n\/* A type to represent a collection of routing tables, one for each node\n * in a network. *\/\nusing RoutingTables =\n std::unordered_map>;\n\n\/* Representation of a list of reachability tests. See the description\n * below. *\/\nusing ReachabilityTests = std::vector>;\n\nstruct TestLFDB : public rlite::LFDB {\n using LinksList = std::vector>;\n LinksList links;\n\n \/* Populate rlite::LFDB::db from the list of links coming from\n * the test vector. *\/\n TestLFDB(const LinksList &links, bool lfa_enabled)\n : rlite::LFDB(lfa_enabled, \/*verbose=*\/false), links(links)\n {\n for (const auto &link : links) {\n gpb::LowerFlow lf1, lf2;\n\n lf1.set_local_node(std::to_string(link.first));\n lf1.set_remote_node(std::to_string(link.second));\n lf2.set_local_node(std::to_string(link.second));\n lf2.set_remote_node(std::to_string(link.first));\n lf1.set_cost(1);\n lf2.set_cost(1);\n lf1.set_seqnum(1);\n lf2.set_seqnum(1);\n lf1.set_state(true);\n lf2.set_state(true);\n lf1.set_age(0);\n lf2.set_age(0);\n\n db[lf1.local_node()][lf1.remote_node()] = lf1;\n db[lf2.local_node()][lf2.remote_node()] = lf2;\n }\n }\n};\n\n\/* Returns true if the routing tables are able to route a packet from\n * 'src_node' to 'dst_node' with exactly 'n' hops. *\/\nstatic bool\nreachable(const RoutingTables &rtables, int src_node, int dst_node,\n int expected_nhops, const bool verbose)\n{\n rlite::NodeId dst = std::to_string(dst_node);\n rlite::NodeId cur = std::to_string(src_node);\n\n if (verbose) {\n std::cout << \"---> Start from node \" << cur << std::endl;\n }\n for (; expected_nhops >= 0 && cur != dst; expected_nhops--) {\n const auto &rt = rtables.at(cur);\n NextHops::const_iterator nhops = rt.first.find(dst);\n\n if (nhops != rt.first.end()) {\n \/* Entry find in the routing table. *\/\n cur = nhops->second.front();\n } else {\n \/* Not found, use default next hop. *\/\n cur = rt.second;\n }\n if (verbose) {\n std::cout << \" hop to \" << cur << std::endl;\n }\n }\n return cur == dst && expected_nhops == 0;\n}\n\nint\nmain(int argc, char **argv)\n{\n auto usage = []() {\n std::cout << \"lfdb-test -n SIZE\\n\"\n \" -v be verbose\\n\"\n \" -h show this help and exit\\n\";\n };\n int verbosity = 0;\n int n = 100;\n int opt;\n\n while ((opt = getopt(argc, argv, \"hvn:\")) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n\n case 'v':\n verbosity++;\n break;\n\n case 'n':\n n = std::atoi(optarg);\n break;\n\n default:\n std::cout << \" Unrecognized option \" << static_cast(opt)\n << std::endl;\n usage();\n return -1;\n }\n }\n\n \/* Test vectors are stored in a list of pairs. Each pair is made of a list\n * of links and a list of reachability tests. A list of links describes\n * a network graph, where nodes are integer numbers; each link in the list\n * is a pair of integers, which represents a link between two nodes. An\n * item in list of reachability tests is a pair of integers; the first\n * integer refers to a destination node to be reached (from node 0), and\n * the second integer refers to the number of expected hops to reach the\n * destination node. *\/\n std::list> test_vectors =\n {{\/*links=*\/{{0, 1}, {0, 3}, {1, 2}, {2, 3}},\n \/*reachability_tests=*\/{{1, 1}, {2, 2}, {3, 1}}},\n {\/*links=*\/{{0, 1},\n {0, 2},\n {0, 3},\n {1, 4},\n {2, 3},\n {2, 5},\n {3, 4},\n {3, 5},\n {4, 5},\n {4, 6},\n {4, 7},\n {5, 6},\n {6, 7},\n {7, 8}},\n \/*reachability_tests=*\/{\n {1, 1}, {2, 1}, {3, 1}, {4, 2}, {5, 2}, {6, 3}, {7, 3}, {8, 4}}}};\n\n {\n \/* Generate a grid-shaped network of size 'sqn' x 'sqn'. *\/\n TestLFDB::LinksList links;\n ReachabilityTests reachability_tests;\n int sqn = static_cast(std::sqrt(n));\n\n if (sqn < 2) {\n sqn = 2;\n }\n\n auto coord = [sqn](int i, int j) { return i * sqn + j; };\n\n for (int i = 0; i < sqn; i++) {\n for (int j = 0; j < sqn - 1; j++) {\n links.push_back({coord(i, j), coord(i, j + 1)});\n links.push_back({coord(j, i), coord(j + 1, i)});\n }\n }\n\n \/* Get from node 0 (top left) to top right in sqn-1 steps. *\/\n reachability_tests.push_back({coord(0, sqn - 1), sqn - 1});\n\n \/* Get from node 0 (top left) to bottom left in sqn-1 steps. *\/\n reachability_tests.push_back({coord(sqn - 1, 0), sqn - 1});\n\n \/* Get from node 0 (top left) to bottom right. *\/\n reachability_tests.push_back({coord(sqn - 1, sqn - 1), 2 * (sqn - 1)});\n\n \/* Get from node 0 (top left) to one very close to the the\n * bottom left node. *\/\n reachability_tests.push_back({coord(sqn - 2, 1), sqn - 1});\n\n test_vectors.push_back(\n make_pair(std::move(links), std::move(reachability_tests)));\n }\n\n int counter = 1;\n for (const auto &p : test_vectors) {\n TestLFDB::LinksList links = p.first;\n ReachabilityTests reachability_tests = p.second;\n\n std::cout << \"Test vector #\" << counter << std::endl;\n\n \/* Build the lfdb object under test by populating it with the\n * links in the test vector. *\/\n TestLFDB lfdb(links, \/*lfa_enabled=*\/false);\n\n if (verbosity >= 2) {\n std::stringstream ss;\n lfdb.dump(ss);\n std::cout << ss.str();\n }\n assert(!links.empty());\n\n \/* Compute the routing tables for each node in the network and\n * store them into 'rtables'. *\/\n RoutingTables rtables;\n auto start = std::chrono::system_clock::now();\n\n for (const auto &kv : lfdb.db) {\n const rlite::NodeId &source = kv.first;\n\n lfdb.compute_next_hops(source);\n if (verbosity >= 2) {\n std::stringstream ss;\n lfdb.dump_routing(ss, source);\n std::cout << ss.str();\n }\n rtables[source] =\n make_pair(std::move(lfdb.next_hops), std::move(lfdb.dflt_nhop));\n }\n auto delta = std::chrono::duration_cast(\n std::chrono::system_clock::now() - start);\n\n \/* Use 'rtables' to carry out all the reachability tests defined for\n * this network. *\/\n for (const auto &rtest : reachability_tests) {\n const int src_node = 0;\n if (!reachable(rtables, \/*src_node=*\/src_node,\n \/*dst_node=*\/rtest.first,\n \/*expected_nhops=*\/rtest.second,\n \/*verbose=*\/verbosity >= 1)) {\n std::cerr << \"Cannot reach node \" << rtest.first\n << \" from node \" << src_node << \" in \" << rtest.second\n << \" steps\" << std::endl;\n std::cout << \"Test # \" << counter << \" failed\" << std::endl;\n return -1;\n }\n }\n\n std::cout << \"Test # \" << counter << \" completed in \" << delta.count()\n << \" ms\" << std::endl;\n counter++;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"processor.h\"\n\n#include \n\n#include \"io_dispatcher.h\"\n#include \"file.h\"\n#include \"chunk.h\"\n\nusing namespace upload;\n\ntbb::task* ChunkProcessingTask::execute() {\n \/\/ Thread Safety:\n \/\/ * Only one ChunkProcessingTask for any given Chunk at any given time\n \/\/ * Parallel execution of more than one ChunkProcessingTask for chunks of\n \/\/ the same File is possible\n\n assert (chunk_->IsInitialized());\n assert (buffer_->IsInitialized());\n\n \/\/ get the position from where the current input buffer needs to be processed\n const off_t internal_offset =\n std::max(off_t(0), chunk_->offset() - buffer_->base_offset());\n assert (internal_offset >= 0);\n assert (static_cast(internal_offset) < buffer_->used_bytes());\n const unsigned char *data = buffer_->ptr() + internal_offset;\n\n \/\/ determine how many bytes need to be processed\n const size_t byte_count = (chunk_->size() == 0)\n ? buffer_->used_bytes() - internal_offset\n : std::min(buffer_->base_offset() + buffer_->used_bytes(),\n chunk_->offset() + chunk_->size())\n - std::max(buffer_->base_offset(), chunk_->offset());\n assert (byte_count <= buffer_->used_bytes() - internal_offset);\n\n \/\/ find out, if we are going to process the final block of the chunk\n const bool finalize = (\n (chunk_->size() > 0) &&\n (buffer_->base_offset() + internal_offset + byte_count\n == chunk_->offset() + chunk_->size())\n );\n\n \/\/ crunch the data\n Crunch(data, byte_count, finalize);\n\n \/\/ finalize the chunk if necessary\n if (finalize) {\n chunk_->Finalize();\n }\n\n \/\/ the TBB scheduler should figure out what to do next\n return NULL;\n}\n\n\nvoid ChunkProcessingTask::Crunch(const unsigned char *data,\n const size_t bytes,\n const bool finalize) const {\n z_stream &stream = chunk_->zlib_context();\n SHA_CTX &sha1_ctx = chunk_->sha1_context();\n\n const size_t max_output_size = deflateBound(&stream, bytes);\n CharBuffer *compress_buffer = new CharBuffer(max_output_size);\n\n stream.avail_in = bytes;\n stream.next_in = const_cast(data); \/\/ sry, but zlib forces me...\n const int flush = (finalize) ? Z_FINISH : Z_NO_FLUSH;\n\n int retcode = -1;\n while (true) {\n stream.avail_out = compress_buffer->size();\n stream.next_out = compress_buffer->ptr();\n\n retcode = deflate(&stream, flush);\n assert (retcode == Z_OK || retcode == Z_STREAM_END);\n\n const size_t bytes_produced = compress_buffer->size() - stream.avail_out;\n if (bytes_produced > 0) {\n compress_buffer->SetUsedBytes(bytes_produced);\n compress_buffer->SetBaseOffset(chunk_->compressed_size());\n chunk_->add_compressed_size(bytes_produced);\n const int sha_retcode = SHA1_Update(&sha1_ctx,\n compress_buffer->ptr(),\n compress_buffer->used_bytes());\n assert (sha_retcode == 1);\n chunk_->ScheduleWrite(compress_buffer);\n }\n\n if ((flush == Z_NO_FLUSH && retcode == Z_OK) ||\n (flush == Z_FINISH && retcode == Z_STREAM_END)) {\n break;\n }\n\n if (stream.avail_out == 0) {\n compress_buffer = new CharBuffer(4096);\n }\n }\n\n if (finalize) {\n assert (flush == Z_FINISH);\n }\n}\n\n\n\ntbb::task* FileScrubbingTask::execute() {\n \/\/ Thread Safety:\n \/\/ * Only one executing FileScrubbingTask per File at any time\n \/\/ * Execution is done in-order, thus the File is processed as a stream of\n \/\/ CharBuffers. Each CharBuffer will be processed in one FileScrubbingTask\n\n if (file_->MightBecomeChunked()) {\n \/\/ find chunk cut marks in the current buffer and process all chunks that\n \/\/ are fully specified (i.e. not reaching beyond the current buffer)\n const CutMarks cut_marks = FindNextChunkCutMarks();\n CutMarks::const_iterator i = cut_marks.begin();\n CutMarks::const_iterator iend = cut_marks.end();\n for (; i != iend; ++i) {\n Chunk *fully_defined_chunk = file_->CreateNextChunk(*i);\n assert (fully_defined_chunk->IsFullyDefined());\n QueueForDeferredProcessing(fully_defined_chunk);\n }\n\n \/\/ if we reached the last buffer this input file will produce, all but the\n \/\/ last created chunk will be fully defined at this point\n if (IsLastBuffer()) {\n file_->FullyDefineLastChunk();\n }\n\n \/\/ process the current chunk, i.e. the last created chunk that potentially\n \/\/ reaches beyond the current buffer or to the end of the file\n Chunk *current_chunk = file_->current_chunk();\n if (current_chunk != NULL) {\n QueueForDeferredProcessing(current_chunk);\n }\n }\n\n \/\/ check if the file has a bulk chunk and continue processing it using the\n \/\/ current buffer\n if (file_->HasBulkChunk()) {\n QueueForDeferredProcessing(file_->bulk_chunk());\n }\n\n \/\/ wait for all scheduled chunk processing tasks on the current buffer\n SpawnTasksAndWaitForProcessing();\n reader_->ReleaseBuffer(buffer_);\n\n \/\/ commit the chunks that have been finished during this processing step\n CommitFinishedChunks();\n\n \/\/ go on with the next file buffer\n return Next();\n}\n\n\nvoid FileScrubbingTask::SpawnTasksAndWaitForProcessing() {\n tbb::task_list tasks;\n std::vector::const_iterator i = chunks_to_process_.begin();\n std::vector::const_iterator iend = chunks_to_process_.end();\n for (; i != iend; ++i) {\n tbb::task *chunk_processing_task =\n new(allocate_child()) ChunkProcessingTask(*i, buffer_);\n tasks.push_back(*chunk_processing_task);\n }\n\n set_ref_count(chunks_to_process_.size() + 1); \/\/ +1 for the wait\n spawn_and_wait_for_all(tasks);\n}\n\n\nvoid FileScrubbingTask::CommitFinishedChunks() const {\n std::vector::const_iterator i = chunks_to_process_.begin();\n std::vector::const_iterator iend = chunks_to_process_.end();\n for (; i != iend; ++i) {\n Chunk *current_chunk = *i;\n if (current_chunk->IsFullyProcessed()) {\n current_chunk->ScheduleCommit();\n }\n }\n\n}\n\n\nFileScrubbingTask::CutMarks FileScrubbingTask::FindNextChunkCutMarks() {\n const Chunk *current_chunk = file_->current_chunk();\n assert (file_->MightBecomeChunked());\n assert (current_chunk != NULL);\n assert (current_chunk->size() == 0);\n assert (current_chunk->offset() <= buffer_->base_offset());\n assert (current_chunk->offset() < buffer_->base_offset() +\n static_cast(buffer_->used_bytes()));\n\n CutMarks result;\n off_t next_cut;\n while ((next_cut = file_->FindNextCutMark(buffer_)) != 0) {\n result.push_back(next_cut);\n }\n\n return result;\n}\n\n\nbool FileScrubbingTask::IsLastBuffer() const {\n return file_->size() == buffer_->base_offset() + buffer_->used_bytes();\n}\n\nFIX: processing of an empty buffer lead to failed assertion\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"processor.h\"\n\n#include \n\n#include \"io_dispatcher.h\"\n#include \"file.h\"\n#include \"chunk.h\"\n\nusing namespace upload;\n\ntbb::task* ChunkProcessingTask::execute() {\n \/\/ Thread Safety:\n \/\/ * Only one ChunkProcessingTask for any given Chunk at any given time\n \/\/ * Parallel execution of more than one ChunkProcessingTask for chunks of\n \/\/ the same File is possible\n\n assert (chunk_->IsInitialized());\n assert (buffer_->IsInitialized());\n\n \/\/ get the position from where the current input buffer needs to be processed\n const off_t internal_offset =\n std::max(off_t(0), chunk_->offset() - buffer_->base_offset());\n assert (internal_offset >= 0);\n assert (static_cast(internal_offset) <= buffer_->used_bytes());\n const unsigned char *data = buffer_->ptr() + internal_offset;\n\n \/\/ determine how many bytes need to be processed\n const size_t byte_count = (chunk_->size() == 0)\n ? buffer_->used_bytes() - internal_offset\n : std::min(buffer_->base_offset() + buffer_->used_bytes(),\n chunk_->offset() + chunk_->size())\n - std::max(buffer_->base_offset(), chunk_->offset());\n assert (byte_count <= buffer_->used_bytes() - internal_offset);\n if (byte_count == 0) {\n return NULL;\n }\n\n \/\/ find out, if we are going to process the final block of the chunk\n const bool finalize = (\n (chunk_->size() > 0) &&\n (buffer_->base_offset() + internal_offset + byte_count\n == chunk_->offset() + chunk_->size())\n );\n\n \/\/ crunch the data\n Crunch(data, byte_count, finalize);\n\n \/\/ finalize the chunk if necessary\n if (finalize) {\n chunk_->Finalize();\n }\n\n \/\/ the TBB scheduler should figure out what to do next\n return NULL;\n}\n\n\nvoid ChunkProcessingTask::Crunch(const unsigned char *data,\n const size_t bytes,\n const bool finalize) const {\n z_stream &stream = chunk_->zlib_context();\n SHA_CTX &sha1_ctx = chunk_->sha1_context();\n\n const size_t max_output_size = deflateBound(&stream, bytes);\n CharBuffer *compress_buffer = new CharBuffer(max_output_size);\n\n stream.avail_in = bytes;\n stream.next_in = const_cast(data); \/\/ sry, but zlib forces me...\n const int flush = (finalize) ? Z_FINISH : Z_NO_FLUSH;\n\n int retcode = -1;\n while (true) {\n stream.avail_out = compress_buffer->size();\n stream.next_out = compress_buffer->ptr();\n\n retcode = deflate(&stream, flush);\n assert (retcode == Z_OK || retcode == Z_STREAM_END);\n\n const size_t bytes_produced = compress_buffer->size() - stream.avail_out;\n if (bytes_produced > 0) {\n compress_buffer->SetUsedBytes(bytes_produced);\n compress_buffer->SetBaseOffset(chunk_->compressed_size());\n chunk_->add_compressed_size(bytes_produced);\n const int sha_retcode = SHA1_Update(&sha1_ctx,\n compress_buffer->ptr(),\n compress_buffer->used_bytes());\n assert (sha_retcode == 1);\n chunk_->ScheduleWrite(compress_buffer);\n }\n\n if ((flush == Z_NO_FLUSH && retcode == Z_OK) ||\n (flush == Z_FINISH && retcode == Z_STREAM_END)) {\n break;\n }\n\n if (stream.avail_out == 0) {\n compress_buffer = new CharBuffer(4096);\n }\n }\n\n if (finalize) {\n assert (flush == Z_FINISH);\n }\n}\n\n\n\ntbb::task* FileScrubbingTask::execute() {\n \/\/ Thread Safety:\n \/\/ * Only one executing FileScrubbingTask per File at any time\n \/\/ * Execution is done in-order, thus the File is processed as a stream of\n \/\/ CharBuffers. Each CharBuffer will be processed in one FileScrubbingTask\n\n if (file_->MightBecomeChunked()) {\n \/\/ find chunk cut marks in the current buffer and process all chunks that\n \/\/ are fully specified (i.e. not reaching beyond the current buffer)\n const CutMarks cut_marks = FindNextChunkCutMarks();\n CutMarks::const_iterator i = cut_marks.begin();\n CutMarks::const_iterator iend = cut_marks.end();\n for (; i != iend; ++i) {\n Chunk *fully_defined_chunk = file_->CreateNextChunk(*i);\n assert (fully_defined_chunk->IsFullyDefined());\n QueueForDeferredProcessing(fully_defined_chunk);\n }\n\n \/\/ if we reached the last buffer this input file will produce, all but the\n \/\/ last created chunk will be fully defined at this point\n if (IsLastBuffer()) {\n file_->FullyDefineLastChunk();\n }\n\n \/\/ process the current chunk, i.e. the last created chunk that potentially\n \/\/ reaches beyond the current buffer or to the end of the file\n Chunk *current_chunk = file_->current_chunk();\n if (current_chunk != NULL) {\n QueueForDeferredProcessing(current_chunk);\n }\n }\n\n \/\/ check if the file has a bulk chunk and continue processing it using the\n \/\/ current buffer\n if (file_->HasBulkChunk()) {\n QueueForDeferredProcessing(file_->bulk_chunk());\n }\n\n \/\/ wait for all scheduled chunk processing tasks on the current buffer\n SpawnTasksAndWaitForProcessing();\n reader_->ReleaseBuffer(buffer_);\n\n \/\/ commit the chunks that have been finished during this processing step\n CommitFinishedChunks();\n\n \/\/ go on with the next file buffer\n return Next();\n}\n\n\nvoid FileScrubbingTask::SpawnTasksAndWaitForProcessing() {\n tbb::task_list tasks;\n std::vector::const_iterator i = chunks_to_process_.begin();\n std::vector::const_iterator iend = chunks_to_process_.end();\n for (; i != iend; ++i) {\n tbb::task *chunk_processing_task =\n new(allocate_child()) ChunkProcessingTask(*i, buffer_);\n tasks.push_back(*chunk_processing_task);\n }\n\n set_ref_count(chunks_to_process_.size() + 1); \/\/ +1 for the wait\n spawn_and_wait_for_all(tasks);\n}\n\n\nvoid FileScrubbingTask::CommitFinishedChunks() const {\n std::vector::const_iterator i = chunks_to_process_.begin();\n std::vector::const_iterator iend = chunks_to_process_.end();\n for (; i != iend; ++i) {\n Chunk *current_chunk = *i;\n if (current_chunk->IsFullyProcessed()) {\n current_chunk->ScheduleCommit();\n }\n }\n\n}\n\n\nFileScrubbingTask::CutMarks FileScrubbingTask::FindNextChunkCutMarks() {\n const Chunk *current_chunk = file_->current_chunk();\n assert (file_->MightBecomeChunked());\n assert (current_chunk != NULL);\n assert (current_chunk->size() == 0);\n assert (current_chunk->offset() <= buffer_->base_offset());\n assert (current_chunk->offset() < buffer_->base_offset() +\n static_cast(buffer_->used_bytes()));\n\n CutMarks result;\n off_t next_cut;\n while ((next_cut = file_->FindNextCutMark(buffer_)) != 0) {\n result.push_back(next_cut);\n }\n\n return result;\n}\n\n\nbool FileScrubbingTask::IsLastBuffer() const {\n return file_->size() == buffer_->base_offset() + buffer_->used_bytes();\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\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\n\/\/ CLASS HEADER\n#include \n\n\/\/ EXTERNAL INCLUDES\n\n\/\/ INTERNAL INCLUDES\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Dali::Internal::SceneGraph::UpdateManager;\n\nnamespace Dali\n{\n\nnamespace\n{\ntypedef Dali::Layer::Behavior Behavior;\n\nDALI_ENUM_TO_STRING_TABLE_BEGIN( Behavior )\nDALI_ENUM_TO_STRING( Dali::Layer::LAYER_2D )\nDALI_ENUM_TO_STRING( Dali::Layer::LAYER_3D )\nDALI_ENUM_TO_STRING_TABLE_END( Behavior )\n} \/\/ namespace\n\nnamespace Internal\n{\n\nnamespace\n{\n\n\/\/ Properties\n\n\/\/ Name Type writable animatable constraint-input enum for index-checking\nDALI_PROPERTY_TABLE_BEGIN\nDALI_PROPERTY( \"clipping-enable\", BOOLEAN, true, false, true, Dali::Layer::Property::CLIPPING_ENABLE )\nDALI_PROPERTY( \"clipping-box\", RECTANGLE, true, false, true, Dali::Layer::Property::CLIPPING_BOX )\nDALI_PROPERTY( \"behavior\", STRING, true, false, false, Dali::Layer::Property::BEHAVIOR )\nDALI_PROPERTY_TABLE_END( DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX )\n\n\/\/ Actions\n\nconst char* const ACTION_RAISE = \"raise\";\nconst char* const ACTION_LOWER = \"lower\";\nconst char* const ACTION_RAISE_TO_TOP = \"raise-to-top\";\nconst char* const ACTION_LOWER_TO_BOTTOM = \"lower-to-bottom\";\n\nBaseHandle Create()\n{\n return Dali::Layer::New();\n}\n\nTypeRegistration mType( typeid( Dali::Layer ), typeid( Dali::Actor ), Create );\n\nTypeAction a1( mType, ACTION_RAISE, &Layer::DoAction );\nTypeAction a2( mType, ACTION_LOWER, &Layer::DoAction );\nTypeAction a3( mType, ACTION_RAISE_TO_TOP, &Layer::DoAction );\nTypeAction a4( mType, ACTION_LOWER_TO_BOTTOM, &Layer::DoAction );\n\n} \/\/ unnamed namespace\n\n\nLayerPtr Layer::New()\n{\n LayerPtr layer( new Layer( Actor::LAYER ) );\n\n \/\/ Second-phase construction\n layer->Initialize();\n\n return layer;\n}\n\nLayerPtr Layer::NewRoot( LayerList& layerList, UpdateManager& manager, bool systemLevel )\n{\n LayerPtr root( new Layer( Actor::ROOT_LAYER ) );\n\n \/\/ Second-phase construction\n SceneGraph::Layer* layer = static_cast( root->CreateNode() );\n InstallRootMessage( manager, *layer, systemLevel ); \/\/ Transfer ownership to scene-graph\n\n \/\/ Keep a raw pointer to the layer node.\n root->mNode = layer;\n\n \/\/ root actor is immediately considered to be on-stage\n root->mIsOnStage = true;\n\n \/\/ The root actor will not emit a stage connection signal so set the signalled flag here as well\n root->mOnStageSignalled = true;\n\n \/\/ layer-list must be set for the root layer\n root->mLayerList = &layerList;\n layerList.RegisterLayer( *root );\n\n return root;\n}\n\nLayer::Layer( Actor::DerivedType type )\n: Actor( type ),\n mLayerList(NULL),\n mClippingBox(0,0,0,0),\n mSortFunction(Layer::ZValue),\n mIsClipping(false),\n mDepthTestDisabled(false),\n mTouchConsumed(false),\n mHoverConsumed(false)\n{\n}\n\nvoid Layer::OnInitialize()\n{\n}\n\nLayer::~Layer()\n{\n}\n\nunsigned int Layer::GetDepth() const\n{\n return mLayerList ? mLayerList->GetDepth( this ) : 0u;\n}\n\nvoid Layer::Raise()\n{\n if ( mLayerList )\n {\n mLayerList->RaiseLayer(*this);\n }\n}\n\nvoid Layer::Lower()\n{\n if ( mLayerList )\n {\n mLayerList->LowerLayer(*this);\n }\n}\n\nvoid Layer::RaiseAbove( const Internal::Layer& target )\n{\n \/\/ cannot raise above ourself, both have to be on stage\n if( ( this != &target ) && OnStage() && target.OnStage() )\n {\n \/\/ get parameters depth\n const unsigned int targetDepth = target.GetDepth();\n if( GetDepth() < targetDepth )\n {\n MoveAbove( target );\n }\n }\n}\n\nvoid Layer::LowerBelow( const Internal::Layer& target )\n{\n \/\/ cannot lower below ourself, both have to be on stage\n if( ( this != &target ) && OnStage() && target.OnStage() )\n {\n \/\/ get parameters depth\n const unsigned int targetDepth = target.GetDepth();\n if( GetDepth() > targetDepth )\n {\n MoveBelow( target );\n }\n }\n}\n\nvoid Layer::RaiseToTop()\n{\n if ( mLayerList )\n {\n mLayerList->RaiseLayerToTop(*this);\n }\n}\n\nvoid Layer::LowerToBottom()\n{\n if ( mLayerList )\n {\n mLayerList->LowerLayerToBottom(*this);\n }\n}\n\nvoid Layer::MoveAbove( const Internal::Layer& target )\n{\n \/\/ cannot raise above ourself, both have to be on stage\n if( ( this != &target ) && mLayerList && target.OnStage() )\n {\n mLayerList->MoveLayerAbove(*this, target );\n }\n}\n\nvoid Layer::MoveBelow( const Internal::Layer& target )\n{\n \/\/ cannot lower below ourself, both have to be on stage\n if( ( this != &target ) && mLayerList && target.OnStage() )\n {\n mLayerList->MoveLayerBelow(*this, target );\n }\n}\n\nvoid Layer::SetBehavior( Dali::Layer::Behavior behavior )\n{\n mBehavior = behavior;\n\n \/\/ notify update side object\n SetBehaviorMessage( GetEventThreadServices(), GetSceneLayerOnStage(), behavior );\n}\n\nvoid Layer::SetClipping(bool enabled)\n{\n if (enabled != mIsClipping)\n {\n mIsClipping = enabled;\n\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetClippingMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mIsClipping );\n }\n}\n\nvoid Layer::SetClippingBox(int x, int y, int width, int height)\n{\n if( ( x != mClippingBox.x ) ||\n ( y != mClippingBox.y ) ||\n ( width != mClippingBox.width ) ||\n ( height != mClippingBox.height ) )\n {\n \/\/ Clipping box is not animatable; this is the most up-to-date value\n mClippingBox.Set(x, y, width, height);\n\n \/\/ Convert mClippingBox to GL based coordinates (from bottom-left)\n ClippingBox clippingBox( mClippingBox );\n\n StagePtr stage = Stage::GetCurrent();\n if( stage )\n {\n clippingBox.y = stage->GetSize().height - clippingBox.y - clippingBox.height;\n\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetClippingBoxMessage( GetEventThreadServices(), GetSceneLayerOnStage(), clippingBox );\n }\n }\n}\n\nvoid Layer::SetDepthTestDisabled( bool disable )\n{\n if( disable != mDepthTestDisabled )\n {\n mDepthTestDisabled = disable;\n\n \/\/ Send message .....\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetDepthTestDisabledMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mDepthTestDisabled );\n }\n}\n\nbool Layer::IsDepthTestDisabled() const\n{\n return mDepthTestDisabled || (mBehavior == Dali::Layer::LAYER_2D);\n}\n\nvoid Layer::SetSortFunction(Dali::Layer::SortFunctionType function)\n{\n if( function != mSortFunction )\n {\n mSortFunction = function;\n\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetSortFunctionMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mSortFunction );\n }\n}\n\nvoid Layer::SetTouchConsumed( bool consume )\n{\n mTouchConsumed = consume;\n}\n\nbool Layer::IsTouchConsumed() const\n{\n return mTouchConsumed;\n}\n\nvoid Layer::SetHoverConsumed( bool consume )\n{\n mHoverConsumed = consume;\n}\n\nbool Layer::IsHoverConsumed() const\n{\n return mHoverConsumed;\n}\n\nSceneGraph::Node* Layer::CreateNode() const\n{\n return SceneGraph::Layer::New();\n}\n\nvoid Layer::OnStageConnectionInternal()\n{\n if ( !mIsRoot )\n {\n DALI_ASSERT_DEBUG( NULL == mLayerList );\n\n \/\/ Find the ordered layer-list\n \/\/ This is different for Layers added via Integration::GetSystemOverlay()\n for ( Actor* parent = mParent; parent != NULL; parent = parent->GetParent() )\n {\n if( parent->IsLayer() )\n {\n Layer* parentLayer = static_cast< Layer* >( parent ); \/\/ cheaper than dynamic_cast\n mLayerList = parentLayer->mLayerList;\n }\n }\n }\n\n DALI_ASSERT_DEBUG( NULL != mLayerList );\n mLayerList->RegisterLayer( *this );\n}\n\nvoid Layer::OnStageDisconnectionInternal()\n{\n mLayerList->UnregisterLayer(*this);\n\n \/\/ mLayerList is only valid when on-stage\n mLayerList = NULL;\n}\n\nconst SceneGraph::Layer& Layer::GetSceneLayerOnStage() const\n{\n DALI_ASSERT_DEBUG( mNode != NULL );\n return dynamic_cast< const SceneGraph::Layer& >( *mNode );\n}\n\nunsigned int Layer::GetDefaultPropertyCount() const\n{\n return Actor::GetDefaultPropertyCount() + DEFAULT_PROPERTY_COUNT;\n}\n\nvoid Layer::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const\n{\n Actor::GetDefaultPropertyIndices( indices ); \/\/ Actor class properties\n indices.Reserve( indices.Size() + DEFAULT_PROPERTY_COUNT );\n\n int index = DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i, ++index )\n {\n indices.PushBack( index );\n }\n}\n\nbool Layer::IsDefaultPropertyWritable( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::IsDefaultPropertyWritable( index );\n }\n\n return DEFAULT_PROPERTY_DETAILS[ index - DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX ].writable;\n}\n\nbool Layer::IsDefaultPropertyAnimatable( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::IsDefaultPropertyAnimatable( index );\n }\n\n return DEFAULT_PROPERTY_DETAILS[ index - DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX ].animatable;\n}\n\nbool Layer::IsDefaultPropertyAConstraintInput( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::IsDefaultPropertyAConstraintInput( index );\n }\n\n return DEFAULT_PROPERTY_DETAILS[ index - DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX ].constraintInput;\n}\n\nProperty::Type Layer::GetDefaultPropertyType( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::GetDefaultPropertyType( index );\n }\n\n index -= DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n\n if ( ( index >= 0 ) && ( index < DEFAULT_PROPERTY_COUNT ) )\n {\n return DEFAULT_PROPERTY_DETAILS[index].type;\n }\n\n \/\/ index out-of-bounds\n return Property::NONE;\n}\n\nconst char* Layer::GetDefaultPropertyName( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::GetDefaultPropertyName( index );\n }\n\n index -= DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n if ( ( index >= 0 ) && ( index < DEFAULT_PROPERTY_COUNT ) )\n {\n return DEFAULT_PROPERTY_DETAILS[index].name;\n }\n\n return NULL;\n}\n\nProperty::Index Layer::GetDefaultPropertyIndex(const std::string& name) const\n{\n Property::Index index = Property::INVALID_INDEX;\n\n \/\/ Look for name in current class' default properties\n for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )\n {\n const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[i];\n if( 0 == name.compare( property->name ) ) \/\/ dont want to convert rhs to string\n {\n index = i + DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n break;\n }\n }\n if( Property::INVALID_INDEX == index )\n {\n \/\/ If not found, check in base class\n index = Actor::GetDefaultPropertyIndex( name );\n }\n\n return index;\n}\n\nvoid Layer::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n Actor::SetDefaultProperty( index, propertyValue );\n }\n else\n {\n switch( index )\n {\n case Dali::Layer::Property::CLIPPING_ENABLE:\n {\n SetClipping( propertyValue.Get() );\n break;\n }\n case Dali::Layer::Property::CLIPPING_BOX:\n {\n Rect clippingBox( propertyValue.Get >() );\n SetClippingBox( clippingBox.x, clippingBox.y, clippingBox.width, clippingBox.height );\n break;\n }\n case Dali::Layer::Property::BEHAVIOR:\n {\n Behavior behavior(Dali::Layer::LAYER_2D);\n if( Scripting::GetEnumeration< Behavior >( propertyValue.Get< std::string >().c_str(), BehaviorTable, BehaviorTableCount, behavior ) )\n {\n SetBehavior( behavior );\n }\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Unknown property (%d)\\n\", index );\n break;\n }\n } \/\/ switch(index)\n\n } \/\/ else\n}\n\nProperty::Value Layer::GetDefaultProperty( Property::Index index ) const\n{\n Property::Value ret;\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n ret = Actor::GetDefaultProperty( index );\n }\n else\n {\n switch( index )\n {\n case Dali::Layer::Property::CLIPPING_ENABLE:\n {\n ret = mIsClipping;\n break;\n }\n case Dali::Layer::Property::CLIPPING_BOX:\n {\n ret = mClippingBox;\n break;\n }\n case Dali::Layer::Property::BEHAVIOR:\n {\n ret = Scripting::GetLinearEnumerationName< Behavior >( GetBehavior(), BehaviorTable, BehaviorTableCount );\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Unknown property (%d)\\n\", index );\n break;\n }\n } \/\/ switch(index)\n }\n\n return ret;\n}\n\nbool Layer::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& \/*attributes*\/ )\n{\n bool done = false;\n Layer* layer = dynamic_cast( object );\n\n if( layer )\n {\n if( 0 == actionName.compare( ACTION_RAISE ) )\n {\n layer->Raise();\n done = true;\n }\n else if( 0 == actionName.compare( ACTION_LOWER ) )\n {\n layer->Lower();\n done = true;\n }\n else if( 0 == actionName.compare( ACTION_RAISE_TO_TOP ) )\n {\n layer->RaiseToTop();\n done = true;\n }\n else if( 0 == actionName.compare( ACTION_LOWER_TO_BOTTOM ) )\n {\n layer->LowerToBottom();\n done = true;\n }\n }\n\n return done;\n}\n\n} \/\/ namespace Internal\n\n} \/\/ namespace Dali\nSet default behavior in Layer - to fix target UTC fail\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\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\n\/\/ CLASS HEADER\n#include \n\n\/\/ EXTERNAL INCLUDES\n\n\/\/ INTERNAL INCLUDES\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Dali::Internal::SceneGraph::UpdateManager;\n\nnamespace Dali\n{\n\nnamespace\n{\ntypedef Dali::Layer::Behavior Behavior;\n\nDALI_ENUM_TO_STRING_TABLE_BEGIN( Behavior )\nDALI_ENUM_TO_STRING( Dali::Layer::LAYER_2D )\nDALI_ENUM_TO_STRING( Dali::Layer::LAYER_3D )\nDALI_ENUM_TO_STRING_TABLE_END( Behavior )\n} \/\/ namespace\n\nnamespace Internal\n{\n\nnamespace\n{\n\n\/\/ Properties\n\n\/\/ Name Type writable animatable constraint-input enum for index-checking\nDALI_PROPERTY_TABLE_BEGIN\nDALI_PROPERTY( \"clipping-enable\", BOOLEAN, true, false, true, Dali::Layer::Property::CLIPPING_ENABLE )\nDALI_PROPERTY( \"clipping-box\", RECTANGLE, true, false, true, Dali::Layer::Property::CLIPPING_BOX )\nDALI_PROPERTY( \"behavior\", STRING, true, false, false, Dali::Layer::Property::BEHAVIOR )\nDALI_PROPERTY_TABLE_END( DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX )\n\n\/\/ Actions\n\nconst char* const ACTION_RAISE = \"raise\";\nconst char* const ACTION_LOWER = \"lower\";\nconst char* const ACTION_RAISE_TO_TOP = \"raise-to-top\";\nconst char* const ACTION_LOWER_TO_BOTTOM = \"lower-to-bottom\";\n\nBaseHandle Create()\n{\n return Dali::Layer::New();\n}\n\nTypeRegistration mType( typeid( Dali::Layer ), typeid( Dali::Actor ), Create );\n\nTypeAction a1( mType, ACTION_RAISE, &Layer::DoAction );\nTypeAction a2( mType, ACTION_LOWER, &Layer::DoAction );\nTypeAction a3( mType, ACTION_RAISE_TO_TOP, &Layer::DoAction );\nTypeAction a4( mType, ACTION_LOWER_TO_BOTTOM, &Layer::DoAction );\n\n} \/\/ unnamed namespace\n\n\nLayerPtr Layer::New()\n{\n LayerPtr layer( new Layer( Actor::LAYER ) );\n\n \/\/ Second-phase construction\n layer->Initialize();\n\n return layer;\n}\n\nLayerPtr Layer::NewRoot( LayerList& layerList, UpdateManager& manager, bool systemLevel )\n{\n LayerPtr root( new Layer( Actor::ROOT_LAYER ) );\n\n \/\/ Second-phase construction\n SceneGraph::Layer* layer = static_cast( root->CreateNode() );\n InstallRootMessage( manager, *layer, systemLevel ); \/\/ Transfer ownership to scene-graph\n\n \/\/ Keep a raw pointer to the layer node.\n root->mNode = layer;\n\n \/\/ root actor is immediately considered to be on-stage\n root->mIsOnStage = true;\n\n \/\/ The root actor will not emit a stage connection signal so set the signalled flag here as well\n root->mOnStageSignalled = true;\n\n \/\/ layer-list must be set for the root layer\n root->mLayerList = &layerList;\n layerList.RegisterLayer( *root );\n\n return root;\n}\n\nLayer::Layer( Actor::DerivedType type )\n: Actor( type ),\n mLayerList(NULL),\n mClippingBox(0,0,0,0),\n mSortFunction(Layer::ZValue),\n mBehavior(Dali::Layer::LAYER_2D),\n mIsClipping(false),\n mDepthTestDisabled(false),\n mTouchConsumed(false),\n mHoverConsumed(false)\n{\n}\n\nvoid Layer::OnInitialize()\n{\n}\n\nLayer::~Layer()\n{\n}\n\nunsigned int Layer::GetDepth() const\n{\n return mLayerList ? mLayerList->GetDepth( this ) : 0u;\n}\n\nvoid Layer::Raise()\n{\n if ( mLayerList )\n {\n mLayerList->RaiseLayer(*this);\n }\n}\n\nvoid Layer::Lower()\n{\n if ( mLayerList )\n {\n mLayerList->LowerLayer(*this);\n }\n}\n\nvoid Layer::RaiseAbove( const Internal::Layer& target )\n{\n \/\/ cannot raise above ourself, both have to be on stage\n if( ( this != &target ) && OnStage() && target.OnStage() )\n {\n \/\/ get parameters depth\n const unsigned int targetDepth = target.GetDepth();\n if( GetDepth() < targetDepth )\n {\n MoveAbove( target );\n }\n }\n}\n\nvoid Layer::LowerBelow( const Internal::Layer& target )\n{\n \/\/ cannot lower below ourself, both have to be on stage\n if( ( this != &target ) && OnStage() && target.OnStage() )\n {\n \/\/ get parameters depth\n const unsigned int targetDepth = target.GetDepth();\n if( GetDepth() > targetDepth )\n {\n MoveBelow( target );\n }\n }\n}\n\nvoid Layer::RaiseToTop()\n{\n if ( mLayerList )\n {\n mLayerList->RaiseLayerToTop(*this);\n }\n}\n\nvoid Layer::LowerToBottom()\n{\n if ( mLayerList )\n {\n mLayerList->LowerLayerToBottom(*this);\n }\n}\n\nvoid Layer::MoveAbove( const Internal::Layer& target )\n{\n \/\/ cannot raise above ourself, both have to be on stage\n if( ( this != &target ) && mLayerList && target.OnStage() )\n {\n mLayerList->MoveLayerAbove(*this, target );\n }\n}\n\nvoid Layer::MoveBelow( const Internal::Layer& target )\n{\n \/\/ cannot lower below ourself, both have to be on stage\n if( ( this != &target ) && mLayerList && target.OnStage() )\n {\n mLayerList->MoveLayerBelow(*this, target );\n }\n}\n\nvoid Layer::SetBehavior( Dali::Layer::Behavior behavior )\n{\n mBehavior = behavior;\n\n \/\/ notify update side object\n SetBehaviorMessage( GetEventThreadServices(), GetSceneLayerOnStage(), behavior );\n}\n\nvoid Layer::SetClipping(bool enabled)\n{\n if (enabled != mIsClipping)\n {\n mIsClipping = enabled;\n\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetClippingMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mIsClipping );\n }\n}\n\nvoid Layer::SetClippingBox(int x, int y, int width, int height)\n{\n if( ( x != mClippingBox.x ) ||\n ( y != mClippingBox.y ) ||\n ( width != mClippingBox.width ) ||\n ( height != mClippingBox.height ) )\n {\n \/\/ Clipping box is not animatable; this is the most up-to-date value\n mClippingBox.Set(x, y, width, height);\n\n \/\/ Convert mClippingBox to GL based coordinates (from bottom-left)\n ClippingBox clippingBox( mClippingBox );\n\n StagePtr stage = Stage::GetCurrent();\n if( stage )\n {\n clippingBox.y = stage->GetSize().height - clippingBox.y - clippingBox.height;\n\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetClippingBoxMessage( GetEventThreadServices(), GetSceneLayerOnStage(), clippingBox );\n }\n }\n}\n\nvoid Layer::SetDepthTestDisabled( bool disable )\n{\n if( disable != mDepthTestDisabled )\n {\n mDepthTestDisabled = disable;\n\n \/\/ Send message .....\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetDepthTestDisabledMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mDepthTestDisabled );\n }\n}\n\nbool Layer::IsDepthTestDisabled() const\n{\n return mDepthTestDisabled || (mBehavior == Dali::Layer::LAYER_2D);\n}\n\nvoid Layer::SetSortFunction(Dali::Layer::SortFunctionType function)\n{\n if( function != mSortFunction )\n {\n mSortFunction = function;\n\n \/\/ layerNode is being used in a separate thread; queue a message to set the value\n SetSortFunctionMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mSortFunction );\n }\n}\n\nvoid Layer::SetTouchConsumed( bool consume )\n{\n mTouchConsumed = consume;\n}\n\nbool Layer::IsTouchConsumed() const\n{\n return mTouchConsumed;\n}\n\nvoid Layer::SetHoverConsumed( bool consume )\n{\n mHoverConsumed = consume;\n}\n\nbool Layer::IsHoverConsumed() const\n{\n return mHoverConsumed;\n}\n\nSceneGraph::Node* Layer::CreateNode() const\n{\n return SceneGraph::Layer::New();\n}\n\nvoid Layer::OnStageConnectionInternal()\n{\n if ( !mIsRoot )\n {\n DALI_ASSERT_DEBUG( NULL == mLayerList );\n\n \/\/ Find the ordered layer-list\n \/\/ This is different for Layers added via Integration::GetSystemOverlay()\n for ( Actor* parent = mParent; parent != NULL; parent = parent->GetParent() )\n {\n if( parent->IsLayer() )\n {\n Layer* parentLayer = static_cast< Layer* >( parent ); \/\/ cheaper than dynamic_cast\n mLayerList = parentLayer->mLayerList;\n }\n }\n }\n\n DALI_ASSERT_DEBUG( NULL != mLayerList );\n mLayerList->RegisterLayer( *this );\n}\n\nvoid Layer::OnStageDisconnectionInternal()\n{\n mLayerList->UnregisterLayer(*this);\n\n \/\/ mLayerList is only valid when on-stage\n mLayerList = NULL;\n}\n\nconst SceneGraph::Layer& Layer::GetSceneLayerOnStage() const\n{\n DALI_ASSERT_DEBUG( mNode != NULL );\n return dynamic_cast< const SceneGraph::Layer& >( *mNode );\n}\n\nunsigned int Layer::GetDefaultPropertyCount() const\n{\n return Actor::GetDefaultPropertyCount() + DEFAULT_PROPERTY_COUNT;\n}\n\nvoid Layer::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const\n{\n Actor::GetDefaultPropertyIndices( indices ); \/\/ Actor class properties\n indices.Reserve( indices.Size() + DEFAULT_PROPERTY_COUNT );\n\n int index = DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i, ++index )\n {\n indices.PushBack( index );\n }\n}\n\nbool Layer::IsDefaultPropertyWritable( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::IsDefaultPropertyWritable( index );\n }\n\n return DEFAULT_PROPERTY_DETAILS[ index - DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX ].writable;\n}\n\nbool Layer::IsDefaultPropertyAnimatable( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::IsDefaultPropertyAnimatable( index );\n }\n\n return DEFAULT_PROPERTY_DETAILS[ index - DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX ].animatable;\n}\n\nbool Layer::IsDefaultPropertyAConstraintInput( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::IsDefaultPropertyAConstraintInput( index );\n }\n\n return DEFAULT_PROPERTY_DETAILS[ index - DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX ].constraintInput;\n}\n\nProperty::Type Layer::GetDefaultPropertyType( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::GetDefaultPropertyType( index );\n }\n\n index -= DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n\n if ( ( index >= 0 ) && ( index < DEFAULT_PROPERTY_COUNT ) )\n {\n return DEFAULT_PROPERTY_DETAILS[index].type;\n }\n\n \/\/ index out-of-bounds\n return Property::NONE;\n}\n\nconst char* Layer::GetDefaultPropertyName( Property::Index index ) const\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n return Actor::GetDefaultPropertyName( index );\n }\n\n index -= DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n if ( ( index >= 0 ) && ( index < DEFAULT_PROPERTY_COUNT ) )\n {\n return DEFAULT_PROPERTY_DETAILS[index].name;\n }\n\n return NULL;\n}\n\nProperty::Index Layer::GetDefaultPropertyIndex(const std::string& name) const\n{\n Property::Index index = Property::INVALID_INDEX;\n\n \/\/ Look for name in current class' default properties\n for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )\n {\n const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[i];\n if( 0 == name.compare( property->name ) ) \/\/ dont want to convert rhs to string\n {\n index = i + DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX;\n break;\n }\n }\n if( Property::INVALID_INDEX == index )\n {\n \/\/ If not found, check in base class\n index = Actor::GetDefaultPropertyIndex( name );\n }\n\n return index;\n}\n\nvoid Layer::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )\n{\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n Actor::SetDefaultProperty( index, propertyValue );\n }\n else\n {\n switch( index )\n {\n case Dali::Layer::Property::CLIPPING_ENABLE:\n {\n SetClipping( propertyValue.Get() );\n break;\n }\n case Dali::Layer::Property::CLIPPING_BOX:\n {\n Rect clippingBox( propertyValue.Get >() );\n SetClippingBox( clippingBox.x, clippingBox.y, clippingBox.width, clippingBox.height );\n break;\n }\n case Dali::Layer::Property::BEHAVIOR:\n {\n Behavior behavior(Dali::Layer::LAYER_2D);\n if( Scripting::GetEnumeration< Behavior >( propertyValue.Get< std::string >().c_str(), BehaviorTable, BehaviorTableCount, behavior ) )\n {\n SetBehavior( behavior );\n }\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Unknown property (%d)\\n\", index );\n break;\n }\n } \/\/ switch(index)\n\n } \/\/ else\n}\n\nProperty::Value Layer::GetDefaultProperty( Property::Index index ) const\n{\n Property::Value ret;\n if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )\n {\n ret = Actor::GetDefaultProperty( index );\n }\n else\n {\n switch( index )\n {\n case Dali::Layer::Property::CLIPPING_ENABLE:\n {\n ret = mIsClipping;\n break;\n }\n case Dali::Layer::Property::CLIPPING_BOX:\n {\n ret = mClippingBox;\n break;\n }\n case Dali::Layer::Property::BEHAVIOR:\n {\n ret = Scripting::GetLinearEnumerationName< Behavior >( GetBehavior(), BehaviorTable, BehaviorTableCount );\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Unknown property (%d)\\n\", index );\n break;\n }\n } \/\/ switch(index)\n }\n\n return ret;\n}\n\nbool Layer::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& \/*attributes*\/ )\n{\n bool done = false;\n Layer* layer = dynamic_cast( object );\n\n if( layer )\n {\n if( 0 == actionName.compare( ACTION_RAISE ) )\n {\n layer->Raise();\n done = true;\n }\n else if( 0 == actionName.compare( ACTION_LOWER ) )\n {\n layer->Lower();\n done = true;\n }\n else if( 0 == actionName.compare( ACTION_RAISE_TO_TOP ) )\n {\n layer->RaiseToTop();\n done = true;\n }\n else if( 0 == actionName.compare( ACTION_LOWER_TO_BOTTOM ) )\n {\n layer->LowerToBottom();\n done = true;\n }\n }\n\n return done;\n}\n\n} \/\/ namespace Internal\n\n} \/\/ namespace Dali\n<|endoftext|>"} {"text":"\/* OpenSceneGraph example, osgtexture3D.\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\n\/\/\n\/\/ A simple demo demonstrating different texturing modes,\n\/\/ including using of texture extensions.\n\/\/\n\n\ntypedef std::vector< osg::ref_ptr > ImageList;\n\nosg::StateSet* createState()\n{\n \/\/ read 4 2d images\n osg::ref_ptr image_0 = osgDB::readImageFile(\"Images\/lz.rgb\");\n osg::ref_ptr image_1 = osgDB::readImageFile(\"Images\/reflect.rgb\");\n osg::ref_ptr image_2 = osgDB::readImageFile(\"Images\/tank.rgb\");\n osg::ref_ptr image_3 = osgDB::readImageFile(\"Images\/skymap.jpg\");\n\n if (!image_0 || !image_1 || !image_2 || !image_3)\n {\n std::cout << \"Warning: could not open files.\"<getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())\n {\n std::cout << \"Warning: image pixel formats not compatible.\"<scaleImage(textureSize,textureSize,1);\n image_1->scaleImage(textureSize,textureSize,1);\n image_2->scaleImage(textureSize,textureSize,1);\n image_3->scaleImage(textureSize,textureSize,1);\n\n\n \/\/ then allocated a 3d image to use for texturing.\n osg::Image* image_3d = new osg::Image;\n image_3d->allocateImage(textureSize,textureSize,4,\n image_0->getPixelFormat(),image_0->getDataType());\n\n \/\/ copy the 2d images into the 3d image.\n image_3d->copySubImage(0,0,0,image_0.get());\n image_3d->copySubImage(0,0,1,image_1.get());\n image_3d->copySubImage(0,0,2,image_2.get());\n image_3d->copySubImage(0,0,3,image_3.get());\n\n image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());\n\n \/\/ set up the 3d texture itself,\n \/\/ note, well set the filtering up so that mip mapping is disabled,\n \/\/ gluBuild3DMipsmaps doesn't do a very good job of handled the\n \/\/ inbalanced dimensions of the 256x256x4 texture.\n osg::Texture3D* texture3D = new osg::Texture3D;\n texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);\n texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);\n texture3D->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT);\n texture3D->setImage(image_3d);\n\n\n \/\/ create a texgen to generate a R texture coordinate, the geometry\n \/\/ itself will supply the S & T texture coordinates.\n \/\/ in the animateStateSet callback well alter this R value to\n \/\/ move the texture through the 3d texture, 3d texture filtering\n \/\/ will do the blending for us.\n osg::TexGen* texgen = new osg::TexGen;\n texgen->setMode(osg::TexGen::OBJECT_LINEAR);\n texgen->setPlane(osg::TexGen::R, osg::Plane(0.0f,0.0f,0.0f,0.2f));\n\n \/\/ create the StateSet to store the texture data\n osg::StateSet* stateset = new osg::StateSet;\n stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);\n stateset->setTextureAttribute(0,texgen);\n stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);\n\n return stateset;\n}\n\n\nclass UpdateStateCallback : public osg::NodeCallback\n{\n public:\n UpdateStateCallback() {}\n\n void animateState(osg::StateSet* stateset)\n {\n \/\/ here we simply get any existing texgen, and then increment its\n \/\/ plane, pushing the R coordinate through the texture.\n osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);\n osg::TexGen* texgen = dynamic_cast(attribute);\n if (texgen)\n {\n texgen->getPlane(osg::TexGen::R)[3] += 0.001f;\n }\n\n }\n\n virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)\n {\n\n osg::StateSet* stateset = node->getStateSet();\n if (stateset)\n {\n \/\/ we have an exisitng stateset, so lets animate it.\n animateState(stateset);\n }\n\n \/\/ note, callback is repsonsible for scenegraph traversal so\n \/\/ should always include call the traverse(node,nv) to ensure\n \/\/ that the rest of cullbacks and the scene graph are traversed.\n traverse(node,nv);\n }\n};\n\n\/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan *\/\nosg::Drawable* createSquare(float textureCoordMax=1.0f)\n{\n \/\/ set up the Geometry.\n osg::Geometry* geom = new osg::Geometry;\n\n osg::Vec3Array* coords = new osg::Vec3Array(4);\n (*coords)[0].set(-1.0f,0.0f,1.0f);\n (*coords)[1].set(-1.0f,0.0f,-1.0f);\n (*coords)[2].set(1.0f,0.0f,-1.0f);\n (*coords)[3].set(1.0f,0.0f,1.0f);\n geom->setVertexArray(coords);\n\n osg::Vec3Array* norms = new osg::Vec3Array(1);\n (*norms)[0].set(0.0f,-1.0f,0.0f);\n geom->setNormalArray(norms, osg::Array::BIND_OVERALL);\n\n osg::Vec2Array* tcoords = new osg::Vec2Array(4);\n (*tcoords)[0].set(0.0f,textureCoordMax);\n (*tcoords)[1].set(0.0f,0.0f);\n (*tcoords)[2].set(textureCoordMax,0.0f);\n (*tcoords)[3].set(textureCoordMax,textureCoordMax);\n geom->setTexCoordArray(0,tcoords);\n\n geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));\n\n return geom;\n}\n\nosg::Node* createModel()\n{\n\n \/\/ create the geometry of the model, just a simple 2d quad right now.\n osg::Geode* geode = new osg::Geode;\n geode->addDrawable(createSquare());\n\n \/\/ normally we'd create the stateset's to contain all the textures\n \/\/ etc here, but, the above technique uses osg::Image::scaleImage and\n \/\/ osg::Image::copySubImage() which are implemented with OpenGL utility\n \/\/ library, which unfortunately can't be used until we have a valid\n \/\/ OpenGL context, and at this point in initilialization we don't have\n \/\/ a valid OpenGL context, so we have to delay creation of state until\n \/\/ there is a valid OpenGL context. I'll manage this by using an\n \/\/ app callback which will create the state during the first traversal.\n \/\/ A bit hacky, and my plan is to reimplement the osg::scaleImage and\n \/\/ osg::Image::copySubImage() without using GLU which will get round\n \/\/ this current limitation.\n geode->setUpdateCallback(new UpdateStateCallback());\n geode->setStateSet(createState());\n\n return geode;\n\n}\n\n\nint main(int , char **)\n{\n \/\/ construct the viewer.\n osgViewer::Viewer viewer;\n\n \/\/ create a model from the images and pass it to the viewer.\n viewer.setSceneData(createModel());\n\n return viewer.run();\n}\nUpdated the comments to be more relevant\/* OpenSceneGraph example, osgtexture3D.\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\n\/\/\n\/\/ A simple demo demonstrating use osg::Texture3D to create a blended animation between four seperate images packed together into a 3d texture\n\/\/\n\ntypedef std::vector< osg::ref_ptr > ImageList;\n\nosg::StateSet* createState()\n{\n \/\/ read 4 2d images\n osg::ref_ptr image_0 = osgDB::readImageFile(\"Images\/lz.rgb\");\n osg::ref_ptr image_1 = osgDB::readImageFile(\"Images\/reflect.rgb\");\n osg::ref_ptr image_2 = osgDB::readImageFile(\"Images\/tank.rgb\");\n osg::ref_ptr image_3 = osgDB::readImageFile(\"Images\/skymap.jpg\");\n\n if (!image_0 || !image_1 || !image_2 || !image_3)\n {\n std::cout << \"Warning: could not open files.\"<getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())\n {\n std::cout << \"Warning: image pixel formats not compatible.\"<scaleImage(textureSize,textureSize,1);\n image_1->scaleImage(textureSize,textureSize,1);\n image_2->scaleImage(textureSize,textureSize,1);\n image_3->scaleImage(textureSize,textureSize,1);\n\n\n \/\/ then allocated a 3d image to use for texturing.\n osg::Image* image_3d = new osg::Image;\n image_3d->allocateImage(textureSize,textureSize,4,\n image_0->getPixelFormat(),image_0->getDataType());\n\n \/\/ copy the 2d images into the 3d image.\n image_3d->copySubImage(0,0,0,image_0.get());\n image_3d->copySubImage(0,0,1,image_1.get());\n image_3d->copySubImage(0,0,2,image_2.get());\n image_3d->copySubImage(0,0,3,image_3.get());\n\n image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());\n\n \/\/ set up the 3d texture itself,\n \/\/ note, well set the filtering up so that mip mapping is disabled,\n \/\/ gluBuild3DMipsmaps doesn't do a very good job of handled the\n \/\/ inbalanced dimensions of the 256x256x4 texture.\n osg::Texture3D* texture3D = new osg::Texture3D;\n texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);\n texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);\n texture3D->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT);\n texture3D->setImage(image_3d);\n\n\n \/\/ create a texgen to generate a R texture coordinate, the geometry\n \/\/ itself will supply the S & T texture coordinates.\n \/\/ in the animateStateSet callback well alter this R value to\n \/\/ move the texture through the 3d texture, 3d texture filtering\n \/\/ will do the blending for us.\n osg::TexGen* texgen = new osg::TexGen;\n texgen->setMode(osg::TexGen::OBJECT_LINEAR);\n texgen->setPlane(osg::TexGen::R, osg::Plane(0.0f,0.0f,0.0f,0.2f));\n\n \/\/ create the StateSet to store the texture data\n osg::StateSet* stateset = new osg::StateSet;\n stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);\n stateset->setTextureAttribute(0,texgen);\n stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);\n\n return stateset;\n}\n\n\nclass UpdateStateCallback : public osg::NodeCallback\n{\n public:\n UpdateStateCallback() {}\n\n void animateState(osg::StateSet* stateset)\n {\n \/\/ here we simply get any existing texgen, and then increment its\n \/\/ plane, pushing the R coordinate through the texture.\n osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);\n osg::TexGen* texgen = dynamic_cast(attribute);\n if (texgen)\n {\n texgen->getPlane(osg::TexGen::R)[3] += 0.001f;\n }\n\n }\n\n virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)\n {\n\n osg::StateSet* stateset = node->getStateSet();\n if (stateset)\n {\n \/\/ we have an exisitng stateset, so lets animate it.\n animateState(stateset);\n }\n\n \/\/ note, callback is repsonsible for scenegraph traversal so\n \/\/ should always include call the traverse(node,nv) to ensure\n \/\/ that the rest of cullbacks and the scene graph are traversed.\n traverse(node,nv);\n }\n};\n\n\/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan *\/\nosg::Drawable* createSquare(float textureCoordMax=1.0f)\n{\n \/\/ set up the Geometry.\n osg::Geometry* geom = new osg::Geometry;\n\n osg::Vec3Array* coords = new osg::Vec3Array(4);\n (*coords)[0].set(-1.0f,0.0f,1.0f);\n (*coords)[1].set(-1.0f,0.0f,-1.0f);\n (*coords)[2].set(1.0f,0.0f,-1.0f);\n (*coords)[3].set(1.0f,0.0f,1.0f);\n geom->setVertexArray(coords);\n\n osg::Vec3Array* norms = new osg::Vec3Array(1);\n (*norms)[0].set(0.0f,-1.0f,0.0f);\n geom->setNormalArray(norms, osg::Array::BIND_OVERALL);\n\n osg::Vec2Array* tcoords = new osg::Vec2Array(4);\n (*tcoords)[0].set(0.0f,textureCoordMax);\n (*tcoords)[1].set(0.0f,0.0f);\n (*tcoords)[2].set(textureCoordMax,0.0f);\n (*tcoords)[3].set(textureCoordMax,textureCoordMax);\n geom->setTexCoordArray(0,tcoords);\n\n geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));\n\n return geom;\n}\n\nosg::Node* createModel()\n{\n \/\/ create the geometry of the model, just a simple 2d quad right now.\n osg::Geode* geode = new osg::Geode;\n\n geode->addDrawable(createSquare());\n\n geode->setUpdateCallback(new UpdateStateCallback());\n\n geode->setStateSet(createState());\n\n return geode;\n}\n\n\nint main(int , char **)\n{\n \/\/ construct the viewer.\n osgViewer::Viewer viewer;\n\n \/\/ create a model from the images and pass it to the viewer.\n viewer.setSceneData(createModel());\n\n return viewer.run();\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2016 Neil Moore, Jason Stavrinaky, Micheal McGee, Robert Medina\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of this \n * software and associated documentation files (the \"Software\"), to deal in the Software \n * without restriction, including without limitation the rights to use, copy, modify, \n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to \n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all copies \n * or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR \n * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE \n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"sql\/statements\/builder.h\"\n\n#include \"data\/data_store.h\"\n\n#include \n\n\/\/ Helper functions\nstatic DataType getSQLType(std::string* type);\n\nstatic Expression* createExpression(Token op, Token left, Token right);\n\nvoid builderStartCreateTable(StatementBuilder* builder, Token table_name)\n{\n CreateTableCommand* command = new CreateTableCommand;\n command->table_name = table_name->text;\n \n builder->started = true;\n builder->statement = command;\n builder->valid = true;\n}\n\nvoid builderStartDropTable(StatementBuilder* builder, Token table_name)\n{\n DropTableCommand* command = new DropTableCommand;\n command->table_name = table_name->text;\n \n builder->started = true;\n builder->statement = command;\n builder->valid = true;\n}\n\nvoid builderAddColumnConstraint(StatementBuilder* builder, SQLConstraintType type,\n Token value) \n{\n assert(builder != nullptr);\n\n SQLConstraint constraint;\n constraint.type = type;\n \n if(value && value->is_value)\n {\n constraint.value = value->value;\n }\n\n builder->temp_constraints.push_back(constraint);\n}\n\nvoid builderStartSelectQuery(StatementBuilder* builder)\n{\n SelectQuery* query = new (std::nothrow) SelectQuery();\n if(query == nullptr)\n {\n \/\/ TODO: Error handling\n }\n \n builder->started = true;\n builder->statement = query;\n builder->valid = true;\n}\n\nvoid builderStartInsertCommand(StatementBuilder* builder)\n{\n InsertCommand* cmd = new (std::nothrow) InsertCommand();\n \/\/ TODO: Error handling\n\n builder->started = true;\n builder->statement = cmd;\n builder->valid = true;\n}\n\nvoid builderStartUpdateCommand(StatementBuilder* builder)\n{\n UpdateCommand* cmd = new (std::nothrow) UpdateCommand();\n \/\/ TODO: Error handling\n\n builder->started = true;\n builder->statement = cmd;\n builder->valid = true;\n}\n\nvoid builderStartDeleteCommand(StatementBuilder* builder)\n{\n DeleteCommand* cmd = new (std::nothrow) DeleteCommand();\n \/\/ TODO: Error handling\n\n builder->started = true;\n builder->statement = cmd;\n builder->valid = true;\n}\n\n\/\/ SELECT helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid builderAddSelectAllColumns(StatementBuilder* builder, Token table)\n{\n \/\/ Don't want to override a currently active statement\n if(!builder->started)\n {\n builderStartSelectQuery(builder);\n }\n\n if(builder->statement == nullptr)\n {\n \/\/ TODO: Error handling\n }\n\n \/\/ TODO: Add all columns in the given table to this query\n switch(builder->statement->type)\n {\n case SQLStatement::SELECT:\n break;\n default:\n \/\/ TODO: Error handling?\n break;\n }\n}\n\nvoid builderAddQualifiedSelectColumn(StatementBuilder* builder,\n Token table, Token source_column,\n Token output_column)\n{\n \/\/ This means the output column should be named the same as the \n \/\/ source column\n if(output_column == nullptr)\n {\n output_column = source_column;\n }\n \n if(!builder->started)\n {\n \/\/ Start the SELECT statement then\n builderStartSelectQuery(builder);\n }\n else\n {\n \/\/ TODO: Error handling\n }\n\n ColumnReference source;\n source.table = table->text;\n\n auto res = builder->data_store->getColumnIndex(source.table, source_column->text);\n if(res.status == ResultStatus::SUCCESS)\n {\n source.column_idx = res.result;\n }\n else\n {\n \/\/ TODO: Error handling\n printf(\"%s: Error encountered while finding column index! Error code = %u\\n\",\n __FUNCTION__, (uint16_t)res.status);\n }\n \n SelectQuery* query = reinterpret_cast(builder->statement);\n \n \/\/ Push the previously calculated information into the query object\n query->source_columns.push_back(source);\n\n query->output_columns.push_back(output_column->text);\n}\n\nvoid builderFinishSelectQuery(StatementBuilder* builder)\n{\n if(!builder->started || builder->statement->type != SQLStatement::SELECT)\n {\n return;\n }\n\n SelectQuery* query = reinterpret_cast(builder->statement);\n\n \/\/ Push all unique tables into the tables vector in the query.\n for(auto col_ref : query->source_columns)\n {\n if(std::find(query->tables.begin(), query->tables.end(), col_ref.table) == query->tables.end())\n {\n query->tables.push_back(col_ref.table);\n }\n }\n}\n\n\/\/ Insert command helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid builderAddDataItem(StatementBuilder* builder, Token data)\n{\n if(data->is_value && builder->started)\n {\n InsertCommand* cmd = reinterpret_cast(builder->statement);\n\n cmd->data.push_back(data->value);\n }\n}\n\nvoid builderFinishInsertCommand(StatementBuilder* builder)\n{\n (void)builder;\n}\n\n\/\/ Update command helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid builderAddUpdateExpr(StatementBuilder* builder, Token operation,\n Token left, Token right)\n{\n if(!builder->started)\n {\n return;\n }\n\n if(!operation->is_operation || \n operation->operation != static_cast(ExpressionOperation::EQUALS))\n {\n printf(\"Invalid expression for UPDATE statements!\\n\");\n return;\n }\n\n UpdateCommand* update = reinterpret_cast(builder->statement);\n ColumnUpdate update_info;\n\n SchemaResult schema_res = builder->data_store->getTableSchema(update->table);\n if(schema_res.status != ResultStatus::SUCCESS)\n {\n \/\/ TODO: Table doesn't exist\n printf(\"%s: Unable to retrieve table schema! Handle this TODO!\\n\", __FUNCTION__);\n }\n\n update->table_schema = schema_res.result;\n\n auto column_idx_result = builder->data_store->getColumnIndex(update->table, left->text);\n if(column_idx_result.status == ResultStatus::SUCCESS)\n {\n update_info.column_idx = column_idx_result.result;\n }\n else\n {\n \/\/ Column doesn't exist\n \/\/ TODO: Error handling\n printf(\"%s: Unable to find column!\\n\", __FUNCTION__);\n }\n\n if(right->is_value)\n {\n update_info.new_data = right->value;\n }\n else\n {\n \/\/ Not a value\n \/\/ TODO: Error handling\n printf(\"%s: Invalid type! Handle TODO!\\n\", __FUNCTION__);\n }\n\n update->columns.push_back(update_info);\n}\n\nvoid builderFinishUpdateCommand(StatementBuilder* builder)\n{\n if(builder->started && builder->valid)\n {\n UpdateCommand* update_cmd = reinterpret_cast(builder->statement);\n\n if(update_cmd->table_schema.columns.size() == 0)\n {\n \/\/ Attempt to get the table schema one more time\n SchemaResult schema_check = builder->data_store->getTableSchema(update_cmd->table);\n if(schema_check.status != ResultStatus::SUCCESS)\n {\n update_cmd->runnable = false;\n \/\/ No point going any further\n return;\n }\n else\n {\n update_cmd->table_schema = schema_check.result;\n }\n }\n\n TervelData null_data = { .value = 0 };\n null_data.data.null = 1;\n\n update_cmd->full_record.resize(update_cmd->table_schema.columns.size(), null_data);\n for(auto updated_col : update_cmd->columns)\n {\n update_cmd->full_record[updated_col.column_idx] = updated_col.new_data;\n }\n\n update_cmd->runnable = true;\n }\n}\n\n\/\/ Generic-ish helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid builderAddColumn(StatementBuilder* builder, Token column_name,\n Token column_type, Token column_constraints)\n{\n (void)column_constraints;\n\n \/\/printf(\"Entered builderAddColumn\\n\");\n\n if(!builder->started)\n {\n printf(\"Builder not started, but attempting to add column?!\\n\");\n }\n\n switch(builder->statement->type)\n {\n case SQLStatement::CREATE_TABLE:\n {\n CreateTableCommand* cmd = (CreateTableCommand*)builder->statement;\n SQLColumn column;\n column.name = column_name->text;\n column.type = getSQLType(&column_type->text);\n\n std::swap(column.constraint, builder->temp_constraints);\n builder->temp_constraints.clear();\n\n cmd->columns.push_back(column);\n }\n break;\n case SQLStatement::SELECT:\n case SQLStatement::INVALID:\n default:\n {\n printf(\"%s: SQL statement type isn't supported in this function!\\n\", __FUNCTION__);\n }\n break;\n }\n}\n\nvoid builderAddTableName(StatementBuilder* builder, Token table_name)\n{\n if(!builder->started)\n {\n printf(\"%s: Builder hasn't been started!\\n\", __FUNCTION__);\n return;\n }\n\n switch(builder->statement->type)\n {\n case SQLStatement::INSERT_INTO:\n {\n InsertCommand* insert = reinterpret_cast(builder->statement);\n insert->table = table_name->text;\n }\n break;\n case SQLStatement::UPDATE:\n {\n UpdateCommand* update = reinterpret_cast(builder->statement);\n update->table = table_name->text;\n\n \/\/ Grab the table schema\n SchemaResult schema_check = builder->data_store->getTableSchema(update->table);\n if(schema_check.status == ResultStatus::SUCCESS)\n {\n update->table_schema = schema_check.result;\n }\n else\n {\n \/\/ TODO: Handle error here?\n }\n }\n break;\n case SQLStatement::DELETE:\n {\n DeleteCommand* del = reinterpret_cast(builder->statement);\n del->table = table_name->text;\n }\n break;\n default:\n printf(\"%s: SQL statement being built isn't supported!\\n\", __FUNCTION__);\n break;\n }\n}\n\nvoid builderStartNestedExpr(StatementBuilder* builder, Token operation)\n{\n if(builder == nullptr)\n {\n printf(\"This shouldn't happen\\n\");\n \/\/ TODO: Assert?\n\t return; \n }\n\n printf(\"Starting nested expression: [%s]\\n\", operation->text.c_str());\n\n if(isExprFlagContained(builder->expr->flags, ExpressionFlags::NESTED))\n {\n builder->expr->op = static_cast(operation->operation);\n printf(\"Nested operation = %u\\n\", (uint32_t)builder->expr->op);\n builder->expr->flags = ExpressionFlags::NESTED;\n }\n\n printExpressionTree(builder->expr);\n}\n\nvoid builderAddValueExpr(StatementBuilder* builder,\n\tToken operation, Token left_term, Token right_term)\n{\n \/\/ printf(\"Adding value expression: %s %s %s\\n\",\n \/\/ left_term->text.c_str(),\n \/\/ operation->text.c_str(),\n \/\/ right_term->text.c_str());\n\n if(builder->expr == nullptr)\n {\n builder->expr = createExpression(operation, left_term, right_term);\n if(builder->expr == nullptr)\n {\n printf(\"Fatal error, unable to generate value expression\\n\");\n return;\n }\n }\n else\n {\n \/\/ printf(\"Non-null builder->expr\\n\");\n \/\/ Create nested expression and set the previous to the left child\n Expression* right = createExpression(operation, left_term, right_term);\n if(right == nullptr)\n {\n printf(\"Fatal error, unable to generate value expression\\n\");\n return;\n }\n\n Expression* parent = new (std::nothrow) Expression();\n if(parent == nullptr)\n {\n printf(\"Fatal error, unable to generate value expression\\n\");\n return;\n }\n\n parent->flags = ExpressionFlags::NESTED | ExpressionFlags::EMPTY;\n parent->left = builder->expr;\n parent->right = right;\n\n builder->expr = parent;\n }\n\n \/\/ printExpressionTree(builder->expr); \n}\n\nExpression* createExpression(Token op, Token left, Token right)\n{\n Expression* parent = new (std::nothrow) Expression(op);\n if(parent)\n {\n Expression* left_expr = new (std::nothrow) Expression(left);\n if(left_expr)\n {\n parent->left = left_expr;\n }\n else\n {\n delete parent;\n return nullptr;\n }\n\n Expression* right_expr = new (std::nothrow) Expression(right);\n if(right_expr)\n {\n parent->right = right_expr;\n }\n else\n {\n delete parent;\n return nullptr;\n }\n }\n else\n {\n return nullptr;\n }\n\n return parent;\n}\n\nvoid builderClean(StatementBuilder* builder)\n{\n \/\/ DEBUG\n printf(\"builderClean called\\n\");\n\n if(builder->started)\n {\n delete builder->statement;\n }\n\n builder->statement = nullptr;\n\n builder->started = false;\n}\n\nDataType getSQLType(std::string* type)\n{\n if(type == nullptr)\n {\n printf(\"Null pointer in getSQLType, check your parser.\\n\");\n return DataType::NONE;\n }\n \n if((*type) == \"INTEGER\")\n {\n return DataType::INTEGER;\n }\n \n if((*type) == \"SMALLINT\")\n {\n return DataType::SMALL_INT;\n }\n \n if((*type) == \"BIGINT\")\n {\n return DataType::BIG_INT;\n }\n \n if((*type) == \"BOOLEAN\")\n {\n return DataType::BOOLEAN;\n }\n \n if((*type) == \"DATE\")\n {\n return DataType::DATE;\n }\n \n if((*type) == \"TIME\")\n {\n return DataType::TIME;\n }\n \n return DataType::NONE;\n}\nAdded ability to perform full table SELECT queries\/* Copyright (c) 2016 Neil Moore, Jason Stavrinaky, Micheal McGee, Robert Medina\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of this \n * software and associated documentation files (the \"Software\"), to deal in the Software \n * without restriction, including without limitation the rights to use, copy, modify, \n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to \n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all copies \n * or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR \n * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE \n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"sql\/statements\/builder.h\"\n\n#include \"data\/data_store.h\"\n\n#include \n\n\/\/ Helper functions\nstatic DataType getSQLType(std::string* type);\n\nstatic Expression* createExpression(Token op, Token left, Token right);\n\nvoid builderStartCreateTable(StatementBuilder* builder, Token table_name)\n{\n CreateTableCommand* command = new CreateTableCommand;\n command->table_name = table_name->text;\n \n builder->started = true;\n builder->statement = command;\n builder->valid = true;\n}\n\nvoid builderStartDropTable(StatementBuilder* builder, Token table_name)\n{\n DropTableCommand* command = new DropTableCommand;\n command->table_name = table_name->text;\n \n builder->started = true;\n builder->statement = command;\n builder->valid = true;\n}\n\nvoid builderAddColumnConstraint(StatementBuilder* builder, SQLConstraintType type,\n Token value) \n{\n assert(builder != nullptr);\n\n SQLConstraint constraint;\n constraint.type = type;\n \n if(value && value->is_value)\n {\n constraint.value = value->value;\n }\n\n builder->temp_constraints.push_back(constraint);\n}\n\nvoid builderStartSelectQuery(StatementBuilder* builder)\n{\n SelectQuery* query = new (std::nothrow) SelectQuery();\n if(query == nullptr)\n {\n \/\/ TODO: Error handling\n }\n \n builder->started = true;\n builder->statement = query;\n builder->valid = true;\n}\n\nvoid builderStartInsertCommand(StatementBuilder* builder)\n{\n InsertCommand* cmd = new (std::nothrow) InsertCommand();\n \/\/ TODO: Error handling\n\n builder->started = true;\n builder->statement = cmd;\n builder->valid = true;\n}\n\nvoid builderStartUpdateCommand(StatementBuilder* builder)\n{\n UpdateCommand* cmd = new (std::nothrow) UpdateCommand();\n \/\/ TODO: Error handling\n\n builder->started = true;\n builder->statement = cmd;\n builder->valid = true;\n}\n\nvoid builderStartDeleteCommand(StatementBuilder* builder)\n{\n DeleteCommand* cmd = new (std::nothrow) DeleteCommand();\n \/\/ TODO: Error handling\n\n builder->started = true;\n builder->statement = cmd;\n builder->valid = true;\n}\n\n\/\/ SELECT helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid builderAddSelectAllColumns(StatementBuilder* builder, Token table)\n{\n \/\/ Don't want to override a currently active statement\n if(!builder->started)\n {\n builderStartSelectQuery(builder);\n }\n\n if(builder->statement == nullptr)\n {\n \/\/ TODO: Error handling\n }\n\n switch(builder->statement->type)\n {\n case SQLStatement::SELECT:\n {\n SelectQuery* query = reinterpret_cast(builder->statement);\n SchemaResult schema = builder->data_store->getTableSchema(table->text);\n if(schema.status != ResultStatus::SUCCESS)\n {\n printf(\"Error retrieving schema for table \\\"%s\\\"\\n\", table->text.c_str());\n }\n\n size_t num_columns = schema.result.columns.size();\n for(size_t i = 0; i < num_columns; i++)\n {\n ColumnReference col;\n col.column_idx = i;\n col.table = table->text;\n query->source_columns.push_back(col);\n query->output_columns.push_back(schema.result.columns[i].name);\n }\n }\n break;\n default:\n \/\/ TODO: Error handling?\n break;\n }\n}\n\nvoid builderAddQualifiedSelectColumn(StatementBuilder* builder,\n Token table, Token source_column,\n Token output_column)\n{\n \/\/ This means the output column should be named the same as the \n \/\/ source column\n if(output_column == nullptr)\n {\n output_column = source_column;\n }\n \n if(!builder->started)\n {\n \/\/ Start the SELECT statement then\n builderStartSelectQuery(builder);\n }\n else\n {\n \/\/ TODO: Error handling\n }\n\n ColumnReference source;\n source.table = table->text;\n\n auto res = builder->data_store->getColumnIndex(source.table, source_column->text);\n if(res.status == ResultStatus::SUCCESS)\n {\n source.column_idx = res.result;\n }\n else\n {\n \/\/ TODO: Error handling\n printf(\"%s: Error encountered while finding column index! Error code = %u\\n\",\n __FUNCTION__, (uint16_t)res.status);\n }\n \n SelectQuery* query = reinterpret_cast(builder->statement);\n \n \/\/ Push the previously calculated information into the query object\n query->source_columns.push_back(source);\n\n query->output_columns.push_back(output_column->text);\n}\n\nvoid builderFinishSelectQuery(StatementBuilder* builder)\n{\n if(!builder->started || builder->statement->type != SQLStatement::SELECT)\n {\n return;\n }\n\n SelectQuery* query = reinterpret_cast(builder->statement);\n\n \/\/ Push all unique tables into the tables vector in the query.\n for(auto col_ref : query->source_columns)\n {\n if(std::find(query->tables.begin(), query->tables.end(), col_ref.table) == query->tables.end())\n {\n query->tables.push_back(col_ref.table);\n }\n }\n}\n\n\/\/ Insert command helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid builderAddDataItem(StatementBuilder* builder, Token data)\n{\n if(data->is_value && builder->started)\n {\n InsertCommand* cmd = reinterpret_cast(builder->statement);\n\n cmd->data.push_back(data->value);\n }\n}\n\nvoid builderFinishInsertCommand(StatementBuilder* builder)\n{\n (void)builder;\n}\n\n\/\/ Update command helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid builderAddUpdateExpr(StatementBuilder* builder, Token operation,\n Token left, Token right)\n{\n if(!builder->started)\n {\n return;\n }\n\n if(!operation->is_operation || \n operation->operation != static_cast(ExpressionOperation::EQUALS))\n {\n printf(\"Invalid expression for UPDATE statements!\\n\");\n return;\n }\n\n UpdateCommand* update = reinterpret_cast(builder->statement);\n ColumnUpdate update_info;\n\n SchemaResult schema_res = builder->data_store->getTableSchema(update->table);\n if(schema_res.status != ResultStatus::SUCCESS)\n {\n \/\/ TODO: Table doesn't exist\n printf(\"%s: Unable to retrieve table schema! Handle this TODO!\\n\", __FUNCTION__);\n }\n\n update->table_schema = schema_res.result;\n\n auto column_idx_result = builder->data_store->getColumnIndex(update->table, left->text);\n if(column_idx_result.status == ResultStatus::SUCCESS)\n {\n update_info.column_idx = column_idx_result.result;\n }\n else\n {\n \/\/ Column doesn't exist\n \/\/ TODO: Error handling\n printf(\"%s: Unable to find column!\\n\", __FUNCTION__);\n }\n\n if(right->is_value)\n {\n update_info.new_data = right->value;\n }\n else\n {\n \/\/ Not a value\n \/\/ TODO: Error handling\n printf(\"%s: Invalid type! Handle TODO!\\n\", __FUNCTION__);\n }\n\n update->columns.push_back(update_info);\n}\n\nvoid builderFinishUpdateCommand(StatementBuilder* builder)\n{\n if(builder->started && builder->valid)\n {\n UpdateCommand* update_cmd = reinterpret_cast(builder->statement);\n\n if(update_cmd->table_schema.columns.size() == 0)\n {\n \/\/ Attempt to get the table schema one more time\n SchemaResult schema_check = builder->data_store->getTableSchema(update_cmd->table);\n if(schema_check.status != ResultStatus::SUCCESS)\n {\n update_cmd->runnable = false;\n \/\/ No point going any further\n return;\n }\n else\n {\n update_cmd->table_schema = schema_check.result;\n }\n }\n\n TervelData null_data = { .value = 0 };\n null_data.data.null = 1;\n\n update_cmd->full_record.resize(update_cmd->table_schema.columns.size(), null_data);\n for(auto updated_col : update_cmd->columns)\n {\n update_cmd->full_record[updated_col.column_idx] = updated_col.new_data;\n }\n\n update_cmd->runnable = true;\n }\n}\n\n\/\/ Generic-ish helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid builderAddColumn(StatementBuilder* builder, Token column_name,\n Token column_type, Token column_constraints)\n{\n (void)column_constraints;\n\n \/\/printf(\"Entered builderAddColumn\\n\");\n\n if(!builder->started)\n {\n printf(\"Builder not started, but attempting to add column?!\\n\");\n }\n\n switch(builder->statement->type)\n {\n case SQLStatement::CREATE_TABLE:\n {\n CreateTableCommand* cmd = (CreateTableCommand*)builder->statement;\n SQLColumn column;\n column.name = column_name->text;\n column.type = getSQLType(&column_type->text);\n\n std::swap(column.constraint, builder->temp_constraints);\n builder->temp_constraints.clear();\n\n cmd->columns.push_back(column);\n }\n break;\n case SQLStatement::SELECT:\n case SQLStatement::INVALID:\n default:\n {\n printf(\"%s: SQL statement type isn't supported in this function!\\n\", __FUNCTION__);\n }\n break;\n }\n}\n\nvoid builderAddTableName(StatementBuilder* builder, Token table_name)\n{\n if(!builder->started)\n {\n printf(\"%s: Builder hasn't been started!\\n\", __FUNCTION__);\n return;\n }\n\n switch(builder->statement->type)\n {\n case SQLStatement::INSERT_INTO:\n {\n InsertCommand* insert = reinterpret_cast(builder->statement);\n insert->table = table_name->text;\n }\n break;\n case SQLStatement::UPDATE:\n {\n UpdateCommand* update = reinterpret_cast(builder->statement);\n update->table = table_name->text;\n\n \/\/ Grab the table schema\n SchemaResult schema_check = builder->data_store->getTableSchema(update->table);\n if(schema_check.status == ResultStatus::SUCCESS)\n {\n update->table_schema = schema_check.result;\n }\n else\n {\n \/\/ TODO: Handle error here?\n }\n }\n break;\n case SQLStatement::DELETE:\n {\n DeleteCommand* del = reinterpret_cast(builder->statement);\n del->table = table_name->text;\n }\n break;\n default:\n printf(\"%s: SQL statement being built isn't supported!\\n\", __FUNCTION__);\n break;\n }\n}\n\nvoid builderStartNestedExpr(StatementBuilder* builder, Token operation)\n{\n if(builder == nullptr)\n {\n printf(\"This shouldn't happen\\n\");\n \/\/ TODO: Assert?\n\t return; \n }\n\n printf(\"Starting nested expression: [%s]\\n\", operation->text.c_str());\n\n if(isExprFlagContained(builder->expr->flags, ExpressionFlags::NESTED))\n {\n builder->expr->op = static_cast(operation->operation);\n printf(\"Nested operation = %u\\n\", (uint32_t)builder->expr->op);\n builder->expr->flags = ExpressionFlags::NESTED;\n }\n\n printExpressionTree(builder->expr);\n}\n\nvoid builderAddValueExpr(StatementBuilder* builder,\n\tToken operation, Token left_term, Token right_term)\n{\n \/\/ printf(\"Adding value expression: %s %s %s\\n\",\n \/\/ left_term->text.c_str(),\n \/\/ operation->text.c_str(),\n \/\/ right_term->text.c_str());\n\n if(builder->expr == nullptr)\n {\n builder->expr = createExpression(operation, left_term, right_term);\n if(builder->expr == nullptr)\n {\n printf(\"Fatal error, unable to generate value expression\\n\");\n return;\n }\n }\n else\n {\n \/\/ printf(\"Non-null builder->expr\\n\");\n \/\/ Create nested expression and set the previous to the left child\n Expression* right = createExpression(operation, left_term, right_term);\n if(right == nullptr)\n {\n printf(\"Fatal error, unable to generate value expression\\n\");\n return;\n }\n\n Expression* parent = new (std::nothrow) Expression();\n if(parent == nullptr)\n {\n printf(\"Fatal error, unable to generate value expression\\n\");\n return;\n }\n\n parent->flags = ExpressionFlags::NESTED | ExpressionFlags::EMPTY;\n parent->left = builder->expr;\n parent->right = right;\n\n builder->expr = parent;\n }\n\n \/\/ printExpressionTree(builder->expr); \n}\n\nExpression* createExpression(Token op, Token left, Token right)\n{\n Expression* parent = new (std::nothrow) Expression(op);\n if(parent)\n {\n Expression* left_expr = new (std::nothrow) Expression(left);\n if(left_expr)\n {\n parent->left = left_expr;\n }\n else\n {\n delete parent;\n return nullptr;\n }\n\n Expression* right_expr = new (std::nothrow) Expression(right);\n if(right_expr)\n {\n parent->right = right_expr;\n }\n else\n {\n delete parent;\n return nullptr;\n }\n }\n else\n {\n return nullptr;\n }\n\n return parent;\n}\n\nvoid builderClean(StatementBuilder* builder)\n{\n \/\/ DEBUG\n printf(\"builderClean called\\n\");\n\n if(builder->started)\n {\n delete builder->statement;\n }\n\n builder->statement = nullptr;\n\n builder->started = false;\n}\n\nDataType getSQLType(std::string* type)\n{\n if(type == nullptr)\n {\n printf(\"Null pointer in getSQLType, check your parser.\\n\");\n return DataType::NONE;\n }\n \n if((*type) == \"INTEGER\")\n {\n return DataType::INTEGER;\n }\n \n if((*type) == \"SMALLINT\")\n {\n return DataType::SMALL_INT;\n }\n \n if((*type) == \"BIGINT\")\n {\n return DataType::BIG_INT;\n }\n \n if((*type) == \"BOOLEAN\")\n {\n return DataType::BOOLEAN;\n }\n \n if((*type) == \"DATE\")\n {\n return DataType::DATE;\n }\n \n if((*type) == \"TIME\")\n {\n return DataType::TIME;\n }\n \n return DataType::NONE;\n}\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"workerthread.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/platform\/snprintf.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/job\/ijob.h\"\n#include \"foundation\/utility\/job\/jobmanager.h\"\n#include \"foundation\/utility\/job\/jobqueue.h\"\n#include \"foundation\/utility\/log.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace boost;\nusing namespace std;\n\nnamespace foundation\n{\n\n\/\/\n\/\/ WorkerThread class implementation.\n\/\/\n\nWorkerThread::WorkerThread(\n const size_t index,\n Logger& logger,\n JobQueue& job_queue,\n const int flags)\n : m_index(index)\n , m_logger(logger)\n , m_job_queue(job_queue)\n , m_flags(flags)\n , m_thread_func(*this)\n , m_thread(0)\n{\n}\n\nWorkerThread::~WorkerThread()\n{\n stop();\n}\n\nvoid WorkerThread::start()\n{\n \/\/ Don't do anything if the worker thread is already running.\n if (m_thread)\n return;\n\n assert(m_pause_flag.is_clear());\n assert(!m_abort_switch.is_aborted());\n\n \/\/ Start the thread.\n m_thread = new thread(m_thread_func);\n}\n\nvoid WorkerThread::stop()\n{\n \/\/ Don't do anything if the worker thread is already stopped.\n if (!m_thread)\n return;\n\n \/\/ Resume the thread if it was paused.\n m_pause_flag.clear();\n m_pause_event.notify_all();\n\n \/\/ Ask the thread to stop, and wait until it has.\n m_abort_switch.abort();\n m_job_queue.signal_event();\n m_thread->join();\n m_abort_switch.clear();\n\n \/\/ Delete the thread object.\n delete m_thread;\n m_thread = 0;\n}\n\nvoid WorkerThread::pause()\n{\n \/\/ Don't do anything if the worker thread is not running.\n if (!m_thread)\n return;\n\n mutex::scoped_lock lock(m_pause_mutex);\n m_pause_flag.set();\n}\n\nvoid WorkerThread::resume()\n{\n \/\/ Don't do anything if the worker thread is not running.\n if (!m_thread)\n return;\n\n mutex::scoped_lock lock(m_pause_mutex);\n m_pause_flag.clear();\n m_pause_event.notify_all();\n}\n\nvoid WorkerThread::set_thread_name()\n{\n char thread_name[16];\n portable_snprintf(thread_name, sizeof(thread_name), \"worker_%03u\", m_index);\n set_current_thread_name(thread_name);\n}\n\nvoid WorkerThread::run()\n{\n set_thread_name();\n\n while (!m_abort_switch.is_aborted())\n {\n if (m_pause_flag.is_set())\n {\n \/\/ Wait until the resume event.\n mutex::scoped_lock lock(m_pause_mutex);\n while (m_pause_flag.is_set())\n m_pause_event.wait(lock);\n }\n\n \/\/ Acquire a job.\n const JobQueue::RunningJobInfo running_job_info =\n m_job_queue.wait_for_scheduled_job(m_abort_switch);\n\n \/\/ Handle the case where the job queue is empty.\n if (running_job_info.first.m_job == 0)\n {\n if (m_flags & JobManager::KeepRunningOnEmptyQueue)\n {\n \/\/ Keep the thread running and waiting for new jobs.\n continue;\n }\n else\n {\n \/\/ Terminate the thread.\n break;\n }\n }\n\n \/\/ Execute the job.\n const bool success = execute_job(*running_job_info.first.m_job);\n\n \/\/ Retire the job.\n m_job_queue.retire_running_job(running_job_info);\n\n \/\/ Handle job execution failures.\n if (!success && !(m_flags & JobManager::KeepRunningOnJobFailure))\n {\n m_job_queue.clear_scheduled_jobs();\n break;\n }\n }\n}\n\nbool WorkerThread::execute_job(IJob& job)\n{\n try\n {\n job.execute(m_index);\n }\n catch (const bad_alloc&)\n {\n LOG_ERROR(\n m_logger,\n \"worker thread \" FMT_SIZE_T \": job was terminated (ran out of memory).\",\n m_index);\n\n return false;\n }\n#ifdef NDEBUG\n catch (const std::exception& e)\n {\n LOG_ERROR(\n m_logger,\n \"worker thread \" FMT_SIZE_T \": job was terminated (%s).\",\n m_index,\n e.what());\n\n return false;\n }\n catch (...)\n {\n LOG_ERROR(\n m_logger,\n \"worker thread \" FMT_SIZE_T \": job was terminated (unknown exception).\",\n m_index);\n\n return false;\n }\n#endif\n\n return true;\n}\n\n} \/\/ namespace foundation\nFixed WorkerThread::set_thread_name() for OSX 10.7.5 (GCC 4.2.1).\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"workerthread.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/platform\/snprintf.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/job\/ijob.h\"\n#include \"foundation\/utility\/job\/jobmanager.h\"\n#include \"foundation\/utility\/job\/jobqueue.h\"\n#include \"foundation\/utility\/log.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace boost;\nusing namespace std;\n\nnamespace foundation\n{\n\n\/\/\n\/\/ WorkerThread class implementation.\n\/\/\n\nWorkerThread::WorkerThread(\n const size_t index,\n Logger& logger,\n JobQueue& job_queue,\n const int flags)\n : m_index(index)\n , m_logger(logger)\n , m_job_queue(job_queue)\n , m_flags(flags)\n , m_thread_func(*this)\n , m_thread(0)\n{\n}\n\nWorkerThread::~WorkerThread()\n{\n stop();\n}\n\nvoid WorkerThread::start()\n{\n \/\/ Don't do anything if the worker thread is already running.\n if (m_thread)\n return;\n\n assert(m_pause_flag.is_clear());\n assert(!m_abort_switch.is_aborted());\n\n \/\/ Start the thread.\n m_thread = new thread(m_thread_func);\n}\n\nvoid WorkerThread::stop()\n{\n \/\/ Don't do anything if the worker thread is already stopped.\n if (!m_thread)\n return;\n\n \/\/ Resume the thread if it was paused.\n m_pause_flag.clear();\n m_pause_event.notify_all();\n\n \/\/ Ask the thread to stop, and wait until it has.\n m_abort_switch.abort();\n m_job_queue.signal_event();\n m_thread->join();\n m_abort_switch.clear();\n\n \/\/ Delete the thread object.\n delete m_thread;\n m_thread = 0;\n}\n\nvoid WorkerThread::pause()\n{\n \/\/ Don't do anything if the worker thread is not running.\n if (!m_thread)\n return;\n\n mutex::scoped_lock lock(m_pause_mutex);\n m_pause_flag.set();\n}\n\nvoid WorkerThread::resume()\n{\n \/\/ Don't do anything if the worker thread is not running.\n if (!m_thread)\n return;\n\n mutex::scoped_lock lock(m_pause_mutex);\n m_pause_flag.clear();\n m_pause_event.notify_all();\n}\n\nvoid WorkerThread::set_thread_name()\n{\n char thread_name[16];\n portable_snprintf(thread_name, sizeof(thread_name), \"worker_%03lu\", (long unsigned int)m_index);\n set_current_thread_name(thread_name);\n}\n\nvoid WorkerThread::run()\n{\n set_thread_name();\n\n while (!m_abort_switch.is_aborted())\n {\n if (m_pause_flag.is_set())\n {\n \/\/ Wait until the resume event.\n mutex::scoped_lock lock(m_pause_mutex);\n while (m_pause_flag.is_set())\n m_pause_event.wait(lock);\n }\n\n \/\/ Acquire a job.\n const JobQueue::RunningJobInfo running_job_info =\n m_job_queue.wait_for_scheduled_job(m_abort_switch);\n\n \/\/ Handle the case where the job queue is empty.\n if (running_job_info.first.m_job == 0)\n {\n if (m_flags & JobManager::KeepRunningOnEmptyQueue)\n {\n \/\/ Keep the thread running and waiting for new jobs.\n continue;\n }\n else\n {\n \/\/ Terminate the thread.\n break;\n }\n }\n\n \/\/ Execute the job.\n const bool success = execute_job(*running_job_info.first.m_job);\n\n \/\/ Retire the job.\n m_job_queue.retire_running_job(running_job_info);\n\n \/\/ Handle job execution failures.\n if (!success && !(m_flags & JobManager::KeepRunningOnJobFailure))\n {\n m_job_queue.clear_scheduled_jobs();\n break;\n }\n }\n}\n\nbool WorkerThread::execute_job(IJob& job)\n{\n try\n {\n job.execute(m_index);\n }\n catch (const bad_alloc&)\n {\n LOG_ERROR(\n m_logger,\n \"worker thread \" FMT_SIZE_T \": job was terminated (ran out of memory).\",\n m_index);\n\n return false;\n }\n#ifdef NDEBUG\n catch (const std::exception& e)\n {\n LOG_ERROR(\n m_logger,\n \"worker thread \" FMT_SIZE_T \": job was terminated (%s).\",\n m_index,\n e.what());\n\n return false;\n }\n catch (...)\n {\n LOG_ERROR(\n m_logger,\n \"worker thread \" FMT_SIZE_T \": job was terminated (unknown exception).\",\n m_index);\n\n return false;\n }\n#endif\n\n return true;\n}\n\n} \/\/ namespace foundation\n<|endoftext|>"} {"text":"\/\/ Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace vespalib;\nusing namespace vespalib::eval;\nusing namespace vespalib::eval::test;\n\nusing vespalib::make_string_short::fmt;\n\nstd::vector add_layouts = {\n {x({\"a\"})}, {x({\"b\"})},\n {x({\"a\",\"b\"})}, {x({\"a\",\"c\"})},\n float_cells({x({\"a\",\"b\"})}), {x({\"a\",\"c\"})},\n {x({\"a\",\"b\"})}, float_cells({x({\"a\",\"c\"})}),\n float_cells({x({\"a\",\"b\"})}), float_cells({x({\"a\",\"c\"})}),\n {x({\"a\",\"b\",\"c\"}),y({\"d\",\"e\"})}, {x({\"b\",\"f\"}),y({\"d\",\"g\"})}, \n {x(3),y({\"a\",\"b\"})}, {x(3),y({\"b\",\"c\"})}\n};\n\nTensorSpec reference_add(const TensorSpec &a, const TensorSpec &b) {\n TensorSpec result(a.type());\n for (const auto &cell: b.cells()) {\n result.add(cell.first, cell.second);\n }\n auto end_iter = b.cells().end();\n for (const auto &cell: a.cells()) {\n auto iter = b.cells().find(cell.first);\n if (iter == end_iter) {\n result.add(cell.first, cell.second);\n }\n }\n return result;\n}\n\nTensorSpec perform_partial_add(const TensorSpec &a, const TensorSpec &b) {\n const auto &factory = SimpleValueBuilderFactory::get();\n auto lhs = value_from_spec(a, factory);\n auto rhs = value_from_spec(b, factory);\n auto up = tensor::TensorPartialUpdate::add(*lhs, *rhs, factory);\n if (up) {\n return spec_from_value(*up);\n } else {\n return TensorSpec(a.type());\n }\n}\n\nTensorSpec perform_old_add(const TensorSpec &a, const TensorSpec &b) {\n const auto &engine = tensor::DefaultTensorEngine::ref();\n auto lhs = engine.from_spec(a);\n auto rhs = engine.from_spec(b);\n auto lhs_tensor = dynamic_cast(lhs.get());\n EXPECT_TRUE(lhs_tensor);\n auto rhs_tensor = dynamic_cast(rhs.get());\n EXPECT_TRUE(rhs_tensor);\n auto up = lhs_tensor->add(*rhs_tensor);\n EXPECT_TRUE(up);\n return engine.to_spec(*up);\n}\n\n\nTEST(PartialAddTest, partial_add_works_for_simple_values) {\n ASSERT_TRUE((add_layouts.size() % 2) == 0);\n for (size_t i = 0; i < add_layouts.size(); i += 2) {\n TensorSpec lhs = spec(add_layouts[i], N());\n TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));\n SCOPED_TRACE(fmt(\"\\n===\\nLHS: %s\\nRHS: %s\\n===\\n\", lhs.to_string().c_str(), rhs.to_string().c_str()));\n auto expect = reference_add(lhs, rhs);\n auto actual = perform_partial_add(lhs, rhs);\n EXPECT_EQ(actual, expect);\n }\n}\n\nTEST(PartialAddTest, partial_add_works_like_old_add) {\n ASSERT_TRUE((add_layouts.size() % 2) == 0);\n for (size_t i = 0; i < add_layouts.size(); i += 2) {\n TensorSpec lhs = spec(add_layouts[i], N());\n TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));\n SCOPED_TRACE(fmt(\"\\n===\\nLHS: %s\\nRHS: %s\\n===\\n\", lhs.to_string().c_str(), rhs.to_string().c_str()));\n auto expect = perform_old_add(lhs, rhs);\n auto actual = perform_partial_add(lhs, rhs);\n EXPECT_EQ(actual, expect);\n printf(\"%s add %s -> %s\\n\", lhs.to_string().c_str(), rhs.to_string().c_str(), actual.to_string().c_str());\n\n }\n}\n\nGTEST_MAIN_RUN_ALL_TESTS()\nadd PartialAdd unit test for bad input\/\/ Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace vespalib;\nusing namespace vespalib::eval;\nusing namespace vespalib::eval::test;\n\nusing vespalib::make_string_short::fmt;\n\nstd::vector add_layouts = {\n {x({\"a\"})}, {x({\"b\"})},\n {x({\"a\",\"b\"})}, {x({\"a\",\"c\"})},\n float_cells({x({\"a\",\"b\"})}), {x({\"a\",\"c\"})},\n {x({\"a\",\"b\"})}, float_cells({x({\"a\",\"c\"})}),\n float_cells({x({\"a\",\"b\"})}), float_cells({x({\"a\",\"c\"})}),\n {x({\"a\",\"b\",\"c\"}),y({\"d\",\"e\"})}, {x({\"b\",\"f\"}),y({\"d\",\"g\"})}, \n {x(3),y({\"a\",\"b\"})}, {x(3),y({\"b\",\"c\"})}\n};\n\nTensorSpec reference_add(const TensorSpec &a, const TensorSpec &b) {\n TensorSpec result(a.type());\n for (const auto &cell: b.cells()) {\n result.add(cell.first, cell.second);\n }\n auto end_iter = b.cells().end();\n for (const auto &cell: a.cells()) {\n auto iter = b.cells().find(cell.first);\n if (iter == end_iter) {\n result.add(cell.first, cell.second);\n }\n }\n return result;\n}\n\nValue::UP try_partial_add(const TensorSpec &a, const TensorSpec &b) {\n const auto &factory = SimpleValueBuilderFactory::get();\n auto lhs = value_from_spec(a, factory);\n auto rhs = value_from_spec(b, factory);\n return tensor::TensorPartialUpdate::add(*lhs, *rhs, factory);\n}\n\nTensorSpec perform_partial_add(const TensorSpec &a, const TensorSpec &b) {\n auto up = try_partial_add(a, b);\n EXPECT_TRUE(up);\n if (up) {\n return spec_from_value(*up);\n } else {\n return TensorSpec(a.type());\n }\n}\n\nTensorSpec perform_old_add(const TensorSpec &a, const TensorSpec &b) {\n const auto &engine = tensor::DefaultTensorEngine::ref();\n auto lhs = engine.from_spec(a);\n auto rhs = engine.from_spec(b);\n auto lhs_tensor = dynamic_cast(lhs.get());\n EXPECT_TRUE(lhs_tensor);\n auto rhs_tensor = dynamic_cast(rhs.get());\n EXPECT_TRUE(rhs_tensor);\n auto up = lhs_tensor->add(*rhs_tensor);\n EXPECT_TRUE(up);\n return engine.to_spec(*up);\n}\n\n\nTEST(PartialAddTest, partial_add_works_for_simple_values) {\n ASSERT_TRUE((add_layouts.size() % 2) == 0);\n for (size_t i = 0; i < add_layouts.size(); i += 2) {\n TensorSpec lhs = spec(add_layouts[i], N());\n TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));\n SCOPED_TRACE(fmt(\"\\n===\\nLHS: %s\\nRHS: %s\\n===\\n\", lhs.to_string().c_str(), rhs.to_string().c_str()));\n auto expect = reference_add(lhs, rhs);\n auto actual = perform_partial_add(lhs, rhs);\n EXPECT_EQ(actual, expect);\n }\n}\n\nTEST(PartialAddTest, partial_add_works_like_old_add) {\n ASSERT_TRUE((add_layouts.size() % 2) == 0);\n for (size_t i = 0; i < add_layouts.size(); i += 2) {\n TensorSpec lhs = spec(add_layouts[i], N());\n TensorSpec rhs = spec(add_layouts[i + 1], Div16(N()));\n SCOPED_TRACE(fmt(\"\\n===\\nLHS: %s\\nRHS: %s\\n===\\n\", lhs.to_string().c_str(), rhs.to_string().c_str()));\n auto expect = perform_old_add(lhs, rhs);\n auto actual = perform_partial_add(lhs, rhs);\n EXPECT_EQ(actual, expect);\n }\n}\n\nstd::vector bad_layouts = {\n {x(3)}, {x(3),y(1)},\n {x(3),y(1)}, {x(3)},\n {x(3),y(3)}, {x(3),y({\"a\"})},\n {x(3),y({\"a\"})}, {x(3),y(3)},\n {x({\"a\"})}, {x({\"a\"}),y({\"b\"})},\n {x({\"a\"}),y({\"b\"})}, {x({\"a\"})},\n {x({\"a\"})}, {x({\"a\"}),y(1)}\n};\n\nTEST(PartialAddTest, partial_add_returns_nullptr_on_invalid_inputs) {\n ASSERT_TRUE((bad_layouts.size() % 2) == 0);\n for (size_t i = 0; i < bad_layouts.size(); i += 2) {\n TensorSpec lhs = spec(bad_layouts[i], N());\n TensorSpec rhs = spec(bad_layouts[i + 1], Div16(N()));\n SCOPED_TRACE(fmt(\"\\n===\\nLHS: %s\\nRHS: %s\\n===\\n\", lhs.to_string().c_str(), rhs.to_string().c_str()));\n auto actual = try_partial_add(lhs, rhs);\n auto expect = Value::UP();\n EXPECT_EQ(actual, expect);\n }\n}\n\nGTEST_MAIN_RUN_ALL_TESTS()\n<|endoftext|>"} {"text":"\/*\n * MIT License\n *\n * Copyright (c) 2016 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"Player\/Player.h\"\n#include \"Common\/config.h\"\n#include \"PlayerProxy.h\"\n#include \"Util\/mini.h\"\n#include \"Util\/MD5.h\"\n#include \"Util\/logger.h\"\n#include \"Thread\/AsyncTaskThread.h\"\n\nusing namespace toolkit;\n\nnamespace mediakit {\n\nstatic uint8_t s_mute_adts[] = {0xff, 0xf1, 0x6c, 0x40, 0x2d, 0x3f, 0xfc, 0x00, 0xe0, 0x34, 0x20, 0xad, 0xf2, 0x3f, 0xb5, 0xdd,\n 0x73, 0xac, 0xbd, 0xca, 0xd7, 0x7d, 0x4a, 0x13, 0x2d, 0x2e, 0xa2, 0x62, 0x02, 0x70, 0x3c, 0x1c,\n 0xc5, 0x63, 0x55, 0x69, 0x94, 0xb5, 0x8d, 0x70, 0xd7, 0x24, 0x6a, 0x9e, 0x2e, 0x86, 0x24, 0xea,\n 0x4f, 0xd4, 0xf8, 0x10, 0x53, 0xa5, 0x4a, 0xb2, 0x9a, 0xf0, 0xa1, 0x4f, 0x2f, 0x66, 0xf9, 0xd3,\n 0x8c, 0xa6, 0x97, 0xd5, 0x84, 0xac, 0x09, 0x25, 0x98, 0x0b, 0x1d, 0x77, 0x04, 0xb8, 0x55, 0x49,\n 0x85, 0x27, 0x06, 0x23, 0x58, 0xcb, 0x22, 0xc3, 0x20, 0x3a, 0x12, 0x09, 0x48, 0x24, 0x86, 0x76,\n 0x95, 0xe3, 0x45, 0x61, 0x43, 0x06, 0x6b, 0x4a, 0x61, 0x14, 0x24, 0xa9, 0x16, 0xe0, 0x97, 0x34,\n 0xb6, 0x58, 0xa4, 0x38, 0x34, 0x90, 0x19, 0x5d, 0x00, 0x19, 0x4a, 0xc2, 0x80, 0x4b, 0xdc, 0xb7,\n 0x00, 0x18, 0x12, 0x3d, 0xd9, 0x93, 0xee, 0x74, 0x13, 0x95, 0xad, 0x0b, 0x59, 0x51, 0x0e, 0x99,\n 0xdf, 0x49, 0x98, 0xde, 0xa9, 0x48, 0x4b, 0xa5, 0xfb, 0xe8, 0x79, 0xc9, 0xe2, 0xd9, 0x60, 0xa5,\n 0xbe, 0x74, 0xa6, 0x6b, 0x72, 0x0e, 0xe3, 0x7b, 0x28, 0xb3, 0x0e, 0x52, 0xcc, 0xf6, 0x3d, 0x39,\n 0xb7, 0x7e, 0xbb, 0xf0, 0xc8, 0xce, 0x5c, 0x72, 0xb2, 0x89, 0x60, 0x33, 0x7b, 0xc5, 0xda, 0x49,\n 0x1a, 0xda, 0x33, 0xba, 0x97, 0x9e, 0xa8, 0x1b, 0x6d, 0x5a, 0x77, 0xb6, 0xf1, 0x69, 0x5a, 0xd1,\n 0xbd, 0x84, 0xd5, 0x4e, 0x58, 0xa8, 0x5e, 0x8a, 0xa0, 0xc2, 0xc9, 0x22, 0xd9, 0xa5, 0x53, 0x11,\n 0x18, 0xc8, 0x3a, 0x39, 0xcf, 0x3f, 0x57, 0xb6, 0x45, 0x19, 0x1e, 0x8a, 0x71, 0xa4, 0x46, 0x27,\n 0x9e, 0xe9, 0xa4, 0x86, 0xdd, 0x14, 0xd9, 0x4d, 0xe3, 0x71, 0xe3, 0x26, 0xda, 0xaa, 0x17, 0xb4,\n 0xac, 0xe1, 0x09, 0xc1, 0x0d, 0x75, 0xba, 0x53, 0x0a, 0x37, 0x8b, 0xac, 0x37, 0x39, 0x41, 0x27,\n 0x6a, 0xf0, 0xe9, 0xb4, 0xc2, 0xac, 0xb0, 0x39, 0x73, 0x17, 0x64, 0x95, 0xf4, 0xdc, 0x33, 0xbb,\n 0x84, 0x94, 0x3e, 0xf8, 0x65, 0x71, 0x60, 0x7b, 0xd4, 0x5f, 0x27, 0x79, 0x95, 0x6a, 0xba, 0x76,\n 0xa6, 0xa5, 0x9a, 0xec, 0xae, 0x55, 0x3a, 0x27, 0x48, 0x23, 0xcf, 0x5c, 0x4d, 0xbc, 0x0b, 0x35,\n 0x5c, 0xa7, 0x17, 0xcf, 0x34, 0x57, 0xc9, 0x58, 0xc5, 0x20, 0x09, 0xee, 0xa5, 0xf2, 0x9c, 0x6c,\n 0x39, 0x1a, 0x77, 0x92, 0x9b, 0xff, 0xc6, 0xae, 0xf8, 0x36, 0xba, 0xa8, 0xaa, 0x6b, 0x1e, 0x8c,\n 0xc5, 0x97, 0x39, 0x6a, 0xb8, 0xa2, 0x55, 0xa8, 0xf8};\n#define MUTE_ADTS_DATA s_mute_adts\n#define MUTE_ADTS_DATA_LEN sizeof(s_mute_adts)\n#define MUTE_ADTS_DATA_MS 130\n\nPlayerProxy::PlayerProxy(const char *strVhost,\n const char *strApp,\n const char *strSrc,\n bool bEnableHls,\n bool bEnableMp4,\n int iRetryCount){\n\t_strVhost = strVhost;\n\t_strApp = strApp;\n\t_strSrc = strSrc;\n _bEnableHls = bEnableHls;\n _bEnableMp4 = bEnableMp4;\n _iRetryCount = iRetryCount;\n}\nvoid PlayerProxy::play(const char* strUrl) {\n\tweak_ptr weakSelf = shared_from_this();\n\tstd::shared_ptr piFailedCnt(new int(0)); \/\/连续播放失败次数\n\tstring strUrlTmp(strUrl);\n\tsetOnPlayResult([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {\n\t\tauto strongSelf = weakSelf.lock();\n\t\tif(!strongSelf) {\n\t\t\treturn;\n\t\t}\n\t\tif(!err) {\n\t\t\t\/\/ 播放成功\n\t\t\t*piFailedCnt = 0;\/\/连续播放失败次数清0\n\t\t\tstrongSelf->onPlaySuccess();\n\t\t}else if(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {\n\t\t\t\/\/ 播放失败,延时重试播放\n\t\t\tstrongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);\n\t\t}\n\t});\n\tsetOnShutdown([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {\n\t\tauto strongSelf = weakSelf.lock();\n\t\tif(!strongSelf) {\n\t\t\treturn;\n\t\t}\n\t\tif(strongSelf->_pChn) {\n\t\t\tstrongSelf->_pChn.reset();\n\t\t}\n\t\t\/\/播放异常中断,延时重试播放\n\t\tif(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {\n\t\t\tstrongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);\n\t\t}\n\t});\n\tMediaPlayer::play(strUrl);\n}\n\nPlayerProxy::~PlayerProxy() {\n\tauto iTaskId = reinterpret_cast(this);\n\tAsyncTaskThread::Instance().CancelTask(iTaskId);\n}\nvoid PlayerProxy::rePlay(const string &strUrl,int iFailedCnt){\n\tauto iTaskId = reinterpret_cast(this);\n\tauto iDelay = MAX(2 * 1000, MIN(iFailedCnt * 3000,60*1000));\n\tweak_ptr weakSelf = shared_from_this();\n\tAsyncTaskThread::Instance().CancelTask(iTaskId);\n\tAsyncTaskThread::Instance().DoTaskDelay(iTaskId, iDelay, [weakSelf,strUrl,iFailedCnt]() {\n\t\t\/\/播放失败次数越多,则延时越长\n\t\tauto strongPlayer = weakSelf.lock();\n\t\tif(!strongPlayer) {\n\t\t\treturn false;\n\t\t}\n\t\tWarnL << \"重试播放[\" << iFailedCnt << \"]:\" << strUrl;\n\t\tstrongPlayer->MediaPlayer::play(strUrl.data());\n\t\treturn false;\n\t});\n}\nbool PlayerProxy::close() {\n \/\/通知其停止推流\n weak_ptr weakSlef = dynamic_pointer_cast(shared_from_this());\n\tauto executor = getExecutor();\n\tif(executor) {\n\t\texecutor->async_first([weakSlef]() {\n\t\t\tauto stronSelf = weakSlef.lock();\n\t\t\tif (stronSelf) {\n\t\t\t\tstronSelf->_pChn.reset();\n\t\t\t\tstronSelf->teardown();\n\t\t\t}\n\t\t});\n\t}\n return true;\n}\n\n\nclass MuteAudioMaker : public FrameRingInterfaceDelegate{\npublic:\n\ttypedef std::shared_ptr Ptr;\n\n\tMuteAudioMaker(){};\n\tvirtual ~MuteAudioMaker(){}\n\tvoid inputFrame(const Frame::Ptr &frame) override {\n\t\tif(frame->getTrackType() == TrackVideo){\n\t\t\tauto iAudioIndex = frame->stamp() \/ MUTE_ADTS_DATA_MS;\n\t\t\tif(_iAudioIndex != iAudioIndex){\n\t\t\t\t_iAudioIndex = iAudioIndex;\n\t\t\t\tauto aacFrame = std::make_shared((char *)MUTE_ADTS_DATA,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MUTE_ADTS_DATA_LEN,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _iAudioIndex * MUTE_ADTS_DATA_MS);\n\t\t\t\tFrameRingInterfaceDelegate::inputFrame(aacFrame);\n\t\t\t}\n\t\t}\n\t}\nprivate:\n\tint _iAudioIndex = 0;\n};\n\nvoid PlayerProxy::onPlaySuccess() {\n\t_pChn.reset(new DevChannel(_strVhost.data(),_strApp.data(),_strSrc.data(),getDuration(),_bEnableHls,_bEnableMp4));\n\t_pChn->setListener(shared_from_this());\n\n\tauto videoTrack = getTrack(TrackVideo);\n\tif(videoTrack){\n\t\t\/\/添加视频\n\t\t_pChn->addTrack(videoTrack);\n\t\t\/\/视频数据写入_pChn\n\t\tvideoTrack->addDelegate(_pChn);\n\t}\n\n\tauto audioTrack = getTrack(TrackAudio);\n\tif(audioTrack){\n\t\t\/\/添加音频\n\t\t_pChn->addTrack(audioTrack);\n\t\t\/\/音频数据写入_pChn\n audioTrack->addDelegate(_pChn);\n }else if(videoTrack){\n\t\t\/\/没有音频信息,产生一个静音音频\n\t\tMuteAudioMaker::Ptr audioMaker = std::make_shared();\n\t\t\/\/videoTrack把数据写入MuteAudioMaker\n\t\tvideoTrack->addDelegate(audioMaker);\n\t\t\/\/添加一个静音Track至_pChn\n\t\t_pChn->addTrack(std::make_shared());\n\t\t\/\/MuteAudioMaker生成静音音频然后写入_pChn;\n\t\taudioMaker->addDelegate(_pChn);\n\t}\n}\n\n\n} \/* namespace mediakit *\/\n修复小bug\/*\n * MIT License\n *\n * Copyright (c) 2016 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"Player\/Player.h\"\n#include \"Common\/config.h\"\n#include \"PlayerProxy.h\"\n#include \"Util\/mini.h\"\n#include \"Util\/MD5.h\"\n#include \"Util\/logger.h\"\n#include \"Thread\/AsyncTaskThread.h\"\n\nusing namespace toolkit;\n\nnamespace mediakit {\n\nstatic uint8_t s_mute_adts[] = {0xff, 0xf1, 0x6c, 0x40, 0x2d, 0x3f, 0xfc, 0x00, 0xe0, 0x34, 0x20, 0xad, 0xf2, 0x3f, 0xb5, 0xdd,\n 0x73, 0xac, 0xbd, 0xca, 0xd7, 0x7d, 0x4a, 0x13, 0x2d, 0x2e, 0xa2, 0x62, 0x02, 0x70, 0x3c, 0x1c,\n 0xc5, 0x63, 0x55, 0x69, 0x94, 0xb5, 0x8d, 0x70, 0xd7, 0x24, 0x6a, 0x9e, 0x2e, 0x86, 0x24, 0xea,\n 0x4f, 0xd4, 0xf8, 0x10, 0x53, 0xa5, 0x4a, 0xb2, 0x9a, 0xf0, 0xa1, 0x4f, 0x2f, 0x66, 0xf9, 0xd3,\n 0x8c, 0xa6, 0x97, 0xd5, 0x84, 0xac, 0x09, 0x25, 0x98, 0x0b, 0x1d, 0x77, 0x04, 0xb8, 0x55, 0x49,\n 0x85, 0x27, 0x06, 0x23, 0x58, 0xcb, 0x22, 0xc3, 0x20, 0x3a, 0x12, 0x09, 0x48, 0x24, 0x86, 0x76,\n 0x95, 0xe3, 0x45, 0x61, 0x43, 0x06, 0x6b, 0x4a, 0x61, 0x14, 0x24, 0xa9, 0x16, 0xe0, 0x97, 0x34,\n 0xb6, 0x58, 0xa4, 0x38, 0x34, 0x90, 0x19, 0x5d, 0x00, 0x19, 0x4a, 0xc2, 0x80, 0x4b, 0xdc, 0xb7,\n 0x00, 0x18, 0x12, 0x3d, 0xd9, 0x93, 0xee, 0x74, 0x13, 0x95, 0xad, 0x0b, 0x59, 0x51, 0x0e, 0x99,\n 0xdf, 0x49, 0x98, 0xde, 0xa9, 0x48, 0x4b, 0xa5, 0xfb, 0xe8, 0x79, 0xc9, 0xe2, 0xd9, 0x60, 0xa5,\n 0xbe, 0x74, 0xa6, 0x6b, 0x72, 0x0e, 0xe3, 0x7b, 0x28, 0xb3, 0x0e, 0x52, 0xcc, 0xf6, 0x3d, 0x39,\n 0xb7, 0x7e, 0xbb, 0xf0, 0xc8, 0xce, 0x5c, 0x72, 0xb2, 0x89, 0x60, 0x33, 0x7b, 0xc5, 0xda, 0x49,\n 0x1a, 0xda, 0x33, 0xba, 0x97, 0x9e, 0xa8, 0x1b, 0x6d, 0x5a, 0x77, 0xb6, 0xf1, 0x69, 0x5a, 0xd1,\n 0xbd, 0x84, 0xd5, 0x4e, 0x58, 0xa8, 0x5e, 0x8a, 0xa0, 0xc2, 0xc9, 0x22, 0xd9, 0xa5, 0x53, 0x11,\n 0x18, 0xc8, 0x3a, 0x39, 0xcf, 0x3f, 0x57, 0xb6, 0x45, 0x19, 0x1e, 0x8a, 0x71, 0xa4, 0x46, 0x27,\n 0x9e, 0xe9, 0xa4, 0x86, 0xdd, 0x14, 0xd9, 0x4d, 0xe3, 0x71, 0xe3, 0x26, 0xda, 0xaa, 0x17, 0xb4,\n 0xac, 0xe1, 0x09, 0xc1, 0x0d, 0x75, 0xba, 0x53, 0x0a, 0x37, 0x8b, 0xac, 0x37, 0x39, 0x41, 0x27,\n 0x6a, 0xf0, 0xe9, 0xb4, 0xc2, 0xac, 0xb0, 0x39, 0x73, 0x17, 0x64, 0x95, 0xf4, 0xdc, 0x33, 0xbb,\n 0x84, 0x94, 0x3e, 0xf8, 0x65, 0x71, 0x60, 0x7b, 0xd4, 0x5f, 0x27, 0x79, 0x95, 0x6a, 0xba, 0x76,\n 0xa6, 0xa5, 0x9a, 0xec, 0xae, 0x55, 0x3a, 0x27, 0x48, 0x23, 0xcf, 0x5c, 0x4d, 0xbc, 0x0b, 0x35,\n 0x5c, 0xa7, 0x17, 0xcf, 0x34, 0x57, 0xc9, 0x58, 0xc5, 0x20, 0x09, 0xee, 0xa5, 0xf2, 0x9c, 0x6c,\n 0x39, 0x1a, 0x77, 0x92, 0x9b, 0xff, 0xc6, 0xae, 0xf8, 0x36, 0xba, 0xa8, 0xaa, 0x6b, 0x1e, 0x8c,\n 0xc5, 0x97, 0x39, 0x6a, 0xb8, 0xa2, 0x55, 0xa8, 0xf8};\n#define MUTE_ADTS_DATA s_mute_adts\n#define MUTE_ADTS_DATA_LEN sizeof(s_mute_adts)\n#define MUTE_ADTS_DATA_MS 130\n\nPlayerProxy::PlayerProxy(const char *strVhost,\n const char *strApp,\n const char *strSrc,\n bool bEnableHls,\n bool bEnableMp4,\n int iRetryCount){\n\t_strVhost = strVhost;\n\t_strApp = strApp;\n\t_strSrc = strSrc;\n _bEnableHls = bEnableHls;\n _bEnableMp4 = bEnableMp4;\n _iRetryCount = iRetryCount;\n}\nvoid PlayerProxy::play(const char* strUrl) {\n\tweak_ptr weakSelf = shared_from_this();\n\tstd::shared_ptr piFailedCnt(new int(0)); \/\/连续播放失败次数\n\tstring strUrlTmp(strUrl);\n\tsetOnPlayResult([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {\n\t\tauto strongSelf = weakSelf.lock();\n\t\tif(!strongSelf) {\n\t\t\treturn;\n\t\t}\n\t\tif(!err) {\n\t\t\t\/\/ 播放成功\n\t\t\t*piFailedCnt = 0;\/\/连续播放失败次数清0\n\t\t\tstrongSelf->onPlaySuccess();\n\t\t}else if(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {\n\t\t\t\/\/ 播放失败,延时重试播放\n\t\t\tstrongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);\n\t\t}\n\t});\n\tsetOnShutdown([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {\n\t\tauto strongSelf = weakSelf.lock();\n\t\tif(!strongSelf) {\n\t\t\treturn;\n\t\t}\n\t\tif(strongSelf->_pChn) {\n\t\t\tauto tracks = strongSelf->getTracks();\n\t\t\tfor (auto & track : tracks){\n\t\t\t\ttrack->delDelegate(strongSelf->_pChn.get());\n\t\t\t}\n\t\t\tstrongSelf->_pChn.reset();\n\t\t}\n\t\t\/\/播放异常中断,延时重试播放\n\t\tif(*piFailedCnt < strongSelf->_iRetryCount || strongSelf->_iRetryCount < 0) {\n\t\t\tstrongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);\n\t\t}\n\t});\n\tMediaPlayer::play(strUrl);\n}\n\nPlayerProxy::~PlayerProxy() {\n\tauto iTaskId = reinterpret_cast(this);\n\tAsyncTaskThread::Instance().CancelTask(iTaskId);\n}\nvoid PlayerProxy::rePlay(const string &strUrl,int iFailedCnt){\n\tauto iTaskId = reinterpret_cast(this);\n\tauto iDelay = MAX(2 * 1000, MIN(iFailedCnt * 3000,60*1000));\n\tweak_ptr weakSelf = shared_from_this();\n\tAsyncTaskThread::Instance().CancelTask(iTaskId);\n\tAsyncTaskThread::Instance().DoTaskDelay(iTaskId, iDelay, [weakSelf,strUrl,iFailedCnt]() {\n\t\t\/\/播放失败次数越多,则延时越长\n\t\tauto strongPlayer = weakSelf.lock();\n\t\tif(!strongPlayer) {\n\t\t\treturn false;\n\t\t}\n\t\tWarnL << \"重试播放[\" << iFailedCnt << \"]:\" << strUrl;\n\t\tstrongPlayer->MediaPlayer::play(strUrl.data());\n\t\treturn false;\n\t});\n}\nbool PlayerProxy::close() {\n \/\/通知其停止推流\n weak_ptr weakSlef = dynamic_pointer_cast(shared_from_this());\n\tauto executor = getExecutor();\n\tif(executor) {\n\t\texecutor->async_first([weakSlef]() {\n\t\t\tauto stronSelf = weakSlef.lock();\n\t\t\tif (stronSelf) {\n\t\t\t\tstronSelf->_pChn.reset();\n\t\t\t\tstronSelf->teardown();\n\t\t\t}\n\t\t});\n\t}\n return true;\n}\n\n\nclass MuteAudioMaker : public FrameRingInterfaceDelegate{\npublic:\n\ttypedef std::shared_ptr Ptr;\n\n\tMuteAudioMaker(){};\n\tvirtual ~MuteAudioMaker(){}\n\tvoid inputFrame(const Frame::Ptr &frame) override {\n\t\tif(frame->getTrackType() == TrackVideo){\n\t\t\tauto iAudioIndex = frame->stamp() \/ MUTE_ADTS_DATA_MS;\n\t\t\tif(_iAudioIndex != iAudioIndex){\n\t\t\t\t_iAudioIndex = iAudioIndex;\n\t\t\t\tauto aacFrame = std::make_shared((char *)MUTE_ADTS_DATA,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MUTE_ADTS_DATA_LEN,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _iAudioIndex * MUTE_ADTS_DATA_MS);\n\t\t\t\tFrameRingInterfaceDelegate::inputFrame(aacFrame);\n\t\t\t}\n\t\t}\n\t}\nprivate:\n\tint _iAudioIndex = 0;\n};\n\nvoid PlayerProxy::onPlaySuccess() {\n\t_pChn.reset(new DevChannel(_strVhost.data(),_strApp.data(),_strSrc.data(),getDuration(),_bEnableHls,_bEnableMp4));\n\t_pChn->setListener(shared_from_this());\n\n\tauto videoTrack = getTrack(TrackVideo);\n\tif(videoTrack){\n\t\t\/\/添加视频\n\t\t_pChn->addTrack(videoTrack);\n\t\t\/\/视频数据写入_pChn\n\t\tvideoTrack->addDelegate(_pChn);\n\t}\n\n\tauto audioTrack = getTrack(TrackAudio);\n\tif(audioTrack){\n\t\t\/\/添加音频\n\t\t_pChn->addTrack(audioTrack);\n\t\t\/\/音频数据写入_pChn\n audioTrack->addDelegate(_pChn);\n }else if(videoTrack){\n\t\t\/\/没有音频信息,产生一个静音音频\n\t\tMuteAudioMaker::Ptr audioMaker = std::make_shared();\n\t\t\/\/videoTrack把数据写入MuteAudioMaker\n\t\tvideoTrack->addDelegate(audioMaker);\n\t\t\/\/添加一个静音Track至_pChn\n\t\t_pChn->addTrack(std::make_shared());\n\t\t\/\/MuteAudioMaker生成静音音频然后写入_pChn;\n\t\taudioMaker->addDelegate(_pChn);\n\t}\n}\n\n\n} \/* namespace mediakit *\/\n<|endoftext|>"} {"text":"Remove depracated limitation code in Modelica generator<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: dbtreeview.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: oj $ $Date: 2002-05-02 07:14:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef DBACCESS_UI_DBTREEVIEW_HXX\n#include \"dbtreeview.hxx\"\n#endif\n#ifndef _SVTREEBOX_HXX\n#include \n#endif\n#ifndef DBAUI_DBTREELISTBOX_HXX\n#include \"dbtreelistbox.hxx\"\n#endif\n#ifndef DBAUI_DBTREEMODEL_HXX\n#include \"dbtreemodel.hxx\"\n#endif\n#include \"dbaccess_helpid.hrc\"\n\n\/\/ .........................................................................\nnamespace dbaui\n{\n\/\/ .........................................................................\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nDBG_NAME(DBTreeView)\n\/\/========================================================================\n\/\/ class DBTreeView\n\/\/========================================================================\nDBTreeView::DBTreeView( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nBits)\n : Window( pParent, nBits )\n , m_pTreeListBox(NULL)\n{\n DBG_CTOR(DBTreeView,NULL);\n\n m_pTreeListBox = new DBTreeListBox(this, _rxORB ,WB_BORDER | WB_HASLINES | WB_HASLINESATROOT | WB_SORT | WB_HASBUTTONS | WB_HSCROLL |WB_HASBUTTONSATROOT);\n m_pTreeListBox->EnableCheckButton(NULL);\n m_pTreeListBox->SetDragDropMode( 0 );\n m_pTreeListBox->EnableInplaceEditing( sal_True );\n m_pTreeListBox->SetHelpId(HID_TLB_TREELISTBOX);\n m_pTreeListBox->Show();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nDBTreeView::~DBTreeView()\n{\n if (m_pTreeListBox)\n {\n if (m_pTreeListBox->GetModel())\n {\n m_pTreeListBox->GetModel()->RemoveView(m_pTreeListBox);\n m_pTreeListBox->DisconnectFromModel();\n }\n Window* pDeleteIt = m_pTreeListBox;\n m_pTreeListBox = NULL;\n delete pDeleteIt;\n }\n DBG_DTOR(DBTreeView,NULL);\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::SetPreExpandHandler(const Link& _rHdl)\n{\n m_pTreeListBox->SetPreExpandHandler(_rHdl);\n}\n\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::GetPreExpandHandler() const\n{\n return m_pTreeListBox->GetPreExpandHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setCutHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setCutHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getCutHandler() const\n{\n return m_pTreeListBox->getCutHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setCopyHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setCopyHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getCopyHandler() const\n{\n return m_pTreeListBox->getCopyHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setPasteHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setPasteHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getPasteHandler() const\n{\n return m_pTreeListBox->getPasteHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setDeleteHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setDeleteHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getDeleteHandler() const\n{\n return m_pTreeListBox->getDeleteHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setEditingHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setEditingHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getEditingHandler() const\n{\n return m_pTreeListBox->getEditingHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setEditedHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setEditedHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getEditedHandler() const\n{\n return m_pTreeListBox->getEditedHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::Resize()\n{\n Window::Resize();\n m_pTreeListBox->SetPosSizePixel(Point(0,0),GetOutputSizePixel());\n}\n\n\/\/ -------------------------------------------------------------------------\nDBTreeListModel* DBTreeView::getModel() const\n{\n return (DBTreeListModel*)m_pTreeListBox->GetModel();\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid DBTreeView::setModel(DBTreeListModel* _pTreeModel)\n{\n if (_pTreeModel)\n _pTreeModel->InsertView(m_pTreeListBox);\n m_pTreeListBox->SetModel(_pTreeModel);\n}\n\n\/\/ -------------------------------------------------------------------------\nDBTreeListBox* DBTreeView::getListBox() const\n{\n return m_pTreeListBox;\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid DBTreeView::setSelectHdl(const Link& _rHdl)\n{\n m_pTreeListBox->SetSelectHdl(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::GetFocus()\n{\n Window::GetFocus();\n if ( m_pTreeListBox )\/\/&& !m_pTreeListBox->HasChildPathFocus())\n m_pTreeListBox->GrabFocus();\n}\n\n\n\/\/ .........................................................................\n} \/\/ namespace dbaui\n\/\/ .........................................................................\n\n\nINTEGRATION: CWS insight01 (1.17.112); FILE MERGED 2004\/07\/15 10:58:37 oj 1.17.112.4: add chkthis macros 2004\/05\/26 08:35:45 oj 1.17.112.3: handle return key event 2003\/12\/18 13:54:32 oj 1.17.112.2: #111075# ongoing work 2003\/11\/05 11:41:02 oj 1.17.112.1: #111075# ongoing work\/*************************************************************************\n *\n * $RCSfile: dbtreeview.cxx,v $\n *\n * $Revision: 1.18 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 15:33:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef DBACCESS_UI_DBTREEVIEW_HXX\n#include \"dbtreeview.hxx\"\n#endif\n#ifndef _SVTREEBOX_HXX\n#include \n#endif\n#ifndef DBAUI_DBTREELISTBOX_HXX\n#include \"dbtreelistbox.hxx\"\n#endif\n#ifndef DBAUI_DBTREEMODEL_HXX\n#include \"dbtreemodel.hxx\"\n#endif\n#include \"dbaccess_helpid.hrc\"\n\n\/\/ .........................................................................\nnamespace dbaui\n{\n\/\/ .........................................................................\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nDBG_NAME(DBTreeView)\n\/\/========================================================================\n\/\/ class DBTreeView\n\/\/========================================================================\nDBTreeView::DBTreeView( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nBits)\n : Window( pParent, nBits )\n , m_pTreeListBox(NULL)\n{\n DBG_CTOR(DBTreeView,NULL);\n\n m_pTreeListBox = new DBTreeListBox(this, _rxORB ,WB_HASLINES | WB_SORT | WB_HASBUTTONS | WB_HSCROLL |WB_HASBUTTONSATROOT,sal_True);\n m_pTreeListBox->EnableCheckButton(NULL);\n m_pTreeListBox->SetDragDropMode( 0 );\n m_pTreeListBox->EnableInplaceEditing( sal_True );\n m_pTreeListBox->SetHelpId(HID_TLB_TREELISTBOX);\n m_pTreeListBox->Show();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nDBTreeView::~DBTreeView()\n{\n DBG_DTOR(DBTreeView,NULL);\n if (m_pTreeListBox)\n {\n if (m_pTreeListBox->GetModel())\n {\n m_pTreeListBox->GetModel()->RemoveView(m_pTreeListBox);\n m_pTreeListBox->DisconnectFromModel();\n }\n ::std::auto_ptr aTemp(m_pTreeListBox);\n m_pTreeListBox = NULL;\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::SetPreExpandHandler(const Link& _rHdl)\n{\n m_pTreeListBox->SetPreExpandHandler(_rHdl);\n}\n\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::GetPreExpandHandler() const\n{\n return m_pTreeListBox->GetPreExpandHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setCutHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setCutHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getCutHandler() const\n{\n return m_pTreeListBox->getCutHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setCopyHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setCopyHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getCopyHandler() const\n{\n return m_pTreeListBox->getCopyHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setPasteHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setPasteHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getPasteHandler() const\n{\n return m_pTreeListBox->getPasteHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setDeleteHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setDeleteHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getDeleteHandler() const\n{\n return m_pTreeListBox->getDeleteHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setEditingHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setEditingHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getEditingHandler() const\n{\n return m_pTreeListBox->getEditingHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::setEditedHandler(const Link& _rHdl)\n{\n m_pTreeListBox->setEditedHandler(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nLink DBTreeView::getEditedHandler() const\n{\n return m_pTreeListBox->getEditedHandler();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::Resize()\n{\n Window::Resize();\n m_pTreeListBox->SetPosSizePixel(Point(0,0),GetOutputSizePixel());\n}\n\n\/\/ -------------------------------------------------------------------------\nDBTreeListModel* DBTreeView::getModel() const\n{\n return (DBTreeListModel*)m_pTreeListBox->GetModel();\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid DBTreeView::setModel(DBTreeListModel* _pTreeModel)\n{\n if (_pTreeModel)\n _pTreeModel->InsertView(m_pTreeListBox);\n m_pTreeListBox->SetModel(_pTreeModel);\n}\n\n\/\/ -------------------------------------------------------------------------\nDBTreeListBox* DBTreeView::getListBox() const\n{\n return m_pTreeListBox;\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid DBTreeView::setSelectHdl(const Link& _rHdl)\n{\n m_pTreeListBox->SetSelectHdl(_rHdl);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid DBTreeView::GetFocus()\n{\n Window::GetFocus();\n if ( m_pTreeListBox )\/\/&& !m_pTreeListBox->HasChildPathFocus())\n m_pTreeListBox->GrabFocus();\n}\n\n\n\/\/ .........................................................................\n} \/\/ namespace dbaui\n\/\/ .........................................................................\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: QTableConnection.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 10:37:32 $\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#ifndef DBAUI_QUERYTABLECONNECTION_HXX\n#define DBAUI_QUERYTABLECONNECTION_HXX\n\n#ifndef DBAUI_TABLECONNECTION_HXX\n#include \"TableConnection.hxx\"\n#endif\n#ifndef DBAUI_QTABLECONNECTIONDATA_HXX\n#include \"QTableConnectionData.hxx\"\n#endif\n#ifndef DBAUI_ENUMTYPES_HXX\n#include \"QEnumTypes.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/==================================================================\n class OQueryTableView;\n class OQueryTableConnection : public OTableConnection\n {\n sal_Bool m_bVisited; \/\/ is true if the conn was already visited through the join algorithm\n public:\n TYPEINFO();\n OQueryTableConnection(OQueryTableView* pContainer, OQueryTableConnectionData* pTabConnData);\n OQueryTableConnection(const OQueryTableConnection& rConn);\n virtual ~OQueryTableConnection();\n\n OQueryTableConnection& operator=(const OQueryTableConnection& rConn);\n sal_Bool operator==(const OQueryTableConnection& rCompare);\n\n ::rtl::OUString GetAliasName(EConnectionSide nWhich) const { return static_cast(GetData())->GetAliasName(nWhich); }\n\n sal_Bool IsVisited() const { return m_bVisited; }\n void SetVisited(sal_Bool bVisited) { m_bVisited = bVisited; }\n\n };\n}\n#endif \/\/ DBAUI_QUERYTABLECONNECTION_HXX\nINTEGRATION: CWS dba24b (1.4.46); FILE MERGED 2007\/08\/16 06:14:44 oj 1.4.46.1: #i56898# clean up of the class structure\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: QTableConnection.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-11-01 15:29:45 $\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#ifndef DBAUI_QUERYTABLECONNECTION_HXX\n#define DBAUI_QUERYTABLECONNECTION_HXX\n\n#ifndef DBAUI_TABLECONNECTION_HXX\n#include \"TableConnection.hxx\"\n#endif\n#ifndef DBAUI_QTABLECONNECTIONDATA_HXX\n#include \"QTableConnectionData.hxx\"\n#endif\n#ifndef DBAUI_ENUMTYPES_HXX\n#include \"QEnumTypes.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/==================================================================\n class OQueryTableView;\n class OQueryTableConnection : public OTableConnection\n {\n sal_Bool m_bVisited; \/\/ is true if the conn was already visited through the join algorithm\n public:\n OQueryTableConnection(OQueryTableView* pContainer, const TTableConnectionData::value_type& pTabConnData);\n OQueryTableConnection(const OQueryTableConnection& rConn);\n virtual ~OQueryTableConnection();\n\n OQueryTableConnection& operator=(const OQueryTableConnection& rConn);\n sal_Bool operator==(const OQueryTableConnection& rCompare);\n\n inline ::rtl::OUString GetAliasName(EConnectionSide nWhich) const { return static_cast(GetData().get())->GetAliasName(nWhich); }\n\n inline sal_Bool IsVisited() const { return m_bVisited; }\n inline void SetVisited(sal_Bool bVisited) { m_bVisited = bVisited; }\n\n };\n}\n#endif \/\/ DBAUI_QUERYTABLECONNECTION_HXX\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: setup_help.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:54:33 $\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#ifndef SETUP_HELP_HXX\n#define SETUP_HELP_HXX\n\n\/\/--------------------------------------------------------------------------\n\n\n#ifdef UNICODE\n#else\n #define LanguageDataX LanguageDataA\n#endif\n\n\/\/--------------------------------------------------------------------------\n\nclass SetupHelperX\n{\n};\n\n\/\/--------------------------------------------------------------------------\n\n#endifINTEGRATION: CWS changefileheader (1.4.614); FILE MERGED 2008\/03\/28 15:27:23 rt 1.4.614.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: setup_help.hxx,v $\n * $Revision: 1.5 $\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#ifndef SETUP_HELP_HXX\n#define SETUP_HELP_HXX\n\n\/\/--------------------------------------------------------------------------\n\n\n#ifdef UNICODE\n#else\n #define LanguageDataX LanguageDataA\n#endif\n\n\/\/--------------------------------------------------------------------------\n\nclass SetupHelperX\n{\n};\n\n\/\/--------------------------------------------------------------------------\n\n#endif<|endoftext|>"} {"text":"\/\/--------------------------------------------------------------------------------------------------\n\/**\n * @file moduleBuildScript.cpp\n *\n * Implementation of the build script generator for pre-built kernel modules.\n *\n *
\n *\n * Copyright (C) Sierra Wireless Inc.\n *\/\n\/\/--------------------------------------------------------------------------------------------------\n\n#include \"mkTools.h\"\n#include \"buildScriptCommon.h\"\n#include \"moduleBuildScript.h\"\n\nnamespace ninja\n{\n\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate comment header for a build script.\n *\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateCommentHeader\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n script << \"# Build script for module '\" << modulePtr->name << \"'\\n\"\n \"\\n\"\n \"# == Auto-generated file. Do not edit. ==\\n\"\n \"\\n\";\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Print to a given build script the build statements related to a given module.\n * If it's a pre-built module, just copy it. Otherwise generate a module Makefile and build it.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateBuildStatements\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n if (modulePtr->moduleBuildType == model::Module_t::Sources)\n {\n \/\/ In case of Sources, koFiles map will consist of only one element.\n \/\/ Hence, use the first element in koFiles for generating build statement.\n auto const it = modulePtr->koFiles.begin();\n if (it != modulePtr->koFiles.end())\n {\n script << \"build \" << \"$builddir\/\" << it->second->path << \": \";\n\n \/\/ No pre-built module: generate and invoke a Makefile\n GenerateMakefile(modulePtr);\n script << \"MakeKernelModule \" << \"$builddir\/\"\n << path::GetContainingDir(it->second->path) << \"\\n\";\n }\n else\n {\n throw mk::Exception_t(\n mk::format(LE_I18N(\"error: %s container of kernel object file is empty.\"),\n modulePtr->defFilePtr->path));\n }\n }\n else if (modulePtr->moduleBuildType == model::Module_t::Prebuilt)\n {\n for (auto const& it: modulePtr->koFiles)\n {\n script << \"build \" << \"$builddir\/\" << it.second->path << \": \";\n\n \/\/ Pre-built module: add build statement for bundling the .ko file\n script << \"BundleFile \" << it.first << \"\\n\"\n << \" modeFlags = u+rw-x,g+r-wx,o+r-wx\\n\";\n }\n }\n else\n {\n throw mk::Exception_t(\n mk::format(LE_I18N(\"error: %s must have either 'sources' or 'preBuilt' section.\"),\n modulePtr->defFilePtr->path));\n }\n script << \"\\n\";\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Write to a given build script the build statements for the build script itself.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateNinjaScriptBuildStatement\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n \/\/ The build.ninja depends on module .mdef and .ko files\n \/\/ Create a set of dependencies.\n std::set dependencies;\n\n for (auto const& it : modulePtr->koFiles)\n {\n dependencies.insert(it.first);\n }\n\n dependencies.insert(modulePtr->defFilePtr->path);\n \/\/ It also depends on changes to the mk tools.\n dependencies.insert(path::Combine(envVars::Get(\"LEGATO_ROOT\"), \"build\/tools\/mk\"));\n\n baseGeneratorPtr->GenerateNinjaScriptBuildStatement(dependencies);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate a Makefile for a kernel module.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateMakefile\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n std::string buildPath = path::MakeAbsolute(buildParams.workingDir\n + \"\/modules\/\" + modulePtr->name);\n const std::string& compilerPath = buildParams.cCompilerPath;\n\n std::ofstream makefile;\n OpenFile(makefile, buildPath + \"\/Makefile\", buildParams.beVerbose);\n\n \/\/ Specify kernel module name and list all object files to link\n makefile << \"obj-m += \" << modulePtr->name << \".o\\n\";\n\n \/\/ Don't list object files in case of a single source file with module name\n if (modulePtr->cObjectFiles.size() > 1 ||\n modulePtr->cObjectFiles.front()->path != modulePtr->name + \".o\")\n {\n for (auto obj : modulePtr->cObjectFiles)\n {\n makefile << modulePtr->name << \"-objs += \" << obj->path << \"\\n\";\n }\n }\n makefile << \"\\n\";\n\n \/\/ Specify directory where the sources are located\n makefile << \"src = \" << modulePtr->dir << \"\\n\\n\";\n\n \/\/ Add compiler and linker options\n for (auto const &obj : modulePtr->cFlags)\n {\n makefile << \"ccflags-y += \" << obj << \"\\n\";\n }\n for (auto const &obj : modulePtr->ldFlags)\n {\n makefile << \"ldflags-y += \" << obj << \"\\n\";\n }\n makefile << \"\\n\";\n\n makefile << \"KBUILD := \" << modulePtr->kernelDir << \"\\n\";\n\n if (buildParams.target != \"localhost\")\n {\n \/\/ Specify the CROSS_COMPILE and ARCH environment variables\n \/\/ Note: compiler path may contain dashes in directory names\n std::string compiler = path::GetLastNode(compilerPath);\n std::string cross = path::GetContainingDir(compilerPath) + \"\/\"\n + compiler.substr(0, compiler.rfind('-') + 1);\n std::string arch = compiler.substr(0, compiler.find('-'));\n\n makefile << \"export CROSS_COMPILE := \" << cross << \"\\n\";\n makefile << \"export ARCH := \" << arch << \"\\n\";\n }\n makefile << \"\\n\";\n\n \/\/ Specify build rules\n makefile << \"all:\\n\";\n makefile << \"\\tmake -C $(KBUILD) M=\" + buildPath + \" modules\\n\";\n makefile << \"\\n\";\n makefile << \"clean:\\n\";\n makefile << \"\\t make -C $(KBUILD) M=\" + buildPath + \" clean\\n\";\n\n CloseFile(makefile);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate a build script for a pre-built kernel module.\n *\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::Generate\n(\n model::Module_t* modulePtr\n)\n{\n \/\/ Start the script with a comment, the file-level variable definitions, and\n \/\/ a set of generic rules.\n GenerateCommentHeader(modulePtr);\n script << \"builddir = \" << path::MakeAbsolute(buildParams.workingDir) << \"\\n\\n\";\n script << \"target = \" << buildParams.target << \"\\n\\n\";\n baseGeneratorPtr->GenerateIfgenFlagsDef();\n baseGeneratorPtr->GenerateBuildRules();\n\n if (!buildParams.codeGenOnly)\n {\n \/\/ Add build statements for the module.\n GenerateBuildStatements(modulePtr);\n }\n\n \/\/ Add a build statement for the build.ninja file itself.\n GenerateNinjaScriptBuildStatement(modulePtr);\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate a build script for a pre-built kernel module.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid Generate\n(\n model::Module_t* modulePtr,\n const mk::BuildParams_t& buildParams\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n std::string filePath = path::Minimize(buildParams.workingDir + \"\/build.ninja\");\n\n ModuleBuildScriptGenerator_t scriptGenerator(filePath, buildParams);\n scriptGenerator.Generate(modulePtr);\n}\n\n\n} \/\/ namespace ninja\n[kernelModules] Fix incorrect kernel arch for i586\/\/--------------------------------------------------------------------------------------------------\n\/**\n * @file moduleBuildScript.cpp\n *\n * Implementation of the build script generator for pre-built kernel modules.\n *\n *
\n *\n * Copyright (C) Sierra Wireless Inc.\n *\/\n\/\/--------------------------------------------------------------------------------------------------\n\n#include \"mkTools.h\"\n#include \"buildScriptCommon.h\"\n#include \"moduleBuildScript.h\"\n\nnamespace ninja\n{\n\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate comment header for a build script.\n *\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateCommentHeader\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n script << \"# Build script for module '\" << modulePtr->name << \"'\\n\"\n \"\\n\"\n \"# == Auto-generated file. Do not edit. ==\\n\"\n \"\\n\";\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Print to a given build script the build statements related to a given module.\n * If it's a pre-built module, just copy it. Otherwise generate a module Makefile and build it.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateBuildStatements\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n if (modulePtr->moduleBuildType == model::Module_t::Sources)\n {\n \/\/ In case of Sources, koFiles map will consist of only one element.\n \/\/ Hence, use the first element in koFiles for generating build statement.\n auto const it = modulePtr->koFiles.begin();\n if (it != modulePtr->koFiles.end())\n {\n script << \"build \" << \"$builddir\/\" << it->second->path << \": \";\n\n \/\/ No pre-built module: generate and invoke a Makefile\n GenerateMakefile(modulePtr);\n script << \"MakeKernelModule \" << \"$builddir\/\"\n << path::GetContainingDir(it->second->path) << \"\\n\";\n }\n else\n {\n throw mk::Exception_t(\n mk::format(LE_I18N(\"error: %s container of kernel object file is empty.\"),\n modulePtr->defFilePtr->path));\n }\n }\n else if (modulePtr->moduleBuildType == model::Module_t::Prebuilt)\n {\n for (auto const& it: modulePtr->koFiles)\n {\n script << \"build \" << \"$builddir\/\" << it.second->path << \": \";\n\n \/\/ Pre-built module: add build statement for bundling the .ko file\n script << \"BundleFile \" << it.first << \"\\n\"\n << \" modeFlags = u+rw-x,g+r-wx,o+r-wx\\n\";\n }\n }\n else\n {\n throw mk::Exception_t(\n mk::format(LE_I18N(\"error: %s must have either 'sources' or 'preBuilt' section.\"),\n modulePtr->defFilePtr->path));\n }\n script << \"\\n\";\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Write to a given build script the build statements for the build script itself.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateNinjaScriptBuildStatement\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n \/\/ The build.ninja depends on module .mdef and .ko files\n \/\/ Create a set of dependencies.\n std::set dependencies;\n\n for (auto const& it : modulePtr->koFiles)\n {\n dependencies.insert(it.first);\n }\n\n dependencies.insert(modulePtr->defFilePtr->path);\n \/\/ It also depends on changes to the mk tools.\n dependencies.insert(path::Combine(envVars::Get(\"LEGATO_ROOT\"), \"build\/tools\/mk\"));\n\n baseGeneratorPtr->GenerateNinjaScriptBuildStatement(dependencies);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate a Makefile for a kernel module.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::GenerateMakefile\n(\n model::Module_t* modulePtr\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n std::string buildPath = path::MakeAbsolute(buildParams.workingDir\n + \"\/modules\/\" + modulePtr->name);\n const std::string& compilerPath = buildParams.cCompilerPath;\n\n std::ofstream makefile;\n OpenFile(makefile, buildPath + \"\/Makefile\", buildParams.beVerbose);\n\n \/\/ Specify kernel module name and list all object files to link\n makefile << \"obj-m += \" << modulePtr->name << \".o\\n\";\n\n \/\/ Don't list object files in case of a single source file with module name\n if (modulePtr->cObjectFiles.size() > 1 ||\n modulePtr->cObjectFiles.front()->path != modulePtr->name + \".o\")\n {\n for (auto obj : modulePtr->cObjectFiles)\n {\n makefile << modulePtr->name << \"-objs += \" << obj->path << \"\\n\";\n }\n }\n makefile << \"\\n\";\n\n \/\/ Specify directory where the sources are located\n makefile << \"src = \" << modulePtr->dir << \"\\n\\n\";\n\n \/\/ Add compiler and linker options\n for (auto const &obj : modulePtr->cFlags)\n {\n makefile << \"ccflags-y += \" << obj << \"\\n\";\n }\n for (auto const &obj : modulePtr->ldFlags)\n {\n makefile << \"ldflags-y += \" << obj << \"\\n\";\n }\n makefile << \"\\n\";\n\n makefile << \"KBUILD := \" << modulePtr->kernelDir << \"\\n\";\n\n if (buildParams.target != \"localhost\")\n {\n \/\/ Specify the CROSS_COMPILE and ARCH environment variables\n \/\/ Note: compiler path may contain dashes in directory names\n std::string compiler = path::GetLastNode(compilerPath);\n std::string cross = path::GetContainingDir(compilerPath) + \"\/\"\n + compiler.substr(0, compiler.rfind('-') + 1);\n std::string arch = compiler.substr(0, compiler.find('-'));\n if ((arch == \"i586\") || (arch == \"i686\"))\n {\n arch = \"x86\";\n }\n\n makefile << \"export CROSS_COMPILE := \" << cross << \"\\n\";\n makefile << \"export ARCH := \" << arch << \"\\n\";\n }\n makefile << \"\\n\";\n\n \/\/ Specify build rules\n makefile << \"all:\\n\";\n makefile << \"\\tmake -C $(KBUILD) M=\" + buildPath + \" modules\\n\";\n makefile << \"\\n\";\n makefile << \"clean:\\n\";\n makefile << \"\\t make -C $(KBUILD) M=\" + buildPath + \" clean\\n\";\n\n CloseFile(makefile);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate a build script for a pre-built kernel module.\n *\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid ModuleBuildScriptGenerator_t::Generate\n(\n model::Module_t* modulePtr\n)\n{\n \/\/ Start the script with a comment, the file-level variable definitions, and\n \/\/ a set of generic rules.\n GenerateCommentHeader(modulePtr);\n script << \"builddir = \" << path::MakeAbsolute(buildParams.workingDir) << \"\\n\\n\";\n script << \"target = \" << buildParams.target << \"\\n\\n\";\n baseGeneratorPtr->GenerateIfgenFlagsDef();\n baseGeneratorPtr->GenerateBuildRules();\n\n if (!buildParams.codeGenOnly)\n {\n \/\/ Add build statements for the module.\n GenerateBuildStatements(modulePtr);\n }\n\n \/\/ Add a build statement for the build.ninja file itself.\n GenerateNinjaScriptBuildStatement(modulePtr);\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\/**\n * Generate a build script for a pre-built kernel module.\n **\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid Generate\n(\n model::Module_t* modulePtr,\n const mk::BuildParams_t& buildParams\n)\n\/\/--------------------------------------------------------------------------------------------------\n{\n std::string filePath = path::Minimize(buildParams.workingDir + \"\/build.ninja\");\n\n ModuleBuildScriptGenerator_t scriptGenerator(filePath, buildParams);\n scriptGenerator.Generate(modulePtr);\n}\n\n\n} \/\/ namespace ninja\n<|endoftext|>"} {"text":"#include \n#include \n#include \"catch.hh\"\n#include \"lib\/File.h\"\n#include \"test_crc_support.h\"\n\nvoid test_computing(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"123456789\";\n\n auto inFile = File::fromFileName(\n \"test-in.txt\",\n File::Mode::Write | File::Mode::Read | File::Mode::Binary);\n\n inFile->write(content.data(), content.size());\n inFile->seek(0, File::Origin::Start);\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::remove(\"test-in.txt\");\n}\n\nvoid test_appending(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"test content\";\n\n {\n auto inFile = File::fromFileName(\"test-in.txt\", File::Mode::Write);\n inFile->write(content.data(), content.size());\n REQUIRE(inFile->getSize() == content.size());\n }\n\n auto size1 = content.size();\n auto size2 = size1 + crc.getSpecs().numBytes;\n {\n auto inFile = File::fromFileName(\n \"test-in.txt\", File::Mode::Read | File::Mode::Binary);\n auto outFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Write | File::Mode::Binary);\n crc.applyPatch(\n checksum, size1, *inFile, *outFile, false, progress, progress);\n }\n\n {\n auto inFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Read | File::Mode::Binary);\n REQUIRE(inFile->getSize() == size2);\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::unique_ptr buf(new char[size1]);\n inFile->seek(0, File::Origin::Start);\n inFile->read(buf.get(), size1);\n REQUIRE(std::string(buf.get()) == content);\n std::remove(\"test-in.txt\");\n std::remove(\"test-out.txt\");\n }\n}\n\nvoid test_inserting(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"test content\";\n\n {\n auto inFile = File::fromFileName(\"test-in.txt\", File::Mode::Write);\n inFile->write(content.data(), content.size());\n REQUIRE(inFile->getSize() == content.size());\n }\n\n size_t offset1 = content.size() \/ 2;\n size_t offset2 = offset1 + crc.getSpecs().numBytes;\n size_t size = content.size() + crc.getSpecs().numBytes;\n\n {\n auto inFile = File::fromFileName(\n \"test-in.txt\", File::Mode::Read | File::Mode::Binary);\n auto outFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Write | File::Mode::Binary);\n crc.applyPatch(\n checksum, offset1, *inFile, *outFile, false, progress, progress);\n }\n\n {\n auto inFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Read | File::Mode::Binary);\n REQUIRE(inFile->getSize() == size);\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::unique_ptr buf(new char[size]);\n inFile->seek(0, File::Origin::Start);\n inFile->read(buf.get(), size);\n REQUIRE(std::string(buf.get(), offset1) == content.substr(0, offset1));\n REQUIRE(std::string(buf.get() + offset2, size - offset2)\n == content.substr(offset1, size - offset2));\n std::remove(\"test-in.txt\");\n std::remove(\"test-out.txt\");\n }\n}\n\nvoid test_overwriting(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"test content\";\n\n {\n auto inFile = File::fromFileName(\"test-in.txt\", File::Mode::Write);\n inFile->write(content.data(), content.size());\n REQUIRE(inFile->getSize() == content.size());\n }\n\n size_t offset = content.size() - crc.getSpecs().numBytes;\n\n {\n auto inFile = File::fromFileName(\n \"test-in.txt\", File::Mode::Read | File::Mode::Binary);\n auto outFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Write | File::Mode::Binary);\n crc.applyPatch(\n checksum, offset, *inFile, *outFile, true, progress, progress);\n }\n\n {\n auto inFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Read | File::Mode::Binary);\n REQUIRE(inFile->getSize() == content.size());\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::unique_ptr buf(new char[offset]);\n inFile->seek(0, File::Origin::Start);\n inFile->read(buf.get(), offset);\n REQUIRE(std::string(buf.get(), offset) == content.substr(0, offset));\n std::remove(\"test-in.txt\");\n std::remove(\"test-out.txt\");\n }\n}\nFixed buffer overflow in tests#include \n#include \n#include \"catch.hh\"\n#include \"lib\/File.h\"\n#include \"test_crc_support.h\"\n\nvoid test_computing(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"123456789\";\n\n auto inFile = File::fromFileName(\n \"test-in.txt\",\n File::Mode::Write | File::Mode::Read | File::Mode::Binary);\n\n inFile->write(content.data(), content.size());\n inFile->seek(0, File::Origin::Start);\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::remove(\"test-in.txt\");\n}\n\nvoid test_appending(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"test content\";\n\n {\n auto inFile = File::fromFileName(\"test-in.txt\", File::Mode::Write);\n inFile->write(content.data(), content.size());\n REQUIRE(inFile->getSize() == content.size());\n }\n\n auto size1 = content.size();\n auto size2 = size1 + crc.getSpecs().numBytes;\n {\n auto inFile = File::fromFileName(\n \"test-in.txt\", File::Mode::Read | File::Mode::Binary);\n auto outFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Write | File::Mode::Binary);\n crc.applyPatch(\n checksum, size1, *inFile, *outFile, false, progress, progress);\n }\n\n {\n auto inFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Read | File::Mode::Binary);\n REQUIRE(inFile->getSize() == size2);\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::unique_ptr buf(new char[size1]);\n inFile->seek(0, File::Origin::Start);\n inFile->read(buf.get(), size1);\n REQUIRE(std::string(buf.get(), size1) == content.substr(0, size1));\n std::remove(\"test-in.txt\");\n std::remove(\"test-out.txt\");\n }\n}\n\nvoid test_inserting(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"test content\";\n\n {\n auto inFile = File::fromFileName(\"test-in.txt\", File::Mode::Write);\n inFile->write(content.data(), content.size());\n REQUIRE(inFile->getSize() == content.size());\n }\n\n size_t offset1 = content.size() \/ 2;\n size_t offset2 = offset1 + crc.getSpecs().numBytes;\n size_t size = content.size() + crc.getSpecs().numBytes;\n\n {\n auto inFile = File::fromFileName(\n \"test-in.txt\", File::Mode::Read | File::Mode::Binary);\n auto outFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Write | File::Mode::Binary);\n crc.applyPatch(\n checksum, offset1, *inFile, *outFile, false, progress, progress);\n }\n\n {\n auto inFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Read | File::Mode::Binary);\n REQUIRE(inFile->getSize() == size);\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::unique_ptr buf(new char[size]);\n inFile->seek(0, File::Origin::Start);\n inFile->read(buf.get(), size);\n REQUIRE(std::string(buf.get(), offset1) == content.substr(0, offset1));\n REQUIRE(std::string(buf.get() + offset2, size - offset2)\n == content.substr(offset1, size - offset2));\n std::remove(\"test-in.txt\");\n std::remove(\"test-out.txt\");\n }\n}\n\nvoid test_overwriting(const CRC &crc, CRCType checksum)\n{\n Progress progress;\n std::string content = \"test content\";\n\n {\n auto inFile = File::fromFileName(\"test-in.txt\", File::Mode::Write);\n inFile->write(content.data(), content.size());\n REQUIRE(inFile->getSize() == content.size());\n }\n\n size_t offset = content.size() - crc.getSpecs().numBytes;\n\n {\n auto inFile = File::fromFileName(\n \"test-in.txt\", File::Mode::Read | File::Mode::Binary);\n auto outFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Write | File::Mode::Binary);\n crc.applyPatch(\n checksum, offset, *inFile, *outFile, true, progress, progress);\n }\n\n {\n auto inFile = File::fromFileName(\n \"test-out.txt\", File::Mode::Read | File::Mode::Binary);\n REQUIRE(inFile->getSize() == content.size());\n REQUIRE(crc.computeChecksum(*inFile, progress) == checksum);\n\n std::unique_ptr buf(new char[offset]);\n inFile->seek(0, File::Origin::Start);\n inFile->read(buf.get(), offset);\n REQUIRE(std::string(buf.get(), offset) == content.substr(0, offset));\n std::remove(\"test-in.txt\");\n std::remove(\"test-out.txt\");\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n#include \n\n#include \"webrtc\/modules\/audio_device\/android\/audio_device_template.h\"\n#include \"webrtc\/modules\/audio_device\/android\/audio_record_jni.h\"\n#include \"webrtc\/modules\/audio_device\/android\/audio_track_jni.h\"\n#include \"webrtc\/modules\/audio_device\/android\/opensles_input.h\"\n#include \"webrtc\/modules\/audio_device\/android\/opensles_output.h\"\n#include \"webrtc\/modules\/audio_device\/android\/test\/fake_audio_device_buffer.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n\n\/\/ Java globals\nstatic JavaVM* g_vm = NULL;\nstatic jclass g_osr = NULL;\n\nnamespace webrtc {\n\ntemplate \nclass OpenSlRunnerTemplate {\n public:\n OpenSlRunnerTemplate()\n : output_(0),\n input_(0, &output_) {\n output_.AttachAudioBuffer(&audio_buffer_);\n if (output_.Init() != 0) {\n assert(false);\n }\n if (output_.InitPlayout() != 0) {\n assert(false);\n }\n input_.AttachAudioBuffer(&audio_buffer_);\n if (input_.Init() != 0) {\n assert(false);\n }\n if (input_.InitRecording() != 0) {\n assert(false);\n }\n }\n\n ~OpenSlRunnerTemplate() {}\n\n void StartPlayRecord() {\n output_.StartPlayout();\n input_.StartRecording();\n }\n\n void StopPlayRecord() {\n \/\/ There are large enough buffers to compensate for recording and playing\n \/\/ jitter such that the timing of stopping playing or recording should not\n \/\/ result in over or underrun.\n input_.StopRecording();\n output_.StopPlayout();\n audio_buffer_.ClearBuffer();\n }\n\n void RegisterApplicationContext(\n JNIEnv* env,\n jobject obj,\n jobject context) {\n OutputType::SetAndroidAudioDeviceObjects(env, obj, context);\n InputType::SetAndroidAudioDeviceObjects(env, obj, context);\n }\n\n private:\n OutputType output_;\n InputType input_;\n FakeAudioDeviceBuffer audio_buffer_;\n};\n\nclass OpenSlRunner\n : public OpenSlRunnerTemplate {\n public:\n \/\/ Global class implementing native code.\n static OpenSlRunner* g_runner;\n\n\n OpenSlRunner() {}\n virtual ~OpenSlRunner() {}\n\n static JNIEXPORT void JNICALL RegisterApplicationContext(\n JNIEnv* env,\n jobject obj,\n jobject context) {\n assert(!g_runner); \/\/ Should only be called once.\n g_runner = new OpenSlRunner();\n }\n\n static JNIEXPORT void JNICALL Start(JNIEnv * env, jobject) {\n g_runner->StartPlayRecord();\n }\n\n static JNIEXPORT void JNICALL Stop(JNIEnv * env, jobject) {\n g_runner->StopPlayRecord();\n }\n};\n\nOpenSlRunner* OpenSlRunner::g_runner = NULL;\n\n} \/\/ namespace webrtc\n\njint JNI_OnLoad(JavaVM* vm, void* reserved) {\n \/\/ Only called once.\n assert(!g_vm);\n JNIEnv* env;\n if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) {\n return -1;\n }\n\n jclass local_osr = env->FindClass(\"org\/webrtc\/app\/OpenSlRunner\");\n assert(local_osr != NULL);\n g_osr = static_cast(env->NewGlobalRef(local_osr));\n JNINativeMethod nativeFunctions[] = {\n {\"RegisterApplicationContext\", \"(Landroid\/content\/Context;)V\",\n reinterpret_cast(\n &webrtc::OpenSlRunner::RegisterApplicationContext)},\n {\"Start\", \"()V\", reinterpret_cast(&webrtc::OpenSlRunner::Start)},\n {\"Stop\", \"()V\", reinterpret_cast(&webrtc::OpenSlRunner::Stop)}\n };\n int ret_val = env->RegisterNatives(g_osr, nativeFunctions, 3);\n if (ret_val != 0) {\n assert(false);\n }\n g_vm = vm;\n return JNI_VERSION_1_6;\n}\nAndroid, OpenSlDemo: fixes issue where app would crash as soon as the application is started.\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n#include \n\n#include \"webrtc\/modules\/audio_device\/android\/audio_device_template.h\"\n#include \"webrtc\/modules\/audio_device\/android\/audio_record_jni.h\"\n#include \"webrtc\/modules\/audio_device\/android\/audio_track_jni.h\"\n#include \"webrtc\/modules\/audio_device\/android\/opensles_input.h\"\n#include \"webrtc\/modules\/audio_device\/android\/opensles_output.h\"\n#include \"webrtc\/modules\/audio_device\/android\/test\/fake_audio_device_buffer.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n\n\/\/ Java globals\nstatic JavaVM* g_vm = NULL;\nstatic jclass g_osr = NULL;\n\nnamespace webrtc {\n\ntemplate \nclass OpenSlRunnerTemplate {\n public:\n OpenSlRunnerTemplate()\n : output_(0),\n input_(0, &output_) {\n output_.AttachAudioBuffer(&audio_buffer_);\n if (output_.Init() != 0) {\n assert(false);\n }\n if (output_.InitPlayout() != 0) {\n assert(false);\n }\n input_.AttachAudioBuffer(&audio_buffer_);\n if (input_.Init() != 0) {\n assert(false);\n }\n if (input_.InitRecording() != 0) {\n assert(false);\n }\n }\n\n ~OpenSlRunnerTemplate() {}\n\n void StartPlayRecord() {\n output_.StartPlayout();\n input_.StartRecording();\n }\n\n void StopPlayRecord() {\n \/\/ There are large enough buffers to compensate for recording and playing\n \/\/ jitter such that the timing of stopping playing or recording should not\n \/\/ result in over or underrun.\n input_.StopRecording();\n output_.StopPlayout();\n audio_buffer_.ClearBuffer();\n }\n\n private:\n OutputType output_;\n InputType input_;\n FakeAudioDeviceBuffer audio_buffer_;\n};\n\nclass OpenSlRunner\n : public OpenSlRunnerTemplate {\n public:\n \/\/ Global class implementing native code.\n static OpenSlRunner* g_runner;\n\n\n OpenSlRunner() {}\n virtual ~OpenSlRunner() {}\n\n static JNIEXPORT void JNICALL RegisterApplicationContext(\n JNIEnv* env,\n jobject obj,\n jobject context) {\n assert(!g_runner); \/\/ Should only be called once.\n \/\/ Register the application context in the superclass to avoid having to\n \/\/ qualify the template instantiation again.\n OpenSlesInput::SetAndroidAudioDeviceObjects(g_vm, env, context);\n OpenSlesOutput::SetAndroidAudioDeviceObjects(g_vm, env, context);\n g_runner = new OpenSlRunner();\n }\n\n static JNIEXPORT void JNICALL Start(JNIEnv * env, jobject) {\n g_runner->StartPlayRecord();\n }\n\n static JNIEXPORT void JNICALL Stop(JNIEnv * env, jobject) {\n g_runner->StopPlayRecord();\n }\n};\n\nOpenSlRunner* OpenSlRunner::g_runner = NULL;\n\n} \/\/ namespace webrtc\n\njint JNI_OnLoad(JavaVM* vm, void* reserved) {\n \/\/ Only called once.\n assert(!g_vm);\n JNIEnv* env;\n if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) {\n return -1;\n }\n\n jclass local_osr = env->FindClass(\"org\/webrtc\/app\/OpenSlRunner\");\n assert(local_osr != NULL);\n g_osr = static_cast(env->NewGlobalRef(local_osr));\n JNINativeMethod nativeFunctions[] = {\n {\"RegisterApplicationContext\", \"(Landroid\/content\/Context;)V\",\n reinterpret_cast(\n &webrtc::OpenSlRunner::RegisterApplicationContext)},\n {\"Start\", \"()V\", reinterpret_cast(&webrtc::OpenSlRunner::Start)},\n {\"Stop\", \"()V\", reinterpret_cast(&webrtc::OpenSlRunner::Stop)}\n };\n int ret_val = env->RegisterNatives(g_osr, nativeFunctions, 3);\n if (ret_val != 0) {\n assert(false);\n }\n g_vm = vm;\n return JNI_VERSION_1_6;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"StorageFlattening.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Bounds.h\"\n#include \"Parameter.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::pair;\nusing std::set;\n\nnamespace {\n\nclass FlattenDimensions : public IRMutator {\npublic:\n FlattenDimensions(const map> &e, const Target &t)\n : env(e), target(t) {}\n Scope scope;\nprivate:\n const map> &env;\n const Target ⌖\n Scope realizations;\n\n Expr flatten_args(const string &name, const vector &args) {\n bool internal = realizations.contains(name);\n Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n vector mins(args.size()), strides(args.size());\n\n for (size_t i = 0; i < args.size(); i++) {\n string dim = std::to_string(i);\n string stride_name = name + \".stride.\" + dim;\n string min_name = name + \".min.\" + dim;\n string stride_name_constrained = stride_name + \".constrained\";\n string min_name_constrained = min_name + \".constrained\";\n if (scope.contains(stride_name_constrained)) {\n stride_name = stride_name_constrained;\n }\n if (scope.contains(min_name_constrained)) {\n min_name = min_name_constrained;\n }\n strides[i] = Variable::make(Int(32), stride_name);\n mins[i] = Variable::make(Int(32), min_name);\n }\n\n if (internal) {\n \/\/ f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This\n \/\/ strategy makes sense when we expect x to cancel with\n \/\/ something in xmin. We use this for internal allocations\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast(args[i] - mins[i]) * cast(strides[i]);\n } else {\n idx += (args[i] - mins[i]) * strides[i];\n }\n }\n } else {\n \/\/ f(x, y) -> f[x*stride + y*ystride - (xstride*xmin +\n \/\/ ystride*ymin)]. The idea here is that the last term\n \/\/ will be pulled outside the inner loop. We use this for\n \/\/ external buffers, where the mins and strides are likely\n \/\/ to be symbolic\n Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast(args[i]) * cast(strides[i]);\n base += cast(mins[i]) * cast(strides[i]);\n } else {\n idx += args[i] * strides[i];\n base += mins[i] * strides[i];\n }\n }\n idx -= base;\n }\n\n return idx;\n }\n\n using IRMutator::visit;\n\n void visit(const Realize *op) {\n realizations.push(op->name, 0);\n\n Stmt body = mutate(op->body);\n\n \/\/ Compute the size\n std::vector extents;\n for (size_t i = 0; i < op->bounds.size(); i++) {\n extents.push_back(op->bounds[i].extent);\n extents[i] = mutate(extents[i]);\n }\n Expr condition = mutate(op->condition);\n\n realizations.pop(op->name);\n\n vector storage_permutation;\n {\n auto iter = env.find(op->name);\n Function f = iter->second.first;\n internal_assert(iter != env.end()) << \"Realize node refers to function not in environment.\\n\";\n const vector &storage_dims = f.schedule().storage_dims();\n const vector &args = f.args();\n for (size_t i = 0; i < storage_dims.size(); i++) {\n for (size_t j = 0; j < args.size(); j++) {\n if (args[j] == storage_dims[i].var) {\n storage_permutation.push_back((int)j);\n Expr alignment = storage_dims[i].alignment;\n if (alignment.defined()) {\n extents[j] = ((extents[j] + alignment - 1)\/alignment)*alignment;\n }\n }\n }\n internal_assert(storage_permutation.size() == i+1);\n }\n }\n\n internal_assert(storage_permutation.size() == op->bounds.size());\n\n stmt = body;\n internal_assert(op->types.size() == 1);\n\n \/\/ Make the names for the mins, extents, and strides\n int dims = op->bounds.size();\n vector min_name(dims), extent_name(dims), stride_name(dims);\n for (int i = 0; i < dims; i++) {\n string d = std::to_string(i);\n min_name[i] = op->name + \".min.\" + d;\n stride_name[i] = op->name + \".stride.\" + d;\n extent_name[i] = op->name + \".extent.\" + d;\n }\n vector min_var(dims), extent_var(dims), stride_var(dims);\n for (int i = 0; i < dims; i++) {\n min_var[i] = Variable::make(Int(32), min_name[i]);\n extent_var[i] = Variable::make(Int(32), extent_name[i]);\n stride_var[i] = Variable::make(Int(32), stride_name[i]);\n }\n\n \/\/ Create a buffer_t object for this allocation.\n if (dims <= 4) {\n BufferBuilder builder;\n Expr first_elem = Load::make(op->types[0], op->name, 0, Buffer<>(), Parameter(),\n const_true(op->types[0].lanes()));\n builder.host = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);\n builder.type = op->types[0];\n builder.dimensions = dims;\n for (int i = 0; i < dims; i++) {\n builder.mins.push_back(min_var[i]);\n builder.extents.push_back(extent_var[i]);\n builder.strides.push_back(stride_var[i]);\n }\n stmt = LetStmt::make(op->name + \".buffer\", builder.build(), stmt);\n }\n\n \/\/ Make the allocation node\n stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt);\n\n \/\/ Compute the strides\n for (int i = (int)op->bounds.size()-1; i > 0; i--) {\n int prev_j = storage_permutation[i-1];\n int j = storage_permutation[i];\n Expr stride = stride_var[prev_j] * extent_var[prev_j];\n stmt = LetStmt::make(stride_name[j], stride, stmt);\n }\n\n \/\/ Innermost stride is one\n if (dims > 0) {\n int innermost = storage_permutation.empty() ? 0 : storage_permutation[0];\n stmt = LetStmt::make(stride_name[innermost], 1, stmt);\n }\n\n \/\/ Assign the mins and extents stored\n for (size_t i = op->bounds.size(); i > 0; i--) {\n stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt);\n stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt);\n }\n }\n\n void visit(const Provide *op) {\n internal_assert(op->values.size() == 1);\n\n Expr idx = mutate(flatten_args(op->name, op->args));\n Expr value = mutate(op->values[0]);\n stmt = Store::make(op->name, value, idx, Parameter(), const_true(value.type().lanes()));\n }\n\n void visit(const Call *op) {\n if (op->call_type == Call::Halide ||\n op->call_type == Call::Image) {\n internal_assert(op->value_index == 0);\n Expr idx = mutate(flatten_args(op->name, op->args));\n expr = Load::make(op->type, op->name, idx, op->image, op->param,\n const_true(op->type.lanes()));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const LetStmt *let) {\n \/\/ Discover constrained versions of things.\n bool constrained_version_exists = ends_with(let->name, \".constrained\");\n if (constrained_version_exists) {\n scope.push(let->name, 0);\n }\n\n IRMutator::visit(let);\n\n if (constrained_version_exists) {\n scope.pop(let->name);\n }\n }\n};\n\n\/\/ Realizations, stores, and loads must all be on types that are\n\/\/ multiples of 8-bits. This really only affects bools\nclass PromoteToMemoryType : public IRMutator {\n using IRMutator::visit;\n\n Type upgrade(Type t) {\n return t.with_bits(((t.bits() + 7)\/8)*8);\n }\n\n void visit(const Call *op) {\n if (op->is_intrinsic(Call::address_of)) {\n Expr load = mutate(op->args[0]);\n if (const Cast *cast = load.as()) {\n load = cast->value;\n }\n expr = Call::make(op->type, op->name, {load}, op->call_type);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Load *op) {\n Type t = upgrade(op->type);\n if (t != op->type) {\n expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index),\n op->image, op->param, mutate(op->predicate)));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n Type t = upgrade(op->value.type());\n if (t != op->value.type()) {\n stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index),\n op->param, mutate(op->predicate));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Allocate *op) {\n Type t = upgrade(op->type);\n if (t != op->type) {\n vector extents;\n for (Expr e : op->extents) {\n extents.push_back(mutate(e));\n }\n stmt = Allocate::make(op->name, t, extents,\n mutate(op->condition), mutate(op->body),\n mutate(op->new_expr), op->free_function);\n } else {\n IRMutator::visit(op);\n }\n }\n};\n\n\/\/ Connect Store nodes to their output buffers\nclass ConnectOutputBuffers : public IRMutator {\n using IRMutator::visit;\n\n void visit(const Store *op) {\n Parameter output_buf;\n auto it = env.find(op->name);\n if (it != env.end()) {\n const Function &f = it->second.first;\n int idx = it->second.second;\n\n \/\/ We only want to do this for actual pipeline outputs,\n \/\/ even though every Function has an output buffer. Any\n \/\/ constraints you set on the output buffer of a Func that\n \/\/ isn't actually an output is ignored. This is a language\n \/\/ wart.\n if (outputs.count(f.name())) {\n output_buf = f.output_buffers()[idx];\n }\n }\n\n if (output_buf.defined()) {\n stmt = Store::make(op->name, op->value, op->index, output_buf, const_true());\n } else {\n stmt = op;\n }\n }\n\n const map> &env;\n set outputs;\n\npublic:\n ConnectOutputBuffers(const std::map> &e,\n const vector &o) : env(e) {\n for (auto &f : o) {\n outputs.insert(f.name());\n }\n }\n};\n\n} \/\/ namespace\n\nStmt storage_flattening(Stmt s,\n const vector &outputs,\n const map &env,\n const Target &target) {\n \/\/ Make an environment that makes it easier to figure out which\n \/\/ Function corresponds to a tuple component. foo.0, foo.1, foo.2,\n \/\/ all point to the function foo.\n map> tuple_env;\n for (auto p : env) {\n if (p.second.outputs() > 1) {\n for (int i = 0; i < p.second.outputs(); i++) {\n tuple_env[p.first + \".\" + std::to_string(i)] = {p.second, i};\n }\n } else {\n tuple_env[p.first] = {p.second, 0};\n }\n }\n\n s = FlattenDimensions(tuple_env, target).mutate(s);\n s = PromoteToMemoryType().mutate(s);\n s = ConnectOutputBuffers(tuple_env, outputs).mutate(s);\n return s;\n}\n\n}\n}\nFix .min\/.stride symbols not being connected to Param#include \n\n#include \"StorageFlattening.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Bounds.h\"\n#include \"Parameter.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::pair;\nusing std::set;\n\nnamespace {\n\nclass FlattenDimensions : public IRMutator {\npublic:\n FlattenDimensions(const map> &e,\n const vector &o,\n const Target &t)\n : env(e), target(t) {\n for (auto &f : o) {\n outputs.insert(f.name());\n }\n }\n Scope scope;\nprivate:\n const map> &env;\n set outputs;\n const Target ⌖\n Scope realizations;\n\n Expr flatten_args(const string &name, const vector &args,\n const Buffer<> &buf, const Parameter ¶m) {\n bool internal = realizations.contains(name);\n Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n vector mins(args.size()), strides(args.size());\n\n ReductionDomain rdom;\n for (size_t i = 0; i < args.size(); i++) {\n string dim = std::to_string(i);\n string stride_name = name + \".stride.\" + dim;\n string min_name = name + \".min.\" + dim;\n string stride_name_constrained = stride_name + \".constrained\";\n string min_name_constrained = min_name + \".constrained\";\n if (scope.contains(stride_name_constrained)) {\n stride_name = stride_name_constrained;\n }\n if (scope.contains(min_name_constrained)) {\n min_name = min_name_constrained;\n }\n strides[i] = Variable::make(Int(32), stride_name, buf, param, rdom);\n mins[i] = Variable::make(Int(32), min_name, buf, param, rdom);\n }\n\n if (internal) {\n \/\/ f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This\n \/\/ strategy makes sense when we expect x to cancel with\n \/\/ something in xmin. We use this for internal allocations\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast(args[i] - mins[i]) * cast(strides[i]);\n } else {\n idx += (args[i] - mins[i]) * strides[i];\n }\n }\n } else {\n \/\/ f(x, y) -> f[x*stride + y*ystride - (xstride*xmin +\n \/\/ ystride*ymin)]. The idea here is that the last term\n \/\/ will be pulled outside the inner loop. We use this for\n \/\/ external buffers, where the mins and strides are likely\n \/\/ to be symbolic\n Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast(args[i]) * cast(strides[i]);\n base += cast(mins[i]) * cast(strides[i]);\n } else {\n idx += args[i] * strides[i];\n base += mins[i] * strides[i];\n }\n }\n idx -= base;\n }\n\n return idx;\n }\n\n using IRMutator::visit;\n\n void visit(const Realize *op) {\n realizations.push(op->name, 0);\n\n Stmt body = mutate(op->body);\n\n \/\/ Compute the size\n std::vector extents;\n for (size_t i = 0; i < op->bounds.size(); i++) {\n extents.push_back(op->bounds[i].extent);\n extents[i] = mutate(extents[i]);\n }\n Expr condition = mutate(op->condition);\n\n realizations.pop(op->name);\n\n vector storage_permutation;\n {\n auto iter = env.find(op->name);\n Function f = iter->second.first;\n internal_assert(iter != env.end()) << \"Realize node refers to function not in environment.\\n\";\n const vector &storage_dims = f.schedule().storage_dims();\n const vector &args = f.args();\n for (size_t i = 0; i < storage_dims.size(); i++) {\n for (size_t j = 0; j < args.size(); j++) {\n if (args[j] == storage_dims[i].var) {\n storage_permutation.push_back((int)j);\n Expr alignment = storage_dims[i].alignment;\n if (alignment.defined()) {\n extents[j] = ((extents[j] + alignment - 1)\/alignment)*alignment;\n }\n }\n }\n internal_assert(storage_permutation.size() == i+1);\n }\n }\n\n internal_assert(storage_permutation.size() == op->bounds.size());\n\n stmt = body;\n internal_assert(op->types.size() == 1);\n\n \/\/ Make the names for the mins, extents, and strides\n int dims = op->bounds.size();\n vector min_name(dims), extent_name(dims), stride_name(dims);\n for (int i = 0; i < dims; i++) {\n string d = std::to_string(i);\n min_name[i] = op->name + \".min.\" + d;\n stride_name[i] = op->name + \".stride.\" + d;\n extent_name[i] = op->name + \".extent.\" + d;\n }\n vector min_var(dims), extent_var(dims), stride_var(dims);\n for (int i = 0; i < dims; i++) {\n min_var[i] = Variable::make(Int(32), min_name[i]);\n extent_var[i] = Variable::make(Int(32), extent_name[i]);\n stride_var[i] = Variable::make(Int(32), stride_name[i]);\n }\n\n \/\/ Create a buffer_t object for this allocation.\n if (dims <= 4) {\n BufferBuilder builder;\n Expr first_elem = Load::make(op->types[0], op->name, 0, Buffer<>(), Parameter(),\n const_true(op->types[0].lanes()));\n builder.host = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);\n builder.type = op->types[0];\n builder.dimensions = dims;\n for (int i = 0; i < dims; i++) {\n builder.mins.push_back(min_var[i]);\n builder.extents.push_back(extent_var[i]);\n builder.strides.push_back(stride_var[i]);\n }\n stmt = LetStmt::make(op->name + \".buffer\", builder.build(), stmt);\n }\n\n \/\/ Make the allocation node\n stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt);\n\n \/\/ Compute the strides\n for (int i = (int)op->bounds.size()-1; i > 0; i--) {\n int prev_j = storage_permutation[i-1];\n int j = storage_permutation[i];\n Expr stride = stride_var[prev_j] * extent_var[prev_j];\n stmt = LetStmt::make(stride_name[j], stride, stmt);\n }\n\n \/\/ Innermost stride is one\n if (dims > 0) {\n int innermost = storage_permutation.empty() ? 0 : storage_permutation[0];\n stmt = LetStmt::make(stride_name[innermost], 1, stmt);\n }\n\n \/\/ Assign the mins and extents stored\n for (size_t i = op->bounds.size(); i > 0; i--) {\n stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt);\n stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt);\n }\n }\n\n void visit(const Provide *op) {\n internal_assert(op->values.size() == 1);\n\n Parameter output_buf;\n auto it = env.find(op->name);\n if (it != env.end()) {\n const Function &f = it->second.first;\n int idx = it->second.second;\n\n \/\/ We only want to do this for actual pipeline outputs,\n \/\/ even though every Function has an output buffer. Any\n \/\/ constraints you set on the output buffer of a Func that\n \/\/ isn't actually an output is ignored. This is a language\n \/\/ wart.\n if (outputs.count(f.name())) {\n output_buf = f.output_buffers()[idx];\n }\n }\n\n Expr idx = mutate(flatten_args(op->name, op->args, Buffer<>(), output_buf));\n Expr value = mutate(op->values[0]);\n stmt = Store::make(op->name, value, idx, output_buf, const_true(value.type().lanes()));\n }\n\n void visit(const Call *op) {\n if (op->call_type == Call::Halide ||\n op->call_type == Call::Image) {\n internal_assert(op->value_index == 0);\n Expr idx = mutate(flatten_args(op->name, op->args, op->image, op->param));\n expr = Load::make(op->type, op->name, idx, op->image, op->param,\n const_true(op->type.lanes()));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const LetStmt *let) {\n \/\/ Discover constrained versions of things.\n bool constrained_version_exists = ends_with(let->name, \".constrained\");\n if (constrained_version_exists) {\n scope.push(let->name, 0);\n }\n\n IRMutator::visit(let);\n\n if (constrained_version_exists) {\n scope.pop(let->name);\n }\n }\n};\n\n\/\/ Realizations, stores, and loads must all be on types that are\n\/\/ multiples of 8-bits. This really only affects bools\nclass PromoteToMemoryType : public IRMutator {\n using IRMutator::visit;\n\n Type upgrade(Type t) {\n return t.with_bits(((t.bits() + 7)\/8)*8);\n }\n\n void visit(const Call *op) {\n if (op->is_intrinsic(Call::address_of)) {\n Expr load = mutate(op->args[0]);\n if (const Cast *cast = load.as()) {\n load = cast->value;\n }\n expr = Call::make(op->type, op->name, {load}, op->call_type);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Load *op) {\n Type t = upgrade(op->type);\n if (t != op->type) {\n expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index),\n op->image, op->param, mutate(op->predicate)));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n Type t = upgrade(op->value.type());\n if (t != op->value.type()) {\n stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index),\n op->param, mutate(op->predicate));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Allocate *op) {\n Type t = upgrade(op->type);\n if (t != op->type) {\n vector extents;\n for (Expr e : op->extents) {\n extents.push_back(mutate(e));\n }\n stmt = Allocate::make(op->name, t, extents,\n mutate(op->condition), mutate(op->body),\n mutate(op->new_expr), op->free_function);\n } else {\n IRMutator::visit(op);\n }\n }\n};\n\n} \/\/ namespace\n\nStmt storage_flattening(Stmt s,\n const vector &outputs,\n const map &env,\n const Target &target) {\n \/\/ Make an environment that makes it easier to figure out which\n \/\/ Function corresponds to a tuple component. foo.0, foo.1, foo.2,\n \/\/ all point to the function foo.\n map> tuple_env;\n for (auto p : env) {\n if (p.second.outputs() > 1) {\n for (int i = 0; i < p.second.outputs(); i++) {\n tuple_env[p.first + \".\" + std::to_string(i)] = {p.second, i};\n }\n } else {\n tuple_env[p.first] = {p.second, 0};\n }\n }\n\n s = FlattenDimensions(tuple_env, outputs, target).mutate(s);\n s = PromoteToMemoryType().mutate(s);\n return s;\n}\n\n}\n}\n<|endoftext|>"} {"text":"#ifdef LINUX\n\n#include \"Os.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nusing namespace std;\n\nDisplay *display = NULL;\nint screen = 0;\nXIM xim = NULL;\n\n\n\nstruct OsWindowData {\n OsWindowData() { window = NULL; }\n ~OsWindowData() {\n glXDestroyContext(display, context);\n XDestroyIC(inputcontext);\n XDestroyWindow(display, window);\n }\n \n Window window;\n GLXContext context;\n XIC inputcontext;\n};\n\n\nvoid Os::Init() {\n display = XOpenDisplay(NULL);\n ASSERT(display);\n \n screen = DefaultScreen(display);\n \n xim = XOpenIM(display, NULL, NULL, NULL);\n ASSERT(xim);\n}\nvoid Os::ShutDown() {\n XCloseIM(xim);\n XCloseDisplay(display);\n}\n\nvector events;\n\nBool EventTester(Display *display, XEvent *event, XPointer arg) {\n return true; \/\/ hurrr\n}\nvoid Os::Think() { } \/\/ we don't actually do anything here\nvoid Os::WindowThink(OsWindowData* data) {\n XEvent event;\n while(XCheckIfEvent(display, &event, &EventTester, NULL)) {\n LOGF(\"Event incoming!\\n\");\n }\n}\n\n\nOsWindowData* Os::CreateWindow(const string& title, int x, int y, int width, int height, bool full_screen, short stencil_bits, const Image* icon, bool is_resizable) {\n OsWindowData *nw = new OsWindowData();\n \n \/\/ this is bad\n if(x == -1) x = 100;\n if(y == -1) y = 100;\n \n \/\/ I think there's a way to specify more of this but I'll be damned if I can find it\n XVisualInfo vinfo_template;\n vinfo_template.screen = screen;\n int vinfo_ct;\n XVisualInfo *visualinfo = XGetVisualInfo(display, VisualScreenMask, &vinfo_template, &vinfo_ct);\n ASSERT(visualinfo);\n ASSERT(vinfo_ct);\n \n XVisualInfo vinfo;\n bool found = false;\n for(int i = 0; i < vinfo_ct; i++) {\n int use_gl, rgba, doublebuffer, red_size, green_size, blue_size, alpha_size;\n glXGetConfig(display, &visualinfo[i], GLX_USE_GL, &use_gl);\n glXGetConfig(display, &visualinfo[i], GLX_RGBA, &rgba);\n glXGetConfig(display, &visualinfo[i], GLX_DOUBLEBUFFER, &doublebuffer);\n glXGetConfig(display, &visualinfo[i], GLX_RED_SIZE, &red_size);\n glXGetConfig(display, &visualinfo[i], GLX_GREEN_SIZE, &green_size);\n glXGetConfig(display, &visualinfo[i], GLX_BLUE_SIZE, &blue_size);\n glXGetConfig(display, &visualinfo[i], GLX_ALPHA_SIZE, &alpha_size);\n \/\/LOGF(\"%d %d %d %d %d %d %d\", use_gl, rgba, doublebuffer, red_size, green_size, blue_size, alpha_size);\n \n \n if(use_gl && rgba && doublebuffer && red_size == 8 && green_size == 8 && blue_size == 8 && alpha_size == 8) {\n LOGF(\"Found something!\");\n found = true;\n vinfo = visualinfo[i]; \/\/ I'm just going to hope the rest of the values are appropriate, because, really, who knows\n break;\n }\n }\n \n ASSERT(found);\n \n nw->context = glXCreateContext(display, &vinfo, NULL, True);\n ASSERT(nw->context);\n \n nw->window = XCreateWindow(display, RootWindow(display, screen), x, y, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, 0, NULL); \/\/ I don't know if I need anything further here\n \n SetTitle(nw, title);\n \n \/\/ I think in here is where we're meant to set window styles and stuff\n \n nw->inputcontext = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, nw->window, XNFocusWindow, nw->window, NULL);\n ASSERT(nw->inputcontext);\n \n XFree(visualinfo);\n \n XMapWindow(display, nw->window);\n \n SetCurrentContext(nw);\n \n return nw;\n}\n\nvoid Os::SetCurrentContext(OsWindowData* data) {\n glXMakeCurrent(display, data->window, data->context);\n}\n\n\n\/\/ Destroys a window that is completely or partially created.\nvoid Os::DestroyWindow(OsWindowData* data) {\n delete data;\n}\n\nbool Os::IsWindowMinimized(const OsWindowData* data) {\n return false;\n}\n\nvoid Os::GetWindowFocusState(OsWindowData* data, bool* is_in_focus, bool* focus_changed) {\n *is_in_focus = true;\n *focus_changed = false;\n}\n\nvoid Os::GetWindowPosition(const OsWindowData* data, int* x, int* y) {\n XWindowAttributes attrs;\n XGetWindowAttributes(display, data->window, &attrs);\n *x = attrs.x;\n *y = attrs.y;\n}\n\nvoid Os::GetWindowSize(const OsWindowData* data, int* width, int* height) {\n XWindowAttributes attrs;\n XGetWindowAttributes(display, data->window, &attrs);\n *width = attrs.width;\n *height = attrs.height;\n}\n\nvoid Os::SetTitle(OsWindowData* data, const string& title) {\n XStoreName(display, data->window, title.c_str());\n}\n\nvoid Os::SetIcon(OsWindowData *window, const Image *icon) {\n fprintf(stderr, \"Os::SetIcon(%p, %p)\\n\", window, icon); \/\/ TBI\n}\n\nvoid Os::SetWindowSize(OsWindowData *window, int width, int height) {\n fprintf(stderr, \"Os::SetWindowSize(%p, %d, %d)\\n\", window, width, height); \/\/ TBI\n}\n\n\n\/\/ Input functions\n\/\/ ===============\n\n\/\/ See Os.h\n\nvector Os::GetInputEvents(OsWindowData *window) {\n vector ret; \/\/ weeeeeeeeeeee\n ret.swap(events);\n \n Window root, child;\n int x, y, winx, winy;\n unsigned int mask;\n XQueryPointer(display, window->window, &root, &child, &x, &y, &winx, &winy, &mask);\n \n ret.push_back(Os::KeyEvent(GetTime(), x, y, mask & (1 << 4), mask & LockMask));\n \n return ret;\n}\n\nvoid Os::SetMousePosition(int x, int y) { \/\/ TBI\n}\n\nvoid Os::ShowMouseCursor(bool is_shown) { \/\/ TBI\n}\n\nvoid Os::RefreshJoysticks(OsWindowData *window) { \/\/ TBI\n}\n\nint Os::GetNumJoysticks(OsWindowData *window) { \/\/ TBI\n return 0;\n}\n\n\/\/ Threading functions\n\/\/ ===================\n\n#include \n\nvoid Os::StartThread(void(*thread_function)(void*), void* data) {\n pthread_t thread;\n if (pthread_create(&thread, NULL, (void*(*)(void*))thread_function, data) != 0) {\n printf(\"Error forking thread\\n\");\n }\n}\n\nstruct OsMutex {\n pthread_mutex_t mutex;\n};\n\nOsMutex* Os::NewMutex() {\n OsMutex* mutex = new OsMutex;\n pthread_mutex_init(&mutex->mutex, NULL);\n return mutex;\n}\n\nvoid Os::DeleteMutex(OsMutex* mutex) {\n pthread_mutex_destroy(&mutex->mutex);\n delete mutex;\n}\n\nvoid Os::AcquireMutex(OsMutex* mutex) {\n pthread_mutex_lock(&mutex->mutex);\n}\n\nvoid Os::ReleaseMutex(OsMutex* mutex) {\n pthread_mutex_unlock(&mutex->mutex);\n}\n\n\/\/ Miscellaneous functions\n\/\/ =======================\n\nvoid Os::MessageBox(const string& title, const string& message) { \/\/ TBI\n fprintf(stderr,\"MessageBox [%s]: [%s]\\n\", title.c_str(), message.c_str());\n}\n\nvector > Os::GetFullScreenModes() { \/\/ TBI\n return vector >(1,pair(640,480));\n}\n\n\nvoid Os::Sleep(int t) {\n usleep(t*1000);\n}\n\nint Os::GetTime() {\n return GetTimeMicro() \/ 1000;\n}\nlong long Os::GetTimeMicro() {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (long long)tv.tv_sec * 1000000 + tv.tv_usec;\n}\n\n\nvoid Os::SwapBuffers(OsWindowData* data) {\n glXSwapBuffers(display, data->window);\n}\n\nint Os::GetRefreshRate() { \/\/ TBI\n \/\/fprintf(stderr,\"OS::GetRefreshRate()\\n\");\n return 60;\n}\n\nvoid Os::EnableVSync(bool is_enable) { \/\/ TBI\n fprintf(stderr,\"OS::EnableVSync(%d)\\n\", is_enable);\n}\n\n\nvector Os::ListFiles(const string &directory) { \/\/ TBI\n fprintf(stderr,\"OS::ListFiles(%s)\\n\", directory.c_str());\n return vector();\n}\n\nvector Os::ListSubdirectories(const string &directory) { \/\/ TBI\n fprintf(stderr,\"OS::ListSubdirectories(%s)\\n\", directory.c_str());\n return vector();\n}\n\n\n#endif \/\/ LINUX\n\nthings mostly work#ifdef LINUX\n\n#include \"Os.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nusing namespace std;\n\nDisplay *display = NULL;\nint screen = 0;\nXIM xim = NULL;\n\nstatic long long gtm() {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (long long)tv.tv_sec * 1000000 + tv.tv_usec;\n}\nstatic int gt() {\n return gtm() \/ 1000;\n}\n\nstruct OsWindowData {\n OsWindowData() { window = NULL; }\n ~OsWindowData() {\n glXDestroyContext(display, context);\n XDestroyIC(inputcontext);\n XDestroyWindow(display, window);\n }\n \n Window window;\n GLXContext context;\n XIC inputcontext;\n};\n\n\nvoid Os::Init() {\n display = XOpenDisplay(NULL);\n ASSERT(display);\n \n screen = DefaultScreen(display);\n \n xim = XOpenIM(display, NULL, NULL, NULL);\n ASSERT(xim);\n}\nvoid Os::ShutDown() {\n XCloseIM(xim);\n XCloseDisplay(display);\n}\n\nvector events;\nstatic bool SynthKey(const KeySym &sym, bool pushed, const XEvent &event, Window window, Os::KeyEvent *ev) {\n \/\/ mostly ignored\n Window root, child;\n int x, y, winx, winy;\n unsigned int mask;\n XQueryPointer(display, window, &root, &child, &x, &y, &winx, &winy, &mask);\n \n KeySym throwaway_lower, key;\n XConvertCase(sym, &throwaway_lower, &key);\n\n GlopKey ki = 0;\n switch(key) {\n case XK_A: ki = tolower('A'); break;\n case XK_B: ki = tolower('B'); break;\n case XK_C: ki = tolower('C'); break;\n case XK_D: ki = tolower('D'); break;\n case XK_E: ki = tolower('E'); break;\n case XK_F: ki = tolower('F'); break;\n case XK_G: ki = tolower('G'); break;\n case XK_H: ki = tolower('H'); break;\n case XK_I: ki = tolower('I'); break;\n case XK_J: ki = tolower('J'); break;\n case XK_K: ki = tolower('K'); break;\n case XK_L: ki = tolower('L'); break;\n case XK_M: ki = tolower('M'); break;\n case XK_N: ki = tolower('N'); break;\n case XK_O: ki = tolower('O'); break;\n case XK_P: ki = tolower('P'); break;\n case XK_Q: ki = tolower('Q'); break;\n case XK_R: ki = tolower('R'); break;\n case XK_S: ki = tolower('S'); break;\n case XK_T: ki = tolower('T'); break;\n case XK_U: ki = tolower('U'); break;\n case XK_V: ki = tolower('V'); break;\n case XK_W: ki = tolower('W'); break;\n case XK_X: ki = tolower('X'); break;\n case XK_Y: ki = tolower('Y'); break;\n case XK_Z: ki = tolower('Z'); break;\n \n case XK_0: ki = '0'; break;\n case XK_1: ki = '1'; break;\n case XK_2: ki = '2'; break;\n case XK_3: ki = '3'; break;\n case XK_4: ki = '4'; break;\n case XK_5: ki = '5'; break;\n case XK_6: ki = '6'; break;\n case XK_7: ki = '7'; break;\n case XK_8: ki = '8'; break;\n case XK_9: ki = '9'; break;\n \n case XK_F1: ki = kKeyF1; break;\n case XK_F2: ki = kKeyF2; break;\n case XK_F3: ki = kKeyF3; break;\n case XK_F4: ki = kKeyF4; break;\n case XK_F5: ki = kKeyF5; break;\n case XK_F6: ki = kKeyF6; break;\n case XK_F7: ki = kKeyF7; break;\n case XK_F8: ki = kKeyF8; break;\n case XK_F9: ki = kKeyF9; break;\n case XK_F10: ki = kKeyF10; break;\n case XK_F11: ki = kKeyF11; break;\n case XK_F12: ki = kKeyF12; break;\n \n case XK_KP_0: ki = kKeyPad0; break;\n case XK_KP_1: ki = kKeyPad1; break;\n case XK_KP_2: ki = kKeyPad2; break;\n case XK_KP_3: ki = kKeyPad3; break;\n case XK_KP_4: ki = kKeyPad4; break;\n case XK_KP_5: ki = kKeyPad5; break;\n case XK_KP_6: ki = kKeyPad6; break;\n case XK_KP_7: ki = kKeyPad7; break;\n case XK_KP_8: ki = kKeyPad8; break;\n case XK_KP_9: ki = kKeyPad9; break;\n \n case XK_Left: ki = kKeyLeft; break;\n case XK_Right: ki = kKeyRight; break;\n case XK_Up: ki = kKeyUp; break;\n case XK_Down: ki = kKeyDown; break;\n \n case XK_BackSpace: ki = kKeyBackspace; break;\n case XK_Tab: ki = kKeyTab; break;\n case XK_KP_Enter: ki = kKeyPadEnter; break;\n case XK_Return: ki = kKeyReturn; break;\n case XK_Escape: ki = kKeyEscape; break;\n \n case XK_Shift_L: ki = kKeyLeftShift; break;\n case XK_Shift_R: ki = kKeyRightShift; break;\n case XK_Control_L: ki = kKeyLeftControl; break;\n case XK_Control_R: ki = kKeyRightControl; break;\n case XK_Alt_L: ki = kKeyLeftAlt; break;\n case XK_Alt_R: ki = kKeyRightAlt; break;\n case XK_Super_L: ki = kKeyLeftGui; break;\n case XK_Super_R: ki = kKeyRightGui; break;\n \n case XK_KP_Divide: ki = kKeyPadDivide; break;\n case XK_KP_Multiply: ki = kKeyPadMultiply; break;\n case XK_KP_Subtract: ki = kKeyPadSubtract; break;\n case XK_KP_Add: ki = kKeyPadAdd; break;\n \n case XK_dead_grave: ki = '`'; break;\n case XK_minus: ki = '-'; break;\n case XK_equal: ki = '='; break;\n case XK_bracketleft: ki = '['; break;\n case XK_bracketright: ki = ']'; break;\n case XK_backslash: ki = '\\\\'; break;\n case XK_semicolon: ki = ';'; break;\n case XK_dead_acute: ki = '\\''; break;\n case XK_comma: ki = ','; break;\n case XK_period: ki = '.'; break;\n case XK_slash: ki = '\/'; break;\n case XK_space: ki = '\/'; break;\n }\n \n if(ki == 0)\n return false;\n \n *ev = Os::KeyEvent(ki, pushed, gt(), winx, winy, event.xkey.state & (1 << 4), event.xkey.state & LockMask);\n return true;\n}\nstatic bool SynthButton(int button, bool pushed, const XEvent &event, Window window, Os::KeyEvent *ev) {\n \/\/ mostly ignored\n Window root, child;\n int x, y, winx, winy;\n unsigned int mask;\n XQueryPointer(display, window, &root, &child, &x, &y, &winx, &winy, &mask);\n \n GlopKey ki;\n if(button == Button1)\n ki = kMouseLButton;\n else if(button == Button2)\n ki = kMouseMButton;\n else if(button == Button3)\n ki = kMouseRButton;\n \/*\n else if(button == Button4)\n ki = kMouseWheelUp; \/\/ these might be inverted so they're disabled for now\n else if(button == Button5)\n ki = kMouseWheelDown;*\/\n else\n return false;\n \n *ev = Os::KeyEvent(ki, pushed, gt(), winx, winy, event.xkey.state & (1 << 4), event.xkey.state & LockMask);\n return true;\n}\n\nstatic bool SynthMotion(int dx, int dy, const XEvent &event, Window window, Os::KeyEvent *ev) {\n \/\/ mostly ignored\n Window root, child;\n int x, y, winx, winy;\n unsigned int mask;\n XQueryPointer(display, window, &root, &child, &x, &y, &winx, &winy, &mask);\n \n *ev = Os::KeyEvent(dx, dy, gt(), winx, winy, event.xkey.state & (1 << 4), event.xkey.state & LockMask);\n return true;\n}\n\nBool EventTester(Display *display, XEvent *event, XPointer arg) {\n return true; \/\/ hurrr\n}\nvoid Os::Think() { } \/\/ we don't actually do anything here\nvoid Os::WindowThink(OsWindowData* data) {\n XEvent event;\n while(XCheckIfEvent(display, &event, &EventTester, NULL)) {\n Os::KeyEvent ev(0, 0, 0, 0, 0); \/\/ fffff\n switch(event.type) {\n case KeyPress: {\n LOGF(\"keypress\");\n char buf[2];\n KeySym sym;\n XComposeStatus status;\n \n XLookupString(&event.xkey, buf, sizeof(buf), &sym, &status);\n \n if(SynthKey(sym, true, event, data->window, &ev))\n events.push_back(ev);\n break;\n }\n \n case KeyRelease: {\n char buf[2];\n KeySym sym;\n XComposeStatus status;\n \n XLookupString(&event.xkey, buf, sizeof(buf), &sym, &status);\n \n if(SynthKey(sym, false, event, data->window, &ev))\n events.push_back(ev);\n break;\n }\n \n case ButtonPress:\n LOGF(\"buttonpress\");\n if(SynthButton(event.xbutton.button, true, event, data->window, &ev))\n events.push_back(ev);\n break;\n \n case ButtonRelease:\n if(SynthButton(event.xbutton.button, false, event, data->window, &ev))\n events.push_back(ev);\n break;\n\n case MotionNotify:\n if(SynthMotion(event.xmotion.x, event.xmotion.y, event, data->window, &ev))\n events.push_back(ev);\n break;\n \n case FocusIn:\n XSetICFocus(data->inputcontext);\n break;\n \n case FocusOut:\n XUnsetICFocus(data->inputcontext);\n break;\n }\n }\n}\n\n\nOsWindowData* Os::CreateWindow(const string& title, int x, int y, int width, int height, bool full_screen, short stencil_bits, const Image* icon, bool is_resizable) {\n OsWindowData *nw = new OsWindowData();\n \n \/\/ this is bad\n if(x == -1) x = 100;\n if(y == -1) y = 100;\n \n \/\/ I think there's a way to specify more of this but I'll be damned if I can find it\n XVisualInfo vinfo_template;\n vinfo_template.screen = screen;\n int vinfo_ct;\n XVisualInfo *visualinfo = XGetVisualInfo(display, VisualScreenMask, &vinfo_template, &vinfo_ct);\n ASSERT(visualinfo);\n ASSERT(vinfo_ct);\n \n XVisualInfo vinfo;\n bool found = false;\n for(int i = 0; i < vinfo_ct; i++) {\n int use_gl, rgba, doublebuffer, red_size, green_size, blue_size, alpha_size;\n glXGetConfig(display, &visualinfo[i], GLX_USE_GL, &use_gl);\n glXGetConfig(display, &visualinfo[i], GLX_RGBA, &rgba);\n glXGetConfig(display, &visualinfo[i], GLX_DOUBLEBUFFER, &doublebuffer);\n glXGetConfig(display, &visualinfo[i], GLX_RED_SIZE, &red_size);\n glXGetConfig(display, &visualinfo[i], GLX_GREEN_SIZE, &green_size);\n glXGetConfig(display, &visualinfo[i], GLX_BLUE_SIZE, &blue_size);\n glXGetConfig(display, &visualinfo[i], GLX_ALPHA_SIZE, &alpha_size);\n \/\/LOGF(\"%d %d %d %d %d %d %d\", use_gl, rgba, doublebuffer, red_size, green_size, blue_size, alpha_size);\n \n \n if(use_gl && rgba && doublebuffer && red_size == 8 && green_size == 8 && blue_size == 8 && alpha_size == 8) {\n LOGF(\"Found something!\");\n found = true;\n vinfo = visualinfo[i]; \/\/ I'm just going to hope the rest of the values are appropriate, because, really, who knows\n break;\n }\n }\n \n ASSERT(found);\n \n nw->context = glXCreateContext(display, &vinfo, NULL, True);\n ASSERT(nw->context);\n \n \/\/ Define the window attributes\n XSetWindowAttributes attribs;\n attribs.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask | FocusChangeMask;\n nw->window = XCreateWindow(display, RootWindow(display, screen), x, y, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, CWEventMask, &attribs); \/\/ I don't know if I need anything further here\n \n SetTitle(nw, title);\n \n \/\/ I think in here is where we're meant to set window styles and stuff\n \n nw->inputcontext = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, nw->window, XNFocusWindow, nw->window, NULL);\n ASSERT(nw->inputcontext);\n \n XFree(visualinfo);\n \n XMapWindow(display, nw->window);\n \n SetCurrentContext(nw);\n \n return nw;\n}\n\nvoid Os::SetCurrentContext(OsWindowData* data) {\n glXMakeCurrent(display, data->window, data->context);\n}\n\n\n\/\/ Destroys a window that is completely or partially created.\nvoid Os::DestroyWindow(OsWindowData* data) {\n delete data;\n}\n\nbool Os::IsWindowMinimized(const OsWindowData* data) {\n return false;\n}\n\nvoid Os::GetWindowFocusState(OsWindowData* data, bool* is_in_focus, bool* focus_changed) {\n *is_in_focus = true;\n *focus_changed = false;\n}\n\nvoid Os::GetWindowPosition(const OsWindowData* data, int* x, int* y) {\n XWindowAttributes attrs;\n XGetWindowAttributes(display, data->window, &attrs);\n *x = attrs.x;\n *y = attrs.y;\n}\n\nvoid Os::GetWindowSize(const OsWindowData* data, int* width, int* height) {\n XWindowAttributes attrs;\n XGetWindowAttributes(display, data->window, &attrs);\n *width = attrs.width;\n *height = attrs.height;\n}\n\nvoid Os::SetTitle(OsWindowData* data, const string& title) {\n XStoreName(display, data->window, title.c_str());\n}\n\nvoid Os::SetIcon(OsWindowData *window, const Image *icon) {\n fprintf(stderr, \"Os::SetIcon(%p, %p)\\n\", window, icon); \/\/ TBI\n}\n\nvoid Os::SetWindowSize(OsWindowData *window, int width, int height) {\n fprintf(stderr, \"Os::SetWindowSize(%p, %d, %d)\\n\", window, width, height); \/\/ TBI\n}\n\n\n\/\/ Input functions\n\/\/ ===============\n\n\/\/ See Os.h\n\nvector Os::GetInputEvents(OsWindowData *window) {\n vector ret; \/\/ weeeeeeeeeeee\n ret.swap(events);\n \n Window root, child;\n int x, y, winx, winy;\n unsigned int mask;\n XQueryPointer(display, window->window, &root, &child, &x, &y, &winx, &winy, &mask);\n \n if(ret.size())\n LOGF(\"%d events\\n\", ret.size());\n \n ret.push_back(Os::KeyEvent(gt(), winx, winy, mask & (1 << 4), mask & LockMask));\n \n return ret;\n}\n\nvoid Os::SetMousePosition(int x, int y) { \/\/ TBI\n}\n\nvoid Os::ShowMouseCursor(bool is_shown) { \/\/ TBI\n}\n\nvoid Os::RefreshJoysticks(OsWindowData *window) { \/\/ TBI\n}\n\nint Os::GetNumJoysticks(OsWindowData *window) { \/\/ TBI\n return 0;\n}\n\n\/\/ Threading functions\n\/\/ ===================\n\n#include \n\nvoid Os::StartThread(void(*thread_function)(void*), void* data) {\n pthread_t thread;\n if (pthread_create(&thread, NULL, (void*(*)(void*))thread_function, data) != 0) {\n printf(\"Error forking thread\\n\");\n }\n}\n\nstruct OsMutex {\n pthread_mutex_t mutex;\n};\n\nOsMutex* Os::NewMutex() {\n OsMutex* mutex = new OsMutex;\n pthread_mutex_init(&mutex->mutex, NULL);\n return mutex;\n}\n\nvoid Os::DeleteMutex(OsMutex* mutex) {\n pthread_mutex_destroy(&mutex->mutex);\n delete mutex;\n}\n\nvoid Os::AcquireMutex(OsMutex* mutex) {\n pthread_mutex_lock(&mutex->mutex);\n}\n\nvoid Os::ReleaseMutex(OsMutex* mutex) {\n pthread_mutex_unlock(&mutex->mutex);\n}\n\n\/\/ Miscellaneous functions\n\/\/ =======================\n\nvoid Os::MessageBox(const string& title, const string& message) { \/\/ TBI\n fprintf(stderr,\"MessageBox [%s]: [%s]\\n\", title.c_str(), message.c_str());\n}\n\nvector > Os::GetFullScreenModes() { \/\/ TBI\n return vector >(1,pair(640,480));\n}\n\n\nvoid Os::Sleep(int t) {\n usleep(t*1000);\n}\n\nint Os::GetTime() {\n return gt();\n}\nlong long Os::GetTimeMicro() {\n return gtm();\n}\n\n\nvoid Os::SwapBuffers(OsWindowData* data) {\n glXSwapBuffers(display, data->window);\n}\n\nint Os::GetRefreshRate() { \/\/ TBI\n \/\/fprintf(stderr,\"OS::GetRefreshRate()\\n\");\n return 60;\n}\n\nvoid Os::EnableVSync(bool is_enable) { \/\/ TBI\n fprintf(stderr,\"OS::EnableVSync(%d)\\n\", is_enable);\n}\n\n\nvector Os::ListFiles(const string &directory) { \/\/ TBI\n fprintf(stderr,\"OS::ListFiles(%s)\\n\", directory.c_str());\n return vector();\n}\n\nvector Os::ListSubdirectories(const string &directory) { \/\/ TBI\n fprintf(stderr,\"OS::ListSubdirectories(%s)\\n\", directory.c_str());\n return vector();\n}\n\n\n#endif \/\/ LINUX\n\n<|endoftext|>"} {"text":"\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2017 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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 \n#include \n#include \n#include \n#include \n\nextern void default_stdout_handlers();\nextern void __platform_init();\n\nextern \"C\" {\n void __init_serial1();\n void __init_sanity_checks();\n void kernel_sanity_checks();\n uintptr_t _multiboot_free_begin(uintptr_t boot_addr);\n uintptr_t _move_symbols(uintptr_t loc);\n void _init_bss();\n void _init_heap(uintptr_t);\n void _init_c_runtime();\n void _init_syscalls();\n void __libc_init_array();\n uintptr_t _end;\n}\n\nextern \"C\"\nvoid kernel_start(uintptr_t magic, uintptr_t addr)\n{\n\n \/\/ Initialize serial port 1\n __init_serial1();\n\n \/\/ generate checksums of read-only areas etc.\n __init_sanity_checks();\n\n \/\/ Determine where free memory starts\n uintptr_t free_mem_begin = reinterpret_cast(&_end);\n\n if (magic == MULTIBOOT_BOOTLOADER_MAGIC) {\n free_mem_begin = _multiboot_free_begin(addr);\n }\n\n \/\/ Preserve symbols from the ELF binary\n free_mem_begin += _move_symbols(free_mem_begin);\n\n \/\/ Initialize zero-initialized vars\n _init_bss();\n\n \/\/ Initialize heap\n _init_heap(free_mem_begin);\n\n \/\/Initialize stack-unwinder, call global constructors etc.\n _init_c_runtime();\n\n \/\/ Initialize system calls\n _init_syscalls();\n\n \/\/Initialize stdout handlers\n default_stdout_handlers();\n\n \/\/ Call global ctors\n __libc_init_array();\n\n __platform_init();\n\n \/\/ Start the service\n Service::start();\n\n \/\/ verify certain read-only sections in memory\n kernel_sanity_checks();\n\n __arch_poweroff();\n}\nx86_nano: Update to new stdout mechanic\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2017 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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 \n#include \n#include \n#include \n#include \n\nextern void __platform_init();\n\nextern \"C\" {\n void __init_serial1();\n void __init_sanity_checks();\n void kernel_sanity_checks();\n uintptr_t _multiboot_free_begin(uintptr_t boot_addr);\n uintptr_t _move_symbols(uintptr_t loc);\n void _init_bss();\n void _init_heap(uintptr_t);\n void _init_c_runtime();\n void _init_syscalls();\n void __libc_init_array();\n uintptr_t _end;\n}\n\nextern \"C\"\nvoid kernel_start(uintptr_t magic, uintptr_t addr)\n{\n \/\/ Initialize serial port 1\n __init_serial1();\n\n \/\/ generate checksums of read-only areas etc.\n __init_sanity_checks();\n\n \/\/ Determine where free memory starts\n uintptr_t free_mem_begin = reinterpret_cast(&_end);\n\n if (magic == MULTIBOOT_BOOTLOADER_MAGIC) {\n free_mem_begin = _multiboot_free_begin(addr);\n }\n\n \/\/ Preserve symbols from the ELF binary\n free_mem_begin += _move_symbols(free_mem_begin);\n\n \/\/ Initialize zero-initialized vars\n _init_bss();\n\n \/\/ Initialize heap\n _init_heap(free_mem_begin);\n\n \/\/Initialize stack-unwinder, call global constructors etc.\n _init_c_runtime();\n\n \/\/ Initialize system calls\n _init_syscalls();\n\n \/\/Initialize stdout handlers\n OS::add_stdout(&OS::default_stdout);\n\n \/\/ Call global ctors\n __libc_init_array();\n\n __platform_init();\n\n \/\/ Start the service\n Service::start();\n\n \/\/ verify certain read-only sections in memory\n kernel_sanity_checks();\n\n __arch_poweroff();\n}\n<|endoftext|>"} {"text":"Revert \"fix setting of paper tray from print dialog (fdo#43932)\"<|endoftext|>"} {"text":"assert on attempt to print after cancel<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2020 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n\nnamespace inviwo {\nnamespace plot {\n\n\/\/ The Class Identifier has to be globally unique. Use a reverse DNS naming scheme\nconst ProcessorInfo ColorScaleLegend::processorInfo_{\n \"org.inviwo.ColorScaleLegend\", \/\/ Class identifier\n \"Color Scale Legend\", \/\/ Display name\n \"Plotting\", \/\/ Category\n CodeState::Stable, \/\/ Code state\n \"GL, Plotting, TF\" \/\/ Tags\n};\nconst ProcessorInfo ColorScaleLegend::getProcessorInfo() const { return processorInfo_; }\n\nColorScaleLegend::ColorScaleLegend()\n : Processor()\n , inport_(\"inport\")\n , outport_(\"outport\")\n , volumeInport_(\"volumeInport\")\n , enabled_(\"enabled\", \"Enabled\", true)\n , isotfComposite_(\"isotfComposite\", \"TF & Isovalues\")\n , positioning_(\"positioning\", \"Positioning & Size\")\n , legendPlacement_(\"legendPlacement\", \"Legend Placement\",\n {{\"top\", \"Top\", 0},\n {\"right\", \"Right\", 1},\n {\"bottom\", \"Bottom\", 2},\n {\"left\", \"Left\", 3},\n {\"custom\", \"Custom\", 4}},\n 1)\n , rotation_(\"legendRotation\", \"Legend Rotation\",\n {{\"degree0\", \"0 degrees\", 0},\n {\"degree90\", \"90 degrees\", 1},\n {\"degree180\", \"180 degrees\", 2},\n {\"degree270\", \"270 degrees\", 3}},\n 1)\n , position_(\"position\", \"Position\", vec2(0.5f), vec2(0.0f), vec2(1.0f))\n , margin_(\"margin\", \"Margin (in pixels)\", 25, 0, 100)\n , legendSize_(\"legendSize\", \"Legend Size\", vec2(200, 25), vec2(10, 10), vec2(2000, 500))\n , axisStyle_(\"style\", \"Style\")\n , title_(\"title\", \"Legend Title\", \"Legend\")\n , backgroundStyle_(\"backgroundStyle\", \"Background\",\n {{\"noBackground\", \"No background\", BackgroundStyle::NoBackground},\n {\"checkerBoard\", \"Checker board\", BackgroundStyle::CheckerBoard},\n {\"solid\", \"Solid\", BackgroundStyle::SolidColor}},\n 0)\n , checkerBoardSize_(\"checkerBoardSize\", \"Checker Board Size\", 5, 1, 20)\n , bgColor_(\"backgroundColor\", \"Background Color\", vec4(0.0f, 0.0f, 0.0f, 1.0f), vec4(0.0f),\n vec4(1.0f), Defaultvalues::getInc(), InvalidationLevel::InvalidOutput,\n PropertySemantics::Color)\n , borderWidth_(\"borderWidth\", \"Border Width\", 2, 0, 10)\n , shader_(\"img_texturequad.vert\", \"legend.frag\")\n , axis_(\"axis\", \"Scale Axis\")\n , axisRenderer_(axis_) {\n\n shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });\n\n inport_.setOptional(true);\n volumeInport_.setOptional(true);\n addPort(inport_);\n addPort(outport_);\n addPort(volumeInport_);\n\n \/\/ legend position\n positioning_.addProperties(legendPlacement_, rotation_, position_, margin_, legendSize_);\n rotation_.visibilityDependsOn(legendPlacement_, [](auto l) { return l.get() == 4; });\n position_.visibilityDependsOn(legendPlacement_, [](auto l) { return l.get() == 4; });\n axis_.flipped_.visibilityDependsOn(legendPlacement_, [](auto l) { return l.get() == 4; });\n\n \/\/ legend style\n axisStyle_.insertProperty(0, title_);\n axisStyle_.addProperties(backgroundStyle_, checkerBoardSize_, bgColor_, borderWidth_);\n checkerBoardSize_.setVisible(false);\n bgColor_.setVisible(false);\n\n axisStyle_.registerProperty(axis_);\n\n addProperties(enabled_, isotfComposite_, positioning_, axisStyle_, axis_);\n\n \/\/ set initial axis parameters\n axis_.width_ = 0;\n axis_.setCaption(title_.get());\n axis_.captionSettings_.setChecked(true);\n axis_.labelSettings_.font_.fontFace_.set(axis_.captionSettings_.font_.fontFace_.get());\n axis_.captionSettings_.offset_.set(20);\n axis_.captionSettings_.font_.anchorPos_.set(vec2{0.0f, 0.0f});\n axis_.setCurrentStateAsDefault();\n\n title_.onChange([&]() { axis_.setCaption(title_.get()); });\n\n const auto getAxisOrientation = [](int i) {\n switch (i) {\n default:\n case 0: \/\/ 0 degrees rotation (top)\n return AxisProperty::Orientation::Horizontal;\n case 1: \/\/ 90 degrees rotation (right)\n return AxisProperty::Orientation::Vertical;\n case 2: \/\/ 180 degrees rotation (bottom)\n return AxisProperty::Orientation::Horizontal;\n case 3: \/\/ 270 degrees rotation (left)\n return AxisProperty::Orientation::Vertical;\n }\n };\n const auto getAxisPlacement = [](int i) {\n switch (i) {\n default:\n case 0: \/\/ 0 degrees rotation (top)\n return AxisProperty::Placement::Outside;\n case 1: \/\/ 90 degrees rotation (right)\n return AxisProperty::Placement::Outside;\n case 2: \/\/ 180 degrees rotation (bottom)\n return AxisProperty::Placement::Inside;\n case 3: \/\/ 270 degrees rotation (left)\n return AxisProperty::Placement::Inside;\n }\n };\n\n legendPlacement_.onChange([this]() {\n if (legendPlacement_ != 4) rotation_.set(legendPlacement_.get());\n });\n if (legendPlacement_ != 4) rotation_.set(legendPlacement_.get());\n\n auto updatePlacement = [&]() {\n axis_.orientation_.set(getAxisOrientation(rotation_.get()));\n axis_.placement_.set(getAxisPlacement(rotation_.get()));\n\n if (rotation_ == 0 || rotation_ == 3) { \/\/ Top\/Left\n axis_.flipped_ = false;\n } else if (rotation_ == 1 || rotation_ == 2) { \/\/ Right\/Bottom\n axis_.flipped_ = true;\n }\n };\n\n rotation_.onChange(updatePlacement);\n updatePlacement();\n\n checkerBoardSize_.visibilityDependsOn(\n backgroundStyle_, [&](auto p) { return p.get() == BackgroundStyle::CheckerBoard; });\n bgColor_.visibilityDependsOn(backgroundStyle_,\n [&](auto p) { return p.get() == BackgroundStyle::SolidColor; });\n}\n\n\/\/ this function handles the legend rotation and updates the axis thereafter\nstd::tuple ColorScaleLegend::getPositions(ivec2 dimensions) const {\n const float ticsWidth = ceil(axis_.majorTicks_.tickWidth_.get());\n const auto borderWidth = borderWidth_.get();\n\n const auto [position, rotation, legendSize] = [&]() {\n const std::array pos = {{{0.5f, 1.0f}, {1.0f, 0.5f}, {0.5f, 0.0f}, {0.0f, 0.5f}}};\n const auto initialPos = legendPlacement_ == 4 ? position_.get() : pos[legendPlacement_];\n const auto rotation = legendPlacement_ == 4 ? rotation_.get() : legendPlacement_.get();\n const auto size =\n rotation % 2 == 0 ? legendSize_.get() : ivec2{legendSize_.get().y, legendSize_.get().x};\n\n auto lpos = 0.5f * vec2{size + 2 * ivec2{margin_}} +\n initialPos * vec2{dimensions - size - 2 * ivec2{margin_}};\n\n return std::make_tuple(lpos, rotation, size);\n }();\n\n \/\/ define the legend corners\n const ivec2 bottomLeft = position - vec2{legendSize} * vec2{0.5};\n const ivec2 bottomRight = vec2(bottomLeft.x + legendSize.x, bottomLeft.y);\n const ivec2 topLeft = vec2(bottomLeft.x, bottomLeft.y + legendSize.y);\n const ivec2 topRight = vec2(bottomRight.x, topLeft.y);\n\n ivec2 axisStart{0};\n ivec2 axisEnd{0};\n\n switch (rotation_.get()) {\n default:\n case 0: \/\/ 0 degrees rotation (top)\n axisStart = bottomLeft + ivec2(ticsWidth \/ 2, 0) - ivec2(borderWidth);\n axisEnd = bottomRight - ivec2(ticsWidth \/ 2, 0) + ivec2(borderWidth, -borderWidth);\n break;\n case 1: \/\/ 90 degrees rotation (right)\n axisStart = bottomLeft + ivec2(0, ticsWidth \/ 2) - ivec2(borderWidth);\n axisEnd = topLeft - ivec2(0, ticsWidth \/ 2) + ivec2(-borderWidth, borderWidth);\n break;\n case 2: \/\/ 180 degrees rotation (bottom)\n axisStart = topLeft + ivec2(ticsWidth \/ 2, 0) + ivec2(-borderWidth, borderWidth);\n axisEnd = topRight - ivec2(ticsWidth \/ 2, 0) + ivec2(borderWidth);\n break;\n case 3: \/\/ 270 degrees rotation (left)\n axisStart = bottomRight + ivec2(0, ticsWidth \/ 2) + ivec2(borderWidth, -borderWidth);\n axisEnd = topRight - ivec2(0, ticsWidth \/ 2) + ivec2(borderWidth);\n break;\n }\n return {bottomLeft, legendSize, axisStart, axisEnd};\n}\n\nvoid ColorScaleLegend::process() {\n utilgl::activateTargetAndClearOrCopySource(outport_, inport_);\n if (!enabled_) {\n return;\n }\n\n \/\/ update the legend range if a volume is connected to inport\n if (volumeInport_.isChanged() && volumeInport_.hasData()) {\n axis_.setRange(volumeInport_.getData()->dataMap_.valueRange);\n } else if (!volumeInport_.isConnected()) {\n axis_.setRange(vec2(0, 1));\n }\n\n const ivec2 dimensions = outport_.getDimensions();\n const auto [bottomLeft, legendSize, axisStart, axisEnd] = getPositions(dimensions);\n axisRenderer_.render(dimensions, axisStart, axisEnd);\n\n utilgl::DepthFuncState depthFunc(GL_ALWAYS);\n utilgl::BlendModeState blending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\n TextureUnitContainer units;\n utilgl::Activate activate(&shader_);\n utilgl::bindAndSetUniforms(shader_, units, isotfComposite_);\n utilgl::setUniforms(shader_, axis_.color_, borderWidth_, backgroundStyle_, checkerBoardSize_,\n rotation_, isotfComposite_);\n\n if (backgroundStyle_ == BackgroundStyle::NoBackground) {\n shader_.setUniform(\"backgroundColor\", vec4(0.0f));\n } else {\n shader_.setUniform(\"backgroundColor\", bgColor_);\n }\n\n const ivec4 view{bottomLeft - ivec2{borderWidth_}, legendSize + ivec2{borderWidth_ * 2}};\n shader_.setUniform(\"viewport\", view);\n utilgl::ViewportState viewport(view);\n\n utilgl::singleDrawImagePlaneRect();\n utilgl::deactivateCurrentTarget();\n}\n\n} \/\/ namespace plot\n\n} \/\/ namespace inviwo\nPlottingGL: requested changes\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2020 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n\nnamespace inviwo {\nnamespace plot {\n\n\/\/ The Class Identifier has to be globally unique. Use a reverse DNS naming scheme\nconst ProcessorInfo ColorScaleLegend::processorInfo_{\n \"org.inviwo.ColorScaleLegend\", \/\/ Class identifier\n \"Color Scale Legend\", \/\/ Display name\n \"Plotting\", \/\/ Category\n CodeState::Stable, \/\/ Code state\n \"GL, Plotting, TF\" \/\/ Tags\n};\nconst ProcessorInfo ColorScaleLegend::getProcessorInfo() const { return processorInfo_; }\n\nColorScaleLegend::ColorScaleLegend()\n : Processor()\n , inport_(\"inport\")\n , outport_(\"outport\")\n , volumeInport_(\"volumeInport\")\n , enabled_(\"enabled\", \"Enabled\", true)\n , isotfComposite_(\"isotfComposite\", \"TF & Isovalues\")\n , positioning_(\"positioning\", \"Positioning & Size\")\n , legendPlacement_(\"legendPlacement\", \"Legend Placement\",\n {{\"top\", \"Top\", 0},\n {\"right\", \"Right\", 1},\n {\"bottom\", \"Bottom\", 2},\n {\"left\", \"Left\", 3},\n {\"custom\", \"Custom\", 4}},\n 1)\n , rotation_(\"legendRotation\", \"Legend Rotation\",\n {{\"degree0\", \"0 degrees\", 0},\n {\"degree90\", \"90 degrees\", 1},\n {\"degree180\", \"180 degrees\", 2},\n {\"degree270\", \"270 degrees\", 3}},\n 1)\n , position_(\"position\", \"Position\", vec2(0.5f), vec2(0.0f), vec2(1.0f))\n , margin_(\"margin\", \"Margin (in pixels)\", 25, 0, 100)\n , legendSize_(\"legendSize\", \"Legend Size\", vec2(200, 25), vec2(10, 10), vec2(2000, 500))\n , axisStyle_(\"style\", \"Style\")\n , title_(\"title\", \"Legend Title\", \"Legend\")\n , backgroundStyle_(\"backgroundStyle\", \"Background\",\n {{\"noBackground\", \"No background\", BackgroundStyle::NoBackground},\n {\"checkerBoard\", \"Checker board\", BackgroundStyle::CheckerBoard},\n {\"solid\", \"Solid\", BackgroundStyle::SolidColor}},\n 0)\n , checkerBoardSize_(\"checkerBoardSize\", \"Checker Board Size\", 5, 1, 20)\n , bgColor_(\"backgroundColor\", \"Background Color\", vec4(0.0f, 0.0f, 0.0f, 1.0f), vec4(0.0f),\n vec4(1.0f), Defaultvalues::getInc(), InvalidationLevel::InvalidOutput,\n PropertySemantics::Color)\n , borderWidth_(\"borderWidth\", \"Border Width\", 2, 0, 10)\n , shader_(\"img_texturequad.vert\", \"legend.frag\")\n , axis_(\"axis\", \"Scale Axis\")\n , axisRenderer_(axis_) {\n\n shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });\n\n inport_.setOptional(true);\n volumeInport_.setOptional(true);\n addPort(inport_);\n addPort(outport_);\n addPort(volumeInport_);\n\n \/\/ legend position\n positioning_.addProperties(legendPlacement_, rotation_, position_, margin_, legendSize_);\n rotation_.visibilityDependsOn(legendPlacement_, [](auto l) { return l.get() == 4; });\n position_.visibilityDependsOn(legendPlacement_, [](auto l) { return l.get() == 4; });\n axis_.flipped_.visibilityDependsOn(legendPlacement_, [](auto l) { return l.get() == 4; });\n\n \/\/ legend style\n axisStyle_.insertProperty(0, title_);\n axisStyle_.addProperties(backgroundStyle_, checkerBoardSize_, bgColor_, borderWidth_);\n checkerBoardSize_.setVisible(false);\n bgColor_.setVisible(false);\n\n axisStyle_.registerProperty(axis_);\n\n addProperties(enabled_, isotfComposite_, positioning_, axisStyle_, axis_);\n\n \/\/ set initial axis parameters\n axis_.width_ = 0;\n axis_.setCaption(title_.get());\n axis_.captionSettings_.setChecked(true);\n axis_.labelSettings_.font_.fontFace_.set(axis_.captionSettings_.font_.fontFace_.get());\n axis_.captionSettings_.offset_.set(20);\n axis_.captionSettings_.font_.anchorPos_.set(vec2{0.0f, 0.0f});\n axis_.setCurrentStateAsDefault();\n\n title_.onChange([&]() { axis_.setCaption(title_.get()); });\n\n const auto getAxisOrientation = [](int i) {\n switch (i) {\n default:\n case 0: \/\/ 0 degrees rotation (top)\n return AxisProperty::Orientation::Horizontal;\n case 1: \/\/ 90 degrees rotation (right)\n return AxisProperty::Orientation::Vertical;\n case 2: \/\/ 180 degrees rotation (bottom)\n return AxisProperty::Orientation::Horizontal;\n case 3: \/\/ 270 degrees rotation (left)\n return AxisProperty::Orientation::Vertical;\n }\n };\n const auto getAxisPlacement = [](int i) {\n switch (i) {\n default:\n case 0: \/\/ 0 degrees rotation (top)\n return AxisProperty::Placement::Outside;\n case 1: \/\/ 90 degrees rotation (right)\n return AxisProperty::Placement::Outside;\n case 2: \/\/ 180 degrees rotation (bottom)\n return AxisProperty::Placement::Inside;\n case 3: \/\/ 270 degrees rotation (left)\n return AxisProperty::Placement::Inside;\n }\n };\n\n legendPlacement_.onChange([this]() {\n if (legendPlacement_ != 4) rotation_.set(legendPlacement_.get());\n });\n if (legendPlacement_ != 4) rotation_.set(legendPlacement_.get());\n\n auto updatePlacement = [&]() {\n axis_.orientation_.set(getAxisOrientation(rotation_.get()));\n axis_.placement_.set(getAxisPlacement(rotation_.get()));\n\n if (rotation_ == 0 || rotation_ == 3) { \/\/ Top\/Left\n axis_.flipped_ = false;\n } else if (rotation_ == 1 || rotation_ == 2) { \/\/ Right\/Bottom\n axis_.flipped_ = true;\n }\n };\n\n rotation_.onChange(updatePlacement);\n updatePlacement();\n\n checkerBoardSize_.visibilityDependsOn(\n backgroundStyle_, [&](auto p) { return p.get() == BackgroundStyle::CheckerBoard; });\n bgColor_.visibilityDependsOn(backgroundStyle_,\n [&](auto p) { return p.get() == BackgroundStyle::SolidColor; });\n}\n\n\/\/ this function handles the legend rotation and updates the axis thereafter\nstd::tuple ColorScaleLegend::getPositions(ivec2 dimensions) const {\n const float ticsWidth = ceil(axis_.majorTicks_.tickWidth_.get());\n const auto borderWidth = borderWidth_.get();\n\n const auto [position, rotation, legendSize] = [&]() {\n const std::array pos = {{{0.5f, 1.0f}, {1.0f, 0.5f}, {0.5f, 0.0f}, {0.0f, 0.5f}}};\n const auto initialPos = legendPlacement_ == 4 ? position_.get() : pos[legendPlacement_];\n const auto rotation = legendPlacement_ == 4 ? rotation_.get() : legendPlacement_.get();\n const auto size =\n rotation % 2 == 0 ? legendSize_.get() : ivec2{legendSize_.get().y, legendSize_.get().x};\n\n auto lpos = 0.5f * vec2{size + 2 * ivec2{margin_}} +\n initialPos * vec2{dimensions - size - 2 * ivec2{margin_}};\n\n return std::make_tuple(lpos, rotation, size);\n }();\n\n \/\/ define the legend corners\n const ivec2 bottomLeft = position - vec2{legendSize} * vec2{0.5};\n const ivec2 bottomRight = vec2(bottomLeft.x + legendSize.x, bottomLeft.y);\n const ivec2 topLeft = vec2(bottomLeft.x, bottomLeft.y + legendSize.y);\n const ivec2 topRight = vec2(bottomRight.x, topLeft.y);\n\n ivec2 axisStart{0};\n ivec2 axisEnd{0};\n\n switch (rotation_.get()) {\n default:\n case 0: \/\/ 0 degrees rotation (top)\n axisStart = bottomLeft + ivec2(ticsWidth \/ 2, 0) - ivec2(borderWidth);\n axisEnd = bottomRight - ivec2(ticsWidth \/ 2, 0) + ivec2(borderWidth, -borderWidth);\n break;\n case 1: \/\/ 90 degrees rotation (right)\n axisStart = bottomLeft + ivec2(0, ticsWidth \/ 2) - ivec2(borderWidth);\n axisEnd = topLeft - ivec2(0, ticsWidth \/ 2) + ivec2(-borderWidth, borderWidth);\n break;\n case 2: \/\/ 180 degrees rotation (bottom)\n axisStart = topLeft + ivec2(ticsWidth \/ 2, 0) + ivec2(-borderWidth, borderWidth);\n axisEnd = topRight - ivec2(ticsWidth \/ 2, 0) + ivec2(borderWidth);\n break;\n case 3: \/\/ 270 degrees rotation (left)\n axisStart = bottomRight + ivec2(0, ticsWidth \/ 2) + ivec2(borderWidth, -borderWidth);\n axisEnd = topRight - ivec2(0, ticsWidth \/ 2) + ivec2(borderWidth);\n break;\n }\n return {bottomLeft, legendSize, axisStart, axisEnd};\n}\n\nvoid ColorScaleLegend::process() {\n if (!enabled_) {\n if (inport_.isReady()) {\n outport_.setData(inport_.getData());\n } else {\n utilgl::activateAndClearTarget(outport_);\n }\n\n return;\n }\n utilgl::activateTargetAndClearOrCopySource(outport_, inport_);\n\n \/\/ update the legend range if a volume is connected to inport\n if (volumeInport_.isChanged() && volumeInport_.hasData()) {\n axis_.setRange(volumeInport_.getData()->dataMap_.valueRange);\n } else if (!volumeInport_.isConnected()) {\n axis_.setRange(vec2(0, 1));\n }\n\n const ivec2 dimensions = outport_.getDimensions();\n const auto [bottomLeft, legendSize, axisStart, axisEnd] = getPositions(dimensions);\n axisRenderer_.render(dimensions, axisStart, axisEnd);\n\n utilgl::DepthFuncState depthFunc(GL_ALWAYS);\n utilgl::BlendModeState blending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\n TextureUnitContainer units;\n utilgl::Activate activate(&shader_);\n utilgl::bindAndSetUniforms(shader_, units, isotfComposite_);\n utilgl::setUniforms(shader_, axis_.color_, borderWidth_, backgroundStyle_, checkerBoardSize_,\n rotation_, isotfComposite_);\n\n if (backgroundStyle_ == BackgroundStyle::NoBackground) {\n shader_.setUniform(\"backgroundColor\", vec4(0.0f));\n } else {\n shader_.setUniform(\"backgroundColor\", bgColor_);\n }\n\n const ivec4 view{bottomLeft - ivec2{borderWidth_}, legendSize + ivec2{borderWidth_ * 2}};\n shader_.setUniform(\"viewport\", view);\n utilgl::ViewportState viewport(view);\n\n utilgl::singleDrawImagePlaneRect();\n utilgl::deactivateCurrentTarget();\n}\n\n} \/\/ namespace plot\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright 2014, 2015 Razer Inc.\r\n\/\/\r\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\/\/ you may not use this file except in compliance with the License.\r\n\/\/ You may obtain a copy of the License at\r\n\/\/\r\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software\r\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\/\/ See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\/\/\r\n\r\n#include \"OSVRPrivatePCH.h\"\r\n#include \"OSVRHMD.h\"\r\n\r\n\/\/ Must put path from Engine\/Source to these includes since we are an out-of-tree module.\r\n#include \"Runtime\/Renderer\/Private\/RendererPrivate.h\"\r\n#include \"Runtime\/Renderer\/Private\/ScenePrivate.h\"\r\n#include \"Runtime\/Renderer\/Private\/PostProcess\/PostProcessHMD.h\"\r\n#include \"Runtime\/Engine\/Public\/ScreenRendering.h\"\r\n\r\nvoid FOSVRHMD::DrawDistortionMesh_RenderThread(FRenderingCompositePassContext& Context, const FIntPoint& TextureSize)\r\n{\r\n \/\/ shouldn't be called with a custom present\r\n check(0);\r\n}\r\n\r\nvoid FOSVRHMD::RenderTexture_RenderThread(FRHICommandListImmediate& RHICmdList, FTexture2DRHIParamRef BackBuffer, FTexture2DRHIParamRef SrcTexture) const\r\n\/\/{\r\n\/\/ check(IsInRenderingThread());\r\n\/\/\r\n\/\/ if (DstRect.IsEmpty())\r\n\/\/ {\r\n\/\/ DstRect = FIntRect(0, 0, DstTexture->GetSizeX(), DstTexture->GetSizeY());\r\n\/\/ }\r\n\/\/ const uint32 ViewportWidth = DstRect.Width();\r\n\/\/ const uint32 ViewportHeight = DstRect.Height();\r\n\/\/ const FIntPoint TargetSize(ViewportWidth, ViewportHeight);\r\n\/\/\r\n\/\/ const float SrcTextureWidth = SrcTexture->GetSizeX();\r\n\/\/ const float SrcTextureHeight = SrcTexture->GetSizeY();\r\n\/\/ float U = 0.f, V = 0.f, USize = 1.f, VSize = 1.f;\r\n\/\/ if (!SrcRect.IsEmpty())\r\n\/\/ {\r\n\/\/ U = SrcRect.Min.X \/ SrcTextureWidth;\r\n\/\/ V = SrcRect.Min.Y \/ SrcTextureHeight;\r\n\/\/ USize = SrcRect.Width() \/ SrcTextureWidth;\r\n\/\/ VSize = SrcRect.Height() \/ SrcTextureHeight;\r\n\/\/ }\r\n\/\/\r\n\/\/ SetRenderTarget(RHICmdList, DstTexture, FTextureRHIRef());\r\n\/\/ RHICmdList.SetViewport(DstRect.Min.X, DstRect.Min.Y, 0, DstRect.Max.X, DstRect.Max.Y, 1.0f);\r\n\/\/\r\n\/\/ RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());\r\n\/\/ RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());\r\n\/\/ RHICmdList.SetDepthStencilState(TStaticDepthStencilState::GetRHI());\r\n\/\/\r\n\/\/ const auto FeatureLevel = GMaxRHIFeatureLevel;\r\n\/\/ auto ShaderMap = GetGlobalShaderMap(FeatureLevel);\r\n\/\/\r\n\/\/ TShaderMapRef VertexShader(ShaderMap);\r\n\/\/ TShaderMapRef PixelShader(ShaderMap);\r\n\/\/\r\n\/\/ static FGlobalBoundShaderState BoundShaderState;\r\n\/\/ SetGlobalBoundShaderState(RHICmdList, FeatureLevel, BoundShaderState, RendererModule->GetFilterVertexDeclaration().VertexDeclarationRHI, *VertexShader, *PixelShader);\r\n\/\/\r\n\/\/ PixelShader->SetParameters(RHICmdList, TStaticSamplerState::GetRHI(), SrcTexture);\r\n\/\/\r\n\/\/ RendererModule->DrawRectangle(\r\n\/\/ RHICmdList,\r\n\/\/ 0, 0,\r\n\/\/ ViewportWidth, ViewportHeight,\r\n\/\/ U, V,\r\n\/\/ USize, VSize,\r\n\/\/ TargetSize,\r\n\/\/ FIntPoint(1, 1),\r\n\/\/ *VertexShader,\r\n\/\/ EDRF_Default);\r\n\/\/}\r\n{\r\n check(IsInRenderingThread());\r\n\r\n const uint32 ViewportWidth = BackBuffer->GetSizeX();\r\n const uint32 ViewportHeight = BackBuffer->GetSizeY();\r\n\r\n SetRenderTarget(RHICmdList, BackBuffer, FTextureRHIRef());\r\n RHICmdList.SetViewport(0, 0, 0, ViewportWidth, ViewportHeight, 1.0f);\r\n\r\n RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());\r\n RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());\r\n RHICmdList.SetDepthStencilState(TStaticDepthStencilState::GetRHI());\r\n\r\n const auto FeatureLevel = GMaxRHIFeatureLevel;\r\n auto ShaderMap = GetGlobalShaderMap(FeatureLevel);\r\n\r\n TShaderMapRef VertexShader(ShaderMap);\r\n TShaderMapRef PixelShader(ShaderMap);\r\n\r\n static FGlobalBoundShaderState BoundShaderState;\r\n SetGlobalBoundShaderState(RHICmdList, FeatureLevel, BoundShaderState, RendererModule->GetFilterVertexDeclaration().VertexDeclarationRHI, *VertexShader, *PixelShader);\r\n\r\n PixelShader->SetParameters(RHICmdList, TStaticSamplerState::GetRHI(), SrcTexture);\r\n \/\/if (WindowMirrorMode == 1)\r\n \/\/{\r\n \/\/ \/\/ need to clear when rendering only one eye since the borders won't be touched by the DrawRect below\r\n \/\/ RHICmdList.Clear(true, FLinearColor::Black, false, 0, false, 0, FIntRect());\r\n\r\n \/\/ RendererModule->DrawRectangle(\r\n \/\/ RHICmdList,\r\n \/\/ ViewportWidth \/ 4, 0,\r\n \/\/ ViewportWidth \/ 2, ViewportHeight,\r\n \/\/ 0.1f, 0.2f,\r\n \/\/ 0.3f, 0.6f,\r\n \/\/ FIntPoint(ViewportWidth, ViewportHeight),\r\n \/\/ FIntPoint(1, 1),\r\n \/\/ *VertexShader,\r\n \/\/ EDRF_Default);\r\n \/\/}\r\n \/\/else if (WindowMirrorMode == 2)\r\n \/\/{\r\n RendererModule->DrawRectangle(\r\n RHICmdList,\r\n 0, 0, \/\/ X, Y\r\n ViewportWidth, ViewportHeight, \/\/ SizeX, SizeY\r\n 0.0f, 0.0f, \/\/ U, V\r\n 1.0f, 1.0f, \/\/ SizeU, SizeV\r\n FIntPoint(ViewportWidth, ViewportHeight), \/\/ TargetSize\r\n FIntPoint(1, 1), \/\/ TextureSize\r\n *VertexShader,\r\n EDRF_Default);\r\n \/\/}\r\n}\r\n\r\nvoid FOSVRHMD::GetEyeRenderParams_RenderThread(const struct FRenderingCompositePassContext& Context, FVector2D& EyeToSrcUVScaleValue, FVector2D& EyeToSrcUVOffsetValue) const\r\n{\r\n\tif (Context.View.StereoPass == eSSP_LEFT_EYE)\r\n\t{\r\n\t\tEyeToSrcUVOffsetValue.X = 0.0f;\r\n\t\tEyeToSrcUVOffsetValue.Y = 0.0f;\r\n\r\n\t\tEyeToSrcUVScaleValue.X = 0.5f;\r\n\t\tEyeToSrcUVScaleValue.Y = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tEyeToSrcUVOffsetValue.X = 0.5f;\r\n\t\tEyeToSrcUVOffsetValue.Y = 0.0f;\r\n\r\n\t\tEyeToSrcUVScaleValue.X = 0.5f;\r\n\t\tEyeToSrcUVScaleValue.Y = 1.0f;\r\n\t}\r\n}\r\n\r\nvoid FOSVRHMD::GetTimewarpMatrices_RenderThread(const struct FRenderingCompositePassContext& Context, FMatrix& EyeRotationStart, FMatrix& EyeRotationEnd) const\r\n{\r\n\t\/\/ intentionally left blank\r\n}\r\n\r\n\/\/ @todo: Why is this function never called?\r\nvoid FOSVRHMD::PreRenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneViewFamily& ViewFamily)\r\n{\r\n check(IsInRenderingThread());\r\n if (mCustomPresent) {\r\n mCustomPresent->Initialize();\r\n }\r\n \/\/ steamVR updates the current pose here, should we?\r\n}\r\n\r\nvoid FOSVRHMD::PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& View)\r\n{\r\n \/\/ @todo\r\n\r\n}\r\n\r\nvoid FOSVRHMD::CalculateRenderTargetSize(const FViewport& Viewport, uint32& InOutSizeX, uint32& InOutSizeY)\r\n{\r\n check(IsInGameThread());\r\n\r\n if (!IsStereoEnabled()) {\r\n return;\r\n }\r\n\r\n if (mCustomPresent) {\r\n mCustomPresent->CalculateRenderTargetSize(InOutSizeX, InOutSizeY);\r\n }\r\n}\r\n\r\n\r\nbool FOSVRHMD::NeedReAllocateViewportRenderTarget(const FViewport &viewport) {\r\n check(IsInGameThread());\r\n if (IsStereoEnabled()) {\r\n const uint32 inSizeX = viewport.GetSizeXY().X;\r\n const uint32 inSizeY = viewport.GetSizeXY().Y;\r\n FIntPoint renderTargetSize;\r\n renderTargetSize.X = viewport.GetRenderTargetTexture()->GetSizeX();\r\n renderTargetSize.Y = viewport.GetRenderTargetTexture()->GetSizeY();\r\n\r\n uint32 newSizeX = inSizeX, newSizeY = inSizeY;\r\n CalculateRenderTargetSize(viewport, newSizeX, newSizeY);\r\n if (newSizeX != renderTargetSize.X || newSizeY != renderTargetSize.Y) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nvoid FOSVRHMD::UpdateViewport(bool bUseSeparateRenderTarget, const FViewport& InViewport, class SViewport*)\r\n{\r\n check(IsInGameThread());\r\n\r\n auto viewportRHI = InViewport.GetViewportRHI().GetReference();\r\n if (!IsStereoEnabled()) {\r\n if (!bUseSeparateRenderTarget) {\r\n viewportRHI->SetCustomPresent(nullptr);\r\n }\r\n return;\r\n }\r\n\r\n if (mCustomPresent) {\r\n mCustomPresent->UpdateViewport(InViewport, viewportRHI);\r\n }\r\n}\r\n\r\nbool FOSVRHMD::AllocateRenderTargetTexture(uint32 index, uint32 sizeX, uint32 sizeY, uint8 format, uint32 numMips, uint32 flags, uint32 targetableTextureFlags, FTexture2DRHIRef& outTargetableTexture, FTexture2DRHIRef& outShaderResourceTexture, uint32 numSamples)\r\n{\r\n check(index == 0);\r\n if (mCustomPresent) {\r\n return mCustomPresent->AllocateRenderTargetTexture(index, sizeX, sizeY, format, numMips, flags, targetableTextureFlags, outTargetableTexture, outShaderResourceTexture, numSamples);\r\n }\r\n return false;\r\n}\nFormat\/comment.\/\/\r\n\/\/ Copyright 2014, 2015 Razer Inc.\r\n\/\/\r\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\/\/ you may not use this file except in compliance with the License.\r\n\/\/ You may obtain a copy of the License at\r\n\/\/\r\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software\r\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\/\/ See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\/\/\r\n\r\n#include \"OSVRPrivatePCH.h\"\r\n#include \"OSVRHMD.h\"\r\n\r\n\/\/ Must put path from Engine\/Source to these includes since we are an out-of-tree module.\r\n#include \"Runtime\/Renderer\/Private\/RendererPrivate.h\"\r\n#include \"Runtime\/Renderer\/Private\/ScenePrivate.h\"\r\n#include \"Runtime\/Renderer\/Private\/PostProcess\/PostProcessHMD.h\"\r\n#include \"Runtime\/Engine\/Public\/ScreenRendering.h\"\r\n\r\nvoid FOSVRHMD::DrawDistortionMesh_RenderThread(FRenderingCompositePassContext& Context, const FIntPoint& TextureSize)\r\n{\r\n \/\/ shouldn't be called with a custom present\r\n check(0);\r\n}\r\n\r\n\/\/ Based off of the SteamVR Unreal Plugin implementation.\r\nvoid FOSVRHMD::RenderTexture_RenderThread(FRHICommandListImmediate& rhiCmdList, FTexture2DRHIParamRef backBuffer, FTexture2DRHIParamRef srcTexture) const\r\n{\r\n check(IsInRenderingThread());\r\n\r\n const uint32 viewportWidth = backBuffer->GetSizeX();\r\n const uint32 viewportHeight = backBuffer->GetSizeY();\r\n\r\n SetRenderTarget(rhiCmdList, backBuffer, FTextureRHIRef());\r\n rhiCmdList.SetViewport(0, 0, 0, viewportWidth, viewportHeight, 1.0f);\r\n\r\n rhiCmdList.SetBlendState(TStaticBlendState<>::GetRHI());\r\n rhiCmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());\r\n rhiCmdList.SetDepthStencilState(TStaticDepthStencilState::GetRHI());\r\n\r\n const auto featureLevel = GMaxRHIFeatureLevel;\r\n auto shaderMap = GetGlobalShaderMap(featureLevel);\r\n\r\n TShaderMapRef vertexShader(shaderMap);\r\n TShaderMapRef pixelShader(shaderMap);\r\n\r\n static FGlobalBoundShaderState boundShaderState;\r\n SetGlobalBoundShaderState(rhiCmdList, featureLevel, boundShaderState, RendererModule->GetFilterVertexDeclaration().VertexDeclarationRHI, *vertexShader, *pixelShader);\r\n\r\n pixelShader->SetParameters(rhiCmdList, TStaticSamplerState::GetRHI(), srcTexture);\r\n RendererModule->DrawRectangle(\r\n rhiCmdList,\r\n 0, 0, \/\/ X, Y\r\n viewportWidth, viewportHeight, \/\/ SizeX, SizeY\r\n 0.0f, 0.0f, \/\/ U, V\r\n 1.0f, 1.0f, \/\/ SizeU, SizeV\r\n FIntPoint(viewportWidth, viewportHeight), \/\/ TargetSize\r\n FIntPoint(1, 1), \/\/ TextureSize\r\n *vertexShader,\r\n EDRF_Default);\r\n}\r\n\r\nvoid FOSVRHMD::GetEyeRenderParams_RenderThread(const struct FRenderingCompositePassContext& Context, FVector2D& EyeToSrcUVScaleValue, FVector2D& EyeToSrcUVOffsetValue) const\r\n{\r\n\tif (Context.View.StereoPass == eSSP_LEFT_EYE)\r\n\t{\r\n\t\tEyeToSrcUVOffsetValue.X = 0.0f;\r\n\t\tEyeToSrcUVOffsetValue.Y = 0.0f;\r\n\r\n\t\tEyeToSrcUVScaleValue.X = 0.5f;\r\n\t\tEyeToSrcUVScaleValue.Y = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tEyeToSrcUVOffsetValue.X = 0.5f;\r\n\t\tEyeToSrcUVOffsetValue.Y = 0.0f;\r\n\r\n\t\tEyeToSrcUVScaleValue.X = 0.5f;\r\n\t\tEyeToSrcUVScaleValue.Y = 1.0f;\r\n\t}\r\n}\r\n\r\nvoid FOSVRHMD::GetTimewarpMatrices_RenderThread(const struct FRenderingCompositePassContext& Context, FMatrix& EyeRotationStart, FMatrix& EyeRotationEnd) const\r\n{\r\n\t\/\/ intentionally left blank\r\n}\r\n\r\n\/\/ @todo: Why is this function never called?\r\nvoid FOSVRHMD::PreRenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneViewFamily& ViewFamily)\r\n{\r\n check(IsInRenderingThread());\r\n if (mCustomPresent) {\r\n mCustomPresent->Initialize();\r\n }\r\n \/\/ steamVR updates the current pose here, should we?\r\n}\r\n\r\nvoid FOSVRHMD::PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& View)\r\n{\r\n \/\/ @todo\r\n\r\n}\r\n\r\nvoid FOSVRHMD::CalculateRenderTargetSize(const FViewport& Viewport, uint32& InOutSizeX, uint32& InOutSizeY)\r\n{\r\n check(IsInGameThread());\r\n\r\n if (!IsStereoEnabled()) {\r\n return;\r\n }\r\n\r\n if (mCustomPresent) {\r\n mCustomPresent->CalculateRenderTargetSize(InOutSizeX, InOutSizeY);\r\n }\r\n}\r\n\r\n\r\nbool FOSVRHMD::NeedReAllocateViewportRenderTarget(const FViewport &viewport) {\r\n check(IsInGameThread());\r\n if (IsStereoEnabled()) {\r\n const uint32 inSizeX = viewport.GetSizeXY().X;\r\n const uint32 inSizeY = viewport.GetSizeXY().Y;\r\n FIntPoint renderTargetSize;\r\n renderTargetSize.X = viewport.GetRenderTargetTexture()->GetSizeX();\r\n renderTargetSize.Y = viewport.GetRenderTargetTexture()->GetSizeY();\r\n\r\n uint32 newSizeX = inSizeX, newSizeY = inSizeY;\r\n CalculateRenderTargetSize(viewport, newSizeX, newSizeY);\r\n if (newSizeX != renderTargetSize.X || newSizeY != renderTargetSize.Y) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nvoid FOSVRHMD::UpdateViewport(bool bUseSeparateRenderTarget, const FViewport& InViewport, class SViewport*)\r\n{\r\n check(IsInGameThread());\r\n\r\n auto viewportRHI = InViewport.GetViewportRHI().GetReference();\r\n if (!IsStereoEnabled()) {\r\n if (!bUseSeparateRenderTarget) {\r\n viewportRHI->SetCustomPresent(nullptr);\r\n }\r\n return;\r\n }\r\n\r\n if (mCustomPresent) {\r\n mCustomPresent->UpdateViewport(InViewport, viewportRHI);\r\n }\r\n}\r\n\r\nbool FOSVRHMD::AllocateRenderTargetTexture(uint32 index, uint32 sizeX, uint32 sizeY, uint8 format, uint32 numMips, uint32 flags, uint32 targetableTextureFlags, FTexture2DRHIRef& outTargetableTexture, FTexture2DRHIRef& outShaderResourceTexture, uint32 numSamples)\r\n{\r\n check(index == 0);\r\n if (mCustomPresent) {\r\n return mCustomPresent->AllocateRenderTargetTexture(index, sizeX, sizeY, format, numMips, flags, targetableTextureFlags, outTargetableTexture, outShaderResourceTexture, numSamples);\r\n }\r\n return false;\r\n}\n<|endoftext|>"} {"text":"\n\/\/ LogMainView.cpp : CLogMainView 类的实现\n\/\/\n\n#include \"stdafx.h\"\n\/\/ SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的\n\/\/ ATL 项目中进行定义,并允许与该项目共享文档代码。\n#ifndef SHARED_HANDLERS\n#include \"LogCC.h\"\n#endif\n\n#include \"LogCCDoc.h\"\n#include \"LogMainView.h\"\n#include \"ILogQuery.h\"\n#include \"LogQueryResult.h\"\n#include \"LogItem.h\"\n#include \"ILogItemPainter.h\"\n#include \"LogPainterFactory.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\nstatic const unsigned LineHeight = 15;\n\n\/\/ CLogMainView\n\nIMPLEMENT_DYNCREATE(CLogMainView, CScrollView)\n\nBEGIN_MESSAGE_MAP(CLogMainView, CScrollView)\n\tON_WM_ERASEBKGND()\n\tON_WM_VSCROLL()\n\tON_WM_MOUSEMOVE()\n\tON_WM_MOUSEWHEEL()\n\tON_WM_KEYDOWN()\n\tON_WM_LBUTTONUP()\nEND_MESSAGE_MAP()\n\n\/\/ CLogMainView 构造\/析构\n\nCLogMainView::CLogMainView()\n{\n}\n\nCLogMainView::~CLogMainView()\n{\n}\n\n\/\/ CLogMainView 绘制\n\nvoid CLogMainView::OnDraw(CDC* pDC)\n{\n\tCLogCCDoc* pDoc = GetDocument();\n\tASSERT_VALID(pDoc);\n\tif (!pDoc)\n\t\treturn;\n\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\tDEBUG_INFO(_T(\"客户区区域:\") << clientRect.left << \", \" << clientRect.top << \", \"\n\t\t<< clientRect.right << \", \" << clientRect.bottom);\n\n\tHDC memDC = ::CreateCompatibleDC(pDC->GetSafeHdc());\n\n\tHBITMAP memBmp = ::CreateCompatibleBitmap(pDC->GetSafeHdc(), clientRect.Width(), clientRect.Height());\n\tHGDIOBJ oldBmp = ::SelectObject(memDC, memBmp);\n\n\tHBRUSH bkgdBrush = reinterpret_cast(::GetStockObject(WHITE_BRUSH));\n\t::FillRect(memDC, clientRect, bkgdBrush);\n\n\tHFONT font = ::CreateFont(LineHeight - 2, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n\t\tDEFAULT_QUALITY, FIXED_PITCH, _T(\"新宋体\"));\n\tHGDIOBJ oldFont = ::SelectObject(memDC, font);\n\n\tDEBUG_INFO(_T(\"重绘\"));\n\n\tCPoint scrollPosition = GetScrollPosition();\n\tDEBUG_INFO(_T(\"滚动条位置:\") << scrollPosition.x << \", \" << scrollPosition.y);\n\n\t\/\/ 顶部可以显示半行\n\tint yLogLineStart = scrollPosition.y % LineHeight == 0 ? 0 : scrollPosition.y % LineHeight - LineHeight;\n\tunsigned beginLine = scrollPosition.y \/ LineHeight;\n\t\/\/ +1是为了底部能显示半行\n\tunsigned endLine = (scrollPosition.y + clientRect.Height()) \/ LineHeight + 1;\n\tendLine = min(endLine, GetDocument()->getModel()->getCurQueryResult()->getCount());\n\tDEBUG_INFO(_T(\"行号区间:\") << beginLine << \", \" << endLine);\n\n\tvector vecLines = GetDocument()->getModel()->getCurQueryResult()->getRange(beginLine, endLine);\n\tfor (unsigned i = 0; i < vecLines.size(); i++) {\n\t\tLogItem* item = vecLines[i];\n\t\tCRect rect = clientRect;\n\t\trect.top = yLogLineStart + i * LineHeight;\n\t\trect.bottom = rect.top + LineHeight;\n\t\tLogPainterFactory::GetInstance()->GetSingleLinePainter()->Draw(memDC, rect, *item);\n\t}\n\n\t::BitBlt(pDC->GetSafeHdc(), scrollPosition.x, scrollPosition.y, clientRect.Width(), clientRect.Height(),\n\t\tmemDC, 0, 0, SRCCOPY);\n\n\t::SelectObject(memDC, oldFont);\n\t::DeleteObject(font);\n\t::SelectObject(memDC, oldBmp);\n\t::DeleteObject(memBmp);\n\t::DeleteDC(memDC);\n}\n\nvoid CLogMainView::OnInitialUpdate()\n{\n\tCScrollView::OnInitialUpdate();\n\n\tgetModel()->registerObserver(this);\n\n\tUpdateScroll();\n\tSetFocus();\n}\n\nvoid CLogMainView::PostNcDestroy()\n{\n\tgetModel()->unregisterObserver(this);\n\t__super::PostNcDestroy();\n}\n\nvoid CLogMainView::UpdateScroll()\n{\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\ttotalSize.cx = 0;\n\t\/\/ 加1是为了最后一行一定可见\n\ttotalSize.cy = (getModel()->getCurQueryResult()->getCount() + 1) * LineHeight;\n#define LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE\n#ifdef LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE\n\tCSize pageSize(clientRect.Width(), clientRect.Height() \/ LineHeight * LineHeight);\n\tCSize lineSize(clientRect.Width(), LineHeight);\n\tSetScrollSizes(MM_TEXT, totalSize, pageSize, lineSize);\n#else\n\tSetScrollSizes(MM_TEXT, totalSize);\n#endif\n#define LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE\n#ifdef LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE\n\tint y = totalSize.cy - clientRect.Height();\n\tScrollToPosition(CPoint(0, max(y, 0)));\n#endif\n}\n\nvoid CLogMainView::onGeneralDataChanged() {\n\tInvalidate();\n}\n\nvoid CLogMainView::onQueryResultChanged() {\n\tUpdateScroll();\n\tInvalidate();\n}\n\nvoid CLogMainView::onScrollPositionChanged(int yPosition) {\n\tCPoint position = GetScrollPosition();\n\tposition.y = yPosition;\n\tScrollToPosition(position);\n}\n\n#ifdef _DEBUG\nCLogCCDoc* CLogMainView::GetDocument() const \/\/ 非调试版本是内联的\n{\n\tASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLogCCDoc)));\n\treturn (CLogCCDoc*)m_pDocument;\n}\n#endif \/\/_DEBUG\n\n\n\/\/ CLogMainView 消息处理程序\n\nBOOL CLogMainView::OnEraseBkgnd(CDC* pDC)\n{\n#ifdef LOGCC_WINUI_USE_DEFAULT_ERASE_BACKGROUND\n\treturn CScrollView::OnEraseBkgnd(pDC);\n#else\n\treturn TRUE;\n#endif\n}\n\nvoid CLogMainView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n\tif (nSBCode == SB_ENDSCROLL)\n\t{\n\t\tInvalidate();\n\t}\n\tCScrollView::OnVScroll(nSBCode, nPos, pScrollBar);\n}\n\nvoid CLogMainView::OnMouseMove(UINT nFlags, CPoint point)\n{\n\tif (GetForegroundWindow() == AfxGetMainWnd()) {\n\t\tSetFocus();\n\t}\n\t__super::OnMouseMove(nFlags, point);\n}\n\nvoid CLogMainView::onSubmit() {\n}\n\nBOOL CLogMainView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) {\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\n\tint yScrollPos = GetScrollPosition().y;\n\tif (clientRect.Height() >= totalSize.cy) return FALSE;\n\n\tint delta = 3 * LineHeight;\n\tif (zDelta < 0) {\n\t\t\/\/ 向下3行\n\t\tyScrollPos += delta;\n\t}\n\telse {\n\t\t\/\/ 向上3行\n\t\tyScrollPos -= delta;\n\t\tyScrollPos = max(yScrollPos, 0);\n\t}\n\tgetModel()->scrollTo(yScrollPos);\n\tDEBUG_INFO(_T(\"滚动位置:\") << yScrollPos);\n\treturn __super::OnMouseWheel(nFlags, zDelta, pt);\n}\n\n\nvoid CLogMainView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\n\t\/\/ NOTICE:\t很奇怪的现象,CScrollView在OnInitUpdate之外函数SetScrollSizes,\n\t\/\/\t\t\t如果设置的高度小于ClientRect,虽然没有显示滚动条仍然可以滚动,这里特殊处理一下,禁止滚动\n\tif (clientRect.Height() >= totalSize.cy) return;\n\n\tint yScrollPos = GetScrollPosition().y;\n\tif (::GetKeyState(VK_CONTROL) & 0x80000000) {\n\t\tif (nChar == VK_HOME) {\n\t\t\t\/\/ 跳到第一页\n\t\t\tyScrollPos = 0;\n\t\t} else if (nChar == VK_END) {\n\t\t\t\/\/ 跳到最后一页,多出没事\n\t\t\tyScrollPos = (getModel()->getCurQueryResult()->getCount()) * LineHeight;\n\t\t} else if (nChar == VK_UP) {\n\t\t\t\/\/ 向上1行\n\t\t\tyScrollPos -= LineHeight;\n\t\t\tyScrollPos = max(yScrollPos, 0);\n\t\t} else if (nChar == VK_DOWN) {\n\t\t\t\/\/ 向下1行\n\t\t\tyScrollPos += LineHeight;\n\t\t}\n\t}\n\tif (nChar == VK_PRIOR) {\n\t\t\/\/ 向上1页\n\t\tyScrollPos -= clientRect.Height() \/ LineHeight * LineHeight;\n\t\tyScrollPos = max(yScrollPos, 0);\n\t} else if (nChar == VK_NEXT) {\n\t\t\/\/ 向下1页\n\t\tyScrollPos += clientRect.Height() \/ LineHeight * LineHeight;\n\t}\n\tif (nChar == VK_UP) {\n\t\t\/\/ 选中上一行\n\t\tLogItem* item = getModel()->getSelected();\n\t\tif (item) {\n\t\t\tunsigned i = getModel()->getCurQueryResult()->findIndex(item);\n\t\t\tif (i > 0 && i != 0xFFFFFFFF) {\n\t\t\t\ti--;\n\t\t\t\tgetModel()->setSelected(getModel()->getCurQueryResult()->getIndex(i));\n\t\t\t}\n\t\t}\n\t} else if (nChar == VK_DOWN) {\n\t\t\/\/ 选中下一行\n\t\tLogItem* item = getModel()->getSelected();\n\t\tif (item) {\n\t\t\tunsigned i = getModel()->getCurQueryResult()->findIndex(item);\n\t\t\tif (i != 0xFFFFFFFF && i < getModel()->getCurQueryResult()->getCount() - 1) {\n\t\t\t\ti++;\n\t\t\t\tgetModel()->setSelected(getModel()->getCurQueryResult()->getIndex(i));\n\t\t\t}\n\t\t}\n\t}\n\tScrollToPosition(CPoint(0, yScrollPos));\n\tDEBUG_INFO(_T(\"滚动位置:\") << yScrollPos);\n\t__super::OnKeyDown(nChar, nRepCnt, nFlags);\n}\n\n\nvoid CLogMainView::OnLButtonUp(UINT nFlags, CPoint point)\n{\n\tint yScrollPos = GetScrollPosition().y;\n\tthis->selectedLine = (yScrollPos + point.y) \/ LineHeight;\n\t__super::OnLButtonUp(nFlags, point);\n}\n解决不足一页时上下键不能切换选中行的bug\n\/\/ LogMainView.cpp : CLogMainView 类的实现\n\/\/\n\n#include \"stdafx.h\"\n\/\/ SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的\n\/\/ ATL 项目中进行定义,并允许与该项目共享文档代码。\n#ifndef SHARED_HANDLERS\n#include \"LogCC.h\"\n#endif\n\n#include \"LogCCDoc.h\"\n#include \"LogMainView.h\"\n#include \"ILogQuery.h\"\n#include \"LogQueryResult.h\"\n#include \"LogItem.h\"\n#include \"ILogItemPainter.h\"\n#include \"LogPainterFactory.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\nstatic const unsigned LineHeight = 15;\n\n\/\/ CLogMainView\n\nIMPLEMENT_DYNCREATE(CLogMainView, CScrollView)\n\nBEGIN_MESSAGE_MAP(CLogMainView, CScrollView)\n\tON_WM_ERASEBKGND()\n\tON_WM_VSCROLL()\n\tON_WM_MOUSEMOVE()\n\tON_WM_MOUSEWHEEL()\n\tON_WM_KEYDOWN()\n\tON_WM_LBUTTONUP()\nEND_MESSAGE_MAP()\n\n\/\/ CLogMainView 构造\/析构\n\nCLogMainView::CLogMainView()\n{\n}\n\nCLogMainView::~CLogMainView()\n{\n}\n\n\/\/ CLogMainView 绘制\n\nvoid CLogMainView::OnDraw(CDC* pDC)\n{\n\tCLogCCDoc* pDoc = GetDocument();\n\tASSERT_VALID(pDoc);\n\tif (!pDoc)\n\t\treturn;\n\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\tDEBUG_INFO(_T(\"客户区区域:\") << clientRect.left << \", \" << clientRect.top << \", \"\n\t\t<< clientRect.right << \", \" << clientRect.bottom);\n\n\tHDC memDC = ::CreateCompatibleDC(pDC->GetSafeHdc());\n\n\tHBITMAP memBmp = ::CreateCompatibleBitmap(pDC->GetSafeHdc(), clientRect.Width(), clientRect.Height());\n\tHGDIOBJ oldBmp = ::SelectObject(memDC, memBmp);\n\n\tHBRUSH bkgdBrush = reinterpret_cast(::GetStockObject(WHITE_BRUSH));\n\t::FillRect(memDC, clientRect, bkgdBrush);\n\n\tHFONT font = ::CreateFont(LineHeight - 2, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n\t\tDEFAULT_QUALITY, FIXED_PITCH, _T(\"新宋体\"));\n\tHGDIOBJ oldFont = ::SelectObject(memDC, font);\n\n\tDEBUG_INFO(_T(\"重绘\"));\n\n\tCPoint scrollPosition = GetScrollPosition();\n\tDEBUG_INFO(_T(\"滚动条位置:\") << scrollPosition.x << \", \" << scrollPosition.y);\n\n\t\/\/ 顶部可以显示半行\n\tint yLogLineStart = scrollPosition.y % LineHeight == 0 ? 0 : scrollPosition.y % LineHeight - LineHeight;\n\tunsigned beginLine = scrollPosition.y \/ LineHeight;\n\t\/\/ +1是为了底部能显示半行\n\tunsigned endLine = (scrollPosition.y + clientRect.Height()) \/ LineHeight + 1;\n\tendLine = min(endLine, GetDocument()->getModel()->getCurQueryResult()->getCount());\n\tDEBUG_INFO(_T(\"行号区间:\") << beginLine << \", \" << endLine);\n\n\tvector vecLines = GetDocument()->getModel()->getCurQueryResult()->getRange(beginLine, endLine);\n\tfor (unsigned i = 0; i < vecLines.size(); i++) {\n\t\tLogItem* item = vecLines[i];\n\t\tCRect rect = clientRect;\n\t\trect.top = yLogLineStart + i * LineHeight;\n\t\trect.bottom = rect.top + LineHeight;\n\t\tLogPainterFactory::GetInstance()->GetSingleLinePainter()->Draw(memDC, rect, *item);\n\t}\n\n\t::BitBlt(pDC->GetSafeHdc(), scrollPosition.x, scrollPosition.y, clientRect.Width(), clientRect.Height(),\n\t\tmemDC, 0, 0, SRCCOPY);\n\n\t::SelectObject(memDC, oldFont);\n\t::DeleteObject(font);\n\t::SelectObject(memDC, oldBmp);\n\t::DeleteObject(memBmp);\n\t::DeleteDC(memDC);\n}\n\nvoid CLogMainView::OnInitialUpdate()\n{\n\tCScrollView::OnInitialUpdate();\n\n\tgetModel()->registerObserver(this);\n\n\tUpdateScroll();\n\tSetFocus();\n}\n\nvoid CLogMainView::PostNcDestroy()\n{\n\tgetModel()->unregisterObserver(this);\n\t__super::PostNcDestroy();\n}\n\nvoid CLogMainView::UpdateScroll()\n{\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\ttotalSize.cx = 0;\n\t\/\/ 加1是为了最后一行一定可见\n\ttotalSize.cy = (getModel()->getCurQueryResult()->getCount() + 1) * LineHeight;\n#define LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE\n#ifdef LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE\n\tCSize pageSize(clientRect.Width(), clientRect.Height() \/ LineHeight * LineHeight);\n\tCSize lineSize(clientRect.Width(), LineHeight);\n\tSetScrollSizes(MM_TEXT, totalSize, pageSize, lineSize);\n#else\n\tSetScrollSizes(MM_TEXT, totalSize);\n#endif\n#define LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE\n#ifdef LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE\n\tint y = totalSize.cy - clientRect.Height();\n\tScrollToPosition(CPoint(0, max(y, 0)));\n#endif\n}\n\nvoid CLogMainView::onGeneralDataChanged() {\n\tInvalidate();\n}\n\nvoid CLogMainView::onQueryResultChanged() {\n\tUpdateScroll();\n\tInvalidate();\n}\n\nvoid CLogMainView::onScrollPositionChanged(int yPosition) {\n\tCPoint position = GetScrollPosition();\n\tposition.y = yPosition;\n\tScrollToPosition(position);\n}\n\n#ifdef _DEBUG\nCLogCCDoc* CLogMainView::GetDocument() const \/\/ 非调试版本是内联的\n{\n\tASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLogCCDoc)));\n\treturn (CLogCCDoc*)m_pDocument;\n}\n#endif \/\/_DEBUG\n\n\n\/\/ CLogMainView 消息处理程序\n\nBOOL CLogMainView::OnEraseBkgnd(CDC* pDC)\n{\n#ifdef LOGCC_WINUI_USE_DEFAULT_ERASE_BACKGROUND\n\treturn CScrollView::OnEraseBkgnd(pDC);\n#else\n\treturn TRUE;\n#endif\n}\n\nvoid CLogMainView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n\tif (nSBCode == SB_ENDSCROLL)\n\t{\n\t\tInvalidate();\n\t}\n\tCScrollView::OnVScroll(nSBCode, nPos, pScrollBar);\n}\n\nvoid CLogMainView::OnMouseMove(UINT nFlags, CPoint point)\n{\n\tif (GetForegroundWindow() == AfxGetMainWnd()) {\n\t\tSetFocus();\n\t}\n\t__super::OnMouseMove(nFlags, point);\n}\n\nvoid CLogMainView::onSubmit() {\n}\n\nBOOL CLogMainView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) {\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\n\tint yScrollPos = GetScrollPosition().y;\n\tif (clientRect.Height() >= totalSize.cy) return FALSE;\n\n\tint delta = 3 * LineHeight;\n\tif (zDelta < 0) {\n\t\t\/\/ 向下3行\n\t\tyScrollPos += delta;\n\t}\n\telse {\n\t\t\/\/ 向上3行\n\t\tyScrollPos -= delta;\n\t\tyScrollPos = max(yScrollPos, 0);\n\t}\n\tgetModel()->scrollTo(yScrollPos);\n\tDEBUG_INFO(_T(\"滚动位置:\") << yScrollPos);\n\treturn __super::OnMouseWheel(nFlags, zDelta, pt);\n}\n\n\nvoid CLogMainView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {\n\tCRect clientRect;\n\tGetClientRect(clientRect);\n\t\n\tif (nChar == VK_UP) {\n\t\t\/\/ 选中上一行\n\t\tLogItem* item = getModel()->getSelected();\n\t\tif (item) {\n\t\t\tunsigned i = getModel()->getCurQueryResult()->findIndex(item);\n\t\t\tif (i > 0 && i != 0xFFFFFFFF) {\n\t\t\t\ti--;\n\t\t\t\tgetModel()->setSelected(getModel()->getCurQueryResult()->getIndex(i));\n\t\t\t}\n\t\t}\n\t} else if (nChar == VK_DOWN) {\n\t\t\/\/ 选中下一行\n\t\tLogItem* item = getModel()->getSelected();\n\t\tif (item) {\n\t\t\tunsigned i = getModel()->getCurQueryResult()->findIndex(item);\n\t\t\tif (i != 0xFFFFFFFF && i < getModel()->getCurQueryResult()->getCount() - 1) {\n\t\t\t\ti++;\n\t\t\t\tgetModel()->setSelected(getModel()->getCurQueryResult()->getIndex(i));\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ 以下是滚动的情况\n\t\t\/\/ NOTICE:\t很奇怪的现象,CScrollView在OnInitUpdate之外函数SetScrollSizes,\n\t\t\/\/\t\t\t如果设置的高度小于ClientRect,虽然没有显示滚动条仍然可以滚动,这里特殊处理一下,禁止滚动\n\t\tif (clientRect.Height() >= totalSize.cy) return;\n\n\t\tint yScrollPos = GetScrollPosition().y;\n\t\tif (::GetKeyState(VK_CONTROL) & 0x80000000) {\n\t\t\tif (nChar == VK_HOME) {\n\t\t\t\t\/\/ 跳到第一页\n\t\t\t\tyScrollPos = 0;\n\t\t\t} else if (nChar == VK_END) {\n\t\t\t\t\/\/ 跳到最后一页,多出没事\n\t\t\t\tyScrollPos = (getModel()->getCurQueryResult()->getCount()) * LineHeight;\n\t\t\t} else if (nChar == VK_UP) {\n\t\t\t\t\/\/ 向上1行\n\t\t\t\tyScrollPos -= LineHeight;\n\t\t\t\tyScrollPos = max(yScrollPos, 0);\n\t\t\t} else if (nChar == VK_DOWN) {\n\t\t\t\t\/\/ 向下1行\n\t\t\t\tyScrollPos += LineHeight;\n\t\t\t}\n\t\t}\n\t\tif (nChar == VK_PRIOR) {\n\t\t\t\/\/ 向上1页\n\t\t\tyScrollPos -= clientRect.Height() \/ LineHeight * LineHeight;\n\t\t\tyScrollPos = max(yScrollPos, 0);\n\t\t} else if (nChar == VK_NEXT) {\n\t\t\t\/\/ 向下1页\n\t\t\tyScrollPos += clientRect.Height() \/ LineHeight * LineHeight;\n\t\t}\n\t\tScrollToPosition(CPoint(0, yScrollPos));\n\t\tDEBUG_INFO(_T(\"滚动位置:\") << yScrollPos);\n\t}\n\t__super::OnKeyDown(nChar, nRepCnt, nFlags);\n}\n\n\nvoid CLogMainView::OnLButtonUp(UINT nFlags, CPoint point)\n{\n\tint yScrollPos = GetScrollPosition().y;\n\tthis->selectedLine = (yScrollPos + point.y) \/ LineHeight;\n\t__super::OnLButtonUp(nFlags, point);\n}\n<|endoftext|>"} {"text":"\/\/@author A0097630B\n#include \"stdafx.h\"\n#include \"query_executor.h\"\n#include \"..\/exceptions\/context_index_out_of_range_exception.h\"\n#include \"..\/result.h\"\n#include \"query_executor_builder_visitor.h\"\n\nnamespace You {\nnamespace Controller {\nnamespace Internal {\n\nusing You::NLP::TaskField;\nusing You::NLP::TaskPriority;\nusing You::NLP::QUERY;\nusing You::NLP::ADD_QUERY;\nusing You::NLP::SHOW_QUERY;\nusing You::NLP::EDIT_QUERY;\nusing You::NLP::DELETE_QUERY;\nusing You::NLP::UNDO_QUERY;\n\nQueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor(\n\tconst Controller::Context& context)\n\t: context(context) {\n}\n\n\nstd::unique_ptr buildQuery(const ADD_QUERY& query) {\n\tstd::vector> addSubtasks;\n\tstd::vector> addDependencies;\n\tfor (const auto& subtask : query.subtasks) {\n\t\taddSubtasks.emplace_back(buildQuery(subtask));\n\t}\n\tauto ptrDep = query.dependent;\n\twhile (query.dependent != nullptr) {\n\t\taddDependencies.emplace_back(buildQuery(*ptrDep));\n\t\tptrDep = ptrDep->dependent;\n\t}\n\treturn std::unique_ptr(\n\t\tQueryEngine::AddTask(\n\t\t\tquery.description,\n\t\t\tquery.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,\n\t\t\tquery.priority == TaskPriority::HIGH ?\n\t\t\tTask::Priority::HIGH : Task::Priority::NORMAL,\n\t\t\tstd::move(addDependencies),\n\t\t\tstd::move(addSubtasks)));\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const ADD_QUERY& query) {\n\tclass AddTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit AddTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~AddTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn ADD_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\treturn std::unique_ptr(\n\t\tnew AddTaskQueryExecutor(buildAddQuery(query)));\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::buildAddQuery(const ADD_QUERY& query) {\n\tstd::vector> subtaskQueries;\n\t\/\/subtaskQueries.reserve(query.subtasks.size());\n\n\tstd::transform(begin(query.subtasks), end(query.subtasks),\n\t\tstd::back_inserter(subtaskQueries), [](const ADD_QUERY& q) {\n\t\treturn QueryExecutorBuilderVisitor::buildAddQuery(q);\n\t});\n\n\treturn QueryEngine::AddTask(\n\t\tquery.description,\n\t\tquery.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,\n\t\tquery.priority == TaskPriority::HIGH ?\n\t\tTask::Priority::HIGH : Task::Priority::NORMAL,\n\t\t{},\n\t\tstd::move(subtaskQueries)\n\t);\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const SHOW_QUERY& query) {\n\tclass ShowTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit ShowTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~ShowTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn SHOW_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\tusing You::QueryEngine::Filter;\n\tusing You::QueryEngine::Comparator;\n\tFilter filter = Filter::anyTask();\n\tComparator comparator(Comparator::notSorted());\n\n\tstd::for_each(begin(query.predicates), end(query.predicates),\n\t\t[&filter](const SHOW_QUERY::FIELD_FILTER& field) {\n\t\t\tstd::function currentFilter;\n\t\t\tswitch (field.field) {\n\t\t\tcase TaskField::DESCRIPTION:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::getDescription,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tboost::get(field.value));\n\t\t\t\tbreak;\n\t\t\tcase TaskField::DEADLINE:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::getDeadline,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tboost::get(field.value));\n\t\t\t\tbreak;\n\t\t\tcase TaskField::COMPLETE:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::isCompleted,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tboost::get(field.value));\n\t\t\t\tbreak;\n\t\t\tcase TaskField::PRIORITY:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::getPriority,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tController::nlpToQueryEnginePriority(\n\t\t\t\t\t\tboost::get(field.value)));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false); abort();\n\t\t\t}\n\n\t\t\tfilter = filter && Filter(currentFilter);\n\t\t});\n\n\tstd::for_each(begin(query.order), end(query.order),\n\t\t[&comparator](const SHOW_QUERY::FIELD_ORDER& field) {\n\t\t\tComparator comp(Comparator::notSorted());\n\t\t\tswitch (field.field) {\n\t\t\tcase TaskField::DESCRIPTION:\n\t\t\t\tcomp = Comparator::byDescription();\n\t\t\t\tbreak;\n\t\t\tcase TaskField::DEADLINE:\n\t\t\t\tcomp = Comparator::byDeadline();\n\t\t\t\tbreak;\n\t\t\tcase TaskField::PRIORITY:\n\t\t\t\tcomp = Comparator::byPriority();\n\t\t\t\tbreak;\n\t\t\tcase TaskField::COMPLETE:\n\t\t\tdefault:\n\t\t\t\tassert(false); abort();\n\t\t\t}\n\n\t\t\tif (field.order == SHOW_QUERY::Order::ASCENDING) {\n\t\t\t\tcomp = comp.ascending();\n\t\t\t} else {\n\t\t\t\tcomp = comp.descending();\n\t\t\t}\n\n\t\t\tcomparator = comparator && comp;\n\t\t});\n\n\treturn std::unique_ptr(\n\t\tnew ShowTaskQueryExecutor(\n\t\t\tQueryEngine::GetTask(filter, comparator)\n\t\t)\n\t);\n}\n\ntemplate\nstd::function\nQueryExecutorBuilderVisitor::buildComparator(\n\tTValue(QueryEngine::Task::*selector)() const,\n\tSHOW_QUERY::Predicate predicate,\n\tconst TValue& value) {\n\tswitch (predicate) {\n\tcase SHOW_QUERY::Predicate::EQ:\n\t\treturn std::bind(std::equal_to(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::NOT_EQ:\n\t\treturn std::bind(std::not_equal_to(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::LESS_THAN:\n\t\treturn std::bind(std::less(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::LESS_THAN_EQ:\n\t\treturn std::bind(std::less_equal(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::GREATER_THAN:\n\t\treturn std::bind(std::greater(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::GREATER_THAN_EQ:\n\t\treturn std::bind(std::greater_equal(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tdefault:\n\t\tassert(false); abort();\n\t}\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const {\n\tclass EditTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit EditTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~EditTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn EDIT_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\ttry {\n\t\tTask::ID task = context.at(query.taskID).getID();\n\t\tYou::Utils::Option priority;\n\t\tif (query.priority) {\n\t\t\tpriority = Controller::nlpToQueryEnginePriority(\n\t\t\t\tquery.priority.get());\n\t\t}\n\n\t\tYou::Utils::Option subtasks;\n\t\tif (query.childTask) {\n\t\t\tTask::Subtasks subtasksList;\n\t\t\tsubtasksList.insert(context.at(query.childTask).getID());\n\t\t\tsubtasks = subtasksList;\n\t\t}\n\n\t\tYou::Utils::Option dependencies;\n\t\tif (query.dependingTask) {\n\t\t\tassert(!query.description &&\n\t\t\t\t!query.deadline &&\n\t\t\t\t!priority &&\n\t\t\t\t!query.complete &&\n\t\t\t\t!subtasks && \"Cannot change dependencies and other properties\");\n\t\t\tTask::Dependencies dependenciesList;\n\t\t\tdependenciesList.insert(task);\n\t\t\tdependencies = dependenciesList;\n\t\t\ttask = context.at(query.dependingTask).getID();\n\t\t}\n\n\t\treturn std::unique_ptr(\n\t\t\tnew EditTaskQueryExecutor(\n\t\t\t\tQueryEngine::UpdateTask(\n\t\t\t\t\ttask,\n\t\t\t\t\tquery.description,\n\t\t\t\t\tquery.deadline,\n\t\t\t\t\tpriority,\n\t\t\t\t\tdependencies,\n\t\t\t\t\tquery.complete,\n\t\t\t\t\tboost::none,\n\t\t\t\t\tsubtasks)));\n\t} catch (std::out_of_range& e) {\n\t\tthrow ContextIndexOutOfRangeException(e);\n\t}\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const {\n\tclass DeleteTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit DeleteTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~DeleteTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn DELETE_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\ttry {\n\t\tconst Task& task = context.at(query.taskID);\n\n\t\treturn std::unique_ptr(\n\t\t\tnew DeleteTaskQueryExecutor(\n\t\t\t\tQueryEngine::DeleteTask(\n\t\t\t\t\ttask.getID())));\n\t} catch (std::out_of_range& e) {\n\t\tthrow ContextIndexOutOfRangeException(e);\n\t}\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const UNDO_QUERY& query) const {\n\tclass UndoTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit UndoTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~UndoTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn UNDO_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\treturn std::unique_ptr(\n\t\tnew UndoTaskQueryExecutor(\n\t\t\tQueryEngine::Undo()));\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Controller\n} \/\/ namespace You\nConnect with controller\/\/@author A0097630B\n#include \"stdafx.h\"\n#include \"query_executor.h\"\n#include \"..\/exceptions\/context_index_out_of_range_exception.h\"\n#include \"..\/result.h\"\n#include \"query_executor_builder_visitor.h\"\n\nnamespace You {\nnamespace Controller {\nnamespace Internal {\n\nusing You::NLP::TaskField;\nusing You::NLP::TaskPriority;\nusing You::NLP::QUERY;\nusing You::NLP::ADD_QUERY;\nusing You::NLP::SHOW_QUERY;\nusing You::NLP::EDIT_QUERY;\nusing You::NLP::DELETE_QUERY;\nusing You::NLP::UNDO_QUERY;\n\nQueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor(\n\tconst Controller::Context& context)\n\t: context(context) {\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const ADD_QUERY& query) {\n\tclass AddTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit AddTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~AddTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn ADD_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\treturn std::unique_ptr(\n\t\tnew AddTaskQueryExecutor(buildAddQuery(query)));\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::buildAddQuery(const ADD_QUERY& query) {\n\tstd::vector> subtaskQueries;\n\tstd::vector> dependencyQueries;\n\t\/\/subtaskQueries.reserve(query.subtasks.size());\n\n\tstd::transform(begin(query.subtasks), end(query.subtasks),\n\t\tstd::back_inserter(subtaskQueries), [](const ADD_QUERY& q) {\n\t\treturn QueryExecutorBuilderVisitor::buildAddQuery(q);\n\t});\n\n\tstd::shared_ptr dependentQuery = query.dependent;\n\twhile (dependentQuery) {\n\t\tdependencyQueries.push_back(buildAddQuery(*dependentQuery));\n\t\tdependentQuery = (query.dependent)->dependent;\n\t}\n\n\treturn QueryEngine::AddTask(\n\t\tquery.description,\n\t\tquery.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,\n\t\tquery.priority == TaskPriority::HIGH ?\n\t\tTask::Priority::HIGH : Task::Priority::NORMAL,\n\t\tstd::move(dependencyQueries),\n\t\tstd::move(subtaskQueries)\n\t);\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const SHOW_QUERY& query) {\n\tclass ShowTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit ShowTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~ShowTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn SHOW_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\tusing You::QueryEngine::Filter;\n\tusing You::QueryEngine::Comparator;\n\tFilter filter = Filter::anyTask();\n\tComparator comparator(Comparator::notSorted());\n\n\tstd::for_each(begin(query.predicates), end(query.predicates),\n\t\t[&filter](const SHOW_QUERY::FIELD_FILTER& field) {\n\t\t\tstd::function currentFilter;\n\t\t\tswitch (field.field) {\n\t\t\tcase TaskField::DESCRIPTION:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::getDescription,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tboost::get(field.value));\n\t\t\t\tbreak;\n\t\t\tcase TaskField::DEADLINE:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::getDeadline,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tboost::get(field.value));\n\t\t\t\tbreak;\n\t\t\tcase TaskField::COMPLETE:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::isCompleted,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tboost::get(field.value));\n\t\t\t\tbreak;\n\t\t\tcase TaskField::PRIORITY:\n\t\t\t\tassert(boost::get(&field.value));\n\t\t\t\tcurrentFilter = buildComparator(&Task::getPriority,\n\t\t\t\t\tfield.predicate,\n\t\t\t\t\tController::nlpToQueryEnginePriority(\n\t\t\t\t\t\tboost::get(field.value)));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false); abort();\n\t\t\t}\n\n\t\t\tfilter = filter && Filter(currentFilter);\n\t\t});\n\n\tstd::for_each(begin(query.order), end(query.order),\n\t\t[&comparator](const SHOW_QUERY::FIELD_ORDER& field) {\n\t\t\tComparator comp(Comparator::notSorted());\n\t\t\tswitch (field.field) {\n\t\t\tcase TaskField::DESCRIPTION:\n\t\t\t\tcomp = Comparator::byDescription();\n\t\t\t\tbreak;\n\t\t\tcase TaskField::DEADLINE:\n\t\t\t\tcomp = Comparator::byDeadline();\n\t\t\t\tbreak;\n\t\t\tcase TaskField::PRIORITY:\n\t\t\t\tcomp = Comparator::byPriority();\n\t\t\t\tbreak;\n\t\t\tcase TaskField::COMPLETE:\n\t\t\tdefault:\n\t\t\t\tassert(false); abort();\n\t\t\t}\n\n\t\t\tif (field.order == SHOW_QUERY::Order::ASCENDING) {\n\t\t\t\tcomp = comp.ascending();\n\t\t\t} else {\n\t\t\t\tcomp = comp.descending();\n\t\t\t}\n\n\t\t\tcomparator = comparator && comp;\n\t\t});\n\n\treturn std::unique_ptr(\n\t\tnew ShowTaskQueryExecutor(\n\t\t\tQueryEngine::GetTask(filter, comparator)\n\t\t)\n\t);\n}\n\ntemplate\nstd::function\nQueryExecutorBuilderVisitor::buildComparator(\n\tTValue(QueryEngine::Task::*selector)() const,\n\tSHOW_QUERY::Predicate predicate,\n\tconst TValue& value) {\n\tswitch (predicate) {\n\tcase SHOW_QUERY::Predicate::EQ:\n\t\treturn std::bind(std::equal_to(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::NOT_EQ:\n\t\treturn std::bind(std::not_equal_to(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::LESS_THAN:\n\t\treturn std::bind(std::less(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::LESS_THAN_EQ:\n\t\treturn std::bind(std::less_equal(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::GREATER_THAN:\n\t\treturn std::bind(std::greater(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tcase SHOW_QUERY::Predicate::GREATER_THAN_EQ:\n\t\treturn std::bind(std::greater_equal(),\n\t\t\tstd::bind(selector, std::placeholders::_1),\n\t\t\tvalue);\n\tdefault:\n\t\tassert(false); abort();\n\t}\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const {\n\tclass EditTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit EditTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~EditTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn EDIT_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\ttry {\n\t\tTask::ID task = context.at(query.taskID).getID();\n\t\tYou::Utils::Option priority;\n\t\tif (query.priority) {\n\t\t\tpriority = Controller::nlpToQueryEnginePriority(\n\t\t\t\tquery.priority.get());\n\t\t}\n\n\t\tYou::Utils::Option subtasks;\n\t\tif (query.childTask) {\n\t\t\tTask::Subtasks subtasksList;\n\t\t\tsubtasksList.insert(context.at(query.childTask).getID());\n\t\t\tsubtasks = subtasksList;\n\t\t}\n\n\t\tYou::Utils::Option dependencies;\n\t\tif (query.dependingTask) {\n\t\t\tassert(!query.description &&\n\t\t\t\t!query.deadline &&\n\t\t\t\t!priority &&\n\t\t\t\t!query.complete &&\n\t\t\t\t!subtasks && \"Cannot change dependencies and other properties\");\n\t\t\tTask::Dependencies dependenciesList;\n\t\t\tdependenciesList.insert(task);\n\t\t\tdependencies = dependenciesList;\n\t\t\ttask = context.at(query.dependingTask).getID();\n\t\t}\n\n\t\treturn std::unique_ptr(\n\t\t\tnew EditTaskQueryExecutor(\n\t\t\t\tQueryEngine::UpdateTask(\n\t\t\t\t\ttask,\n\t\t\t\t\tquery.description,\n\t\t\t\t\tquery.deadline,\n\t\t\t\t\tpriority,\n\t\t\t\t\tdependencies,\n\t\t\t\t\tquery.complete,\n\t\t\t\t\tboost::none,\n\t\t\t\t\tsubtasks)));\n\t} catch (std::out_of_range& e) {\n\t\tthrow ContextIndexOutOfRangeException(e);\n\t}\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const {\n\tclass DeleteTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit DeleteTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~DeleteTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn DELETE_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\ttry {\n\t\tconst Task& task = context.at(query.taskID);\n\n\t\treturn std::unique_ptr(\n\t\t\tnew DeleteTaskQueryExecutor(\n\t\t\t\tQueryEngine::DeleteTask(\n\t\t\t\t\ttask.getID())));\n\t} catch (std::out_of_range& e) {\n\t\tthrow ContextIndexOutOfRangeException(e);\n\t}\n}\n\nstd::unique_ptr\nQueryExecutorBuilderVisitor::build(const UNDO_QUERY& query) const {\n\tclass UndoTaskQueryExecutor : public QueryExecutor {\n\tpublic:\n\t\texplicit UndoTaskQueryExecutor(\n\t\t\tstd::unique_ptr&& query)\n\t\t\t: QueryExecutor(std::move(query)) {\n\t\t}\n\n\t\tvirtual ~UndoTaskQueryExecutor() = default;\n\n\tprotected:\n\t\tResult processResponse(\n\t\t\tconst You::QueryEngine::Response& response) override {\n\t\t\treturn UNDO_RESULT {\n\t\t\t\tboost::get(response)\n\t\t\t};\n\t\t}\n\t};\n\n\treturn std::unique_ptr(\n\t\tnew UndoTaskQueryExecutor(\n\t\t\tQueryEngine::Undo()));\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Controller\n} \/\/ namespace You\n<|endoftext|>"} {"text":"#ifndef VIENNAGRID_STORAGE_ID_HPP\n#define VIENNAGRID_STORAGE_ID_HPP\n#include \n#include \n\n\nnamespace viennagrid\n{\n\n namespace storage\n {\n template\n struct id_tag;\n \n template\n struct smart_id_tag;\n \n \n template\n class smart_id\n {\n public:\n typedef smart_id self_type;\n typedef value_type_ value_type;\n \n smart_id() : internal_id(0) {}\n explicit smart_id( base_id_type internal_id_ ) : internal_id(internal_id_) {}\n \n base_id_type get() const { return internal_id; }\n void set( base_id_type internal_id_ ) { internal_id =internal_id_; }\n \n bool operator== ( self_type rhs ) const { return internal_id == rhs.internal_id; }\n bool operator< ( self_type rhs ) const { return internal_id < rhs.internal_id; }\n bool operator<= ( self_type rhs ) const { return internal_id <= rhs.internal_id; }\n bool operator> ( self_type rhs ) const { return internal_id > rhs.internal_id; }\n bool operator>= (self_type rhs ) const { return internal_id >= rhs.internal_id; }\n \n self_type & operator++() { ++internal_id; return *this; }\n self_type operator++(int) { self_type tmp(*this); ++*this; return tmp; }\n \n private:\n base_id_type internal_id;\n };\n \n template\n std::ostream & operator<< (std::ostream & os, smart_id id)\n {\n os << id.get();\n return os;\n }\n \n namespace result_of\n {\n template\n struct id;\n \n template\n struct id >\n {\n typedef id_type type;\n };\n \n template\n struct id >\n {\n typedef smart_id type;\n };\n \n }\n \n \n\/\/ template\n\/\/ smart_id operator+( const smart_id & lhs, const smart_id & rhs )\n\/\/ {\n\/\/ return smart_id( lhs.get() + rhs.get() );\n\/\/ }\n \n\/\/ template\n\/\/ base_id_type operator-( const smart_id & lhs, const smart_id & rhs )\n\/\/ {\n\/\/ return smart_id( lhs.get() - rhs.get() );\n\/\/ }\n \n \n\n \n template\n class id_handler\n {\n public:\n typedef id_type_ id_type;\n \n id_handler() {}\n id_handler(const id_handler & rhs) : id_(rhs.id_) {}\n \n void id(id_type id) { id_ = id; }\n id_type id() const { return id_; }\n\n private:\n id_type id_;\n };\n \n\n \n template\n class id_compare\n {\n public:\n typedeef id_type_ id_type;\n \n id_compare(id_type id__) : id(id__) {}\n \n template\n bool operator() ( const type & to_compare )\n {\n return to_compare.id() == id;\n }\n \n private:\n id_type id;\n };\n \n namespace id\n {\n \n template\n void set_id( element_type & element, id_type id )\n {\n element.id(id);\n }\n \n template void set_id( bool & element, id_type id ) {}\n template void set_id( char & element, id_type id ) {}\n template void set_id( unsigned char & element, id_type id ) {}\n template void set_id( short & element, id_type id ) {}\n template void set_id( unsigned short & element, id_type id ) {}\n template void set_id( int & element, id_type id ) {}\n template void set_id( unsigned int & element, id_type id ) {}\n template void set_id( long & element, id_type id ) {}\n template void set_id( unsigned long & element, id_type id ) {}\n template void set_id( float & element, id_type id ) {}\n template void set_id( double & element, id_type id ) {}\n \n }\n \n \n }\n \n}\n\n#endif\ntemplate\nclass result_of;fixed typo#ifndef VIENNAGRID_STORAGE_ID_HPP\n#define VIENNAGRID_STORAGE_ID_HPP\n#include \n#include \n\n\nnamespace viennagrid\n{\n\n namespace storage\n {\n template\n struct id_tag;\n \n template\n struct smart_id_tag;\n \n \n template\n class smart_id\n {\n public:\n typedef smart_id self_type;\n typedef value_type_ value_type;\n \n smart_id() : internal_id(0) {}\n explicit smart_id( base_id_type internal_id_ ) : internal_id(internal_id_) {}\n \n base_id_type get() const { return internal_id; }\n void set( base_id_type internal_id_ ) { internal_id =internal_id_; }\n \n bool operator== ( self_type rhs ) const { return internal_id == rhs.internal_id; }\n bool operator< ( self_type rhs ) const { return internal_id < rhs.internal_id; }\n bool operator<= ( self_type rhs ) const { return internal_id <= rhs.internal_id; }\n bool operator> ( self_type rhs ) const { return internal_id > rhs.internal_id; }\n bool operator>= (self_type rhs ) const { return internal_id >= rhs.internal_id; }\n \n self_type & operator++() { ++internal_id; return *this; }\n self_type operator++(int) { self_type tmp(*this); ++*this; return tmp; }\n \n private:\n base_id_type internal_id;\n };\n \n template\n std::ostream & operator<< (std::ostream & os, smart_id id)\n {\n os << id.get();\n return os;\n }\n \n namespace result_of\n {\n template\n struct id;\n \n template\n struct id >\n {\n typedef id_type type;\n };\n \n template\n struct id >\n {\n typedef smart_id type;\n };\n \n }\n \n \n\/\/ template\n\/\/ smart_id operator+( const smart_id & lhs, const smart_id & rhs )\n\/\/ {\n\/\/ return smart_id( lhs.get() + rhs.get() );\n\/\/ }\n \n\/\/ template\n\/\/ base_id_type operator-( const smart_id & lhs, const smart_id & rhs )\n\/\/ {\n\/\/ return smart_id( lhs.get() - rhs.get() );\n\/\/ }\n \n \n\n \n template\n class id_handler\n {\n public:\n typedef id_type_ id_type;\n \n id_handler() {}\n id_handler(const id_handler & rhs) : id_(rhs.id_) {}\n \n void id(id_type id) { id_ = id; }\n id_type id() const { return id_; }\n\n private:\n id_type id_;\n };\n \n\n \n template\n class id_compare\n {\n public:\n typedef id_type_ id_type;\n \n id_compare(id_type id__) : id(id__) {}\n \n template\n bool operator() ( const type & to_compare )\n {\n return to_compare.id() == id;\n }\n \n private:\n id_type id;\n };\n \n namespace id\n {\n \n template\n void set_id( element_type & element, id_type id )\n {\n element.id(id);\n }\n \n template void set_id( bool & element, id_type id ) {}\n template void set_id( char & element, id_type id ) {}\n template void set_id( unsigned char & element, id_type id ) {}\n template void set_id( short & element, id_type id ) {}\n template void set_id( unsigned short & element, id_type id ) {}\n template void set_id( int & element, id_type id ) {}\n template void set_id( unsigned int & element, id_type id ) {}\n template void set_id( long & element, id_type id ) {}\n template void set_id( unsigned long & element, id_type id ) {}\n template void set_id( float & element, id_type id ) {}\n template void set_id( double & element, id_type id ) {}\n \n }\n \n \n }\n \n}\n\n#endif\ntemplate\nclass result_of;<|endoftext|>"} {"text":"#include\n#include\n#include \"vmf\/metadatastream.hpp\"\n#include \"..\/com_intel_vmf_MetadataSet.h\"\n\nusing namespace vmf;\n\nstatic void throwJavaException(JNIEnv *env, const std::exception *e, const char *method)\n{\n std::string what = \"unknown exception\";\n jclass je = 0;\n\n if (e)\n {\n std::string exception_type = \"std::exception\";\n\n if (dynamic_cast(e))\n {\n exception_type = \"vmf::Exception\";\n je = env->FindClass(\"com\/intel\/vmf\/VmfException\");\n }\n\n what = exception_type + \": \" + e->what();\n }\n\n if (!je)\n je = env->FindClass(\"java\/lang\/Exception\");\n\n env->ThrowNew(je, what.c_str());\n\n VMF_LOG_ERROR(what.c_str());\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_MetadataSet\n * Signature: ()J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__ (JNIEnv *env, jclass)\n{\n std::shared_ptr* p = new std::shared_ptr(new MetadataSet());\n return (jlong) p;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_MetadataSet\n * Signature: (J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__J (JNIEnv *, jclass, jlong otherAddr)\n{\n std::shared_ptr* other = (std::shared_ptr*)otherAddr;\n return (jlong) new std::shared_ptr (new MetadataSet (**other));\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_setTo\n * Signature: (JJ)V\n *\/\nJNIEXPORT void JNICALL Java_com_intel_vmf_MetadataSet_n_1setTo (JNIEnv *, jclass, jlong selfAddr, jlong otherAddr)\n{\n std::shared_ptr* self = (std::shared_ptr*)selfAddr;\n std::shared_ptr* other = (std::shared_ptr*)otherAddr;\n (**self) = (**other);\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByFrameIndex\n * Signature: (JJ)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByFrameIndex (JNIEnv *env, jclass, jlong self, jlong id)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByFrameIndex\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n size_t index = (size_t) id;\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByFrameIndex(index)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByTime\n * Signature: (JJJ)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByTime (JNIEnv *env, jclass, jlong self, jlong startTime, jlong endTime)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByTime\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByTime((long long)startTime, (long long)endTime)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryBySchema\n * Signature: (JLjava\/lang\/String;)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryBySchema (JNIEnv *env, jclass, jlong self, jstring schemaName)\n{\n static const char method_name[] = \"MetadataSet::n_1queryBySchema\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (schemaName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryBySchema(sName)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByName\n * Signature: (JLjava\/lang\/String;)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByName (JNIEnv *env, jclass, jlong self, jstring mdName)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByName\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (mdName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByName(sName)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByNameAndValue\n * Signature: (JLjava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndValue (JNIEnv *env, jclass, jlong self, jstring mdName, jlong fieldValueAddr)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByNameAndValue\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::shared_ptr* value = (std::shared_ptr*)fieldValueAddr;\n std::string sName (env->GetStringUTFChars (mdName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByNameAndValue(sName, (**value))));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByNameAndFields\n * Signature: (JLjava\/lang\/String;[J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndFields (JNIEnv *env, jclass, jlong self, jstring mdName, jlongArray fieldValues)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByNameAndFields\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::vector values;\n \n std::string sName (env->GetStringUTFChars (mdName, NULL));\n jlong* cArray= env->GetLongArrayElements (fieldValues, 0);\n jsize len = env->GetArrayLength (fieldValues);\n \n for (int i = 0; i < len; i++)\n {\n std::shared_ptr* addr = (std::shared_ptr*)cArray[i];\n values.push_back (**addr);\n }\n \n env->ReleaseLongArrayElements (fieldValues, cArray, 0);\n return (jlong) new std::shared_ptr(new MetadataSet ((*obj)->queryByNameAndFields(sName, values)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByReference\n * Signature: (JLjava\/lang\/String;)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2 (JNIEnv *env, jclass, jlong self, jstring refName)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByReference__JLjava_lang_String_2\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (refName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByReference(sName)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByReference\n * Signature: (JLjava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2J (JNIEnv *env, jclass, jlong self, jstring refName, jlong valueAddr)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByReference__JLjava_lang_String_2J\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::shared_ptr* value = (std::shared_ptr*)valueAddr;\n std::string sName (env->GetStringUTFChars (refName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByReference(sName, **value)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByReference\n * Signature: (JLjava\/lang\/String;[J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2_3J (JNIEnv *env, jclass, jlong self, jstring refName, jlongArray fieldValues)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByReference__JLjava_lang_String_2_3J\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (refName, NULL));\n jlong *body = env->GetLongArrayElements (fieldValues, 0);\n std::vector values;\n jsize len = env->GetArrayLength (fieldValues);\n \n for (int i = 0; i < len; i++)\n {\n std::shared_ptr* addr = (std::shared_ptr*)body[i];\n values.push_back (**addr);\n }\n \n env->ReleaseLongArrayElements (fieldValues, body, 0);\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByReference(sName, values)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_shift\n * Signature: (JJJJJ)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1shift (JNIEnv *env, jclass, jlong self, jlong dstFrameIndex, jlong srcFrameIndex, jlong numOfFrames, jlong setFailureAddr)\n{\n static const char method_name[] = \"MetadataSet::n_1shift\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::shared_ptr* setFailure = (std::shared_ptr*)setFailureAddr;\n \n return (jlong) (*obj)->shift((long long) dstFrameIndex, (long long) srcFrameIndex, (long long) numOfFrames, (*setFailure).get());\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_delete\n * Signature: (J)V\n *\/\nJNIEXPORT void JNICALL Java_com_intel_vmf_MetadataSet_n_1delete (JNIEnv *env, jclass, jlong self)\n{\n static const char method_name[] = \"MetadataSet::n_1delete\";\n\n try\n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n delete obj;\n }\n catch (const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n }\n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n}\nfix for gcc compilation issue 2#include\n#include\n#include \"vmf\/metadatastream.hpp\"\n#include \"..\/com_intel_vmf_MetadataSet.h\"\n\nusing namespace vmf;\n\nstatic void throwJavaException(JNIEnv *env, const std::exception *e, const char *method)\n{\n std::string what = \"unknown exception\";\n jclass je = 0;\n\n if (e)\n {\n std::string exception_type = \"std::exception\";\n\n if (dynamic_cast(e))\n {\n exception_type = \"vmf::Exception\";\n je = env->FindClass(\"com\/intel\/vmf\/VmfException\");\n }\n\n what = exception_type + \": \" + e->what();\n }\n\n if (!je)\n je = env->FindClass(\"java\/lang\/Exception\");\n\n env->ThrowNew(je, what.c_str());\n\n VMF_LOG_ERROR(what.c_str());\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_MetadataSet\n * Signature: ()J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__ (JNIEnv *env, jclass)\n{\n std::shared_ptr* p = new std::shared_ptr(new MetadataSet());\n return (jlong) p;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_MetadataSet\n * Signature: (J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__J (JNIEnv *, jclass, jlong otherAddr)\n{\n std::shared_ptr* other = (std::shared_ptr*)otherAddr;\n return (jlong) new std::shared_ptr (new MetadataSet (**other));\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_setTo\n * Signature: (JJ)V\n *\/\nJNIEXPORT void JNICALL Java_com_intel_vmf_MetadataSet_n_1setTo (JNIEnv *, jclass, jlong selfAddr, jlong otherAddr)\n{\n std::shared_ptr* self = (std::shared_ptr*)selfAddr;\n std::shared_ptr* other = (std::shared_ptr*)otherAddr;\n MetadataSet tmp = (*(*other));\n (*(*self)) = tmp;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByFrameIndex\n * Signature: (JJ)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByFrameIndex (JNIEnv *env, jclass, jlong self, jlong id)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByFrameIndex\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n size_t index = (size_t) id;\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByFrameIndex(index)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByTime\n * Signature: (JJJ)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByTime (JNIEnv *env, jclass, jlong self, jlong startTime, jlong endTime)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByTime\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByTime((long long)startTime, (long long)endTime)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryBySchema\n * Signature: (JLjava\/lang\/String;)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryBySchema (JNIEnv *env, jclass, jlong self, jstring schemaName)\n{\n static const char method_name[] = \"MetadataSet::n_1queryBySchema\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (schemaName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryBySchema(sName)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByName\n * Signature: (JLjava\/lang\/String;)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByName (JNIEnv *env, jclass, jlong self, jstring mdName)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByName\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (mdName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByName(sName)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByNameAndValue\n * Signature: (JLjava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndValue (JNIEnv *env, jclass, jlong self, jstring mdName, jlong fieldValueAddr)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByNameAndValue\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::shared_ptr* value = (std::shared_ptr*)fieldValueAddr;\n std::string sName (env->GetStringUTFChars (mdName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByNameAndValue(sName, (**value))));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByNameAndFields\n * Signature: (JLjava\/lang\/String;[J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndFields (JNIEnv *env, jclass, jlong self, jstring mdName, jlongArray fieldValues)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByNameAndFields\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::vector values;\n \n std::string sName (env->GetStringUTFChars (mdName, NULL));\n jlong* cArray= env->GetLongArrayElements (fieldValues, 0);\n jsize len = env->GetArrayLength (fieldValues);\n \n for (int i = 0; i < len; i++)\n {\n std::shared_ptr* addr = (std::shared_ptr*)cArray[i];\n values.push_back (**addr);\n }\n \n env->ReleaseLongArrayElements (fieldValues, cArray, 0);\n return (jlong) new std::shared_ptr(new MetadataSet ((*obj)->queryByNameAndFields(sName, values)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByReference\n * Signature: (JLjava\/lang\/String;)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2 (JNIEnv *env, jclass, jlong self, jstring refName)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByReference__JLjava_lang_String_2\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (refName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByReference(sName)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByReference\n * Signature: (JLjava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2J (JNIEnv *env, jclass, jlong self, jstring refName, jlong valueAddr)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByReference__JLjava_lang_String_2J\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::shared_ptr* value = (std::shared_ptr*)valueAddr;\n std::string sName (env->GetStringUTFChars (refName, NULL));\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByReference(sName, **value)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_queryByReference\n * Signature: (JLjava\/lang\/String;[J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2_3J (JNIEnv *env, jclass, jlong self, jstring refName, jlongArray fieldValues)\n{\n static const char method_name[] = \"MetadataSet::n_1queryByReference__JLjava_lang_String_2_3J\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::string sName (env->GetStringUTFChars (refName, NULL));\n jlong *body = env->GetLongArrayElements (fieldValues, 0);\n std::vector values;\n jsize len = env->GetArrayLength (fieldValues);\n \n for (int i = 0; i < len; i++)\n {\n std::shared_ptr* addr = (std::shared_ptr*)body[i];\n values.push_back (**addr);\n }\n \n env->ReleaseLongArrayElements (fieldValues, body, 0);\n return (jlong) new std::shared_ptr(new MetadataSet((*obj)->queryByReference(sName, values)));\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_shift\n * Signature: (JJJJJ)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1shift (JNIEnv *env, jclass, jlong self, jlong dstFrameIndex, jlong srcFrameIndex, jlong numOfFrames, jlong setFailureAddr)\n{\n static const char method_name[] = \"MetadataSet::n_1shift\";\n \n try \n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n std::shared_ptr* setFailure = (std::shared_ptr*)setFailureAddr;\n \n return (jlong) (*obj)->shift((long long) dstFrameIndex, (long long) srcFrameIndex, (long long) numOfFrames, (*setFailure).get());\n }\n catch(const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n } \n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n \n return 0;\n}\n\n\/*\n * Class: com_intel_vmf_MetadataSet\n * Method: n_delete\n * Signature: (J)V\n *\/\nJNIEXPORT void JNICALL Java_com_intel_vmf_MetadataSet_n_1delete (JNIEnv *env, jclass, jlong self)\n{\n static const char method_name[] = \"MetadataSet::n_1delete\";\n\n try\n {\n std::shared_ptr* obj = (std::shared_ptr*)self;\n delete obj;\n }\n catch (const std::exception &e)\n {\n throwJavaException(env, &e, method_name);\n }\n catch (...)\n {\n throwJavaException(env, 0, method_name);\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkMutualInformationMetricTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"itkImage.h\"\n#include \"itkImageRegionIterator.h\"\n\n#include \"itkImageMapper.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkMutualInformationImageToImageMetric.h\"\n\n#include \n\n\/**\n * This test uses two 2D-Gaussians (standard deviation RegionSize\/2)\n * One is shifted by 5 pixels from the other.\n *\n * This test computes the mutual information value and derivatives\n * for various shift values in (-10,10).\n *\n *\/\n\nint main()\n{\n\n\/\/------------------------------------------------------------\n\/\/ Create two simple images\n\/\/------------------------------------------------------------\n\n \/\/Allocate Images\n typedef itk::Image ReferenceType;\n typedef itk::Image TargetType;\n enum { ImageDimension = ReferenceType::ImageDimension };\n\n ReferenceType::SizeType size = {{100,100}};\n ReferenceType::IndexType index = {{0,0}};\n ReferenceType::RegionType region;\n region.SetSize( size );\n region.SetIndex( index );\n\n ReferenceType::Pointer imgReference = ReferenceType::New();\n imgReference->SetLargestPossibleRegion( region );\n imgReference->SetBufferedRegion( region );\n imgReference->SetRequestedRegion( region );\n imgReference->Allocate();\n\n TargetType::Pointer imgTarget = TargetType::New();\n imgTarget->SetLargestPossibleRegion( region );\n imgTarget->SetBufferedRegion( region );\n imgTarget->SetRequestedRegion( region );\n imgTarget->Allocate();\n\n \/\/ Fill images with a 2D gaussian\n typedef itk::ImageRegionIterator\n ReferenceIteratorType;\n typedef itk::ImageRegionIterator\n TargetIteratorType;\n\n itk::Point center;\n center[0] = (double)region.GetSize()[0]\/2.0;\n center[1] = (double)region.GetSize()[1]\/2.0;\n\n const double s = (double)region.GetSize()[0]\/2.0;\n\n itk::Point p;\n itk::Vector d;\n\n \/\/ Set the displacement\n itk::Vector displacement;\n displacement[0] = 5;\n displacement[1] = 0;\n\n ReferenceIteratorType ri(imgReference,region);\n TargetIteratorType ti(imgTarget,region);\n ri.Begin();\n while(!ri.IsAtEnd())\n {\n p[0] = ri.GetIndex()[0];\n p[1] = ri.GetIndex()[1];\n d = p-center;\n d += displacement;\n const double x = d[0];\n const double y = d[1];\n ri.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ri;\n }\n\n\n ti.Begin();\n while(!ti.IsAtEnd())\n {\n p[0] = ti.GetIndex()[0];\n p[1] = ti.GetIndex()[1];\n d = p-center;\n const double x = d[0];\n const double y = d[1];\n ti.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ti;\n }\n\n\/\/-----------------------------------------------------------\n\/\/ Set up a transformer\n\/\/-----------------------------------------------------------\n enum{ ParametersDimension = ImageDimension * ( ImageDimension + 1 ) };\n typedef itk::Vector ParametersType;\n typedef itk::AffineTransform<\n double, ImageDimension, ParametersType > TransformType;\n\n TransformType::Pointer transformer = TransformType::New();\n\n\/\/------------------------------------------------------------\n\/\/ Set up a mapper\n\/\/------------------------------------------------------------\n typedef itk::ImageMapper< ReferenceType, TransformType >\n MapperType;\n\n MapperType::Pointer mapper = MapperType::New();\n\n \/\/ connect the transformer to the mapper\n mapper->SetTransform( transformer );\n\n \/\/ connect the reference image to the mapper\n mapper->SetDomain( imgReference );\n\n\/\/------------------------------------------------------------\n\/\/ Set up the metric\n\/\/------------------------------------------------------------\n typedef itk::MutualInformationImageToImageMetric<\n TargetType, MapperType > MetricType;\n\n MetricType::Pointer metric = MetricType::New();\n\n \/\/ connect the mapper to the metric\n metric->SetMapper( mapper );\n\n \/\/ connect the target image to the mapper\n metric->SetTarget( imgTarget );\n\n \/\/ set the standard deviations\n metric->SetTargetStandardDeviation( 5.0 );\n metric->SetReferenceStandardDeviation( 5.0 );\n\n \/\/ set the number of samples to use\n metric->SetNumberOfSpatialSamples( 100 );\n\n\/\/------------------------------------------------------------\n\/\/ Set up a affine transform parameters\n\/\/------------------------------------------------------------\n ParametersType parameters;\n\n \/\/ set the parameters to the identity\n ParametersType::Iterator it = parameters.Begin();\n\n \/\/ initialize the linear\/matrix part\n for( unsigned int row = 0; row < ImageDimension; row++ )\n {\n for( unsigned int col = 0; col < ImageDimension; col++ )\n {\n *it = 0;\n if( row == col )\n {\n *it = 1;\n }\n ++it;\n }\n }\n\n \/\/ initialize the offset\/vector part\n for( unsigned int k = 0; k < ImageDimension; k++ )\n {\n *it = 0;\n ++it;\n }\n\n\n\/\/---------------------------------------------------------\n\/\/ Print out mutual information values\n\/\/ for parameters[4] = {-10,10}\n\/\/---------------------------------------------------------\n\n MetricType::MeasureType measure;\n MetricType::DerivativeType derivative;\n\n printf(\"%s\\t%s\\t%s\\n\", \"param[4]\", \"MI\", \"dMI\/dparam[4]\" );\n\n for( double trans = -10; trans <= 5; trans += 0.5 )\n {\n parameters[4] = trans;\n metric->GetValueAndDerivative( parameters, measure, derivative );\n\n printf( \"%f\\t%f\\t%f\\n\", trans, measure,\n derivative[4] );\n\n \/\/ exercise the other functions\n metric->GetValue( parameters );\n metric->GetDerivative( parameters );\n\n }\n\n\/\/-------------------------------------------------------\n\/\/ exercise misc member functions\n\/\/-------------------------------------------------------\n std::cout << \"Name of class: \" <<\n metric->GetNameOfClass() << std::endl;\n std::cout << \"No. of samples used = \" << \n metric->GetNumberOfSpatialSamples() << std::endl;\n std::cout << \"Target std dev = \" <<\n metric->GetTargetStandardDeviation() << std::endl;\n std::cout << \"Reference std dev = \" <<\n metric->GetReferenceStandardDeviation() << std::endl;\n\n std::cout << \"Try causing a exception by making std dev too small\";\n std::cout << std::endl;\n metric->SetTargetStandardDeviation( 0.001 );\n try\n {\n std::cout << \"Value = \" << metric->GetValue( parameters );\n std::cout << std::endl;\n }\n catch(...)\n {\n std::cout << \"Caught the exception.\" << std::endl;\n }\n\n \/\/ reset standard deviation\n metric->SetTargetStandardDeviation( 5.0 );\n\n std::cout << \"Check case when Target is NULL\" << std::endl;\n metric->SetTarget( NULL );\n std::cout << \"Value = \" << metric->GetValue( parameters );\n std::cout << std::endl;\n \n metric->GetValueAndDerivative( parameters, measure, derivative );\n std::cout << \"Value = \" << measure << std::endl;\n\n\n return EXIT_SUCCESS;\n\n}\n\nENH: tests more member functions. Cleanup spacing\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkMutualInformationMetricTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"itkImage.h\"\n#include \"itkImageRegionIterator.h\"\n\n#include \"itkImageMapper.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkMutualInformationImageToImageMetric.h\"\n\n#include \n\n\/**\n * This test uses two 2D-Gaussians (standard deviation RegionSize\/2)\n * One is shifted by 5 pixels from the other.\n *\n * This test computes the mutual information value and derivatives\n * for various shift values in (-10,10).\n *\n *\/\n\nint main()\n{\n\n\/\/------------------------------------------------------------\n\/\/ Create two simple images\n\/\/------------------------------------------------------------\n\n \/\/Allocate Images\n typedef itk::Image ReferenceType;\n typedef itk::Image TargetType;\n enum { ImageDimension = ReferenceType::ImageDimension };\n\n ReferenceType::SizeType size = {{100,100}};\n ReferenceType::IndexType index = {{0,0}};\n ReferenceType::RegionType region;\n region.SetSize( size );\n region.SetIndex( index );\n\n ReferenceType::Pointer imgReference = ReferenceType::New();\n imgReference->SetLargestPossibleRegion( region );\n imgReference->SetBufferedRegion( region );\n imgReference->SetRequestedRegion( region );\n imgReference->Allocate();\n\n TargetType::Pointer imgTarget = TargetType::New();\n imgTarget->SetLargestPossibleRegion( region );\n imgTarget->SetBufferedRegion( region );\n imgTarget->SetRequestedRegion( region );\n imgTarget->Allocate();\n\n \/\/ Fill images with a 2D gaussian\n typedef itk::ImageRegionIterator\n ReferenceIteratorType;\n typedef itk::ImageRegionIterator\n TargetIteratorType;\n\n itk::Point center;\n center[0] = (double)region.GetSize()[0]\/2.0;\n center[1] = (double)region.GetSize()[1]\/2.0;\n\n const double s = (double)region.GetSize()[0]\/2.0;\n\n itk::Point p;\n itk::Vector d;\n\n \/\/ Set the displacement\n itk::Vector displacement;\n displacement[0] = 5;\n displacement[1] = 0;\n\n ReferenceIteratorType ri(imgReference,region);\n TargetIteratorType ti(imgTarget,region);\n ri.Begin();\n while(!ri.IsAtEnd())\n {\n p[0] = ri.GetIndex()[0];\n p[1] = ri.GetIndex()[1];\n d = p-center;\n d += displacement;\n const double x = d[0];\n const double y = d[1];\n ri.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ri;\n }\n\n\n ti.Begin();\n while(!ti.IsAtEnd())\n {\n p[0] = ti.GetIndex()[0];\n p[1] = ti.GetIndex()[1];\n d = p-center;\n const double x = d[0];\n const double y = d[1];\n ti.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ti;\n }\n\n\/\/-----------------------------------------------------------\n\/\/ Set up a transformer\n\/\/-----------------------------------------------------------\n enum{ ParametersDimension = ImageDimension * ( ImageDimension + 1 ) };\n typedef itk::Vector ParametersType;\n typedef itk::AffineTransform<\n double, ImageDimension, ParametersType > TransformType;\n\n TransformType::Pointer transformer = TransformType::New();\n\n\/\/------------------------------------------------------------\n\/\/ Set up a mapper\n\/\/------------------------------------------------------------\n typedef itk::ImageMapper< ReferenceType, TransformType >\n MapperType;\n\n MapperType::Pointer mapper = MapperType::New();\n\n \/\/ connect the transformer to the mapper\n mapper->SetTransform( transformer );\n\n \/\/ connect the reference image to the mapper\n mapper->SetDomain( imgReference );\n\n\/\/------------------------------------------------------------\n\/\/ Set up the metric\n\/\/------------------------------------------------------------\n typedef itk::MutualInformationImageToImageMetric<\n TargetType, MapperType > MetricType;\n\n MetricType::Pointer metric = MetricType::New();\n\n \/\/ connect the mapper to the metric\n metric->SetMapper( mapper );\n\n \/\/ connect the target image to the mapper\n metric->SetTarget( imgTarget );\n\n \/\/ set the standard deviations\n metric->SetTargetStandardDeviation( 5.0 );\n metric->SetReferenceStandardDeviation( 5.0 );\n\n \/\/ set the number of samples to use\n metric->SetNumberOfSpatialSamples( 100 );\n\n\/\/------------------------------------------------------------\n\/\/ Set up a affine transform parameters\n\/\/------------------------------------------------------------\n ParametersType parameters;\n\n \/\/ set the parameters to the identity\n ParametersType::Iterator it = parameters.Begin();\n\n \/\/ initialize the linear\/matrix part\n for( unsigned int row = 0; row < ImageDimension; row++ )\n {\n for( unsigned int col = 0; col < ImageDimension; col++ )\n {\n *it = 0;\n if( row == col )\n {\n *it = 1;\n }\n ++it;\n }\n }\n\n \/\/ initialize the offset\/vector part\n for( unsigned int k = 0; k < ImageDimension; k++ )\n {\n *it = 0;\n ++it;\n }\n\n\n\/\/---------------------------------------------------------\n\/\/ Print out mutual information values\n\/\/ for parameters[4] = {-10,10}\n\/\/---------------------------------------------------------\n\n MetricType::MeasureType measure;\n MetricType::DerivativeType derivative;\n\n printf(\"%s\\t%s\\t%s\\n\", \"param[4]\", \"MI\", \"dMI\/dparam[4]\" );\n\n for( double trans = -10; trans <= 5; trans += 0.5 )\n {\n parameters[4] = trans;\n metric->GetValueAndDerivative( parameters, measure, derivative );\n\n printf( \"%f\\t%f\\t%f\\n\", trans, measure,\n derivative[4] );\n\n \/\/ exercise the other functions\n metric->GetValue( parameters );\n metric->GetDerivative( parameters );\n\n }\n\n\/\/-------------------------------------------------------\n\/\/ exercise misc member functions\n\/\/-------------------------------------------------------\n std::cout << \"Name of class: \" <<\n metric->GetNameOfClass() << std::endl;\n std::cout << \"No. of samples used = \" << \n metric->GetNumberOfSpatialSamples() << std::endl;\n std::cout << \"Target std dev = \" <<\n metric->GetTargetStandardDeviation() << std::endl;\n std::cout << \"Reference std dev = \" <<\n metric->GetReferenceStandardDeviation() << std::endl;\n\n metric->Print( std::cout );\n\n itk::KernelFunction::Pointer theKernel = metric->GetKernelFunction();\n metric->SetKernelFunction( theKernel );\n theKernel->Print( std::cout );\n\n std::cout << \"Try causing a exception by making std dev too small\";\n std::cout << std::endl;\n metric->SetTargetStandardDeviation( 0.001 );\n try\n {\n std::cout << \"Value = \" << metric->GetValue( parameters );\n std::cout << std::endl;\n }\n catch(...)\n {\n std::cout << \"Caught the exception.\" << std::endl;\n }\n\n \/\/ reset standard deviation\n metric->SetTargetStandardDeviation( 5.0 );\n\n std::cout << \"Check case when Target is NULL\" << std::endl;\n metric->SetTarget( NULL );\n std::cout << \"Value = \" << metric->GetValue( parameters );\n std::cout << std::endl;\n \n metric->GetValueAndDerivative( parameters, measure, derivative );\n std::cout << \"Value = \" << measure << std::endl;\n\n\n return EXIT_SUCCESS;\n\n}\n\n<|endoftext|>"} {"text":"#include \"BtuLinear.h\"\n\nBtuLinear::BtuLinear():\n m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n m_posAPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n m_posBPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n m_velAPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n m_velBPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n m_actAPwm(PIN_ACTA_PWM),\n m_actBPwm(PIN_ACTB_PWM),\n m_actAPot(PIN_ACTA_POT),\n m_actBPot(PIN_ACTB_POT),\n m_actADir(PIN_ACTA_DIR),\n m_actBDir(PIN_ACTB_DIR)\n{};\n\nBtuLinear::~BtuLinear(){}\n\nvoid BtuLinear::init() {\n m_mode = DEFAULT_CTRL_MODE;\n\n \/\/ default gain values for depth controller\n m_kc = DEP_K_C;\n m_tauI = DEP_TAU_I;\n m_tauD = DEP_TAU_D;\n\n \/\/ default gain values for position controller\n m_p_kc = SP_K_C;\n m_p_tauI = SP_TAU_I;\n m_p_tauD = SP_TAU_D;\n\n \/\/ default gain values for velocity controller\n m_v_kc = VEL_K_C;\n m_v_tauI = VEL_TAU_I;\n m_v_tauD = VEL_TAU_D;\n\n \/\/ initialize Pressure Sensor\n m_pressureSensor.MS5837Init();\n m_pressureSensor.MS5837Start();\n wait(0.1); \/\/ remnant from old BTU class TODO: check if can be removed\n\n \/\/ initialize old position readings for Actuators\n m_oldPosA = getActPosition(ACT_A);\n m_oldPosB = getActPosition(ACT_B);\n\n \/\/ initialize the Windows for SMA to 0\n for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {\n m_avg_windowA[i] = 0;\n m_avg_windowB[i] = 0;\n }\n\n \/\/ initialize all pointers, size of window to reflect that it is empty\n m_avg_windowPtr = 0;\n m_avg_windowSize = 0;\n m_currentAvgA = 0;\n\n m_currentAvgB = 0;\n\n \/\/ initialize starting voltage for velocity control to 0\n m_currentVoltage = 0;\n}\n\n\/\/ return a pressure reading\nfloat BtuLinear::getPressure() {\n return m_pressureSensor.MS5837_Pressure();\n}\n\n\/\/ resets values of the controllers\nvoid BtuLinear::stop() {\n\tm_currentVoltage = 0;\n\tm_currentAvgA = 0;\n\tm_currentAvgB = 0;\n\tm_avg_windowSize = 0;\n\tm_depthPid.reset();\n\tm_posAPid.reset();\n\tm_posBPid.reset();\n\tm_velAPid.reset();\n\tm_velBPid.reset();\n\treturn;\n}\n\n\/\/ updates depth PID tunings\nvoid BtuLinear::updateDepthTunings(float kc, float tauI, float tauD) {\n m_kc = kc;\n m_tauI = tauI;\n m_tauD = tauD;\n m_depthPid.setTunings(kc, tauI, tauD);\n}\n\n\/\/ updates Position PID tunings\nvoid BtuLinear::updatePosTunings(float kc, float tauI, float tauD) {\n m_p_kc = kc;\n m_p_tauI = tauI;\n m_p_tauD = tauD;\n m_posAPid.setTunings(kc, tauI, tauD);\n m_posBPid.setTunings(kc, tauI, tauD);\n}\n\n\/\/ updates Velocity PID tunings\nvoid BtuLinear::updateVelTunings(float kc, float tauI, float tauD) {\n m_v_kc = kc;\n m_v_tauI = tauI;\n m_v_tauD = tauD;\n m_velAPid.setTunings(kc, tauI, tauD);\n m_velBPid.setTunings(kc, tauI, tauD);\n}\n\n\/\/ updates Mode. Resets most values if the mode has changed\nvoid BtuLinear::updateMode(int mode) {\n if(m_mode != mode) {\n stop();\n m_mode = mode;\n }\n}\n\n\/\/ runs one cycle of the controller dictated by mode\nvoid BtuLinear::runCycle(float setVal) {\n switch (m_mode) {\n\n case VOLTAGE_CTRL_MODE:\n voltageControl(setVal);\n break;\n\n case VELOCITY_CTRL_MODE:\n velocityControl(setVal);\n break;\n\n case DEPTH_CTRL_MODE:\n depthControl(setVal);\n break;\n\n case POSITION_CTRL_MODE:\n positionControl(setVal);\n break;\n }\n}\n\n\/\/ convenience function, updates mode, then runs a cycle in the chosen mode\nvoid BtuLinear::updateAndRunCycle(int mode, float value) {\n updateMode(mode);\n runCycle(value);\n}\n\n\/\/ sends a duty cycle to one of the actuators, based on the second argument\nvoid BtuLinear::voltageControlHelper(float setDuty, int ctrl) {\n \/\/ PwmOut* actPwm;\n \/\/ DigitalOut* actDir;\n \/\/ if(ctrl == ACT_A) {\n \/\/ actPwm = &m_actAPwm;\n \/\/ actDir = &m_actADir;\n \/\/ } else {\n \/\/ actPwm = &m_actBPwm;\n \/\/ actDir = &m_actBDir;\n \/\/ }\n \/\/ if(setDuty > 0) {\n \/\/ *actPwm = setDuty;\n \/\/ *actDir = 1;\n \/\/ } else {\n \/\/ *actDir = 0;\n \/\/ *actPwm = -setDuty;\n \/\/ }\n if(ctrl == ACT_A) {\n if(setDuty > 0) { \/\/ extending\n m_actAPwm = setDuty;\n m_actADir = 1;\n } else { \/\/ contracting\n m_actADir = 0;\n m_actAPwm = -setDuty;\n }\n } else {\n if(setDuty > 0) {\n m_actBPwm = setDuty;\n m_actBDir = 1;\n } else {\n m_actBDir = 0;\n m_actBPwm = -setDuty;\n }\n }\n}\n\n\/\/ calls voltageControlHelper on both actuators\nvoid BtuLinear::voltageControl(float setDuty) {\n voltageControlHelper(setDuty, ACT_A);\n voltageControlHelper(setDuty, ACT_B);\n}\n\n\/\/ updates the SMA window with the current position reading\nvoid BtuLinear::updatePositionReadings() {\n float aPosition = m_actAPot;\n float bPosition = m_actBPot;\n\n float aOldPos = m_avg_windowA[m_avg_windowPtr];\n float bOldPos = m_avg_windowB[m_avg_windowPtr];\n m_avg_windowA[m_avg_windowPtr] = aPosition;\n m_avg_windowB[m_avg_windowPtr] = bPosition;\n m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;\n if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {\n \/\/ buffer is full\n \tm_currentAvgA = m_currentAvgA + (aPosition \/ AVG_WINDOW_WIDTH)- (aOldPos \/ AVG_WINDOW_WIDTH);\n m_currentAvgB = m_currentAvgB + (bPosition \/ AVG_WINDOW_WIDTH)- (bOldPos \/ AVG_WINDOW_WIDTH);\n } else {\n \t\/\/ buffer is still filling up\n m_avg_windowSize++;\n m_currentAvgA = 0;\n m_currentAvgB = 0;\n for(int i = 0; i < m_avg_windowSize; i++) {\n m_currentAvgA = (m_avg_windowA[i] \/ m_avg_windowSize);\n m_currentAvgB = (m_avg_windowB[i] \/ m_avg_windowSize);\n }\n }\n}\n\n\/\/ gets the current Actuator Position. No SMA, just reads and rescales the potentiometer\nfloat BtuLinear::getActPosition(int act) {\n \/\/ Following code is for moving average, TODO: currently uncommented\n\t\/\/ updatePositionReadings();\n \/\/ float position;\n \/\/ if(act == ACT_A) {\n \/\/ position = m_currentAvgA;\n \/\/ } else {\n \/\/ position = m_currentAvgB;\n \/\/ }\n float position;\n if(act == ACT_A) {\n position = m_actAPot;\n } else {\n position = m_actBPot;\n }\n float scaledPos = (position - POT_MIN) \/ (POT_MAX - POT_MIN);\n return scaledPos;\n}\n\n\/\/ controls velocity on one actuator\nvoid BtuLinear::velocityControlHelper(float setVelocity, int ctrl) {\n \/\/ Check if one of the two allowable actuators is called\n\tif(ctrl != ACT_A && ctrl != ACT_B) {\n return;\n }\n \/\/ Acquire the actuator position from the potentiometer\n\tl_actPosVC = getActPosition(ctrl);\n\n \/\/ avoid going past the very edges:\n\t\/\/ Currently at 0.99 and 0.01 due to some uncertainty in scaling\/pot readings\n \/\/ also to help avoid accumulation of error during such a period\n if ((l_actPosVC <= POSITION_MIN && setVelocity < 0) || (l_actPosVC >= POSITION_MAX && setVelocity > 0)) {\n\t\t\/\/at an edge, set the setVelocity to 0\n l_setVelVC = 0;\n }\n else {\n \t\/\/ not at an edge, use setVelocity\n \tl_setVelVC = setVelocity;\n }\n\n if(ctrl == ACT_A) {\n l_actVelVC = (l_actPosVC - m_oldPosA) \/ PID_FREQ;\n \/\/ set process value to the derivative of position (velocity)\n \tm_velAPid.setProcessValue(l_actVelVC);\n m_velAPid.setSetPoint(l_setVelVC);\n l_deltaVoltVC = m_velAPid.compute();\n m_oldPosA = l_actPosVC; \/\/ update old position for so we can keep calculating derivatives\n }\n else {\n \tl_actVelVC = (l_actPosVC - m_oldPosB) \/ PID_FREQ;\n m_velBPid.setProcessValue(l_actVelVC);\n m_velBPid.setSetPoint(l_setVelVC);\n l_deltaVoltVC = m_velBPid.compute();\n m_oldPosB = l_actPosVC;\n }\n \/\/add the voltage delta to the current voltage that is the current operating point\n m_currentVoltage = utility::clip(m_currentVoltage + l_deltaVoltVC, -1.0, 1.0); \/\/ increase or decrease current voltage to get closer to desired velocity\n\n \/\/ arrest any movement at the edges, and reset accumulated voltage, to aid responsiveness at the edges\n if ((l_actPosVC <= POSITION_MIN && l_setVelVC <= 0) || (l_actPosVC >= POSITION_MAX && l_setVelVC >= 0)) {\n m_currentVoltage = 0;\n }\n\n l_cmdVoltVC = m_currentVoltage;\n\n\t\/\/ have a small dead zone TODO: either better tune or remove,\n \/\/ causes small offsets in position sometimes (of about 0.025% at current gain values)\n l_cmdVoltVC = utility::deadzone(l_cmdVoltVC,VOLTAGE_THRESHOLD);\n\n voltageControlHelper(l_cmdVoltVC, ctrl);\n\n}\n\n\/\/ does velocity control on both actuators\nvoid BtuLinear::velocityControl(float setVel) {\n velocityControlHelper(setVel, ACT_A);\n velocityControlHelper(setVel, ACT_B);\n}\n\n\/\/ control position of one actuator\nvoid BtuLinear::positionControlHelper(float setPos, int ctrl) {\n\t \/\/ Check if one of the two allowable actuators is called\n\tif(ctrl != ACT_A && ctrl != ACT_B) {\n\t\treturn;\n\t}\n \/\/ Acquire the actuator position from the potentiometer\n\tl_actPosPC = getActPosition(ctrl);\n\n\tif(ctrl == ACT_A) {\n m_posAPid.setSetPoint(setPos);\n m_posAPid.setProcessValue(l_actPosPC);\n l_cmdVoltPC = m_posAPid.compute();\n \/\/m_cmdVel = m_posAPid.compute();\n } else {\n m_posBPid.setSetPoint(setPos);\n m_posBPid.setProcessValue(l_actPosPC);\n l_cmdVoltPC = m_posBPid.compute();\n \/\/m_cmdVel = m_posBPid.compute();\n }\n\t\/\/velocityControlHelper(m_cmdVel, ctrl);\n\n\t\/\/clip commanded voltage to upper and lower limit\n\tl_cmdVoltPC = utility::clip(l_cmdVoltPC, -1.0, 1.0); \/\/ increase or decrease current voltage to get closer to desired velocity\n\n \/\/ arrest any movement at the edges, and reset current voltage, to aid responsiveness at the edges\n if ((l_actPosPC <= POSITION_MIN && l_cmdVoltPC <= 0) || (l_actPosPC >= POSITION_MAX && l_cmdVoltPC >= 0)) {\n \tl_cmdVoltPC = 0;\n }\n\n\t\/\/ have a small dead zone TODO: either better tune or remove,\n \/\/ causes small offsets in position sometimes (of about 0.025% at current gain values)\n l_cmdVoltPC = utility::deadzone(l_cmdVoltPC,VOLTAGE_THRESHOLD);\n\n voltageControlHelper(l_cmdVoltPC, ctrl);\n\n}\n\n\/\/ control position of both actuators\nvoid BtuLinear::positionControl(float setPos) {\n positionControlHelper(setPos, ACT_A);\n positionControlHelper(setPos, ACT_B);\n}\n\n\/\/ control depth via master-slave\nvoid BtuLinear::depthControlHelper(float cmdVelocity) {\n velocityControlHelper(cmdVelocity, ACT_B); \/\/ control velocity on one actuator\n positionControlHelper(getActPosition(ACT_B), ACT_A); \/\/ have the other actuator constantly try to mirror the first\n}\n\n\/\/ do depth control\nvoid BtuLinear::depthControl(float setDepthMeters) {\n\n\tm_depthPid.setSetPoint(setDepthMeters);\n\n float curDepth = getDepth();\n\n m_depthPid.setProcessValue(curDepth);\n\n float cmdVel = m_depthPid.compute();\n depthControlHelper(-1*cmdVel);\n \/\/ velocityControl(cmdVel);\n}\n\n\/\/ get a depth reading\nfloat BtuLinear::getDepth() {\n float pvDepth = getPressure();\n float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) \/ P_WATER_SURFACE_MBAR;\n return pvDepthMeters;\n}\n\n\/\/ float BTU::getServoPos() {\n\/\/ \treturn m_motorServo.readPosition();\n\/\/ }\nmoved clipping and other checks to voltage control#include \"BtuLinear.h\"\n\nBtuLinear::BtuLinear():\n m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n m_posAPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n m_posBPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n m_velAPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n m_velBPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n m_actAPwm(PIN_ACTA_PWM),\n m_actBPwm(PIN_ACTB_PWM),\n m_actAPot(PIN_ACTA_POT),\n m_actBPot(PIN_ACTB_POT),\n m_actADir(PIN_ACTA_DIR),\n m_actBDir(PIN_ACTB_DIR)\n{};\n\nBtuLinear::~BtuLinear(){}\n\nvoid BtuLinear::init() {\n m_mode = DEFAULT_CTRL_MODE;\n\n \/\/ default gain values for depth controller\n m_kc = DEP_K_C;\n m_tauI = DEP_TAU_I;\n m_tauD = DEP_TAU_D;\n\n \/\/ default gain values for position controller\n m_p_kc = SP_K_C;\n m_p_tauI = SP_TAU_I;\n m_p_tauD = SP_TAU_D;\n\n \/\/ default gain values for velocity controller\n m_v_kc = VEL_K_C;\n m_v_tauI = VEL_TAU_I;\n m_v_tauD = VEL_TAU_D;\n\n \/\/ initialize Pressure Sensor\n m_pressureSensor.MS5837Init();\n m_pressureSensor.MS5837Start();\n wait(0.1); \/\/ remnant from old BTU class TODO: check if can be removed\n\n \/\/ initialize old position readings for Actuators\n m_oldPosA = getActPosition(ACT_A);\n m_oldPosB = getActPosition(ACT_B);\n\n \/\/ initialize the Windows for SMA to 0\n for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {\n m_avg_windowA[i] = 0;\n m_avg_windowB[i] = 0;\n }\n\n \/\/ initialize all pointers, size of window to reflect that it is empty\n m_avg_windowPtr = 0;\n m_avg_windowSize = 0;\n m_currentAvgA = 0;\n\n m_currentAvgB = 0;\n\n \/\/ initialize starting voltage for velocity control to 0\n m_currentVoltage = 0;\n}\n\n\/\/ return a pressure reading\nfloat BtuLinear::getPressure() {\n return m_pressureSensor.MS5837_Pressure();\n}\n\n\/\/ resets values of the controllers\nvoid BtuLinear::stop() {\n\tm_currentVoltage = 0;\n\tm_currentAvgA = 0;\n\tm_currentAvgB = 0;\n\tm_avg_windowSize = 0;\n\tm_depthPid.reset();\n\tm_posAPid.reset();\n\tm_posBPid.reset();\n\tm_velAPid.reset();\n\tm_velBPid.reset();\n\treturn;\n}\n\n\/\/ updates depth PID tunings\nvoid BtuLinear::updateDepthTunings(float kc, float tauI, float tauD) {\n m_kc = kc;\n m_tauI = tauI;\n m_tauD = tauD;\n m_depthPid.setTunings(kc, tauI, tauD);\n}\n\n\/\/ updates Position PID tunings\nvoid BtuLinear::updatePosTunings(float kc, float tauI, float tauD) {\n m_p_kc = kc;\n m_p_tauI = tauI;\n m_p_tauD = tauD;\n m_posAPid.setTunings(kc, tauI, tauD);\n m_posBPid.setTunings(kc, tauI, tauD);\n}\n\n\/\/ updates Velocity PID tunings\nvoid BtuLinear::updateVelTunings(float kc, float tauI, float tauD) {\n m_v_kc = kc;\n m_v_tauI = tauI;\n m_v_tauD = tauD;\n m_velAPid.setTunings(kc, tauI, tauD);\n m_velBPid.setTunings(kc, tauI, tauD);\n}\n\n\/\/ updates Mode. Resets most values if the mode has changed\nvoid BtuLinear::updateMode(int mode) {\n if(m_mode != mode) {\n stop();\n m_mode = mode;\n }\n}\n\n\/\/ runs one cycle of the controller dictated by mode\nvoid BtuLinear::runCycle(float setVal) {\n switch (m_mode) {\n\n case VOLTAGE_CTRL_MODE:\n voltageControl(setVal);\n break;\n\n case VELOCITY_CTRL_MODE:\n velocityControl(setVal);\n break;\n\n case DEPTH_CTRL_MODE:\n depthControl(setVal);\n break;\n\n case POSITION_CTRL_MODE:\n positionControl(setVal);\n break;\n }\n}\n\n\/\/ convenience function, updates mode, then runs a cycle in the chosen mode\nvoid BtuLinear::updateAndRunCycle(int mode, float value) {\n updateMode(mode);\n runCycle(value);\n}\n\n\/\/ sends a duty cycle to one of the actuators, based on the second argument\nvoid BtuLinear::voltageControlHelper(float setDuty, int ctrl) {\n\n l_actPosPC = getActPosition(ctrl);\n\t\/\/clip commanded voltage to upper and lower limit\n\tl_cmdVoltPC = utility::clip(setDuty, -1.0, 1.0); \/\/ increase or decrease current voltage to get closer to desired velocity\n\n \/\/ arrest any movement at the edges, and reset current voltage, to aid responsiveness at the edges\n if ((l_actPosPC <= POSITION_MIN && l_cmdVoltPC <= 0) || (l_actPosPC >= POSITION_MAX && l_cmdVoltPC >= 0)) {\n \tl_cmdVoltPC = 0;\n }\n\n\t\/\/ have a small dead zone TODO: either better tune or remove,\n \/\/ causes small offsets in position sometimes (of about 0.025% at current gain values)\n l_cmdVoltPC = utility::deadzone(l_cmdVoltPC,VOLTAGE_THRESHOLD);\n\n if(ctrl == ACT_A) {\n if(setDuty > 0) { \/\/ extending\n m_actAPwm = setDuty;\n m_actADir = 1;\n } else { \/\/ contracting\n m_actADir = 0;\n m_actAPwm = -setDuty;\n }\n } else {\n if(setDuty > 0) {\n m_actBPwm = setDuty;\n m_actBDir = 1;\n } else {\n m_actBDir = 0;\n m_actBPwm = -setDuty;\n }\n }\n}\n\n\/\/ calls voltageControlHelper on both actuators\nvoid BtuLinear::voltageControl(float setDuty) {\n voltageControlHelper(setDuty, ACT_A);\n voltageControlHelper(setDuty, ACT_B);\n}\n\n\/\/ updates the SMA window with the current position reading\nvoid BtuLinear::updatePositionReadings() {\n float aPosition = m_actAPot;\n float bPosition = m_actBPot;\n\n float aOldPos = m_avg_windowA[m_avg_windowPtr];\n float bOldPos = m_avg_windowB[m_avg_windowPtr];\n m_avg_windowA[m_avg_windowPtr] = aPosition;\n m_avg_windowB[m_avg_windowPtr] = bPosition;\n m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;\n if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {\n \/\/ buffer is full\n \tm_currentAvgA = m_currentAvgA + (aPosition \/ AVG_WINDOW_WIDTH)- (aOldPos \/ AVG_WINDOW_WIDTH);\n m_currentAvgB = m_currentAvgB + (bPosition \/ AVG_WINDOW_WIDTH)- (bOldPos \/ AVG_WINDOW_WIDTH);\n } else {\n \t\/\/ buffer is still filling up\n m_avg_windowSize++;\n m_currentAvgA = 0;\n m_currentAvgB = 0;\n for(int i = 0; i < m_avg_windowSize; i++) {\n m_currentAvgA = (m_avg_windowA[i] \/ m_avg_windowSize);\n m_currentAvgB = (m_avg_windowB[i] \/ m_avg_windowSize);\n }\n }\n}\n\n\/\/ gets the current Actuator Position. No SMA, just reads and rescales the potentiometer\nfloat BtuLinear::getActPosition(int act) {\n \/\/ Following code is for moving average, TODO: currently uncommented\n\t\/\/ updatePositionReadings();\n \/\/ float position;\n \/\/ if(act == ACT_A) {\n \/\/ position = m_currentAvgA;\n \/\/ } else {\n \/\/ position = m_currentAvgB;\n \/\/ }\n float position;\n if(act == ACT_A) {\n position = m_actAPot;\n } else {\n position = m_actBPot;\n }\n float scaledPos = (position - POT_MIN) \/ (POT_MAX - POT_MIN);\n return scaledPos;\n}\n\n\/\/ controls velocity on one actuator\nvoid BtuLinear::velocityControlHelper(float setVelocity, int ctrl) {\n \/\/ Check if one of the two allowable actuators is called\n\tif(ctrl != ACT_A && ctrl != ACT_B) {\n return;\n }\n \/\/ Acquire the actuator position from the potentiometer\n\tl_actPosVC = getActPosition(ctrl);\n\n \/\/ avoid going past the very edges:\n\t\/\/ Currently at 0.99 and 0.01 due to some uncertainty in scaling\/pot readings\n \/\/ also to help avoid accumulation of error during such a period\n if ((l_actPosVC <= POSITION_MIN && setVelocity < 0) || (l_actPosVC >= POSITION_MAX && setVelocity > 0)) {\n\t\t\/\/at an edge, set the setVelocity to 0\n l_setVelVC = 0;\n }\n else {\n \t\/\/ not at an edge, use setVelocity\n \tl_setVelVC = setVelocity;\n }\n\n if(ctrl == ACT_A) {\n l_actVelVC = (l_actPosVC - m_oldPosA) \/ PID_FREQ;\n \/\/ set process value to the derivative of position (velocity)\n \tm_velAPid.setProcessValue(l_actVelVC);\n m_velAPid.setSetPoint(l_setVelVC);\n l_deltaVoltVC = m_velAPid.compute();\n m_oldPosA = l_actPosVC; \/\/ update old position for so we can keep calculating derivatives\n }\n else {\n \tl_actVelVC = (l_actPosVC - m_oldPosB) \/ PID_FREQ;\n m_velBPid.setProcessValue(l_actVelVC);\n m_velBPid.setSetPoint(l_setVelVC);\n l_deltaVoltVC = m_velBPid.compute();\n m_oldPosB = l_actPosVC;\n }\n \/\/add the voltage delta to the current voltage that is the current operating point\n l_cmdVoltVC = utility::clip(m_currentVoltage + l_deltaVoltVC, -1.0, 1.0); \/\/ increase or decrease current voltage to get closer to desired velocity\n\n voltageControlHelper(l_cmdVoltVC, ctrl);\n\n}\n\n\/\/ does velocity control on both actuators\nvoid BtuLinear::velocityControl(float setVel) {\n velocityControlHelper(setVel, ACT_A);\n velocityControlHelper(setVel, ACT_B);\n}\n\n\/\/ control position of one actuator\nvoid BtuLinear::positionControlHelper(float setPos, int ctrl) {\n\t \/\/ Check if one of the two allowable actuators is called\n\tif(ctrl != ACT_A && ctrl != ACT_B) {\n\t\treturn;\n\t}\n \/\/ Acquire the actuator position from the potentiometer\n\tl_actPosPC = getActPosition(ctrl);\n\n\tif(ctrl == ACT_A) {\n m_posAPid.setSetPoint(setPos);\n m_posAPid.setProcessValue(l_actPosPC);\n l_cmdVoltPC = m_posAPid.compute();\n \/\/m_cmdVel = m_posAPid.compute();\n } else {\n m_posBPid.setSetPoint(setPos);\n m_posBPid.setProcessValue(l_actPosPC);\n l_cmdVoltPC = m_posBPid.compute();\n \/\/m_cmdVel = m_posBPid.compute();\n }\n\t\/\/velocityControlHelper(m_cmdVel, ctrl);\n voltageControlHelper(l_cmdVoltPC, ctrl);\n\n\n}\n\n\/\/ control position of both actuators\nvoid BtuLinear::positionControl(float setPos) {\n positionControlHelper(setPos, ACT_A);\n positionControlHelper(setPos, ACT_B);\n}\n\n\/\/ control depth via master-slave\nvoid BtuLinear::depthControlHelper(float cmdVelocity) {\n velocityControlHelper(cmdVelocity, ACT_B); \/\/ control velocity on one actuator\n positionControlHelper(getActPosition(ACT_B), ACT_A); \/\/ have the other actuator constantly try to mirror the first\n}\n\n\/\/ do depth control\nvoid BtuLinear::depthControl(float setDepthMeters) {\n\n\tm_depthPid.setSetPoint(setDepthMeters);\n\n float curDepth = getDepth();\n\n m_depthPid.setProcessValue(curDepth);\n\n float cmdVel = m_depthPid.compute();\n depthControlHelper(-1*cmdVel);\n \/\/ velocityControl(cmdVel);\n}\n\n\/\/ get a depth reading\nfloat BtuLinear::getDepth() {\n float pvDepth = getPressure();\n float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) \/ P_WATER_SURFACE_MBAR;\n return pvDepthMeters;\n}\n\n\/\/ float BTU::getServoPos() {\n\/\/ \treturn m_motorServo.readPosition();\n\/\/ }\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkJoinSeriesImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImage.h\"\n\n#include \"itkJoinSeriesImageFilter.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkStreamingImageFilter.h\"\n#include \"itkCommand.h\"\n#include \"itkFileOutputWindow.h\"\n\n#include \n#include \n\nint itkJoinSeriesImageFilterPrintTest(int, char* [])\n{\n typedef itk::Image InputType;\n typedef itk::Image OutputType;\n\n \/\/ NOTE: A compile error should be here (by extending itk::Concept?),\n \/\/ because InputImageDimension must be less than OutputImageDimension.\n itk::JoinSeriesImageFilter::Pointer JoinSeriesImageFilterObj =\n itk::JoinSeriesImageFilter::New();\n std::cout << \"-------------JoinSeriesImageFilter\" << JoinSeriesImageFilterObj;\n\n return 0;\n}\n\n\nclass ShowProgressObject\n{\npublic:\n ShowProgressObject(itk::ProcessObject* o)\n {m_Process = o;}\n void ShowProgress()\n {std::cout << \"Progress \" << m_Process->GetProgress() << std::endl;}\n itk::ProcessObject::Pointer m_Process;\n};\n\nint itkJoinSeriesImageFilterTest(int, char* [] )\n{\n \/\/ to write informations to \"itkMessageLog.txt\" when DebugOn()\n\/\/ itk::OutputWindow::SetInstance( itk::FileOutputWindow::New() );\n\n const unsigned int streamDivisions = 2;\n typedef unsigned char PixelType;\n typedef itk::Image< PixelType, 2 > InputImageType;\n \/\/ typedef itk::Image< PixelType, 3 > OutputImageType;\n typedef itk::Image< PixelType, 4 > OutputImageType;\n\n \/\/ the expected result\n OutputImageType::IndexType expectedIndex = {{1, 2, 0, 0}};\n OutputImageType::SizeType expectedSize = {{8, 5, 4, 1}};\n OutputImageType::RegionType expectedRegion;\n expectedRegion.SetIndex( expectedIndex );\n expectedRegion.SetSize( expectedSize );\n OutputImageType::SpacingType expectedSpacing;\n expectedSpacing[0] = 1.1;\n expectedSpacing[1] = 1.2;\n expectedSpacing[2] = 1.3;\n expectedSpacing[3] = 1.0;\n OutputImageType::PointType expectedOrigin;\n expectedOrigin[0] = 0.1;\n expectedOrigin[1] = 0.2;\n expectedOrigin[2] = 0.3;\n expectedOrigin[3] = 0.0;\n\n \/\/ make the input images\n int numInputs = 4;\n InputImageType::IndexType index = {{1, 2}};\n InputImageType::SizeType size = {{8, 5}};\n InputImageType::RegionType region;\n region.SetIndex( index );\n region.SetSize( size );\n const double spacingValue = 1.3;\n InputImageType::SpacingType spacing;\n spacing[0] = 1.1;\n spacing[1] = 1.2;\n const double originValue = 0.3;\n InputImageType::PointType origin;\n origin[0] = 0.1;\n origin[1] = 0.2;\n\n std::vector inputs;\n\n PixelType counter1 = 0;\n for ( int i = 0; i < numInputs; i++ )\n {\n inputs.push_back( InputImageType::New() );\n inputs[i]->SetLargestPossibleRegion( region );\n inputs[i]->SetBufferedRegion( region );\n inputs[i]->Allocate();\n\n itk::ImageRegionIterator\n inputIter( inputs[i], inputs[i]->GetBufferedRegion() );\n while ( !inputIter.IsAtEnd() )\n {\n inputIter.Set( counter1 );\n ++counter1;\n ++inputIter;\n }\n\n inputs[i]->SetSpacing( spacing );\n inputs[i]->SetOrigin( origin );\n\/\/ inputs[i]->DebugOn();\n }\n\n \/\/ create the filter\n typedef itk::JoinSeriesImageFilter< InputImageType, OutputImageType >\n JoinSeriesImageType;\n JoinSeriesImageType::Pointer joinSeriesImage = JoinSeriesImageType::New();\n\n \/\/ check the default values\n if ( joinSeriesImage->GetSpacing() != 1.0 )\n {\n std::cout << \"Default spacing is not 1.0\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( joinSeriesImage->GetOrigin() != 0.0 )\n {\n std::cout << \"Default origin is not 0.0\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ setup the filter\n joinSeriesImage->SetSpacing( spacingValue ); \n joinSeriesImage->SetOrigin( originValue ); \n for ( int i = 0; i < numInputs; i++ )\n {\n joinSeriesImage->SetInput( i, inputs[i] );\n }\n\n \/\/ to test ProgressReporter\n ShowProgressObject progressWatch( joinSeriesImage );\n typedef itk::SimpleMemberCommand< ShowProgressObject > CommandType;\n CommandType::Pointer command = CommandType::New();\n command->SetCallbackFunction( &progressWatch,\n &ShowProgressObject::ShowProgress );\n joinSeriesImage->AddObserver( itk::ProgressEvent(), command );\n\n \/\/ to test streaming\n typedef itk::StreamingImageFilter< OutputImageType, OutputImageType >\n StreamingImageType;\n StreamingImageType::Pointer streamingImage = StreamingImageType::New();\n streamingImage->SetInput( joinSeriesImage->GetOutput() );\n streamingImage->SetNumberOfStreamDivisions( streamDivisions );\n\n\n \/\/ run\n try\n {\n streamingImage->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cout << err << std::endl;\n \/\/for InvalidRequestedRegionError\n itk::DataObjectError * errp = dynamic_cast( &err );\n if ( errp )\n {\n errp->GetDataObject()->Print( std::cout );\n }\n return EXIT_FAILURE;\n }\n\n OutputImageType::Pointer output = streamingImage->GetOutput();\n\n\n \/\/ check the informations\n if ( output->GetLargestPossibleRegion() != expectedRegion )\n {\n std::cout << \"LargestPossibleRegion mismatch\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( output->GetSpacing() != expectedSpacing )\n {\n std::cout << \"Spacing mismatch\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( output->GetOrigin() != expectedOrigin )\n {\n std::cout << \"Origin mismatch\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ check the contents\n bool passed = true;\n\n PixelType counter2 = 0;\n itk::ImageRegionIterator\n outputIter( output, output->GetBufferedRegion() );\n while ( !outputIter.IsAtEnd() )\n {\n if ( outputIter.Get() != counter2 )\n {\n passed = false;\n std::cout << \"Mismatch at index: \" << outputIter.GetIndex() << std::endl;\n }\n ++counter2;\n ++outputIter;\n }\n\n if ( !passed || counter1 != counter2 )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ An exception is raised when an input is missing.\n passed = false;\n\n \/\/ set the 2nd input null\n joinSeriesImage->SetInput( 1, 0 );\n try\n {\n joinSeriesImage->Update();\n }\n catch( itk::InvalidRequestedRegionError & err )\n {\n if ( strcmp(\"Missing input 1\", err.GetDescription()) == 0 )\n {\n passed = true;\n }\n else\n {\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n }\n catch( itk::ExceptionObject & err )\n {\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( !passed )\n {\n std::cout << \"Expected exception is missing\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n}\n\n\nBUG: tests should not depend on the text of the exception message.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkJoinSeriesImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImage.h\"\n\n#include \"itkJoinSeriesImageFilter.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkStreamingImageFilter.h\"\n#include \"itkCommand.h\"\n#include \"itkFileOutputWindow.h\"\n\n#include \n#include \n\nint itkJoinSeriesImageFilterPrintTest(int, char* [])\n{\n typedef itk::Image InputType;\n typedef itk::Image OutputType;\n\n \/\/ NOTE: A compile error should be here (by extending itk::Concept?),\n \/\/ because InputImageDimension must be less than OutputImageDimension.\n itk::JoinSeriesImageFilter::Pointer JoinSeriesImageFilterObj =\n itk::JoinSeriesImageFilter::New();\n std::cout << \"-------------JoinSeriesImageFilter\" << JoinSeriesImageFilterObj;\n\n return 0;\n}\n\n\nclass ShowProgressObject\n{\npublic:\n ShowProgressObject(itk::ProcessObject* o)\n {m_Process = o;}\n void ShowProgress()\n {std::cout << \"Progress \" << m_Process->GetProgress() << std::endl;}\n itk::ProcessObject::Pointer m_Process;\n};\n\nint itkJoinSeriesImageFilterTest(int, char* [] )\n{\n \/\/ to write informations to \"itkMessageLog.txt\" when DebugOn()\n\/\/ itk::OutputWindow::SetInstance( itk::FileOutputWindow::New() );\n\n const unsigned int streamDivisions = 2;\n typedef unsigned char PixelType;\n typedef itk::Image< PixelType, 2 > InputImageType;\n \/\/ typedef itk::Image< PixelType, 3 > OutputImageType;\n typedef itk::Image< PixelType, 4 > OutputImageType;\n\n \/\/ the expected result\n OutputImageType::IndexType expectedIndex = {{1, 2, 0, 0}};\n OutputImageType::SizeType expectedSize = {{8, 5, 4, 1}};\n OutputImageType::RegionType expectedRegion;\n expectedRegion.SetIndex( expectedIndex );\n expectedRegion.SetSize( expectedSize );\n OutputImageType::SpacingType expectedSpacing;\n expectedSpacing[0] = 1.1;\n expectedSpacing[1] = 1.2;\n expectedSpacing[2] = 1.3;\n expectedSpacing[3] = 1.0;\n OutputImageType::PointType expectedOrigin;\n expectedOrigin[0] = 0.1;\n expectedOrigin[1] = 0.2;\n expectedOrigin[2] = 0.3;\n expectedOrigin[3] = 0.0;\n\n \/\/ make the input images\n int numInputs = 4;\n InputImageType::IndexType index = {{1, 2}};\n InputImageType::SizeType size = {{8, 5}};\n InputImageType::RegionType region;\n region.SetIndex( index );\n region.SetSize( size );\n const double spacingValue = 1.3;\n InputImageType::SpacingType spacing;\n spacing[0] = 1.1;\n spacing[1] = 1.2;\n const double originValue = 0.3;\n InputImageType::PointType origin;\n origin[0] = 0.1;\n origin[1] = 0.2;\n\n std::vector inputs;\n\n PixelType counter1 = 0;\n for ( int i = 0; i < numInputs; i++ )\n {\n inputs.push_back( InputImageType::New() );\n inputs[i]->SetLargestPossibleRegion( region );\n inputs[i]->SetBufferedRegion( region );\n inputs[i]->Allocate();\n\n itk::ImageRegionIterator\n inputIter( inputs[i], inputs[i]->GetBufferedRegion() );\n while ( !inputIter.IsAtEnd() )\n {\n inputIter.Set( counter1 );\n ++counter1;\n ++inputIter;\n }\n\n inputs[i]->SetSpacing( spacing );\n inputs[i]->SetOrigin( origin );\n\/\/ inputs[i]->DebugOn();\n }\n\n \/\/ create the filter\n typedef itk::JoinSeriesImageFilter< InputImageType, OutputImageType >\n JoinSeriesImageType;\n JoinSeriesImageType::Pointer joinSeriesImage = JoinSeriesImageType::New();\n\n \/\/ check the default values\n if ( joinSeriesImage->GetSpacing() != 1.0 )\n {\n std::cout << \"Default spacing is not 1.0\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( joinSeriesImage->GetOrigin() != 0.0 )\n {\n std::cout << \"Default origin is not 0.0\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ setup the filter\n joinSeriesImage->SetSpacing( spacingValue ); \n joinSeriesImage->SetOrigin( originValue ); \n for ( int i = 0; i < numInputs; i++ )\n {\n joinSeriesImage->SetInput( i, inputs[i] );\n }\n\n \/\/ to test ProgressReporter\n ShowProgressObject progressWatch( joinSeriesImage );\n typedef itk::SimpleMemberCommand< ShowProgressObject > CommandType;\n CommandType::Pointer command = CommandType::New();\n command->SetCallbackFunction( &progressWatch,\n &ShowProgressObject::ShowProgress );\n joinSeriesImage->AddObserver( itk::ProgressEvent(), command );\n\n \/\/ to test streaming\n typedef itk::StreamingImageFilter< OutputImageType, OutputImageType >\n StreamingImageType;\n StreamingImageType::Pointer streamingImage = StreamingImageType::New();\n streamingImage->SetInput( joinSeriesImage->GetOutput() );\n streamingImage->SetNumberOfStreamDivisions( streamDivisions );\n\n\n \/\/ run\n try\n {\n streamingImage->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cout << err << std::endl;\n \/\/for InvalidRequestedRegionError\n itk::DataObjectError * errp = dynamic_cast( &err );\n if ( errp )\n {\n errp->GetDataObject()->Print( std::cout );\n }\n return EXIT_FAILURE;\n }\n\n OutputImageType::Pointer output = streamingImage->GetOutput();\n\n\n \/\/ check the informations\n if ( output->GetLargestPossibleRegion() != expectedRegion )\n {\n std::cout << \"LargestPossibleRegion mismatch\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( output->GetSpacing() != expectedSpacing )\n {\n std::cout << \"Spacing mismatch\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( output->GetOrigin() != expectedOrigin )\n {\n std::cout << \"Origin mismatch\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ check the contents\n bool passed = true;\n\n PixelType counter2 = 0;\n itk::ImageRegionIterator\n outputIter( output, output->GetBufferedRegion() );\n while ( !outputIter.IsAtEnd() )\n {\n if ( outputIter.Get() != counter2 )\n {\n passed = false;\n std::cout << \"Mismatch at index: \" << outputIter.GetIndex() << std::endl;\n }\n ++counter2;\n ++outputIter;\n }\n\n if ( !passed || counter1 != counter2 )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ An exception is raised when an input is missing.\n passed = false;\n\n \/\/ set the 2nd input null\n joinSeriesImage->SetInput( 1, 0 );\n try\n {\n joinSeriesImage->Update();\n }\n catch( itk::InvalidRequestedRegionError & err )\n {\n passed = true;\n }\n catch( itk::ExceptionObject & err )\n {\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( !passed )\n {\n std::cout << \"Expected exception is missing\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file linear_observation_model.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP\n#define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fl\n{\n\n\/**\n * \\ingroup observation_models\n *\n * This represents the linear gaussian observation model \\f$p(y_t \\mid x_t)\\f$\n * governed by the linear equation\n *\n * \\f$ y_t = H_t x_t + N_t v_t \\f$\n *\n * where \\f$ y_t\\f$ is the observation, \\f$ x_t\\f$ is the state. The matrix\n * \\f$H_t\\f$ is the sensor model mapping the state into the observation space.\n * The vector \\f$ v_t \\sim {\\cal N}(v_t; 0, I)\\f$ is a standard normal variate\n * which is mapped into the the observation space via the noise model matrix\n * \\f$N_t\\f$. Any Gaussian noise \\f$\\tilde{v}_t \\sim {\\cal N}(\\tilde{v}_t ; 0,\n * R_t) \\f$ can be represented via \\f$\\tilde{v}_t = N_t v_t\\f$ with\\f$N_t\n * = \\sqrt{R_t}\\f$. Hence, the linear equation may be restated as the more\n * familiar but equivalent form\n *\n * \\f$ y_t = H_t x_t + \\tilde{v}_t \\f$.\n *\/\ntemplate \nclass LinearObservationModel\n#ifdef GENERATING_DOCUMENTATION\n : public LinearObservationModel,\n#else\n : public LinearObservationModel>,\n#endif\n public Descriptor\n{\npublic:\n \/**\n * Constructs a linear gaussian observation model\n * \\param obsrv_dim observation dimension if dynamic size\n * \\param state_dim state dimension if dynamic size\n *\/\n explicit\n LinearObservationModel(int obsrv_dim = DimensionOf(),\n int state_dim = DimensionOf())\n : LinearObservationModel>(\n obsrv_dim, state_dim)\n { }\n\n virtual std::string name() const\n {\n return \"LinearObservationModel\";\n }\n\n virtual std::string description() const\n {\n return \"Linear observation model\";\n }\n};\n\n}\n\n#endif\nUpdated descriptor details\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file linear_observation_model.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP\n#define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fl\n{\n\n\/**\n * \\ingroup observation_models\n *\n * This represents the linear gaussian observation model \\f$p(y_t \\mid x_t)\\f$\n * governed by the linear equation\n *\n * \\f$ y_t = H_t x_t + N_t v_t \\f$\n *\n * where \\f$ y_t\\f$ is the observation, \\f$ x_t\\f$ is the state. The matrix\n * \\f$H_t\\f$ is the sensor model mapping the state into the observation space.\n * The vector \\f$ v_t \\sim {\\cal N}(v_t; 0, I)\\f$ is a standard normal variate\n * which is mapped into the the observation space via the noise model matrix\n * \\f$N_t\\f$. Any Gaussian noise \\f$\\tilde{v}_t \\sim {\\cal N}(\\tilde{v}_t ; 0,\n * R_t) \\f$ can be represented via \\f$\\tilde{v}_t = N_t v_t\\f$ with\\f$N_t\n * = \\sqrt{R_t}\\f$. Hence, the linear equation may be restated as the more\n * familiar but equivalent form\n *\n * \\f$ y_t = H_t x_t + \\tilde{v}_t \\f$.\n *\/\ntemplate \nclass LinearObservationModel\n#ifdef GENERATING_DOCUMENTATION\n : public LinearObservationModel,\n#else\n : public LinearObservationModel>,\n#endif\n public Descriptor\n{\npublic:\n \/**\n * Constructs a linear gaussian observation model\n * \\param obsrv_dim observation dimension if dynamic size\n * \\param state_dim state dimension if dynamic size\n *\/\n explicit\n LinearObservationModel(int obsrv_dim = DimensionOf(),\n int state_dim = DimensionOf())\n : LinearObservationModel>(\n obsrv_dim, state_dim)\n { }\n\n virtual std::string name() const\n {\n return \"LinearGaussianObservationModel\";\n }\n\n virtual std::string description() const\n {\n return \"Linear observation model with additive Gaussian noise\";\n }\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/\n\/\/ (c) Copyright 2017 DESY,ESS\n\/\/\n\/\/ This file is part of h5pp.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor\n\/\/ Boston, MA 02110-1301 USA\n\/\/ ===========================================================================\n\/\/\n\/\/ Author: Eugen Wintersberger \n\/\/ Created on: Aug 25, 2017\n\/\/\n#include \n#include \n#include \n#include \n\nnamespace hdf5 {\nnamespace property {\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetFillValueStatus &status)\n{\n switch(status)\n {\n case DatasetFillValueStatus::UNDEFINED:\n return stream<<\"UNDEFINED\";\n case DatasetFillValueStatus::DEFAULT:\n return stream<<\"DEFAULT\";\n case DatasetFillValueStatus::USER_DEFINED:\n return stream<<\"USER_DEFINED\";\n }\n}\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetFillTime &time)\n{\n switch(time)\n {\n case DatasetFillTime::IFSET:\n return stream<<\"IFSET\";\n case DatasetFillTime::ALLOC:\n return stream<<\"ALLOC\";\n case DatasetFillTime::NEVER:\n return stream<<\"NEVER\";\n }\n}\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetAllocTime &time)\n{\n switch(time)\n {\n case DatasetAllocTime::DEFAULT:\n return stream<<\"DEFAULT\";\n case DatasetAllocTime::EARLY:\n return stream<<\"EARLY\";\n case DatasetAllocTime::INCR:\n return stream<<\"INCR\";\n case DatasetAllocTime::LATE:\n return stream<<\"LATE\";\n }\n}\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetLayout &layout)\n{\n switch(layout)\n {\n case DatasetLayout::COMPACT:\n return stream<<\"COMPACT\";\n case DatasetLayout::CONTIGUOUS:\n return stream<<\"CONTIGUOUS\";\n case DatasetLayout::CHUNKED:\n return stream<<\"CHUNKED\";\n#if H5_VERSION_GE(1,10,0)\n case DatasetLayout::VIRTUAL:\n return stream<<\"VIRTUAL\";\n#endif\n }\n}\n\n\nDatasetCreationList::DatasetCreationList():\n ObjectCreationList(kDatasetCreate)\n{}\n\nDatasetCreationList::~DatasetCreationList()\n{}\n\nvoid DatasetCreationList::layout(DatasetLayout layout) const\n{\n if(H5Pset_layout(static_cast(*this),static_cast(layout))<0)\n {\n throw std::runtime_error(\"Failure setting the dataset layout!\");\n }\n}\n\nDatasetLayout DatasetCreationList::layout() const\n{\n switch(H5Pget_layout(static_cast(*this)))\n {\n case H5D_COMPACT:\n return DatasetLayout::COMPACT;\n case H5D_CONTIGUOUS:\n return DatasetLayout::CONTIGUOUS;\n case H5D_CHUNKED:\n return DatasetLayout::CHUNKED;\n#if H5_VERSION_GE(1,10,0)\n case H5D_VIRTUAL:\n return DatasetLayout::VIRTUAL;\n#endif\n default:\n throw std::runtime_error(\"Failure retrieving the dataset layout!\");\n }\n}\n\nvoid DatasetCreationList::chunk(const Dimensions &chunk_dims) const\n{\n if(H5Pset_chunk(static_cast(*this),chunk_dims.size(),chunk_dims.data())<0)\n {\n throw std::runtime_error(\"Failure setting chunk dimensions!\");\n }\n}\n\nDimensions DatasetCreationList::chunk() const\n{\n int s = H5Pget_chunk(static_cast(*this),0,NULL);\n if(s<0)\n {\n throw std::runtime_error(\"Failure retrieving the chunk rank!\");\n }\n\n Dimensions buffer(s);\n if(H5Pget_chunk(static_cast(*this),s,buffer.data())<0)\n {\n throw std::runtime_error(\"Failure retrieving the chunk dimension!\");\n }\n\n return buffer;\n}\n\nDatasetFillValueStatus DatasetCreationList::fill_value_status() const\n{\n H5D_fill_value_t status;\n if(H5Pfill_value_defined(static_cast(*this),&status)<0)\n {\n throw std::runtime_error(\"Failure obtaining the fill value status!\");\n }\n return static_cast(status);\n}\n\nvoid DatasetCreationList::fill_time(DatasetFillTime time) const\n{\n if(H5Pset_fill_time(static_cast(*this),\n static_cast(time))<0)\n {\n throw std::runtime_error(\"Failure setting the fill time for the dataset!\");\n }\n}\n\nDatasetFillTime DatasetCreationList::fill_time() const\n{\n H5D_fill_time_t buffer;\n if(H5Pget_fill_time(static_cast(*this),&buffer)<0)\n {\n throw std::runtime_error(\"Failure retrieving dataset fill time!\");\n }\n return static_cast(buffer);\n}\n\nvoid DatasetCreationList::allocation_time(DatasetAllocTime time) const\n{\n if(H5Pset_alloc_time(static_cast(*this),\n static_cast(time))<0)\n {\n throw std::runtime_error(\"Failure setting dataset allocation time!\");\n }\n}\n\nDatasetAllocTime DatasetCreationList::allocation_time() const\n{\n H5D_alloc_time_t buffer;\n if(H5Pget_alloc_time(static_cast(*this),&buffer)<0)\n {\n throw std::runtime_error(\"Failure retrieving dataset allocation time!\");\n }\n return static_cast(buffer);\n}\n\n} \/\/ namespace property\n} \/\/ namespace hdf5\nfixed DatasetCreationList warnings; updates #26'\/\/\n\/\/ (c) Copyright 2017 DESY,ESS\n\/\/\n\/\/ This file is part of h5pp.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor\n\/\/ Boston, MA 02110-1301 USA\n\/\/ ===========================================================================\n\/\/\n\/\/ Author: Eugen Wintersberger \n\/\/ Created on: Aug 25, 2017\n\/\/\n#include \n#include \n#include \n#include \n\nnamespace hdf5 {\nnamespace property {\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetFillValueStatus &status)\n{\n switch(status)\n {\n case DatasetFillValueStatus::UNDEFINED:\n return stream<<\"UNDEFINED\";\n case DatasetFillValueStatus::DEFAULT:\n return stream<<\"DEFAULT\";\n case DatasetFillValueStatus::USER_DEFINED:\n return stream<<\"USER_DEFINED\";\n }\n return stream;\n}\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetFillTime &time)\n{\n switch(time)\n {\n case DatasetFillTime::IFSET:\n return stream<<\"IFSET\";\n case DatasetFillTime::ALLOC:\n return stream<<\"ALLOC\";\n case DatasetFillTime::NEVER:\n return stream<<\"NEVER\";\n }\n return stream;\n}\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetAllocTime &time)\n{\n switch(time)\n {\n case DatasetAllocTime::DEFAULT:\n return stream<<\"DEFAULT\";\n case DatasetAllocTime::EARLY:\n return stream<<\"EARLY\";\n case DatasetAllocTime::INCR:\n return stream<<\"INCR\";\n case DatasetAllocTime::LATE:\n return stream<<\"LATE\";\n }\n return stream;\n}\n\nstd::ostream &operator<<(std::ostream &stream,const DatasetLayout &layout)\n{\n switch(layout)\n {\n case DatasetLayout::COMPACT:\n return stream<<\"COMPACT\";\n case DatasetLayout::CONTIGUOUS:\n return stream<<\"CONTIGUOUS\";\n case DatasetLayout::CHUNKED:\n return stream<<\"CHUNKED\";\n#if H5_VERSION_GE(1,10,0)\n case DatasetLayout::VIRTUAL:\n return stream<<\"VIRTUAL\";\n#endif\n }\n return stream;\n}\n\n\nDatasetCreationList::DatasetCreationList():\n ObjectCreationList(kDatasetCreate)\n{}\n\nDatasetCreationList::~DatasetCreationList()\n{}\n\nvoid DatasetCreationList::layout(DatasetLayout layout) const\n{\n if(H5Pset_layout(static_cast(*this),static_cast(layout))<0)\n {\n throw std::runtime_error(\"Failure setting the dataset layout!\");\n }\n}\n\nDatasetLayout DatasetCreationList::layout() const\n{\n switch(H5Pget_layout(static_cast(*this)))\n {\n case H5D_COMPACT:\n return DatasetLayout::COMPACT;\n case H5D_CONTIGUOUS:\n return DatasetLayout::CONTIGUOUS;\n case H5D_CHUNKED:\n return DatasetLayout::CHUNKED;\n#if H5_VERSION_GE(1,10,0)\n case H5D_VIRTUAL:\n return DatasetLayout::VIRTUAL;\n#endif\n default:\n throw std::runtime_error(\"Failure retrieving the dataset layout!\");\n }\n}\n\nvoid DatasetCreationList::chunk(const Dimensions &chunk_dims) const\n{\n if(H5Pset_chunk(static_cast(*this),chunk_dims.size(),chunk_dims.data())<0)\n {\n throw std::runtime_error(\"Failure setting chunk dimensions!\");\n }\n}\n\nDimensions DatasetCreationList::chunk() const\n{\n int s = H5Pget_chunk(static_cast(*this),0,NULL);\n if(s<0)\n {\n throw std::runtime_error(\"Failure retrieving the chunk rank!\");\n }\n\n Dimensions buffer(s);\n if(H5Pget_chunk(static_cast(*this),s,buffer.data())<0)\n {\n throw std::runtime_error(\"Failure retrieving the chunk dimension!\");\n }\n\n return buffer;\n}\n\nDatasetFillValueStatus DatasetCreationList::fill_value_status() const\n{\n H5D_fill_value_t status;\n if(H5Pfill_value_defined(static_cast(*this),&status)<0)\n {\n throw std::runtime_error(\"Failure obtaining the fill value status!\");\n }\n return static_cast(status);\n}\n\nvoid DatasetCreationList::fill_time(DatasetFillTime time) const\n{\n if(H5Pset_fill_time(static_cast(*this),\n static_cast(time))<0)\n {\n throw std::runtime_error(\"Failure setting the fill time for the dataset!\");\n }\n}\n\nDatasetFillTime DatasetCreationList::fill_time() const\n{\n H5D_fill_time_t buffer;\n if(H5Pget_fill_time(static_cast(*this),&buffer)<0)\n {\n throw std::runtime_error(\"Failure retrieving dataset fill time!\");\n }\n return static_cast(buffer);\n}\n\nvoid DatasetCreationList::allocation_time(DatasetAllocTime time) const\n{\n if(H5Pset_alloc_time(static_cast(*this),\n static_cast(time))<0)\n {\n throw std::runtime_error(\"Failure setting dataset allocation time!\");\n }\n}\n\nDatasetAllocTime DatasetCreationList::allocation_time() const\n{\n H5D_alloc_time_t buffer;\n if(H5Pget_alloc_time(static_cast(*this),&buffer)<0)\n {\n throw std::runtime_error(\"Failure retrieving dataset allocation time!\");\n }\n return static_cast(buffer);\n}\n\n} \/\/ namespace property\n} \/\/ namespace hdf5\n<|endoftext|>"} {"text":"#include \"ofApp.h\"\n\n\n\/\/------------------------------------------------------------------------------\nvoid ofApp::setup()\n{\n ofSetFrameRate(30);\n ofEnableAlphaBlending();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid ofApp::draw()\n{\n\n\n\n ofBackground(0);\n\n \/\/ get the current time\n unsigned long long now = ofGetElapsedTimeMillis();\n\n \/\/ cycle through the rectangles\n for(int i = 0; i < numRectangles; i++)\n {\n \/\/ if now is past the next scheduled blink time\n if(now > nextRectangleBlinkTime[i])\n {\n \/\/ schedule the next blink time\n nextRectangleBlinkTime[i] = now + rectangleDelays[i];\n \/\/ toggle the rectangle state\n rectangleState[i] = !rectangleState[i];\n }\n\n \/\/ draw the rectangles\n if(rectangleState[i])\n {\n \/\/ draw an unfilled rectangle if the state is \"true\"\n ofNoFill();\n }\n else\n {\n \/\/ draw a filled rectangle if the state is \"false\"\n ofFill();\n }\n\n ofSetColor(ofColor::yellow);\n ofRect(rectangles[i]);\n\n \/\/ Uncomment the following to draw based on the amount of time left\n \/\/ before the next blink happens.\n \n\/\/ unsigned long long timeUntilNextBlink = nextRectangleBlinkTime[i] - now;\n\/\/\n\/\/ float percent = ofNormalize(timeUntilNextBlink,0,rectangleDelays[i]);\n\/\/\n\/\/ ofFill();\n\/\/ ofSetColor(255,0,0);\n\/\/ ofRect(rectangles[i].x,\n\/\/ rectangles[i].y + rectangles[i].height,\n\/\/ 10,\n\/\/ -rectangles[i].height * percent);\n\n\n\n }\n}\nCleanup.#include \"ofApp.h\"\n\n\n\/\/------------------------------------------------------------------------------\nvoid ofApp::setup()\n{\n ofSetFrameRate(30);\n ofEnableAlphaBlending();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid ofApp::draw()\n{\n ofBackground(0);\n\n \/\/ get the current time\n unsigned long long now = ofGetElapsedTimeMillis();\n\n \/\/ cycle through the rectangles\n for(int i = 0; i < numRectangles; i++)\n {\n \/\/ if now is past the next scheduled blink time\n if(now > nextRectangleBlinkTime[i])\n {\n \/\/ schedule the next blink time\n nextRectangleBlinkTime[i] = now + rectangleDelays[i];\n \/\/ toggle the rectangle state\n rectangleState[i] = !rectangleState[i];\n }\n\n \/\/ draw the rectangles\n if(rectangleState[i])\n {\n \/\/ draw an unfilled rectangle if the state is \"true\"\n ofNoFill();\n }\n else\n {\n \/\/ draw a filled rectangle if the state is \"false\"\n ofFill();\n }\n\n ofSetColor(ofColor::yellow);\n ofRect(rectangles[i]);\n\n \/\/ Uncomment the following to draw based on the amount of time left\n \/\/ before the next blink happens.\n \n\/\/ unsigned long long timeUntilNextBlink = nextRectangleBlinkTime[i] - now;\n\/\/\n\/\/ float percent = ofNormalize(timeUntilNextBlink,0,rectangleDelays[i]);\n\/\/\n\/\/ ofFill();\n\/\/ ofSetColor(255,0,0);\n\/\/ ofRect(rectangles[i].x,\n\/\/ rectangles[i].y + rectangles[i].height,\n\/\/ 10,\n\/\/ -rectangles[i].height * percent);\n\n\n\n }\n}\n<|endoftext|>"} {"text":"#ifndef SFML_INPUT_HANDLER_HPP\n#define SFML_INPUT_HANDLER_HPP\n#include \n#include \n#include \"hash_pair.hpp\"\n\nclass InputHandler\n{\npublic:\n\tstruct MousePosition\n\t{\n\t\tMousePosition():\n\t\tx(0),y(0){}\n\t\tint x;\n\t\tint y;\n\t};\n\tInputHandler(){}\n\t~InputHandler(){}\n\n\tvoid update()\n\t{\n\t\t#if !(INPUT_DISABLE_KEYBOARD)\n\t\tkeyUpdate();\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_MOUSE)\n\t\tmouseUpdate();\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_JOYSTICK)\n\t\tjoystickUpdate();\n\t\t#endif\n\t}\n\n\tvoid handleEvent(const sf::Event& event)\n\t{\n\t\t#if !(INPUT_DISABLE_KEYBOARD)\n\t\tif (keyEvent(event)) return;\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_MOUSE)\n\t\tif (mouseEvent(event)) return;\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_JOYSTICK)\n\t\tif (joystickEvent(event)) return;\n\t\t#endif\n\t}\n\n#if !(INPUT_DISABLE_KEYBOARD)\n\tbool isKeyPressed(sf::Keyboard::Key key)\n\t{\n\t\treturn p_key_pressed[key];\n\t}\n\n\tbool isKeyDown(sf::Keyboard::Key key)\n\t{\n\t\treturn p_key_down[key];\n\t}\n\n\tbool isKeyReleased(sf::Keyboard::Key key)\n\t{\n\t\treturn p_key_released[key];\n\t}\n#endif\n\n#if !(INPUT_DISABLE_MOUSE)\n\tbool mouseMoved()\n\t{\n\t\treturn p_mouse_move_event;\n\t}\n\n\tconst MousePosition& getMouseCurrentPosition()\n\t{\n\t\treturn p_current_mouse_info;\n\t}\n\n\tconst MousePosition& getMousePreviousPosition()\n\t{\n\t\treturn p_previous_mouse_info;\n\t}\n\n\tbool isMouseButtonPressed(sf::Mouse::Button button)\n\t{\n\t\treturn p_mouse_button_pressed[button];\n\t}\n\n\tbool isMouseButtonDown(sf::Mouse::Button button)\n\t{\n\t\treturn p_mouse_button_down[button];\n\t}\n\n\tbool isMouseButtonReleased(sf::Mouse::Button button)\n\t{\n\t\treturn p_mouse_button_released[button];\n\t}\n\n\tbool mouseWheelScrolled()\n\t{\n\t\treturn p_mouse_wheel_scrolled;\n\t}\n\n\tfloat getMouseWheelScrollDelta()\n\t{\n\t\treturn p_mouse_scroll_delta;\n\t}\n#endif\n\n#if !(INPUT_DISABLE_JOYSTICK)\n\tbool isJoystickConnected(unsigned int joystickId)\n\t{\n\t\treturn p_joystick_connected[joystickId];\n\t}\n\n\tbool isJoystickActive(unsigned int joystickId)\n\t{\n\t\treturn p_joystick_active[joystickId];\n\t}\n\n\tbool isJoystickDisconnected(unsigned int joystickId)\n\t{\n\t\treturn p_joystick_disconnected[joystickId];\n\t}\n\n\tbool isJoystickButtonPressed(unsigned int joystickId, unsigned int button)\n\t{\n\t\treturn p_joystick_button_pressed[std::pair(joystickId, button)];\n\t}\n\n\tbool isJoystickButtonDown(unsigned int joystickId, unsigned int button)\n\t{\n\t\treturn p_joystick_button_down[std::pair(joystickId, button)];\n\t}\n\n\tbool isJoystickButtonReleased(unsigned int joystickId, unsigned int button)\n\t{\n\t\treturn p_joystick_button_released[std::pair(joystickId, button)];\n\t}\n\n\tfloat getJoystickAxisPosition(unsigned int joystickId, sf::Joystick::Axis axis)\n\t{\n\t\treturn p_joystick_axis_position[std::pair(joystickId, axis)];\n\t}\n#endif\n\nprivate:\n#if !(INPUT_DISABLE_KEYBOARD)\n\tvoid keyUpdate()\n\t{\n\t\tfor (auto it = p_key_pressed.begin(); it != p_key_pressed.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_key_down[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_key_released.begin(); it != p_key_released.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\t}\n\n\tbool keyEvent(const sf::Event& event)\n\t{\n\t\tif (event.type == sf::Event::KeyPressed)\n\t\t{\n\t\t\tp_key_pressed[event.key.code] = not p_key_down[event.key.code];\n\t\t\tp_key_released[event.key.code] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::KeyReleased)\n\t\t{\n\t\t\tp_key_pressed[event.key.code] = false;\n\t\t\tp_key_down[event.key.code] = false;\n\t\t\tp_key_released[event.key.code] = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstd::unordered_map p_key_pressed;\n\tstd::unordered_map p_key_down;\n\tstd::unordered_map p_key_released;\n#endif\n\n#if !(INPUT_DISABLE_MOUSE)\n\tvoid mouseUpdate()\n\t{\n\t\tp_mouse_move_event = false;\n\n\t\tfor (auto it = p_mouse_button_pressed.begin(); it != p_mouse_button_pressed.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_mouse_button_down[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_mouse_button_released.begin(); it != p_mouse_button_released.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\n\t\tif (p_mouse_wheel_scrolled)\n\t\t{\n\t\t\tp_mouse_wheel_scrolled = false;\n\t\t\tp_mouse_scroll_delta = 0.0f;\n\t\t}\n\t}\n\n\tbool mouseEvent(const sf::Event& event)\n\t{\n\t\tif (event.type == sf::Event::MouseButtonPressed)\n\t\t{\n\t\t\tp_mouse_button_pressed[event.mouseButton.button] = not p_mouse_button_down[event.mouseButton.button];\n\t\t\tp_mouse_button_released[event.mouseButton.button] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::MouseButtonReleased)\n\t\t{\n\t\t\tp_mouse_button_pressed[event.mouseButton.button] = false;\n\t\t\tp_mouse_button_down[event.mouseButton.button] = false;\n\t\t\tp_mouse_button_released[event.mouseButton.button] = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::MouseMoved)\n\t\t{\n\t\t\tp_previous_mouse_info = p_current_mouse_info;\n\t\t\tMousePosition mouse;\n\t\t\tmouse.x = event.mouseMove.x;\n\t\t\tmouse.y = event.mouseMove.y;\n\t\t\tp_current_mouse_info = mouse;\n\t\t\tp_mouse_move_event = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::MouseWheelMoved)\n\t\t{\n\t\t\tp_mouse_wheel_scrolled = true;\n\t\t\tp_mouse_scroll_delta = event.mouseWheel.delta;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool p_mouse_move_event;\n\tbool p_mouse_wheel_scrolled;\n\tfloat p_mouse_scroll_delta;\n\tMousePosition p_current_mouse_info;\n\tMousePosition p_previous_mouse_info;\n\n\tstd::unordered_map p_mouse_button_pressed;\n\tstd::unordered_map p_mouse_button_down;\n\tstd::unordered_map p_mouse_button_released;\n#endif\n\n#if !(INPUT_DISABLE_JOYSTICK)\n\tvoid joystickUpdate()\n\t{\n\t\tfor (auto it = p_joystick_button_pressed.begin(); it != p_joystick_button_pressed.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_joystick_button_down[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_joystick_button_released.begin(); it != p_joystick_button_released.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\n\t\tfor (auto it = p_joystick_connected.begin(); it != p_joystick_connected.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_joystick_active[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_joystick_disconnected.begin(); it != p_joystick_disconnected.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\t}\n\n\tbool joystickEvent(const sf::Event& event)\n\t{\n\t\tif (event.type == sf::Event::JoystickConnected)\n\t\t{\n\t\t\tp_joystick_connected[event.joystickConnect.joystickId] = not p_joystick_active[event.joystickConnect.joystickId];\n\t\t\tp_joystick_disconnected[event.joystickConnect.joystickId] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickDisconnected)\n\t\t{\n\t\t\tp_joystick_connected[event.joystickConnect.joystickId] = false;\n\t\t\tp_joystick_active[event.joystickConnect.joystickId] = false;\n\t\t\tp_joystick_disconnected[event.joystickConnect.joystickId] = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickButtonPressed)\n\t\t{\n\t\t\tstd::pair k(event.joystickButton.joystickId, event.joystickButton.button);\n\t\t\tp_joystick_button_pressed[k] = not p_joystick_button_down[k];\n\t\t\tp_joystick_button_released[k] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickButtonReleased)\n\t\t{\n\t\t\tstd::pair k(event.joystickButton.joystickId, event.joystickButton.button);\n\t\t\tp_joystick_button_pressed[k] = false;\n\t\t\tp_joystick_button_down[k] = false;\n\t\t\tp_joystick_button_released[k] = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickMoved)\n\t\t{\n\t\t\tstd::pair k(event.joystickMove.joystickId, event.joystickMove.axis);\n\t\t\tp_joystick_axis_position[k] = event.joystickMove.position;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstd::unordered_map p_joystick_connected;\n\tstd::unordered_map p_joystick_active;\n\tstd::unordered_map p_joystick_disconnected;\n\tstd::unordered_map, bool> p_joystick_button_pressed;\n\tstd::unordered_map, bool> p_joystick_button_down;\n\tstd::unordered_map, bool> p_joystick_button_released;\n\tstd::unordered_map, float> p_joystick_axis_position;\n#endif\n\n};\n#endifFixed bug with mouse position on start#ifndef SFML_INPUT_HANDLER_HPP\n#define SFML_INPUT_HANDLER_HPP\n#include \n#include \n#include \"hash_pair.hpp\"\n\nclass InputHandler\n{\npublic:\n\tstruct MousePosition\n\t{\n\t\tMousePosition():\n\t\tx(0),y(0){}\n\t\tint x;\n\t\tint y;\n\t};\n\tInputHandler()\n\t{\n\t\tauto p = sf::Mouse::getPosition();\n\t\tp_current_mouse_info.x = p.x;\n\t\tp_current_mouse_info.y = p.y;\n\t\tp_previous_mouse_info = p_current_mouse_info;\n\t}\n\t~InputHandler(){}\n\n\tvoid update()\n\t{\n\t\t#if !(INPUT_DISABLE_KEYBOARD)\n\t\tkeyUpdate();\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_MOUSE)\n\t\tmouseUpdate();\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_JOYSTICK)\n\t\tjoystickUpdate();\n\t\t#endif\n\t}\n\n\tvoid handleEvent(const sf::Event& event)\n\t{\n\t\t#if !(INPUT_DISABLE_KEYBOARD)\n\t\tif (keyEvent(event)) return;\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_MOUSE)\n\t\tif (mouseEvent(event)) return;\n\t\t#endif\n\t\t#if !(INPUT_DISABLE_JOYSTICK)\n\t\tif (joystickEvent(event)) return;\n\t\t#endif\n\t}\n\n#if !(INPUT_DISABLE_KEYBOARD)\n\tbool isKeyPressed(sf::Keyboard::Key key)\n\t{\n\t\treturn p_key_pressed[key];\n\t}\n\n\tbool isKeyDown(sf::Keyboard::Key key)\n\t{\n\t\treturn p_key_down[key];\n\t}\n\n\tbool isKeyReleased(sf::Keyboard::Key key)\n\t{\n\t\treturn p_key_released[key];\n\t}\n#endif\n\n#if !(INPUT_DISABLE_MOUSE)\n\tbool mouseMoved()\n\t{\n\t\treturn p_mouse_move_event;\n\t}\n\n\tconst MousePosition& getMouseCurrentPosition()\n\t{\n\t\treturn p_current_mouse_info;\n\t}\n\n\tconst MousePosition& getMousePreviousPosition()\n\t{\n\t\treturn p_previous_mouse_info;\n\t}\n\n\tbool isMouseButtonPressed(sf::Mouse::Button button)\n\t{\n\t\treturn p_mouse_button_pressed[button];\n\t}\n\n\tbool isMouseButtonDown(sf::Mouse::Button button)\n\t{\n\t\treturn p_mouse_button_down[button];\n\t}\n\n\tbool isMouseButtonReleased(sf::Mouse::Button button)\n\t{\n\t\treturn p_mouse_button_released[button];\n\t}\n\n\tbool mouseWheelScrolled()\n\t{\n\t\treturn p_mouse_wheel_scrolled;\n\t}\n\n\tfloat getMouseWheelScrollDelta()\n\t{\n\t\treturn p_mouse_scroll_delta;\n\t}\n#endif\n\n#if !(INPUT_DISABLE_JOYSTICK)\n\tbool isJoystickConnected(unsigned int joystickId)\n\t{\n\t\treturn p_joystick_connected[joystickId];\n\t}\n\n\tbool isJoystickActive(unsigned int joystickId)\n\t{\n\t\treturn p_joystick_active[joystickId];\n\t}\n\n\tbool isJoystickDisconnected(unsigned int joystickId)\n\t{\n\t\treturn p_joystick_disconnected[joystickId];\n\t}\n\n\tbool isJoystickButtonPressed(unsigned int joystickId, unsigned int button)\n\t{\n\t\treturn p_joystick_button_pressed[std::pair(joystickId, button)];\n\t}\n\n\tbool isJoystickButtonDown(unsigned int joystickId, unsigned int button)\n\t{\n\t\treturn p_joystick_button_down[std::pair(joystickId, button)];\n\t}\n\n\tbool isJoystickButtonReleased(unsigned int joystickId, unsigned int button)\n\t{\n\t\treturn p_joystick_button_released[std::pair(joystickId, button)];\n\t}\n\n\tfloat getJoystickAxisPosition(unsigned int joystickId, sf::Joystick::Axis axis)\n\t{\n\t\treturn p_joystick_axis_position[std::pair(joystickId, axis)];\n\t}\n#endif\n\nprivate:\n#if !(INPUT_DISABLE_KEYBOARD)\n\tvoid keyUpdate()\n\t{\n\t\tfor (auto it = p_key_pressed.begin(); it != p_key_pressed.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_key_down[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_key_released.begin(); it != p_key_released.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\t}\n\n\tbool keyEvent(const sf::Event& event)\n\t{\n\t\tif (event.type == sf::Event::KeyPressed)\n\t\t{\n\t\t\tp_key_pressed[event.key.code] = not p_key_down[event.key.code];\n\t\t\tp_key_released[event.key.code] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::KeyReleased)\n\t\t{\n\t\t\tp_key_pressed[event.key.code] = false;\n\t\t\tp_key_down[event.key.code] = false;\n\t\t\tp_key_released[event.key.code] = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstd::unordered_map p_key_pressed;\n\tstd::unordered_map p_key_down;\n\tstd::unordered_map p_key_released;\n#endif\n\n#if !(INPUT_DISABLE_MOUSE)\n\tvoid mouseUpdate()\n\t{\n\t\tp_mouse_move_event = false;\n\n\t\tfor (auto it = p_mouse_button_pressed.begin(); it != p_mouse_button_pressed.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_mouse_button_down[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_mouse_button_released.begin(); it != p_mouse_button_released.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\n\t\tif (p_mouse_wheel_scrolled)\n\t\t{\n\t\t\tp_mouse_wheel_scrolled = false;\n\t\t\tp_mouse_scroll_delta = 0.0f;\n\t\t}\n\t}\n\n\tbool mouseEvent(const sf::Event& event)\n\t{\n\t\tif (event.type == sf::Event::MouseButtonPressed)\n\t\t{\n\t\t\tp_mouse_button_pressed[event.mouseButton.button] = not p_mouse_button_down[event.mouseButton.button];\n\t\t\tp_mouse_button_released[event.mouseButton.button] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::MouseButtonReleased)\n\t\t{\n\t\t\tp_mouse_button_pressed[event.mouseButton.button] = false;\n\t\t\tp_mouse_button_down[event.mouseButton.button] = false;\n\t\t\tp_mouse_button_released[event.mouseButton.button] = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::MouseMoved)\n\t\t{\n\t\t\tp_previous_mouse_info = p_current_mouse_info;\n\t\t\tMousePosition mouse;\n\t\t\tmouse.x = event.mouseMove.x;\n\t\t\tmouse.y = event.mouseMove.y;\n\t\t\tp_current_mouse_info = mouse;\n\t\t\tp_mouse_move_event = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::MouseWheelMoved)\n\t\t{\n\t\t\tp_mouse_wheel_scrolled = true;\n\t\t\tp_mouse_scroll_delta = event.mouseWheel.delta;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool p_mouse_move_event;\n\tbool p_mouse_wheel_scrolled;\n\tfloat p_mouse_scroll_delta;\n\tMousePosition p_current_mouse_info;\n\tMousePosition p_previous_mouse_info;\n\n\tstd::unordered_map p_mouse_button_pressed;\n\tstd::unordered_map p_mouse_button_down;\n\tstd::unordered_map p_mouse_button_released;\n#endif\n\n#if !(INPUT_DISABLE_JOYSTICK)\n\tvoid joystickUpdate()\n\t{\n\t\tfor (auto it = p_joystick_button_pressed.begin(); it != p_joystick_button_pressed.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_joystick_button_down[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_joystick_button_released.begin(); it != p_joystick_button_released.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\n\t\tfor (auto it = p_joystick_connected.begin(); it != p_joystick_connected.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t{\n\t\t\t\tp_joystick_active[it->first] = true;\n\t\t\t\tit->second = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto it = p_joystick_disconnected.begin(); it != p_joystick_disconnected.end(); ++it)\n\t\t{\n\t\t\tif (it->second)\n\t\t\t\tit->second = false;\n\t\t}\n\t}\n\n\tbool joystickEvent(const sf::Event& event)\n\t{\n\t\tif (event.type == sf::Event::JoystickConnected)\n\t\t{\n\t\t\tp_joystick_connected[event.joystickConnect.joystickId] = not p_joystick_active[event.joystickConnect.joystickId];\n\t\t\tp_joystick_disconnected[event.joystickConnect.joystickId] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickDisconnected)\n\t\t{\n\t\t\tp_joystick_connected[event.joystickConnect.joystickId] = false;\n\t\t\tp_joystick_active[event.joystickConnect.joystickId] = false;\n\t\t\tp_joystick_disconnected[event.joystickConnect.joystickId] = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickButtonPressed)\n\t\t{\n\t\t\tstd::pair k(event.joystickButton.joystickId, event.joystickButton.button);\n\t\t\tp_joystick_button_pressed[k] = not p_joystick_button_down[k];\n\t\t\tp_joystick_button_released[k] = false;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickButtonReleased)\n\t\t{\n\t\t\tstd::pair k(event.joystickButton.joystickId, event.joystickButton.button);\n\t\t\tp_joystick_button_pressed[k] = false;\n\t\t\tp_joystick_button_down[k] = false;\n\t\t\tp_joystick_button_released[k] = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if (event.type == sf::Event::JoystickMoved)\n\t\t{\n\t\t\tstd::pair k(event.joystickMove.joystickId, event.joystickMove.axis);\n\t\t\tp_joystick_axis_position[k] = event.joystickMove.position;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstd::unordered_map p_joystick_connected;\n\tstd::unordered_map p_joystick_active;\n\tstd::unordered_map p_joystick_disconnected;\n\tstd::unordered_map, bool> p_joystick_button_pressed;\n\tstd::unordered_map, bool> p_joystick_button_down;\n\tstd::unordered_map, bool> p_joystick_button_released;\n\tstd::unordered_map, float> p_joystick_axis_position;\n#endif\n\n};\n#endif\n<|endoftext|>"} {"text":"#define RLUA_REPLACE\n#include \"..\/rlua.h\"\n#if defined(_WIN32)\n#include \n#include \n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\nnamespace rdebug_utility {\n static int fs_absolute(lua_State* L) {\n#if defined(_WIN32)\n#define FS_ABSOLUTE(path) fs::absolute(path)\n#else\n#define FS_ABSOLUTE(path) fs::absolute(path).lexically_normal()\n#endif\n try {\n auto res = FS_ABSOLUTE(fs::path(bee::lua::tostring(L, 1))).generic_u8string();\n lua_pushlstring(L, res.data(), res.size());\n return 1;\n } catch (const std::exception& e) {\n return bee::lua::push_error(L, e);\n }\n }\n static int platform_os(lua_State* L) {\n lua_pushstring(L, BEE_OS_NAME);\n return 1;\n }\n\n \n#if defined(_WIN32)\n static int getThreadId(int pid) {\n HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);\n if (h != INVALID_HANDLE_VALUE) {\n THREADENTRY32 te;\n te.dwSize = sizeof(te);\n for (BOOL ok = Thread32First(h, &te); ok; ok = Thread32Next(h, &te)) {\n if (te.th32OwnerProcessID == pid) {\n CloseHandle(h);\n return te.th32ThreadID;\n }\n }\n }\n CloseHandle(h);\n return 0;\n }\n static void closeWindow() {\n int tid = getThreadId(GetCurrentProcessId());\n PostThreadMessageW(tid, WM_CLOSE, 0, 0);\n PostThreadMessageW(tid, WM_QUIT, 0, 0);\n }\n bool isConsoleExe(const wchar_t* exe) {\n HANDLE hExe = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hExe == 0) {\n return false;\n }\n DWORD read;\n char data[sizeof IMAGE_NT_HEADERS + sizeof IMAGE_DOS_HEADER];\n SetFilePointer(hExe, 0, NULL, FILE_BEGIN);\n if (!ReadFile(hExe, data, sizeof IMAGE_DOS_HEADER, &read, NULL)) {\n CloseHandle(hExe);\n return false;\n }\n SetFilePointer(hExe, ((PIMAGE_DOS_HEADER)data)->e_lfanew, NULL, FILE_BEGIN);\n if (!ReadFile(hExe, data, sizeof IMAGE_NT_HEADERS, &read, NULL)) {\n CloseHandle(hExe);\n return false;\n }\n CloseHandle(hExe);\n return ((PIMAGE_NT_HEADERS)data)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI;\n }\n static bool isConsoleProcess() {\n wchar_t exe[MAX_PATH] = { 0 };\n GetModuleFileNameW(NULL, exe, MAX_PATH);\n return isConsoleExe(exe);\n }\n#endif\n\n static int closeprocess(lua_State* L) {\n#if defined(_WIN32)\n closeWindow();\n if (isConsoleProcess()) {\n raise(SIGINT);\n }\n#else\n raise(SIGINT);\n#endif\n return 0;\n }\n}\n\nRLUA_FUNC\nint luaopen_remotedebug_utility(lua_State* L) {\n#if defined(_WIN32)\n luaopen_bee_unicode(L);\n#else\n lua_newtable(L);\n#endif\n luaL_Reg lib[] = {\n {\"fs_absolute\", rdebug_utility::fs_absolute},\n {\"platform_os\", rdebug_utility::platform_os},\n {\"closeprocess\", rdebug_utility::closeprocess},\n {NULL, NULL}};\n luaL_setfuncs(L, lib, 0);\n return 1;\n}\n给每个线程都发一遍#define RLUA_REPLACE\n#include \"..\/rlua.h\"\n#if defined(_WIN32)\n#include \n#include \n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\nnamespace rdebug_utility {\n static int fs_absolute(lua_State* L) {\n#if defined(_WIN32)\n#define FS_ABSOLUTE(path) fs::absolute(path)\n#else\n#define FS_ABSOLUTE(path) fs::absolute(path).lexically_normal()\n#endif\n try {\n auto res = FS_ABSOLUTE(fs::path(bee::lua::tostring(L, 1))).generic_u8string();\n lua_pushlstring(L, res.data(), res.size());\n return 1;\n } catch (const std::exception& e) {\n return bee::lua::push_error(L, e);\n }\n }\n static int platform_os(lua_State* L) {\n lua_pushstring(L, BEE_OS_NAME);\n return 1;\n }\n\n \n#if defined(_WIN32)\n static void closeWindow() {\n HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);\n if (h != INVALID_HANDLE_VALUE) {\n THREADENTRY32 te;\n te.dwSize = sizeof(te);\n for (BOOL ok = Thread32First(h, &te); ok; ok = Thread32Next(h, &te)) {\n if (te.th32OwnerProcessID == GetCurrentProcessId()) {\n PostThreadMessageW(te.th32ThreadID, WM_QUIT, 0, 0);\n }\n }\n }\n CloseHandle(h);\n }\n bool isConsoleExe(const wchar_t* exe) {\n HANDLE hExe = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hExe == 0) {\n return false;\n }\n DWORD read;\n char data[sizeof IMAGE_NT_HEADERS + sizeof IMAGE_DOS_HEADER];\n SetFilePointer(hExe, 0, NULL, FILE_BEGIN);\n if (!ReadFile(hExe, data, sizeof IMAGE_DOS_HEADER, &read, NULL)) {\n CloseHandle(hExe);\n return false;\n }\n SetFilePointer(hExe, ((PIMAGE_DOS_HEADER)data)->e_lfanew, NULL, FILE_BEGIN);\n if (!ReadFile(hExe, data, sizeof IMAGE_NT_HEADERS, &read, NULL)) {\n CloseHandle(hExe);\n return false;\n }\n CloseHandle(hExe);\n return ((PIMAGE_NT_HEADERS)data)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI;\n }\n static bool isConsoleProcess() {\n wchar_t exe[MAX_PATH] = { 0 };\n GetModuleFileNameW(NULL, exe, MAX_PATH);\n return isConsoleExe(exe);\n }\n#endif\n\n static int closeprocess(lua_State* L) {\n#if defined(_WIN32)\n closeWindow();\n if (isConsoleProcess()) {\n raise(SIGINT);\n }\n#else\n raise(SIGINT);\n#endif\n return 0;\n }\n}\n\nRLUA_FUNC\nint luaopen_remotedebug_utility(lua_State* L) {\n#if defined(_WIN32)\n luaopen_bee_unicode(L);\n#else\n lua_newtable(L);\n#endif\n luaL_Reg lib[] = {\n {\"fs_absolute\", rdebug_utility::fs_absolute},\n {\"platform_os\", rdebug_utility::platform_os},\n {\"closeprocess\", rdebug_utility::closeprocess},\n {NULL, NULL}};\n luaL_setfuncs(L, lib, 0);\n return 1;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014-2020 Real Logic Limited.\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\n#include \n#include \n\n#include \n\nextern \"C\"\n{\n#include \n}\n\n#define CAPACITY (1024)\n#define METADATA_CAPACITY (CAPACITY * 2)\n#define MSG_TYPE_ID (101)\n\ntypedef std::array values_buffer_t;\ntypedef std::array metadata_buffer_t;\n\nstatic const int REUSE_TIMEOUT = 5000;\n\nclass CountersTest : public testing::Test\n{\npublic:\n\n CountersTest()\n {\n m_valuesBuffer.fill(0);\n m_metadataBuffer.fill(0);\n aeron_counters_manager_init(\n &m_manager, m_metadataBuffer.data(), m_metadataBuffer.size(), m_valuesBuffer.data(), m_valuesBuffer.size(),\n aeron_epoch_clock, REUSE_TIMEOUT);\n aeron_counters_reader_init(\n &m_reader, m_metadataBuffer.data(), m_metadataBuffer.size(), m_valuesBuffer.data(), m_valuesBuffer.size());\n }\n\n virtual ~CountersTest()\n {\n aeron_counters_manager_close(&m_manager);\n }\n\nprotected:\n values_buffer_t m_valuesBuffer;\n metadata_buffer_t m_metadataBuffer;\n aeron_counters_reader_t m_reader;\n aeron_counters_manager_t m_manager;\n};\n\nTEST_F(CountersTest, shouldReadCounterState)\n{\n int32_t state;\n\n EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, 0, &state));\n EXPECT_EQ(AERON_COUNTER_RECORD_UNUSED, state);\n\n int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);\n\n EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));\n EXPECT_EQ(AERON_COUNTER_RECORD_ALLOCATED, state);\n\n aeron_counters_manager_free(&m_manager, id);\n\n EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));\n EXPECT_EQ(AERON_COUNTER_RECORD_RECLAIMED, state);\n\n EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, m_reader.max_counter_id, &state));\n EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, -1, &state));\n}\n\nTEST_F(CountersTest, shouldReadCounterLabel)\n{\n const char *label = \"label as text\";\n char buffer[AERON_COUNTERS_MANAGER_METADATA_LENGTH];\n memset(buffer, 0, AERON_COUNTERS_MANAGER_METADATA_LENGTH);\n\n EXPECT_EQ(0, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n\n int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, label, strlen(label));\n\n EXPECT_EQ(\n (int32_t)strlen(label),\n aeron_counters_reader_counter_label(&m_reader, id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n EXPECT_STREQ(label, buffer);\n\n aeron_counters_manager_free(&m_manager, id);\n\n \/\/ We don't reject or change records when freed.\n EXPECT_EQ(13, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n\n EXPECT_EQ(-1, aeron_counters_reader_counter_label(&m_reader, -1, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n EXPECT_EQ(-1, aeron_counters_reader_counter_label(\n &m_reader, m_reader.max_counter_id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n}\n\nTEST_F(CountersTest, shouldReadTimeToReuse)\n{\n int64_t deadline;\n EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, 0, &deadline));\n\n int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);\n\n EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));\n EXPECT_EQ(AERON_COUNTER_NOT_FREE_TO_REUSE, deadline);\n\n int64_t current_time_ms = aeron_epoch_clock();\n aeron_counters_manager_free(&m_manager, id);\n\n EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));\n EXPECT_LE(current_time_ms + REUSE_TIMEOUT, deadline);\n\n EXPECT_EQ(-1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, m_reader.max_counter_id, &deadline));\n EXPECT_EQ(-1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, -1, &deadline));\n}\n\n[C] Fix warnings in counters tests.\/*\n * Copyright 2014-2020 Real Logic Limited.\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\n#include \n#include \n\n#include \n\nextern \"C\"\n{\n#include \n}\n\n#define CAPACITY (1024)\n#define METADATA_CAPACITY (CAPACITY * 2)\n#define MSG_TYPE_ID (101)\n\ntypedef std::array values_buffer_t;\ntypedef std::array metadata_buffer_t;\n\nstatic const int REUSE_TIMEOUT = 5000;\n\nclass CountersTest : public testing::Test\n{\npublic:\n\n CountersTest()\n {\n m_valuesBuffer.fill(0);\n m_metadataBuffer.fill(0);\n aeron_counters_manager_init(\n &m_manager,\n m_metadataBuffer.data(),\n m_metadataBuffer.size(),\n m_valuesBuffer.data(),\n m_valuesBuffer.size(),\n aeron_epoch_clock,\n REUSE_TIMEOUT);\n aeron_counters_reader_init(\n &m_reader,\n m_metadataBuffer.data(),\n m_metadataBuffer.size(),\n m_valuesBuffer.data(),\n m_valuesBuffer.size());\n }\n\n virtual ~CountersTest()\n {\n aeron_counters_manager_close(&m_manager);\n }\n\nprotected:\n values_buffer_t m_valuesBuffer;\n metadata_buffer_t m_metadataBuffer;\n aeron_counters_reader_t m_reader;\n aeron_counters_manager_t m_manager;\n};\n\nTEST_F(CountersTest, shouldReadCounterState)\n{\n int32_t state;\n\n EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, 0, &state));\n EXPECT_EQ(AERON_COUNTER_RECORD_UNUSED, state);\n\n int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);\n\n EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));\n EXPECT_EQ(AERON_COUNTER_RECORD_ALLOCATED, state);\n\n aeron_counters_manager_free(&m_manager, id);\n\n EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));\n EXPECT_EQ(AERON_COUNTER_RECORD_RECLAIMED, state);\n\n EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, (int32_t)m_reader.max_counter_id, &state));\n EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, -1, &state));\n}\n\nTEST_F(CountersTest, shouldReadCounterLabel)\n{\n const char *label = \"label as text\";\n char buffer[AERON_COUNTERS_MANAGER_METADATA_LENGTH];\n memset(buffer, 0, AERON_COUNTERS_MANAGER_METADATA_LENGTH);\n\n EXPECT_EQ(0, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n\n int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, label, strlen(label));\n\n EXPECT_EQ(\n (int32_t)strlen(label),\n aeron_counters_reader_counter_label(&m_reader, id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n EXPECT_STREQ(label, buffer);\n\n aeron_counters_manager_free(&m_manager, id);\n\n \/\/ We don't reject or change records when freed.\n EXPECT_EQ(13, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n\n EXPECT_EQ(-1, aeron_counters_reader_counter_label(&m_reader, -1, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n EXPECT_EQ(-1, aeron_counters_reader_counter_label(\n &m_reader, (int32_t)m_reader.max_counter_id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));\n}\n\nTEST_F(CountersTest, shouldReadTimeToReuse)\n{\n int64_t deadline;\n EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, 0, &deadline));\n\n int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);\n\n EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));\n EXPECT_EQ(AERON_COUNTER_NOT_FREE_TO_REUSE, deadline);\n\n int64_t current_time_ms = aeron_epoch_clock();\n aeron_counters_manager_free(&m_manager, id);\n\n EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));\n EXPECT_LE(current_time_ms + REUSE_TIMEOUT, deadline);\n\n EXPECT_EQ(\n -1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, (int32_t)m_reader.max_counter_id, &deadline));\n EXPECT_EQ(-1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, -1, &deadline));\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2017)\n\/\/ Rene Milk (2014, 2016 - 2017)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_PROLONGATIONS_HH\n#define DUNE_GDT_PROLONGATIONS_HH\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace GDT {\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general\n * variant].\n *\n * \\note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of\n * target.space().grid_view(), other contributions in target remain (which is on purpose).\n *\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate \nstd::enable_if_t, typename PGV::Grid::template Codim<0>::Entity>::value,\n void>\nprolong(const DiscreteFunction& source,\n DiscreteFunction& target,\n const GridView& prolongation_grid_view)\n{\n interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses\n * target.space().grid_view() as prolongation_grid_view].\n *\/\ntemplate \nvoid prolong(const DiscreteFunction& source, DiscreteFunction& target)\n{\n prolong(source, target, target.space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong(source, target_space, prolongation_grid_view);\n\\endcode\n *\/\ntemplate \nstd::enable_if_t, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction>\nprolong(const DiscreteFunction& source,\n const SpaceInterface& target_space,\n const GridView& prolongation_grid_view)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\n * Use as in\n\\code\nauto target_function = prolong(source, target_space);\n\\endcode\n *\/\ntemplate \nDiscreteFunction prolong(const DiscreteFunction& source,\n const SpaceInterface& target_space)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source].\n *\/\ntemplate \nstd::enable_if_t, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction>\nprolong(const DiscreteFunction& source,\n const SpaceInterface& target_space,\n const GridView& prolongation_grid_view)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\/\ntemplate \nDiscreteFunction prolong(const DiscreteFunction& source,\n const SpaceInterface& target_space)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PROLONGATIONS_HH\n[prolongations] implement for time-dependent functions\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2017)\n\/\/ Rene Milk (2014, 2016 - 2017)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_PROLONGATIONS_HH\n#define DUNE_GDT_PROLONGATIONS_HH\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace GDT {\n\n\n\/\/ ## Variants for a DiscreteFunction ##\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general\n * variant].\n *\n * \\note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of\n * target.space().grid_view(), other contributions in target remain (which is on purpose).\n *\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate \nstd::enable_if_t, typename PGV::Grid::template Codim<0>::Entity>::value,\n void>\nprolong(const DiscreteFunction& source,\n DiscreteFunction& target,\n const GridView& prolongation_grid_view)\n{\n interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses\n * target.space().grid_view() as prolongation_grid_view].\n *\/\ntemplate \nvoid prolong(const DiscreteFunction& source, DiscreteFunction& target)\n{\n prolong(source, target, target.space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong(source, target_space, prolongation_grid_view);\n\\endcode\n *\/\ntemplate \nstd::enable_if_t::value\n && std::is_same,\n typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction>\nprolong(const DiscreteFunction& source,\n const SpaceInterface& target_space,\n const GridView& prolongation_grid_view)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\n * Use as in\n\\code\nauto target_function = prolong(source, target_space);\n\\endcode\n *\/\ntemplate \nstd::enable_if_t::value, DiscreteFunction>\nprolong(const DiscreteFunction& source, const SpaceInterface& target_space)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source].\n *\/\ntemplate \nstd::enable_if_t, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction>\nprolong(const DiscreteFunction& source,\n const SpaceInterface& target_space,\n const GridView& prolongation_grid_view)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\/\ntemplate \nDiscreteFunction prolong(const DiscreteFunction& source,\n const SpaceInterface& target_space)\n{\n auto target_function = make_discrete_function(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/\/ ## Variants for a DiscreteBochnerFunction ##\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [most\n * general variant].\n *\n * \\note Uses prolong() in space.\n *\n * \\sa prolong\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate \nvoid prolong(const DiscreteBochnerFunction& source,\n DiscreteBochnerFunction& target,\n const GridView& spatial_prolongation_grid_view)\n{\n \/\/ prepare\n target.dof_vectors().set_all(0.);\n const auto& temporal_space = target.space().temporal_space();\n DynamicVector local_dof_indices(temporal_space.mapper().max_local_size());\n std::vector dof_has_been_handled(temporal_space.mapper().size(), false);\n \/\/ walk the time intervals\n for (auto&& time_interval : elements(temporal_space.grid_view())) {\n temporal_space.mapper().global_indices(time_interval, local_dof_indices);\n const auto& lagrange_points_in_time =\n temporal_space.finite_element(time_interval.geometry().type()).lagrange_points();\n for (size_t ii = 0; ii < lagrange_points_in_time.size(); ++ii) {\n const size_t global_dof_index = local_dof_indices[ii];\n if (!dof_has_been_handled[global_dof_index]) {\n const auto& point_in_time = time_interval.geometry().global(lagrange_points_in_time[ii]);\n \/\/ evaluate in time\n const auto coarse_spatial_function =\n make_discrete_function(source.space().spatial_space(), source.evaluate(point_in_time));\n \/\/ prolong in space\n auto fine_spatial_function =\n make_discrete_function(target.space().spatial_space(), target.dof_vectors()[global_dof_index]);\n prolong(coarse_spatial_function, fine_spatial_function, spatial_prolongation_grid_view);\n dof_has_been_handled[global_dof_index] = true;\n }\n }\n }\n} \/\/ ... prolong(...)\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [uses\n * target.space().spatial_space().grid_view() as spatial_prolongation_grid_view].\n *\n * \\note Uses prolong() in space.\n *\n * \\sa prolong\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate \nvoid prolong(const DiscreteBochnerFunction& source, DiscreteBochnerFunction& target)\n{\n prolong(source, target, target.space().spatial_space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one\n * [creates suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong(source, target_space, spatial_prolongation_grid_view);\n\\endcode\n *\/\ntemplate \nstd::enable_if_t::value\n && std::is_same,\n typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteBochnerFunction>\nprolong(const DiscreteBochnerFunction& source,\n const BochnerSpace& target_space,\n const GridView& spatial_prolongation_grid_view)\n{\n auto target_function = make_discrete_bochner_function(target_space);\n prolong(source, target_function, spatial_prolongation_grid_view);\n return target_function;\n}\n\n\ntemplate \nstd::enable_if_t::value, DiscreteBochnerFunction>\nprolong(const DiscreteBochnerFunction& source, const BochnerSpace& target_space)\n{\n return prolong(source, target_space, target_space.spatial_space().grid_view());\n}\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PROLONGATIONS_HH\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n* @file mnertclientsquidcontroldgl.cpp\n* @author Limin Sun ;\n* Matti Hamalainen \n* @version 1.0\n* @date May, 2013\n*\n* @section LICENSE\n*\n* Copyright (C) 2013, Limin Sun and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Contains the implementation of the mnertclientSQUIDControlDgl class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"..\/mnertclient.h\"\n#include \"mnertclientsquidcontroldgl.h\"\n#include \"ui_mnertclientsquidcontroldgl.h\"\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace MneRtClientPlugin;\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nmnertclientSQUIDControlDgl::mnertclientSQUIDControlDgl(MneRtClient* p_pMneRtClient,QWidget *parent) :\n QDialog(parent),\n m_pMneRtClient(p_pMneRtClient),\n ui(new Ui::mnertclientSQUIDControlDgl)\n{\n ui->setupUi(this);\n\n \/\/ retune\n connect(ui->m_Qbn_retune, &QPushButton::released, this, &mnertclientSQUIDControlDgl::SendRetune);\n\n}\n\nmnertclientSQUIDControlDgl::~mnertclientSQUIDControlDgl()\n{\n delete ui;\n}\n\nvoid mnertclientSQUIDControlDgl::SendRetune()\n{\n \/\/ Send FLL command to cmdclient\n if(m_pMneRtClient->m_bCmdClientIsConnected)\n {\n this->ui->m_tx_info->setText(QString(\"Send Retune Command\"));\n QString t_sReply = m_pMneRtClient->m_pRtCmdClient->sendCLICommand(QString(\"RETUNE\"));\n this->ui->m_tx_info->setText(QString(\"Reply:\")+t_sReply);\n }\n}\nadd one FLL routine\/\/=============================================================================================================\n\/**\n* @file mnertclientsquidcontroldgl.cpp\n* @author Limin Sun ;\n* Matti Hamalainen \n* @version 1.0\n* @date May, 2013\n*\n* @section LICENSE\n*\n* Copyright (C) 2013, Limin Sun and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Contains the implementation of the mnertclientSQUIDControlDgl class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"..\/mnertclient.h\"\n#include \"mnertclientsquidcontroldgl.h\"\n#include \"ui_mnertclientsquidcontroldgl.h\"\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace MneRtClientPlugin;\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nmnertclientSQUIDControlDgl::mnertclientSQUIDControlDgl(MneRtClient* p_pMneRtClient,QWidget *parent) :\n QDialog(parent),\n m_pMneRtClient(p_pMneRtClient),\n ui(new Ui::mnertclientSQUIDControlDgl)\n{\n ui->setupUi(this);\n\n \/\/ retune\n connect(ui->m_Qbn_retune, &QPushButton::released, this, &mnertclientSQUIDControlDgl::SendRetune);\n\n}\n\nmnertclientSQUIDControlDgl::~mnertclientSQUIDControlDgl()\n{\n delete ui;\n}\n\nvoid mnertclientSQUIDControlDgl::SendRetune()\n{\n QString t_sJsonCommand =\n \"{\"\n \" \\\"commands\\\": {\"\n \" \\\"FLL\\\": {\"\n \" \\\"description\\\": \\\"FLL hardware control\\\",\"\n \" \\\"parameters\\\": {}\"\n \" }\"\n \" }\"\n \"}\";\n\n \/\/ Send FLL command to cmdclient\n if(m_pMneRtClient->m_bCmdClientIsConnected)\n {\n this->ui->m_tx_info->setText(QString(\"Send Retune Command\"));\n QString t_sReply = m_pMneRtClient->m_pRtCmdClient->sendCLICommandFLL(t_sJsonCommand);\n this->ui->m_tx_info->setText(QString(\"Reply:\")+t_sReply);\n }\n}\n<|endoftext|>"} {"text":"add languages\/program_on_cpp\/In_Depth_C++_11\/chapter5-thread\/async.cpp<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/phy\/adr32s.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file adr32s.H\n\/\/\/ @brief Subroutines for the PHY ADR32S registers\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_ADR32S_H_\n#define _MSS_ADR32S_H_\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace mss\n{\n\n\/\/ I have a dream that the PHY code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class adr32sTraits\n\/\/\/ @brief a collection of traits associated with the PHY ADR32S interface\n\/\/\/ @tparam T fapi2::TargetType representing the PHY\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass adr32sTraits;\n\n\/\/\/\n\/\/\/ @class adr32sTraits\n\/\/\/ @brief a collection of traits associated with the Centaur PHY ADR32S interface\n\/\/\/\ntemplate<>\nclass adr32sTraits\n{\n};\n\n\/\/\/\n\/\/\/ @class adr32sTraits\n\/\/\/ @brief a collection of traits associated with the Nimbus PHY ADR32S\n\/\/\/\ntemplate<>\nclass adr32sTraits\n{\n public:\n\n \/\/ Number of ADR32S units\n static constexpr uint64_t ADR32S_COUNT = 2;\n\n \/\/ MCA ADR32S control registers all come in pairs.\n static const std::vector DLL_CNFG_REG;\n\n enum\n {\n DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_RESET,\n DLL_CNTL_INIT_RXDLL_CAL_UPDATE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_UPDATE,\n DLL_CNTL_REGS_RXDLL_CAL_SKIP = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP,\n DLL_CNTL_REGS_RXDLL_CAL_SKIP_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP_LEN,\n DLL_CNTL_REGS_RXDLL_COARSE_ADJ_BY2 = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_COARSE_ADJ_BY2,\n DLL_CNTL_RXREG_FILTER_LENGTH_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC,\n DLL_CNTL_RXREG_FILTER_LENGTH_DC_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC_LEN,\n DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC,\n DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC_LEN =\n MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC_LEN,\n DLL_CNTL_EN_DRIVER_INVFB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_EN_DRIVER_INVFB_DC,\n DLL_CNTL_RXREG_FINECAL_2XILSB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FINECAL_2XILSB_DC,\n DLL_CNTL_CAL_GOOD = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_GOOD,\n DLL_CNTL_CAL_ERROR = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR,\n DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR_FINE,\n\n };\n\n};\n\nnamespace adr32s\n{\n\n\/\/\/\n\/\/\/ @brief Read DLL_CNTL\n\/\/\/ @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] i_target the fapi2 target of the port\n\/\/\/ @param[out] o_data the value of the register\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits >\ninline fapi2::ReturnCode read_dll_cntl( const fapi2::Target& i_target, fapi2::buffer& o_data )\n{\n static_assert( I < TT::ADR32S_COUNT, \"adr32s instance out of range\");\n FAPI_TRY( mss::getScom(i_target, TT::DLL_CNFG_REG[I], o_data) );\n FAPI_INF(\"dll_cntl adrs32%d: 0x%016lx\", I, o_data);\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Write DLL_CNTL_ADR32S0\n\/\/\/ @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] i_target the fapi2 target of the port\n\/\/\/ @param[in] i_data the value of the register\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits >\ninline fapi2::ReturnCode write_dll_cntl( const fapi2::Target& i_target, const fapi2::buffer& i_data )\n{\n static_assert( I < TT::ADR32S_COUNT, \"adr32s instance out of range\");\n FAPI_INF(\"dll_cntl adr32s%d: 0x%016lx\", I, i_data);\n FAPI_TRY( mss::putScom(i_target, TT::DLL_CNFG_REG[I], i_data) );\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\n\/\/ Reseting the DLL registers TODO RTC:156518\n\/\/\n\n\/\/\/\n\/\/\/ @brief Set the DLL cal reset (begins DLL cal operations)\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] o_data the value of the register\n\/\/\/ @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit\n\/\/\/ @note Default state is 'low' as writing a 0 forces the cal to begin.\n\/\/\/\ntemplate< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits >\ninline void set_dll_cal_reset( fapi2::buffer& o_data, const states i_state = mss::LOW )\n{\n FAPI_INF(\"set_dll_cal_reset %s\", (i_state == mss::LOW ? \"low\" : \"high\"));\n o_data.writeBit(i_state);\n}\n\n} \/\/ close namespace adr\n\n} \/\/ close namespace mss\n\n#endif\nAdd flush, init io to phy reset\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/phy\/adr32s.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file adr32s.H\n\/\/\/ @brief Subroutines for the PHY ADR32S registers\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_ADR32S_H_\n#define _MSS_ADR32S_H_\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace mss\n{\n\n\/\/ I have a dream that the PHY code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class adr32sTraits\n\/\/\/ @brief a collection of traits associated with the PHY ADR32S interface\n\/\/\/ @tparam T fapi2::TargetType representing the PHY\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass adr32sTraits;\n\n\/\/\/\n\/\/\/ @class adr32sTraits\n\/\/\/ @brief a collection of traits associated with the Centaur PHY ADR32S interface\n\/\/\/\ntemplate<>\nclass adr32sTraits\n{\n};\n\n\/\/\/\n\/\/\/ @class adr32sTraits\n\/\/\/ @brief a collection of traits associated with the Nimbus PHY ADR32S\n\/\/\/\ntemplate<>\nclass adr32sTraits\n{\n public:\n\n \/\/ Number of ADR32S units\n static constexpr uint64_t ADR32S_COUNT = 2;\n\n \/\/ MCA ADR32S control registers all come in pairs.\n static const std::vector DLL_CNFG_REG;\n static const std::vector OUTPUT_DRIVER_REG;\n\n enum\n {\n DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_RESET,\n DLL_CNTL_INIT_RXDLL_CAL_UPDATE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_UPDATE,\n DLL_CNTL_REGS_RXDLL_CAL_SKIP = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP,\n DLL_CNTL_REGS_RXDLL_CAL_SKIP_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP_LEN,\n DLL_CNTL_REGS_RXDLL_COARSE_ADJ_BY2 = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_COARSE_ADJ_BY2,\n DLL_CNTL_RXREG_FILTER_LENGTH_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC,\n DLL_CNTL_RXREG_FILTER_LENGTH_DC_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC_LEN,\n DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC,\n DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC_LEN =\n MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC_LEN,\n DLL_CNTL_EN_DRIVER_INVFB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_EN_DRIVER_INVFB_DC,\n DLL_CNTL_RXREG_FINECAL_2XILSB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FINECAL_2XILSB_DC,\n DLL_CNTL_CAL_GOOD = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_GOOD,\n DLL_CNTL_CAL_ERROR = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR,\n DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR_FINE,\n\n FLUSH = MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0_ADR0_FLUSH,\n INIT_IO = MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0_ADR0_INIT_IO,\n\n };\n\n};\n\nnamespace adr32s\n{\n\n\/\/\/\n\/\/\/ @brief Read DLL_CNTL\n\/\/\/ @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] i_target the fapi2 target of the port\n\/\/\/ @param[out] o_data the value of the register\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits >\ninline fapi2::ReturnCode read_dll_cntl( const fapi2::Target& i_target, fapi2::buffer& o_data )\n{\n static_assert( I < TT::ADR32S_COUNT, \"adr32s instance out of range\");\n FAPI_TRY( mss::getScom(i_target, TT::DLL_CNFG_REG[I], o_data) );\n FAPI_INF(\"dll_cntl adrs32%d: 0x%016lx\", I, o_data);\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Write DLL_CNTL_ADR32S0\n\/\/\/ @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] i_target the fapi2 target of the port\n\/\/\/ @param[in] i_data the value of the register\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits >\ninline fapi2::ReturnCode write_dll_cntl( const fapi2::Target& i_target, const fapi2::buffer& i_data )\n{\n static_assert( I < TT::ADR32S_COUNT, \"adr32s instance out of range\");\n FAPI_INF(\"dll_cntl adr32s%d: 0x%016lx\", I, i_data);\n FAPI_TRY( mss::putScom(i_target, TT::DLL_CNFG_REG[I], i_data) );\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\n\/\/ Reseting the DLL registers TODO RTC:156518\n\/\/\n\n\/\/\/\n\/\/\/ @brief Set the DLL cal reset (begins DLL cal operations)\n\/\/\/ @tparam T fapi2 Target Type - defaults to TARGET_TYPE_MCA\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] o_data the value of the register\n\/\/\/ @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit\n\/\/\/ @note Default state is 'low' as writing a 0 forces the cal to begin.\n\/\/\/\ntemplate< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits >\ninline void set_dll_cal_reset( fapi2::buffer& o_data, const states i_state = mss::LOW )\n{\n FAPI_INF(\"set_dll_cal_reset %s\", (i_state == mss::LOW ? \"low\" : \"high\"));\n o_data.writeBit(i_state);\n}\n\n\/\/\/\n\/\/\/ @brief Read OUTPUT_DRVIER register\n\/\/\/ @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] i_target the fapi2 target of the port\n\/\/\/ @param[out] o_data the value of the register\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits >\ninline fapi2::ReturnCode read_output_driver( const fapi2::Target& i_target, fapi2::buffer& o_data )\n{\n static_assert( I < TT::ADR32S_COUNT, \"adr32s instance out of range\");\n FAPI_TRY( mss::getScom(i_target, TT::OUTPUT_DRIVER_REG[I], o_data) );\n FAPI_INF(\"output_driver adrs32%d: 0x%016lx\", I, o_data);\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Write OUTPUT_DRIVER\n\/\/\/ @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY\n\/\/\/ @tparam T fapi2 Target Type - derived\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] i_target the fapi2 target of the port\n\/\/\/ @param[in] i_data the value of the register\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits >\ninline fapi2::ReturnCode write_output_driver( const fapi2::Target& i_target, const fapi2::buffer& i_data )\n{\n static_assert( I < TT::ADR32S_COUNT, \"adr32s instance out of range\");\n FAPI_INF(\"output_driver adr32s%d: 0x%016lx\", I, i_data);\n FAPI_TRY( mss::putScom(i_target, TT::OUTPUT_DRIVER_REG[I], i_data) );\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Set the output flush\n\/\/\/ @tparam T fapi2 Target Type - defaults to TARGET_TYPE_MCA\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] o_data the value of the register\n\/\/\/ @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit\n\/\/\/ @note Default state is 'low' as writing a 0 forces the cal to begin.\n\/\/\/\ntemplate< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits >\ninline void set_output_flush( fapi2::buffer& o_data, const states i_state )\n{\n FAPI_INF(\"set_output_flush %s\", (i_state == mss::LOW ? \"low\" : \"high\"));\n o_data.writeBit(i_state);\n}\n\n\/\/\/\n\/\/\/ @brief Set the init io state\n\/\/\/ @tparam T fapi2 Target Type - defaults to TARGET_TYPE_MCA\n\/\/\/ @tparam TT traits type defaults to adr32sTraits\n\/\/\/ @param[in] o_data the value of the register\n\/\/\/ @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit\n\/\/\/ @note Default state is 'low' as writing a 0 forces the cal to begin.\n\/\/\/\ntemplate< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits >\ninline void set_init_io( fapi2::buffer& o_data, const states i_state )\n{\n FAPI_INF(\"set_init_io %s\", (i_state == mss::LOW ? \"low\" : \"high\"));\n o_data.writeBit(i_state);\n}\n\n} \/\/ close namespace adr\n\n} \/\/ close namespace mss\n\n#endif\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/utils\/imageProcs\/p9_infrastruct_help.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_INFRASTRUCT_HELP_H_\n#define _P9_INFRASTRUCT_HELP_H_\n\n#include \n#include \n#include \n#include \/\/memcpy()\n#include \n\n\/\/\n\/\/ Various image\/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)\n\/\/\nconst uint32_t MAX_REF_IMAGE_SIZE = 1024 *\n 1024; \/\/ Max reference image size.\nconst uint32_t FIXED_RING_BUF_SIZE =\n 60000; \/\/ Fixed ring buf size for _fixed.\n\n#define CHIPLET_ID_MIN (uint8_t)0x00\n#define CHIPLET_ID_MAX (uint8_t)0x37\n\n#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)\n#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)\n#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)\n\n\n\/\/ Byte-reverse a 32-bit integer\ninline uint32_t myRev32(const uint32_t i_x)\n{\n uint32_t rx;\n\n#ifdef _BIG_ENDIAN\n rx = i_x;\n#else\n uint8_t* pix = (uint8_t*)(&i_x);\n uint8_t* prx = (uint8_t*)(&rx);\n\n prx[0] = pix[3];\n prx[1] = pix[2];\n prx[2] = pix[1];\n prx[3] = pix[0];\n#endif\n\n return rx;\n}\n\n\/\/ Byte-reverse a 64-bit integer\ninline uint64_t myRev64(const uint64_t i_x)\n{\n uint64_t rx;\n\n#ifdef _BIG_ENDIAN\n rx = i_x;\n#else\n uint8_t* pix = (uint8_t*)(&i_x);\n uint8_t* prx = (uint8_t*)(&rx);\n\n prx[0] = pix[7];\n prx[1] = pix[6];\n prx[2] = pix[5];\n prx[3] = pix[4];\n prx[4] = pix[3];\n prx[5] = pix[2];\n prx[6] = pix[1];\n prx[7] = pix[0];\n#endif\n\n return rx;\n}\n\n\n\/\/ Byte-reverse a 16-bit integer if on an LE machine\ninline uint16_t myRev16(const uint16_t i_x)\n{\n uint16_t rx;\n\n#ifdef _BIG_ENDIAN\n rx = i_x;\n#else\n uint8_t* pix = (uint8_t*)(&i_x);\n uint8_t* prx = (uint8_t*)(&rx);\n\n prx[0] = pix[1];\n prx[1] = pix[0];\n#endif\n\n return rx;\n}\n\n\/\/ N-byte align an address, offset or size (aos)\ninline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)\n{\n return ((aos + nBytes - 1) \/ nBytes) * nBytes;\n}\n\n#endif \/\/_P9_INFRASTRUCT_HELP_H_\np9_infrastruct_help: cleaning up endianess conversion\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/utils\/imageProcs\/p9_infrastruct_help.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_INFRASTRUCT_HELP_H_\n#define _P9_INFRASTRUCT_HELP_H_\n\n#include \n#include \n#include \n#include \/\/memcpy()\n#include \n\n\/\/\n\/\/ Various image\/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)\n\/\/\nconst uint32_t MAX_REF_IMAGE_SIZE = 1024 *\n 1024; \/\/ Max reference image size.\nconst uint32_t FIXED_RING_BUF_SIZE =\n 60000; \/\/ Fixed ring buf size for _fixed.\n\n#define CHIPLET_ID_MIN (uint8_t)0x00\n#define CHIPLET_ID_MAX (uint8_t)0x37\n\n#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)\n#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)\n#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)\n\n\n\/\/ N-byte align an address, offset or size (aos)\ninline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)\n{\n return ((aos + nBytes - 1) \/ nBytes) * nBytes;\n}\n\n#endif \/\/_P9_INFRASTRUCT_HELP_H_\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 Fondazione Istituto Italiano di Tecnologia\n * Authors: Silvio Traversaro\n * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n *\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"testModels.h\"\n\n#include \n#include \n\n#include \n\n\/**\n * Return the current time in seconds, with respect\n * to an arbitrary point in time.\n *\/\ninline double clockInSec()\n{\n clock_t ret = clock();\n return ((double)ret)\/((double)CLOCKS_PER_SEC);\n}\n\n\niDynTree::JointPosDoubleArray getRandomJointPositions(const iDynTree::Model & model)\n{\n iDynTree::JointPosDoubleArray sRandom(model);\n getRandomJointPositions(sRandom,model);\n return sRandom;\n}\n\n\ninline iDynTree::JointPosDoubleArray getRandomJointPositionsCloseTo(const iDynTree::Model& model, iDynTree::VectorDynSize s, double maxDelta)\n{\n iDynTree::JointPosDoubleArray vec(model);\n\n assert(vec.size() == model.getNrOfPosCoords());\n for(iDynTree::JointIndex jntIdx=0; jntIdx < model.getNrOfJoints(); jntIdx++)\n {\n iDynTree::IJointConstPtr jntPtr = model.getJoint(jntIdx);\n if( jntPtr->hasPosLimits() )\n {\n for(int i=0; i < jntPtr->getNrOfPosCoords(); i++)\n {\n int dofIndex = jntPtr->getDOFsOffset()+i;\n double max = std::min(jntPtr->getMaxPosLimit(i),s(dofIndex)+maxDelta);\n double min = std::max(jntPtr->getMinPosLimit(i),s(dofIndex)-maxDelta);\n vec(dofIndex) = iDynTree::getRandomDouble(min,max);\n }\n }\n else\n {\n for(int i=0; i < jntPtr->getNrOfPosCoords(); i++)\n {\n int dofIndex = jntPtr->getDOFsOffset()+i;\n vec(jntPtr->getDOFsOffset()+i) = iDynTree::getRandomDouble(s(dofIndex)-maxDelta,s(dofIndex)+maxDelta);\n }\n }\n }\n\n return vec;\n}\n\nstruct simpleChainIKOptions\n{\n iDynTree::InverseKinematicsRotationParametrization rotationParametrization;\n bool useDesiredJointPositionsToActualValue;\n bool useDesiredJointPositionsToRandomValue;\n};\n\nvoid simpleChainIK(int minNrOfJoints, int maxNrOfJoints, const iDynTree::InverseKinematicsRotationParametrization rotationParametrization)\n{\n \/\/ Solve a simple IK problem for a chain, with no constraints\n for (int i = minNrOfJoints; i <= maxNrOfJoints; i++)\n {\n assert(i >= 2);\n\n std::cerr << \"~~~~~~~> simpleChainIK with \" << i << \" dofs \" << std::endl;\n bool noFixedJoints = true;\n iDynTree::Model chain = iDynTree::getRandomChain(i,10,noFixedJoints);\n\n ASSERT_EQUAL_DOUBLE(i, chain.getNrOfDOFs());\n\n \/\/ Name of the targetFrame the leaf added by getRandomChain\n std::string targetFrame = \"link\" + iDynTree::int2string(i - 1);\n\n \/\/ Create IK\n iDynTree::InverseKinematics ik;\n bool ok = ik.setModel(chain);\n ASSERT_IS_TRUE(ok);\n \/\/ Always express the target as cost\n ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone);\n\n \/\/ Use the requested parametrization\n ik.setRotationParametrization(rotationParametrization);\n\n ik.setTol(1e-6);\n ik.setConstrTol(1e-7);\n\n \/\/ Create also a KinDyn object to perform forward kinematics for the desired values and the optimized ones\n iDynTree::KinDynComputations kinDynDes;\n ok = kinDynDes.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n iDynTree::KinDynComputations kinDynOpt;\n ok = kinDynOpt.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a random vector of internal joint positions\n \/\/ used to get reasonable values for the constraints and the targets\n iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model());\n ok = kinDynDes.setJointPos(s);\n ASSERT_IS_TRUE(ok);\n\n \/\/ Add the fixed base constraint\n ok = ik.addFrameConstraint(\"link1\", kinDynDes.getWorldTransform(\"link1\"));\n \/\/ok = ik.addFrameRotationConstraint(\"link1\", iDynTree::Transform::Identity().getRotation());\n \/\/ok = ik.addFramePositionConstraint(\"link1\", iDynTree::Transform::Identity().getPosition());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Add target\n ok = ik.addPositionTarget(targetFrame, kinDynDes.getWorldTransform(targetFrame));\n ASSERT_IS_TRUE(ok);\n\n\n \/\/ Add a random initial guess\n iDynTree::Transform baseDes = kinDynDes.getWorldBaseTransform();\n \/\/ Set a max delta to avoid local minima in testing\n double maxDelta = 0.01;\n iDynTree::JointPosDoubleArray sInitial = getRandomJointPositionsCloseTo(ik.model(),s,maxDelta);\n ik.setInitialCondition(&(baseDes),&(sInitial));\n\n \/\/ Add a random desired position\n iDynTree::JointPosDoubleArray sDesired = getRandomJointPositions(ik.model());\n ik.setDesiredJointConfiguration(sDesired,1e-12);\n\n \/\/ Start from the initial one\n double tic = clockInSec();\n ok = ik.solve();\n double toc = clockInSec();\n\n ASSERT_IS_TRUE(ok);\n\n \/\/ Get the solution\n iDynTree::Transform baseOpt = iDynTree::Transform::Identity();\n iDynTree::JointPosDoubleArray sOpt(ik.model());\n ik.getSolution(baseOpt,sOpt);\n iDynTree::Twist dummyVel;\n dummyVel.zero();\n iDynTree::Vector3 dummyGrav;\n dummyGrav.zero();\n iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model());\n dummyJointVel.zero();\n\n kinDynOpt.setRobotState(baseOpt,sOpt,dummyVel,dummyJointVel,dummyGrav);\n double tolConstraints = 1e-6;\n double tolTargets = 1e-3;\n\n \/\/ Check if the base link constraint is still valid\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynOpt.getWorldTransform(\"link1\"), kinDynDes.getWorldTransform(\"link1\"), tolConstraints);\n\n \/\/ Check if the target is realized\n ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform(targetFrame).getPosition(), kinDynOpt.getWorldTransform(targetFrame).getPosition(), tolTargets);\n }\n\n}\n\n\/\/ Check the consistency of a simple humanoid wholebody IK test case\nvoid simpleHumanoidWholeBodyIKConsistency(const iDynTree::InverseKinematicsRotationParametrization rotationParametrization)\n{\n iDynTree::InverseKinematics ik;\n\n bool ok = ik.loadModelFromFile(getAbsModelPath(\"iCubGenova02.urdf\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ik.setFloatingBaseOnFrameNamed(\"l_foot\");\n\n ik.setRotationParametrization(rotationParametrization);\n\n \/\/ Create also a KinDyn object to perform forward kinematics for the desired values\n iDynTree::KinDynComputations kinDynDes;\n ok = kinDynDes.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a random vector of internal joint positions\n \/\/ used to get reasonable values for the constraints and the targets\n iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model());\n ok = kinDynDes.setJointPos(s);\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a simple IK problem with the foot constraint\n\n \/\/ The l_sole frame is our world absolute frame (i.e. {}^A H_{l_sole} = identity\n ok = ik.addFrameConstraint(\"l_foot\",kinDynDes.getWorldTransform(\"l_foot\"));\n ASSERT_IS_TRUE(ok);\n\n std::cerr << \"kinDynDes.getWorldTransform(l_foot) : \" << kinDynDes.getWorldTransform(\"l_foot\").toString() << std::endl;\n\n \/\/ The relative position of the r_sole should be the initial one\n ok = ik.addFrameConstraint(\"r_sole\",kinDynDes.getWorldTransform(\"r_sole\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ The two cartesian targets should be reasonable values\n ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone);\n ok = ik.addPositionTarget(\"l_elbow_1\",kinDynDes.getWorldTransform(\"l_elbow_1\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ok = ik.addPositionTarget(\"r_elbow_1\",kinDynDes.getRelativeTransform(\"l_sole\",\"r_elbow_1\").getPosition());\n \/\/ASSERT_IS_TRUE(ok);\n\n iDynTree::Transform initialH = kinDynDes.getWorldBaseTransform();\n\n ik.setInitialCondition(&initialH,&s);\n ik.setDesiredJointConfiguration(s,1e-15);\n\n \/\/ Solve the optimization problem\n double tic = clockInSec();\n ok = ik.solve();\n double toc = clockInSec();\n std::cerr << \"Inverse Kinematics solved in \" << toc-tic << \" seconds. \" << std::endl;\n ASSERT_IS_TRUE(ok);\n\n iDynTree::Transform basePosOptimized;\n iDynTree::JointPosDoubleArray sOptimized(ik.model());\n sOptimized.zero();\n\n ik.getSolution(basePosOptimized,sOptimized);\n\n \/\/ We create a new KinDyn object to perform forward kinematics for the optimized values\n iDynTree::KinDynComputations kinDynOpt;\n kinDynOpt.loadRobotModel(ik.model());\n iDynTree::Twist dummyVel;\n dummyVel.zero();\n iDynTree::Vector3 dummyGrav;\n dummyGrav.zero();\n iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model());\n dummyJointVel.zero();\n kinDynOpt.setRobotState(basePosOptimized, sOptimized, dummyVel, dummyJointVel, dummyGrav);\n\n \/\/ Check that the contraint and the targets are respected\n double tolConstraints = 1e-7;\n double tolTargets = 1e-6;\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform(\"l_foot\"),kinDynOpt.getWorldTransform(\"l_foot\"),tolConstraints);\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform(\"r_sole\"),kinDynOpt.getWorldTransform(\"r_sole\"),tolConstraints);\n ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform(\"l_elbow_1\").getPosition(),\n kinDynOpt.getWorldTransform(\"l_elbow_1\").getPosition(),tolTargets);\n\n return;\n}\n\nint main()\n{\n \/\/ Improve repetability (at least in the same platform)\n srand(0);\n\n simpleChainIK(2,13,iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw);\n\n \/\/ This is not working at the moment, there is some problem with quaternion constraints\n \/\/simpleChainIK(10,iDynTree::InverseKinematicsRotationParametrizationQuaternion);\n\n simpleHumanoidWholeBodyIKConsistency(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw);\n\n return EXIT_SUCCESS;\n}\nUpdated unit test\/*\n * Copyright (C) 2017 Fondazione Istituto Italiano di Tecnologia\n * Authors: Silvio Traversaro\n * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n *\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"testModels.h\"\n\n#include \n#include \n\n#include \n\n\/**\n * Return the current time in seconds, with respect\n * to an arbitrary point in time.\n *\/\ninline double clockInSec()\n{\n clock_t ret = clock();\n return ((double)ret)\/((double)CLOCKS_PER_SEC);\n}\n\n\niDynTree::JointPosDoubleArray getRandomJointPositions(const iDynTree::Model & model)\n{\n iDynTree::JointPosDoubleArray sRandom(model);\n getRandomJointPositions(sRandom,model);\n return sRandom;\n}\n\n\ninline iDynTree::JointPosDoubleArray getRandomJointPositionsCloseTo(const iDynTree::Model& model, iDynTree::VectorDynSize s, double maxDelta)\n{\n iDynTree::JointPosDoubleArray vec(model);\n\n assert(vec.size() == model.getNrOfPosCoords());\n for(iDynTree::JointIndex jntIdx=0; jntIdx < model.getNrOfJoints(); jntIdx++)\n {\n iDynTree::IJointConstPtr jntPtr = model.getJoint(jntIdx);\n if( jntPtr->hasPosLimits() )\n {\n for(int i=0; i < jntPtr->getNrOfPosCoords(); i++)\n {\n int dofIndex = jntPtr->getDOFsOffset()+i;\n double max = std::min(jntPtr->getMaxPosLimit(i),s(dofIndex)+maxDelta);\n double min = std::max(jntPtr->getMinPosLimit(i),s(dofIndex)-maxDelta);\n vec(dofIndex) = iDynTree::getRandomDouble(min,max);\n }\n }\n else\n {\n for(int i=0; i < jntPtr->getNrOfPosCoords(); i++)\n {\n int dofIndex = jntPtr->getDOFsOffset()+i;\n vec(jntPtr->getDOFsOffset()+i) = iDynTree::getRandomDouble(s(dofIndex)-maxDelta,s(dofIndex)+maxDelta);\n }\n }\n }\n\n return vec;\n}\n\nstruct simpleChainIKOptions\n{\n iDynTree::InverseKinematicsRotationParametrization rotationParametrization;\n bool useDesiredJointPositionsToActualValue;\n bool useDesiredJointPositionsToRandomValue;\n};\n\nvoid simpleChainIK(int minNrOfJoints, int maxNrOfJoints, const iDynTree::InverseKinematicsRotationParametrization rotationParametrization)\n{\n \/\/ Solve a simple IK problem for a chain, with no constraints\n for (int i = minNrOfJoints; i <= maxNrOfJoints; i++)\n {\n assert(i >= 2);\n\n std::cerr << \"~~~~~~~> simpleChainIK with \" << i << \" dofs \" << std::endl;\n bool noFixedJoints = true;\n iDynTree::Model chain = iDynTree::getRandomChain(i,10,noFixedJoints);\n\n ASSERT_EQUAL_DOUBLE(i, chain.getNrOfDOFs());\n\n \/\/ Name of the targetFrame the leaf added by getRandomChain\n std::string targetFrame = \"link\" + iDynTree::int2string(i - 1);\n\n \/\/ Create IK\n iDynTree::InverseKinematics ik;\n bool ok = ik.setModel(chain);\n ASSERT_IS_TRUE(ok);\n \/\/ Always express the target as cost\n ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone);\n\n \/\/ Use the requested parametrization\n ik.setRotationParametrization(rotationParametrization);\n\n ik.setTol(1e-6);\n ik.setConstrTol(1e-7);\n\n \/\/ Create also a KinDyn object to perform forward kinematics for the desired values and the optimized ones\n iDynTree::KinDynComputations kinDynDes;\n ok = kinDynDes.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n iDynTree::KinDynComputations kinDynOpt;\n ok = kinDynOpt.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a random vector of internal joint positions\n \/\/ used to get reasonable values for the constraints and the targets\n iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model());\n ok = kinDynDes.setJointPos(s);\n ASSERT_IS_TRUE(ok);\n\n \/\/ Add the fixed base constraint\n ok = ik.addFrameConstraint(\"link1\", kinDynDes.getWorldTransform(\"link1\"));\n \/\/ok = ik.addFrameRotationConstraint(\"link1\", iDynTree::Transform::Identity().getRotation());\n \/\/ok = ik.addFramePositionConstraint(\"link1\", iDynTree::Transform::Identity().getPosition());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Add target\n ok = ik.addPositionTarget(targetFrame, kinDynDes.getWorldTransform(targetFrame));\n ASSERT_IS_TRUE(ok);\n\n\n \/\/ Add a random initial guess\n iDynTree::Transform baseDes = kinDynDes.getWorldBaseTransform();\n \/\/ Set a max delta to avoid local minima in testing\n double maxDelta = 0.01;\n iDynTree::JointPosDoubleArray sInitial = getRandomJointPositionsCloseTo(ik.model(),s,maxDelta);\n ik.setInitialCondition(&(baseDes),&(sInitial));\n\n \/\/ Add a random desired position\n iDynTree::JointPosDoubleArray sDesired = getRandomJointPositions(ik.model());\n ik.setDesiredJointConfiguration(sDesired,1e-12);\n\n \/\/ Start from the initial one\n double tic = clockInSec();\n ok = ik.solve();\n double toc = clockInSec();\n\n ASSERT_IS_TRUE(ok);\n\n \/\/ Get the solution\n iDynTree::Transform baseOpt = iDynTree::Transform::Identity();\n iDynTree::JointPosDoubleArray sOpt(ik.model());\n ik.getSolution(baseOpt,sOpt);\n iDynTree::Twist dummyVel;\n dummyVel.zero();\n iDynTree::Vector3 dummyGrav;\n dummyGrav.zero();\n iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model());\n dummyJointVel.zero();\n\n kinDynOpt.setRobotState(baseOpt,sOpt,dummyVel,dummyJointVel,dummyGrav);\n double tolConstraints = 1e-6;\n double tolTargets = 1e-3;\n\n \/\/ Check if the base link constraint is still valid\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynOpt.getWorldTransform(\"link1\"), kinDynDes.getWorldTransform(\"link1\"), tolConstraints);\n\n \/\/ Check if the target is realized\n ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform(targetFrame).getPosition(), kinDynOpt.getWorldTransform(targetFrame).getPosition(), tolTargets);\n }\n\n}\n\n\/\/ Check the consistency of a simple humanoid wholebody IK test case\nvoid simpleHumanoidWholeBodyIKConsistency(const iDynTree::InverseKinematicsRotationParametrization rotationParametrization)\n{\n iDynTree::InverseKinematics ik;\n\n bool ok = ik.loadModelFromFile(getAbsModelPath(\"iCubGenova02.urdf\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ik.setFloatingBaseOnFrameNamed(\"l_foot\");\n\n ik.setRotationParametrization(rotationParametrization);\n\n \/\/ Create also a KinDyn object to perform forward kinematics for the desired values\n iDynTree::KinDynComputations kinDynDes;\n ok = kinDynDes.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a random vector of internal joint positions\n \/\/ used to get reasonable values for the constraints and the targets\n iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model());\n ok = kinDynDes.setJointPos(s);\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a simple IK problem with the foot constraint\n\n \/\/ The l_sole frame is our world absolute frame (i.e. {}^A H_{l_sole} = identity\n ok = ik.addFrameConstraint(\"l_foot\",kinDynDes.getWorldTransform(\"l_foot\"));\n ASSERT_IS_TRUE(ok);\n\n std::cerr << \"kinDynDes.getWorldTransform(l_foot) : \" << kinDynDes.getWorldTransform(\"l_foot\").toString() << std::endl;\n\n \/\/ The relative position of the r_sole should be the initial one\n ok = ik.addFrameConstraint(\"r_sole\",kinDynDes.getWorldTransform(\"r_sole\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ The two cartesian targets should be reasonable values\n ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone);\n ok = ik.addPositionTarget(\"l_elbow_1\",kinDynDes.getWorldTransform(\"l_elbow_1\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ok = ik.addPositionTarget(\"r_elbow_1\",kinDynDes.getRelativeTransform(\"l_sole\",\"r_elbow_1\").getPosition());\n \/\/ASSERT_IS_TRUE(ok);\n\n iDynTree::Transform initialH = kinDynDes.getWorldBaseTransform();\n\n ik.setInitialCondition(&initialH,&s);\n ik.setDesiredJointConfiguration(s,1e-15);\n\n \/\/ Solve the optimization problem\n double tic = clockInSec();\n ok = ik.solve();\n double toc = clockInSec();\n std::cerr << \"Inverse Kinematics solved in \" << toc-tic << \" seconds. \" << std::endl;\n ASSERT_IS_TRUE(ok);\n\n iDynTree::Transform basePosOptimized;\n iDynTree::JointPosDoubleArray sOptimized(ik.model());\n sOptimized.zero();\n\n ik.getSolution(basePosOptimized,sOptimized);\n\n \/\/ We create a new KinDyn object to perform forward kinematics for the optimized values\n iDynTree::KinDynComputations kinDynOpt;\n kinDynOpt.loadRobotModel(ik.model());\n iDynTree::Twist dummyVel;\n dummyVel.zero();\n iDynTree::Vector3 dummyGrav;\n dummyGrav.zero();\n iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model());\n dummyJointVel.zero();\n kinDynOpt.setRobotState(basePosOptimized, sOptimized, dummyVel, dummyJointVel, dummyGrav);\n\n \/\/ Check that the contraint and the targets are respected\n double tolConstraints = 1e-7;\n double tolTargets = 1e-6;\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform(\"l_foot\"),kinDynOpt.getWorldTransform(\"l_foot\"),tolConstraints);\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform(\"r_sole\"),kinDynOpt.getWorldTransform(\"r_sole\"),tolConstraints);\n ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform(\"l_elbow_1\").getPosition(),\n kinDynOpt.getWorldTransform(\"l_elbow_1\").getPosition(),tolTargets);\n\n return;\n}\n\n\/\/ Check the consistency of a simple humanoid wholebody IK test case, setting a CoM target.\nvoid simpleHumanoidWholeBodyIKCoMConsistency(const iDynTree::InverseKinematicsRotationParametrization rotationParametrization, \n const iDynTree::InverseKinematicsTreatTargetAsConstraint targetResolutionMode)\n{\n iDynTree::InverseKinematics ik;\n\n bool ok = ik.loadModelFromFile(getAbsModelPath(\"iCubGenova02.urdf\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ik.setFloatingBaseOnFrameNamed(\"l_foot\");\n\n ik.setRotationParametrization(rotationParametrization);\n\n \/\/ Create also a KinDyn object to perform forward kinematics for the desired values\n iDynTree::KinDynComputations kinDynDes;\n ok = kinDynDes.loadRobotModel(ik.model());\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a random vector of internal joint positions\n \/\/ used to get reasonable values for the constraints and the targets\n iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model());\n ok = kinDynDes.setJointPos(s);\n ASSERT_IS_TRUE(ok);\n\n \/\/ Create a simple IK problem with the foot constraint\n\n \/\/ The l_sole frame is our world absolute frame (i.e. {}^A H_{l_sole} = identity\n ok = ik.addFrameConstraint(\"l_foot\",kinDynDes.getWorldTransform(\"l_foot\"));\n ASSERT_IS_TRUE(ok);\n\n std::cerr << \"kinDynDes.getWorldTransform(l_foot) : \" << kinDynDes.getWorldTransform(\"l_foot\").toString() << std::endl;\n\n \/\/ The relative position of the r_sole should be the initial one\n ok = ik.addFrameConstraint(\"r_sole\",kinDynDes.getWorldTransform(\"r_sole\"));\n ASSERT_IS_TRUE(ok);\n\n \/\/ The two cartesian targets should be reasonable values\n ik.setTargetResolutionMode(targetResolutionMode);\n iDynTree::Position comDes = kinDynDes.getCenterOfMassPosition();\n ik.setCoMTarget(comDes);\n\n \/\/ok = ik.addPositionTarget(\"r_elbow_1\",kinDynDes.getRelativeTransform(\"l_sole\",\"r_elbow_1\").getPosition());\n \/\/ASSERT_IS_TRUE(ok);\n\n iDynTree::Transform initialH = kinDynDes.getWorldBaseTransform();\n\n ik.setInitialCondition(&initialH,&s);\n ik.setDesiredJointConfiguration(s,1e-15);\n\n \/\/ Solve the optimization problem\n double tic = clockInSec();\n ok = ik.solve();\n double toc = clockInSec();\n std::cerr << \"Inverse Kinematics solved in \" << toc-tic << \" seconds. \" << std::endl;\n ASSERT_IS_TRUE(ok);\n\n iDynTree::Transform basePosOptimized;\n iDynTree::JointPosDoubleArray sOptimized(ik.model());\n sOptimized.zero();\n\n ik.getSolution(basePosOptimized,sOptimized);\n\n \/\/ We create a new KinDyn object to perform forward kinematics for the optimized values\n iDynTree::KinDynComputations kinDynOpt;\n kinDynOpt.loadRobotModel(ik.model());\n iDynTree::Twist dummyVel;\n dummyVel.zero();\n iDynTree::Vector3 dummyGrav;\n dummyGrav.zero();\n iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model());\n dummyJointVel.zero();\n kinDynOpt.setRobotState(basePosOptimized, sOptimized, dummyVel, dummyJointVel, dummyGrav);\n\n \/\/ Check that the contraint and the targets are respected\n double tolConstraints = 1e-7;\n double tolTargets = 1e-6;\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform(\"l_foot\"),kinDynOpt.getWorldTransform(\"l_foot\"),tolConstraints);\n ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform(\"r_sole\"),kinDynOpt.getWorldTransform(\"r_sole\"),tolConstraints);\n ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getCenterOfMassPosition(),\n kinDynOpt.getCenterOfMassPosition(),tolTargets);\n\n return;\n}\n\nint main()\n{\n \/\/ Improve repetability (at least in the same platform)\n srand(0);\n\n simpleChainIK(2,13,iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw);\n\n \/\/ This is not working at the moment, there is some problem with quaternion constraints\n \/\/simpleChainIK(10,iDynTree::InverseKinematicsRotationParametrizationQuaternion);\n\n simpleHumanoidWholeBodyIKConsistency(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw);\n simpleHumanoidWholeBodyIKCoMConsistency(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw, iDynTree::InverseKinematicsTreatTargetAsConstraintNone);\n simpleHumanoidWholeBodyIKCoMConsistency(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw, iDynTree::InverseKinematicsTreatTargetAsConstraintFull);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/chrome_web_contents_view_delegate_views.h\"\n\n#include \"chrome\/browser\/defaults.h\"\n#include \"chrome\/browser\/ui\/aura\/tab_contents\/web_drag_bookmark_handler_aura.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_finder.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/sad_tab_helper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/chrome_web_contents_view_delegate.h\"\n#include \"chrome\/browser\/ui\/views\/renderer_context_menu\/render_view_context_menu_views.h\"\n#include \"chrome\/browser\/ui\/views\/sad_tab_view.h\"\n#include \"components\/web_modal\/popup_manager.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/render_widget_host_view.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_delegate.h\"\n#include \"ui\/aura\/client\/screen_position_client.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/focus\/view_storage.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(USE_AURA)\n#include \"chrome\/browser\/ui\/views\/link_disambiguation\/link_disambiguation_popup.h\"\n#endif\n\nChromeWebContentsViewDelegateViews::ChromeWebContentsViewDelegateViews(\n content::WebContents* web_contents)\n : ContextMenuDelegate(web_contents),\n web_contents_(web_contents) {\n last_focused_view_storage_id_ =\n views::ViewStorage::GetInstance()->CreateStorageID();\n}\n\nChromeWebContentsViewDelegateViews::~ChromeWebContentsViewDelegateViews() {\n \/\/ Makes sure to remove any stored view we may still have in the ViewStorage.\n \/\/\n \/\/ It is possible the view went away before us, so we only do this if the\n \/\/ view is registered.\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n}\n\ngfx::NativeWindow ChromeWebContentsViewDelegateViews::GetNativeWindow() {\n Browser* browser = chrome::FindBrowserWithWebContents(web_contents_);\n return browser ? browser->window()->GetNativeWindow() : nullptr;\n}\n\ncontent::WebDragDestDelegate*\n ChromeWebContentsViewDelegateViews::GetDragDestDelegate() {\n \/\/ We install a chrome specific handler to intercept bookmark drags for the\n \/\/ bookmark manager\/extension API.\n bookmark_handler_.reset(new WebDragBookmarkHandlerAura);\n return bookmark_handler_.get();\n}\n\nbool ChromeWebContentsViewDelegateViews::Focus() {\n SadTabHelper* sad_tab_helper = SadTabHelper::FromWebContents(web_contents_);\n if (sad_tab_helper) {\n SadTabView* sad_tab = static_cast(sad_tab_helper->sad_tab());\n if (sad_tab) {\n sad_tab->RequestFocus();\n return true;\n }\n }\n\n web_modal::PopupManager* popup_manager =\n web_modal::PopupManager::FromWebContents(web_contents_);\n if (popup_manager)\n popup_manager->WasFocused(web_contents_);\n\n return false;\n}\n\nvoid ChromeWebContentsViewDelegateViews::TakeFocus(bool reverse) {\n views::FocusManager* focus_manager = GetFocusManager();\n if (focus_manager)\n focus_manager->AdvanceFocus(reverse);\n}\n\nvoid ChromeWebContentsViewDelegateViews::StoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n\n if (!GetFocusManager())\n return;\n views::View* focused_view = GetFocusManager()->GetFocusedView();\n if (focused_view)\n view_storage->StoreView(last_focused_view_storage_id_, focused_view);\n}\n\nvoid ChromeWebContentsViewDelegateViews::RestoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n views::View* last_focused_view =\n view_storage->RetrieveView(last_focused_view_storage_id_);\n\n if (!last_focused_view) {\n SetInitialFocus();\n } else {\n if (last_focused_view->IsFocusable() &&\n GetFocusManager()->ContainsView(last_focused_view)) {\n last_focused_view->RequestFocus();\n } else {\n \/\/ The focused view may not belong to the same window hierarchy (e.g.\n \/\/ if the location bar was focused and the tab is dragged out), or it may\n \/\/ no longer be focusable (e.g. if the location bar was focused and then\n \/\/ we switched to fullscreen mode). In that case we default to the\n \/\/ default focus.\n SetInitialFocus();\n }\n view_storage->RemoveView(last_focused_view_storage_id_);\n }\n}\n\nscoped_ptr\nChromeWebContentsViewDelegateViews::BuildMenu(\n content::WebContents* web_contents,\n const content::ContextMenuParams& params) {\n scoped_ptr menu;\n content::RenderFrameHost* focused_frame = web_contents->GetFocusedFrame();\n \/\/ If the frame tree does not have a focused frame at this point, do not\n \/\/ bother creating RenderViewContextMenuViews.\n \/\/ This happens if the frame has navigated to a different page before\n \/\/ ContextMenu message was received by the current RenderFrameHost.\n if (focused_frame) {\n menu.reset(RenderViewContextMenuViews::Create(focused_frame, params));\n menu->Init();\n }\n return menu.Pass();\n}\n\nvoid ChromeWebContentsViewDelegateViews::ShowMenu(\n scoped_ptr menu) {\n context_menu_ = menu.Pass();\n if (!context_menu_)\n return;\n\n context_menu_->Show();\n}\n\nvoid ChromeWebContentsViewDelegateViews::ShowContextMenu(\n content::RenderFrameHost* render_frame_host,\n const content::ContextMenuParams& params) {\n ShowMenu(\n BuildMenu(content::WebContents::FromRenderFrameHost(render_frame_host),\n params));\n}\n\nvoid ChromeWebContentsViewDelegateViews::ShowDisambiguationPopup(\n const gfx::Rect& target_rect,\n const SkBitmap& zoomed_bitmap,\n const gfx::NativeView content,\n const base::Callback& gesture_cb,\n const base::Callback& mouse_cb) {\n#if defined(USE_AURA)\n \/\/ If we are attempting to show a link disambiguation popup while already\n \/\/ showing one this means that the popup itself received an ambiguous touch.\n \/\/ Don't show another popup in this case.\n if (link_disambiguation_popup_) {\n link_disambiguation_popup_.reset();\n return;\n }\n\n link_disambiguation_popup_.reset(new LinkDisambiguationPopup);\n link_disambiguation_popup_->Show(\n views::Widget::GetTopLevelWidgetForNativeView(GetActiveNativeView()),\n zoomed_bitmap,\n target_rect,\n content,\n gesture_cb,\n mouse_cb);\n#endif\n}\n\nvoid ChromeWebContentsViewDelegateViews::HideDisambiguationPopup() {\n link_disambiguation_popup_.reset();\n}\n\nvoid ChromeWebContentsViewDelegateViews::SizeChanged(const gfx::Size& size) {\n SadTabHelper* sad_tab_helper = SadTabHelper::FromWebContents(web_contents_);\n if (!sad_tab_helper)\n return;\n SadTabView* sad_tab = static_cast(sad_tab_helper->sad_tab());\n if (sad_tab)\n sad_tab->GetWidget()->SetBounds(gfx::Rect(size));\n}\n\naura::Window* ChromeWebContentsViewDelegateViews::GetActiveNativeView() {\n return web_contents_->GetFullscreenRenderWidgetHostView() ?\n web_contents_->GetFullscreenRenderWidgetHostView()->GetNativeView() :\n web_contents_->GetNativeView();\n}\n\nviews::Widget* ChromeWebContentsViewDelegateViews::GetTopLevelWidget() {\n return views::Widget::GetTopLevelWidgetForNativeView(GetActiveNativeView());\n}\n\nviews::FocusManager*\n ChromeWebContentsViewDelegateViews::GetFocusManager() {\n views::Widget* toplevel_widget = GetTopLevelWidget();\n return toplevel_widget ? toplevel_widget->GetFocusManager() : NULL;\n}\n\nvoid ChromeWebContentsViewDelegateViews::SetInitialFocus() {\n if (web_contents_->FocusLocationBarByDefault()) {\n if (web_contents_->GetDelegate())\n web_contents_->GetDelegate()->SetFocusToLocationBar(false);\n } else {\n web_contents_->Focus();\n }\n}\n\nnamespace chrome {\n\ncontent::WebContentsViewDelegate* CreateWebContentsViewDelegate(\n content::WebContents* web_contents) {\n return new ChromeWebContentsViewDelegateViews(web_contents);\n}\n\n} \/\/ namespace chrome\nRemove some unncessary #include-s from ChromeWebContentsViewDelegateViews.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/chrome_web_contents_view_delegate_views.h\"\n\n#include \"chrome\/browser\/defaults.h\"\n#include \"chrome\/browser\/ui\/aura\/tab_contents\/web_drag_bookmark_handler_aura.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_finder.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/sad_tab_helper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/chrome_web_contents_view_delegate.h\"\n#include \"chrome\/browser\/ui\/views\/renderer_context_menu\/render_view_context_menu_views.h\"\n#include \"chrome\/browser\/ui\/views\/sad_tab_view.h\"\n#include \"components\/web_modal\/popup_manager.h\"\n#include \"content\/public\/browser\/render_widget_host_view.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_delegate.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/focus\/view_storage.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(USE_AURA)\n#include \"chrome\/browser\/ui\/views\/link_disambiguation\/link_disambiguation_popup.h\"\n#endif\n\nChromeWebContentsViewDelegateViews::ChromeWebContentsViewDelegateViews(\n content::WebContents* web_contents)\n : ContextMenuDelegate(web_contents),\n web_contents_(web_contents) {\n last_focused_view_storage_id_ =\n views::ViewStorage::GetInstance()->CreateStorageID();\n}\n\nChromeWebContentsViewDelegateViews::~ChromeWebContentsViewDelegateViews() {\n \/\/ Makes sure to remove any stored view we may still have in the ViewStorage.\n \/\/\n \/\/ It is possible the view went away before us, so we only do this if the\n \/\/ view is registered.\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n}\n\ngfx::NativeWindow ChromeWebContentsViewDelegateViews::GetNativeWindow() {\n Browser* browser = chrome::FindBrowserWithWebContents(web_contents_);\n return browser ? browser->window()->GetNativeWindow() : nullptr;\n}\n\ncontent::WebDragDestDelegate*\n ChromeWebContentsViewDelegateViews::GetDragDestDelegate() {\n \/\/ We install a chrome specific handler to intercept bookmark drags for the\n \/\/ bookmark manager\/extension API.\n bookmark_handler_.reset(new WebDragBookmarkHandlerAura);\n return bookmark_handler_.get();\n}\n\nbool ChromeWebContentsViewDelegateViews::Focus() {\n SadTabHelper* sad_tab_helper = SadTabHelper::FromWebContents(web_contents_);\n if (sad_tab_helper) {\n SadTabView* sad_tab = static_cast(sad_tab_helper->sad_tab());\n if (sad_tab) {\n sad_tab->RequestFocus();\n return true;\n }\n }\n\n web_modal::PopupManager* popup_manager =\n web_modal::PopupManager::FromWebContents(web_contents_);\n if (popup_manager)\n popup_manager->WasFocused(web_contents_);\n\n return false;\n}\n\nvoid ChromeWebContentsViewDelegateViews::TakeFocus(bool reverse) {\n views::FocusManager* focus_manager = GetFocusManager();\n if (focus_manager)\n focus_manager->AdvanceFocus(reverse);\n}\n\nvoid ChromeWebContentsViewDelegateViews::StoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n\n if (!GetFocusManager())\n return;\n views::View* focused_view = GetFocusManager()->GetFocusedView();\n if (focused_view)\n view_storage->StoreView(last_focused_view_storage_id_, focused_view);\n}\n\nvoid ChromeWebContentsViewDelegateViews::RestoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n views::View* last_focused_view =\n view_storage->RetrieveView(last_focused_view_storage_id_);\n\n if (!last_focused_view) {\n SetInitialFocus();\n } else {\n if (last_focused_view->IsFocusable() &&\n GetFocusManager()->ContainsView(last_focused_view)) {\n last_focused_view->RequestFocus();\n } else {\n \/\/ The focused view may not belong to the same window hierarchy (e.g.\n \/\/ if the location bar was focused and the tab is dragged out), or it may\n \/\/ no longer be focusable (e.g. if the location bar was focused and then\n \/\/ we switched to fullscreen mode). In that case we default to the\n \/\/ default focus.\n SetInitialFocus();\n }\n view_storage->RemoveView(last_focused_view_storage_id_);\n }\n}\n\nscoped_ptr\nChromeWebContentsViewDelegateViews::BuildMenu(\n content::WebContents* web_contents,\n const content::ContextMenuParams& params) {\n scoped_ptr menu;\n content::RenderFrameHost* focused_frame = web_contents->GetFocusedFrame();\n \/\/ If the frame tree does not have a focused frame at this point, do not\n \/\/ bother creating RenderViewContextMenuViews.\n \/\/ This happens if the frame has navigated to a different page before\n \/\/ ContextMenu message was received by the current RenderFrameHost.\n if (focused_frame) {\n menu.reset(RenderViewContextMenuViews::Create(focused_frame, params));\n menu->Init();\n }\n return menu.Pass();\n}\n\nvoid ChromeWebContentsViewDelegateViews::ShowMenu(\n scoped_ptr menu) {\n context_menu_ = menu.Pass();\n if (!context_menu_)\n return;\n\n context_menu_->Show();\n}\n\nvoid ChromeWebContentsViewDelegateViews::ShowContextMenu(\n content::RenderFrameHost* render_frame_host,\n const content::ContextMenuParams& params) {\n ShowMenu(\n BuildMenu(content::WebContents::FromRenderFrameHost(render_frame_host),\n params));\n}\n\nvoid ChromeWebContentsViewDelegateViews::ShowDisambiguationPopup(\n const gfx::Rect& target_rect,\n const SkBitmap& zoomed_bitmap,\n const gfx::NativeView content,\n const base::Callback& gesture_cb,\n const base::Callback& mouse_cb) {\n#if defined(USE_AURA)\n \/\/ If we are attempting to show a link disambiguation popup while already\n \/\/ showing one this means that the popup itself received an ambiguous touch.\n \/\/ Don't show another popup in this case.\n if (link_disambiguation_popup_) {\n link_disambiguation_popup_.reset();\n return;\n }\n\n link_disambiguation_popup_.reset(new LinkDisambiguationPopup);\n link_disambiguation_popup_->Show(\n views::Widget::GetTopLevelWidgetForNativeView(GetActiveNativeView()),\n zoomed_bitmap,\n target_rect,\n content,\n gesture_cb,\n mouse_cb);\n#endif\n}\n\nvoid ChromeWebContentsViewDelegateViews::HideDisambiguationPopup() {\n link_disambiguation_popup_.reset();\n}\n\nvoid ChromeWebContentsViewDelegateViews::SizeChanged(const gfx::Size& size) {\n SadTabHelper* sad_tab_helper = SadTabHelper::FromWebContents(web_contents_);\n if (!sad_tab_helper)\n return;\n SadTabView* sad_tab = static_cast(sad_tab_helper->sad_tab());\n if (sad_tab)\n sad_tab->GetWidget()->SetBounds(gfx::Rect(size));\n}\n\naura::Window* ChromeWebContentsViewDelegateViews::GetActiveNativeView() {\n return web_contents_->GetFullscreenRenderWidgetHostView() ?\n web_contents_->GetFullscreenRenderWidgetHostView()->GetNativeView() :\n web_contents_->GetNativeView();\n}\n\nviews::Widget* ChromeWebContentsViewDelegateViews::GetTopLevelWidget() {\n return views::Widget::GetTopLevelWidgetForNativeView(GetActiveNativeView());\n}\n\nviews::FocusManager*\n ChromeWebContentsViewDelegateViews::GetFocusManager() {\n views::Widget* toplevel_widget = GetTopLevelWidget();\n return toplevel_widget ? toplevel_widget->GetFocusManager() : NULL;\n}\n\nvoid ChromeWebContentsViewDelegateViews::SetInitialFocus() {\n if (web_contents_->FocusLocationBarByDefault()) {\n if (web_contents_->GetDelegate())\n web_contents_->GetDelegate()->SetFocusToLocationBar(false);\n } else {\n web_contents_->Focus();\n }\n}\n\nnamespace chrome {\n\ncontent::WebContentsViewDelegate* CreateWebContentsViewDelegate(\n content::WebContents* web_contents) {\n return new ChromeWebContentsViewDelegateViews(web_contents);\n}\n\n} \/\/ namespace chrome\n<|endoftext|>"} {"text":"#include \"Engine.h\"\n#include \"Game.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyRigid.h\"\n#include \"BodyDummy.h\"\n\n\n\n#ifdef MEMORY_INFO\n#define new new(__FILE__, __LINE__) \n#endif \/\/ MEMORY_INFO\n\nusing namespace MathLib;\n\n\/*\n*\/\n#define ACTOR_BASE_IFPS (1.0f \/ 60.0f)\n#define ACTOR_BASE_CLAMP 89.9f\n#define ACTOR_BASE_COLLISIONS 4\n\n\/*\n*\/\n\n\nCActorBase::CActorBase()\n{\n\tm_vUp = vec3(0.0f, 0.0f, 1.0f);\n\tm_pObject = new CObjectDummy();\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(1.0f, 1.0f);\n\n\tm_nFlush = 0;\n\tm_vPosition = Vec3_zero;\n\tm_vVelocity = Vec3_zero;\n\tm_fPhiAngle = 0.0f;\t\t\t\/\/б\t\tάƽϵУֱYķX֮ļн\n\tm_fThetaAngle = 0.0f;\t\t\t\/\/λǣ뵱ǰ˳ʱ߹ĽǶ\n\n\tfor (int i = 0; i < NUM_STATES; i++)\n\t{\n\t\tm_pStates[i] = 0;\n\t\tm_pTimes[i] = 0.0f;\n\t}\n\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\n}Signed-off-by: mrlitong #include \"Engine.h\"\n#include \"Game.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyRigid.h\"\n#include \"BodyDummy.h\"\n\n\n\n#ifdef MEMORY_INFO\n#define new new(__FILE__, __LINE__) \n#endif \/\/ MEMORY_INFO\n\nusing namespace MathLib;\n\n\/*\n*\/\n#define ACTOR_BASE_IFPS (1.0f \/ 60.0f)\n#define ACTOR_BASE_CLAMP 89.9f\n#define ACTOR_BASE_COLLISIONS 4\n\n\/*\n*\/\n\n\nCActorBase::CActorBase()\n{\n\tm_vUp = vec3(0.0f, 0.0f, 1.0f);\n\tm_pObject = new CObjectDummy();\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(1.0f, 1.0f);\n\n\tm_nFlush = 0;\n\tm_vPosition = Vec3_zero;\n\tm_vVelocity = Vec3_zero;\n\tm_fPhiAngle = 0.0f;\t\t\t\/\/б\t\tάƽϵУֱYķX֮ļн\n\tm_fThetaAngle = 0.0f;\t\t\t\/\/λǣ뵱ǰ˳ʱ߹ĽǶ\n\n\tfor (int i = 0; i < NUM_STATES; i++)\n\t{\n\t\tm_pStates[i] = 0;\n\t\tm_pTimes[i] = 0.0f;\n\t}\n\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\tm_pShape->SetRestitution(0.0f);\n\tm_pShape->SetCollisionMask(2);\n\n\n}<|endoftext|>"} {"text":"#include \"qjsonobjectconverter_p.h\"\n#include \"qjsonserializerexception.h\"\n#include \"qjsonserializer_p.h\"\n\n#include \n#include \n#include \n#include \n\nconst QRegularExpression QJsonObjectConverter::sharedTypeRegex(QStringLiteral(R\"__(^QSharedPointer<\\s*(.*?)\\s*>$)__\"));\nconst QRegularExpression QJsonObjectConverter::trackingTypeRegex(QStringLiteral(R\"__(^QPointer<\\s*(.*?)\\s*>$)__\"));\n\nbool QJsonObjectConverter::canConvert(int metaTypeId) const\n{\n\tauto flags = QMetaType::typeFlags(metaTypeId);\n\treturn flags.testFlag(QMetaType::PointerToQObject) ||\n\t\t\tflags.testFlag(QMetaType::SharedPointerToQObject) ||\/\/weak ptr cannot be constructed\n\t\t\tflags.testFlag(QMetaType::TrackingPointerToQObject);\n}\n\nQList QJsonObjectConverter::jsonTypes() const\n{\n\treturn {\n\t\tQJsonValue::Object,\n\t\tQJsonValue::Null\n\t};\n}\n\nQJsonValue QJsonObjectConverter::serialize(int propertyType, const QVariant &value, const QJsonTypeConverter::SerializationHelper *helper) const\n{\n\tQObject *object = nullptr;\n\tauto flags = QMetaType::typeFlags(propertyType);\n\tif(flags.testFlag(QMetaType::PointerToQObject))\n\t object = extract(value);\n\telse if(flags.testFlag(QMetaType::SharedPointerToQObject))\n\t object = extract>(value).data();\n\telse if(flags.testFlag(QMetaType::TrackingPointerToQObject))\n\t object = extract>(value).data();\n\telse\n\t Q_UNREACHABLE();\n\n\tif(object) {\n\t\t\/\/get the metaobject, based on polymorphism\n\t\tconst QMetaObject *meta = nullptr;\n\t\tauto poly = (QJsonSerializer::Polymorphing)helper->getProperty(\"polymorphic\").toInt();\n\t\tauto isPoly = false;\n\t\tswitch (poly) {\n\t\tcase QJsonSerializer::Disabled:\n\t\t\tisPoly = false;\n\t\t\tbreak;\n\t\tcase QJsonSerializer::Enabled:\n\t\t\tisPoly = polyMetaObject(object);\n\t\t\tbreak;\n\t\tcase QJsonSerializer::Forced:\n\t\t\tisPoly = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tQ_UNREACHABLE();\n\t\t\tbreak;\n\t\t}\n\n\t\tQJsonObject jsonObject;\n\n\t\tif(isPoly) {\n\t\t\tmeta = object->metaObject();\n\t\t\t\/\/first: pass the class name\n\t\t\tjsonObject[QStringLiteral(\"@class\")] = QString::fromUtf8(meta->className());\n\t\t} else\n\t\t\tmeta = getMetaObject(propertyType);\n\n\t\t\/\/go through all properties and try to serialize them\n\t\tauto keepObjectName = helper->getProperty(\"keepObjectName\").toBool();\n\t\tauto i = QObject::staticMetaObject.indexOfProperty(\"objectName\");\n\t\tif(!keepObjectName)\n\t\t i++;\n\t\tfor(; i < meta->propertyCount(); i++) {\n\t\t\tauto property = meta->property(i);\n\t\t\tif(property.isStored())\n\t\t\t\tjsonObject[QString::fromUtf8(property.name())] = helper->serializeSubtype(property, property.read(object));\n\t\t}\n\n\t\treturn jsonObject;\n\t}\n\telse\n\t\treturn QJsonValue();\n}\n\nQVariant QJsonObjectConverter::deserialize(int propertyType, const QJsonValue &value, QObject *parent, const QJsonTypeConverter::SerializationHelper *helper) const\n{\n\tif(value.isNull())\n\t\treturn toVariant(nullptr, QMetaType::typeFlags(propertyType));\n\n\tauto validationFlags = helper->getProperty(\"validationFlags\").value();\n\tauto keepObjectName = helper->getProperty(\"keepObjectName\").toBool();\n\tauto metaObject = getMetaObject(propertyType);\n\tif(!metaObject)\n\t\tthrow QJsonDeserializationException(QByteArray(\"Unable to get metaobject for type \") + QMetaType::typeName(propertyType));\n\n\t\/\/try to construct the object\n\tauto object = metaObject->newInstance(Q_ARG(QObject*, parent));\n\tif(!object) {\n\t\tthrow QJsonDeserializationException(QByteArray(\"Failed to construct object of type \") +\n\t\t\t\t\t\t\t\t\t\t\tmetaObject->className() +\n\t\t\t\t\t\t\t\t\t\t\tQByteArray(\" (Does the constructor \\\"Q_INVOKABLE class(QObject*);\\\" exist?)\"));\n\t}\n\n\t\/\/collect required properties, if set\n\tQSet reqProps;\n\tif(validationFlags.testFlag(QJsonSerializer::AllProperties)) {\n\t\tauto i = QObject::staticMetaObject.indexOfProperty(\"objectName\");\n\t\tif(!keepObjectName)\n\t\t i++;\n\t\tfor(; i < metaObject->propertyCount(); i++) {\n\t\t\tauto property = metaObject->property(i);\n\t\t\tif(property.isStored())\n\t\t\t\treqProps.insert(property.name());\n\t\t}\n\t}\n\n\t\/\/now deserialize all json properties\n\tauto jsonObject = value.toObject();\n\tfor(auto it = jsonObject.constBegin(); it != jsonObject.constEnd(); it++) {\n\t\tauto propIndex = metaObject->indexOfProperty(qUtf8Printable(it.key()));\n\t\tQVariant value;\n\t\tif(propIndex != -1) {\n\t\t\tauto property = metaObject->property(propIndex);\n\t\t\tvalue = helper->deserializeSubtype(property, it.value(), object);\n\t\t\treqProps.remove(property.name());\n\t\t} else if(validationFlags.testFlag(QJsonSerializer::NoExtraProperties)) {\n\t\t\tthrow QJsonDeserializationException(\"Found extra property \" +\n\t\t\t\t\t\t\t\t\t\t\t\tit.key().toUtf8() +\n\t\t\t\t\t\t\t\t\t\t\t\t\" but extra properties are not allowed\");\n\t\t} else\n\t\t\tvalue = helper->deserializeSubtype(QMetaType::UnknownType, it.value(), object);\n\t\tobject->setProperty(qUtf8Printable(it.key()), value);\n\t}\n\n\t\/\/make shure all required properties have been read\n\tif(validationFlags.testFlag(QJsonSerializer::AllProperties) && !reqProps.isEmpty()) {\n\t\tthrow QJsonDeserializationException(QByteArray(\"Not all properties for \") +\n\t\t\t\t\t\t\t\t\t\t\tmetaObject->className() +\n\t\t\t\t\t\t\t\t\t\t\tQByteArray(\" are present in the json object Missing properties: \") +\n\t\t\t\t\t\t\t\t\t\t\treqProps.toList().join(\", \"));\n\t}\n\n\treturn toVariant(object, QMetaType::typeFlags(propertyType));\n}\n\nconst QMetaObject *QJsonObjectConverter::getMetaObject(int typeId)\n{\n\tauto flags = QMetaType::typeFlags(typeId);\n\tif(flags.testFlag(QMetaType::PointerToQObject))\n\t\treturn QMetaType::metaObjectForType(typeId);\n\telse {\n\t\tQRegularExpression regex;\n\t\tif(flags.testFlag(QMetaType::SharedPointerToQObject))\n\t\t\tregex = sharedTypeRegex;\n\t\telse if(flags.testFlag(QMetaType::TrackingPointerToQObject))\n\t\t\tregex = trackingTypeRegex;\n\t\telse {\n\t\t\tQ_UNREACHABLE();\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t\/\/extract template type, and if found, add the pointer star and find the meta type\n\t\tauto match = regex.match(QString::fromUtf8(QMetaType::typeName(typeId)));\n\t\tif(match.hasMatch()) {\n\t\t\tauto type = QMetaType::type(match.captured(1).toUtf8().trimmed() + \"*\");\n\t\t\treturn QMetaType::metaObjectForType(type);\n\t\t} else\n\t\t\treturn nullptr;\n\t}\n}\n\ntemplate\nT QJsonObjectConverter::extract(QVariant variant)\n{\n auto id = qMetaTypeId();\n if(variant.canConvert(id) && variant.convert(id))\n\treturn variant.value();\n else\n\tthrow QJsonSerializationException(QByteArray(\"unable to get QObject pointer from type \") + QMetaType::typeName(id));\n}\n\nQVariant QJsonObjectConverter::toVariant(QObject *object, QMetaType::TypeFlags flags)\n{\n\tif(flags.testFlag(QMetaType::PointerToQObject))\n\t\treturn QVariant::fromValue(object);\n\telse if(flags.testFlag(QMetaType::SharedPointerToQObject)) {\n\t\t\/\/remove parent, as shared pointers and object tree exclude each other\n\t\tif(object)\n\t\t\tobject->setParent(nullptr);\n\t\treturn QVariant::fromValue(QSharedPointer(object));\n\t} else if(flags.testFlag(QMetaType::TrackingPointerToQObject))\n\t\treturn QVariant::fromValue>(object);\n\telse {\n\t\tQ_UNREACHABLE();\n\t\treturn QVariant();\n\t}\n}\n\nbool QJsonObjectConverter::polyMetaObject(QObject *object)\n{\n\tauto meta = object->metaObject();\n\n\t\/\/check the internal property\n\tif(object->dynamicPropertyNames().contains(\"__qt_json_serializer_polymorphic\")) {\n\t\tauto polyProp = object->property(\"__qt_json_serializer_polymorphic\").toBool();\n\t\treturn polyProp;\n\t}\n\n\t\/\/check the class info\n\tauto polyIndex = meta->indexOfClassInfo(\"polymorphic\");\n\tif(polyIndex != -1) {\n\t\tauto info = meta->classInfo(polyIndex);\n\t\tif(info.value() == QByteArray(\"true\"))\n\t\t\treturn true;\/\/ use the object\n\t\telse if(info.value() == QByteArray(\"false\"))\n\t\t\treturn false;\/\/ use the class\n\t\telse\n\t\t\tqWarning() << \"Invalid value for polymorphic classinfo on object type\" << meta->className() << \"ignored\";\n\t}\n\n\t\/\/default: the class\n\treturn false;\/\/ use the class\n}\nadded poly deserialize#include \"qjsonobjectconverter_p.h\"\n#include \"qjsonserializerexception.h\"\n#include \"qjsonserializer_p.h\"\n\n#include \n#include \n#include \n#include \n\nconst QRegularExpression QJsonObjectConverter::sharedTypeRegex(QStringLiteral(R\"__(^QSharedPointer<\\s*(.*?)\\s*>$)__\"));\nconst QRegularExpression QJsonObjectConverter::trackingTypeRegex(QStringLiteral(R\"__(^QPointer<\\s*(.*?)\\s*>$)__\"));\n\nbool QJsonObjectConverter::canConvert(int metaTypeId) const\n{\n\tauto flags = QMetaType::typeFlags(metaTypeId);\n\treturn flags.testFlag(QMetaType::PointerToQObject) ||\n\t\t\tflags.testFlag(QMetaType::SharedPointerToQObject) ||\/\/weak ptr cannot be constructed\n\t\t\tflags.testFlag(QMetaType::TrackingPointerToQObject);\n}\n\nQList QJsonObjectConverter::jsonTypes() const\n{\n\treturn {\n\t\tQJsonValue::Object,\n\t\tQJsonValue::Null\n\t};\n}\n\nQJsonValue QJsonObjectConverter::serialize(int propertyType, const QVariant &value, const QJsonTypeConverter::SerializationHelper *helper) const\n{\n\tQObject *object = nullptr;\n\tauto flags = QMetaType::typeFlags(propertyType);\n\tif(flags.testFlag(QMetaType::PointerToQObject))\n\t object = extract(value);\n\telse if(flags.testFlag(QMetaType::SharedPointerToQObject))\n\t object = extract>(value).data();\n\telse if(flags.testFlag(QMetaType::TrackingPointerToQObject))\n\t object = extract>(value).data();\n\telse\n\t Q_UNREACHABLE();\n\n\tif(object) {\n\t\t\/\/get the metaobject, based on polymorphism\n\t\tconst QMetaObject *meta = nullptr;\n\t\tauto poly = (QJsonSerializer::Polymorphing)helper->getProperty(\"polymorphic\").toInt();\n\t\tauto isPoly = false;\n\t\tswitch (poly) {\n\t\tcase QJsonSerializer::Disabled:\n\t\t\tisPoly = false;\n\t\t\tbreak;\n\t\tcase QJsonSerializer::Enabled:\n\t\t\tisPoly = polyMetaObject(object);\n\t\t\tbreak;\n\t\tcase QJsonSerializer::Forced:\n\t\t\tisPoly = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tQ_UNREACHABLE();\n\t\t\tbreak;\n\t\t}\n\n\t\tQJsonObject jsonObject;\n\n\t\tif(isPoly) {\n\t\t\tmeta = object->metaObject();\n\t\t\t\/\/first: pass the class name\n\t\t\tjsonObject[QStringLiteral(\"@class\")] = QString::fromUtf8(meta->className());\n\t\t} else\n\t\t\tmeta = getMetaObject(propertyType);\n\n\t\t\/\/go through all properties and try to serialize them\n\t\tauto keepObjectName = helper->getProperty(\"keepObjectName\").toBool();\n\t\tauto i = QObject::staticMetaObject.indexOfProperty(\"objectName\");\n\t\tif(!keepObjectName)\n\t\t i++;\n\t\tfor(; i < meta->propertyCount(); i++) {\n\t\t\tauto property = meta->property(i);\n\t\t\tif(property.isStored())\n\t\t\t\tjsonObject[QString::fromUtf8(property.name())] = helper->serializeSubtype(property, property.read(object));\n\t\t}\n\n\t\treturn jsonObject;\n\t}\n\telse\n\t\treturn QJsonValue();\n}\n\nQVariant QJsonObjectConverter::deserialize(int propertyType, const QJsonValue &value, QObject *parent, const QJsonTypeConverter::SerializationHelper *helper) const\n{\n\tif(value.isNull())\n\t\treturn toVariant(nullptr, QMetaType::typeFlags(propertyType));\n\n\tauto validationFlags = helper->getProperty(\"validationFlags\").value();\n\tauto keepObjectName = helper->getProperty(\"keepObjectName\").toBool();\n\tauto poly = (QJsonSerializer::Polymorphing)helper->getProperty(\"polymorphic\").toInt();\n\n\tauto metaObject = getMetaObject(propertyType);\n\tif(!metaObject)\n\t\tthrow QJsonDeserializationException(QByteArray(\"Unable to get metaobject for type \") + QMetaType::typeName(propertyType));\n\n\t\/\/try to get the polymorphic metatype (if allowed)\n\tauto jsonObject = value.toObject();\n\tif(poly != QJsonSerializer::Disabled) {\n\t\tif(jsonObject.contains(QStringLiteral(\"@class\"))) {\n\t\t\tauto classField = jsonObject[QStringLiteral(\"@class\")].toString().toUtf8();\n\t\t\tauto typeId = QMetaType::type(classField.constData());\n\t\t\tauto nMeta = QMetaType::metaObjectForType(typeId);\n\t\t\tif(!nMeta)\n\t\t\t\tthrow QJsonDeserializationException(\"Unable to find class requested from json \\\"@class\\\" property: \" + classField);\n\t\t\tif(!nMeta->inherits(metaObject)) {\n\t\t\t\tthrow QJsonDeserializationException(\"Requested class from \\\"@class\\\" field, \" +\n\t\t\t\t\t\t\t\t\t\t\t\t\tclassField +\n\t\t\t\t\t\t\t\t\t\t\t\t\tQByteArray(\", does not inhert the property type \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\tQMetaType::typeName(propertyType));\n\t\t\t}\n\t\t\tmetaObject = nMeta;\n\t\t} else if(poly == QJsonSerializer::Forced)\n\t\t\tthrow QJsonDeserializationException(\"Json does not contain the \\\"@class\\\" field, but forced polymorphism requires it\");\n\t}\n\n\t\/\/try to construct the object\n\tauto object = metaObject->newInstance(Q_ARG(QObject*, parent));\n\tif(!object) {\n\t\tthrow QJsonDeserializationException(QByteArray(\"Failed to construct object of type \") +\n\t\t\t\t\t\t\t\t\t\t\tmetaObject->className() +\n\t\t\t\t\t\t\t\t\t\t\tQByteArray(\" (Does the constructor \\\"Q_INVOKABLE class(QObject*);\\\" exist?)\"));\n\t}\n\n\t\/\/collect required properties, if set\n\tQSet reqProps;\n\tif(validationFlags.testFlag(QJsonSerializer::AllProperties)) {\n\t\tauto i = QObject::staticMetaObject.indexOfProperty(\"objectName\");\n\t\tif(!keepObjectName)\n\t\t i++;\n\t\tfor(; i < metaObject->propertyCount(); i++) {\n\t\t\tauto property = metaObject->property(i);\n\t\t\tif(property.isStored())\n\t\t\t\treqProps.insert(property.name());\n\t\t}\n\t}\n\n\t\/\/now deserialize all json properties\n\tfor(auto it = jsonObject.constBegin(); it != jsonObject.constEnd(); it++) {\n\t\tauto propIndex = metaObject->indexOfProperty(qUtf8Printable(it.key()));\n\t\tQVariant value;\n\t\tif(propIndex != -1) {\n\t\t\tauto property = metaObject->property(propIndex);\n\t\t\tvalue = helper->deserializeSubtype(property, it.value(), object);\n\t\t\treqProps.remove(property.name());\n\t\t} else if(validationFlags.testFlag(QJsonSerializer::NoExtraProperties)) {\n\t\t\tthrow QJsonDeserializationException(\"Found extra property \" +\n\t\t\t\t\t\t\t\t\t\t\t\tit.key().toUtf8() +\n\t\t\t\t\t\t\t\t\t\t\t\t\" but extra properties are not allowed\");\n\t\t} else\n\t\t\tvalue = helper->deserializeSubtype(QMetaType::UnknownType, it.value(), object);\n\t\tobject->setProperty(qUtf8Printable(it.key()), value);\n\t}\n\n\t\/\/make shure all required properties have been read\n\tif(validationFlags.testFlag(QJsonSerializer::AllProperties) && !reqProps.isEmpty()) {\n\t\tthrow QJsonDeserializationException(QByteArray(\"Not all properties for \") +\n\t\t\t\t\t\t\t\t\t\t\tmetaObject->className() +\n\t\t\t\t\t\t\t\t\t\t\tQByteArray(\" are present in the json object Missing properties: \") +\n\t\t\t\t\t\t\t\t\t\t\treqProps.toList().join(\", \"));\n\t}\n\n\treturn toVariant(object, QMetaType::typeFlags(propertyType));\n}\n\nconst QMetaObject *QJsonObjectConverter::getMetaObject(int typeId)\n{\n\tauto flags = QMetaType::typeFlags(typeId);\n\tif(flags.testFlag(QMetaType::PointerToQObject))\n\t\treturn QMetaType::metaObjectForType(typeId);\n\telse {\n\t\tQRegularExpression regex;\n\t\tif(flags.testFlag(QMetaType::SharedPointerToQObject))\n\t\t\tregex = sharedTypeRegex;\n\t\telse if(flags.testFlag(QMetaType::TrackingPointerToQObject))\n\t\t\tregex = trackingTypeRegex;\n\t\telse {\n\t\t\tQ_UNREACHABLE();\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t\/\/extract template type, and if found, add the pointer star and find the meta type\n\t\tauto match = regex.match(QString::fromUtf8(QMetaType::typeName(typeId)));\n\t\tif(match.hasMatch()) {\n\t\t\tauto type = QMetaType::type(match.captured(1).toUtf8().trimmed() + \"*\");\n\t\t\treturn QMetaType::metaObjectForType(type);\n\t\t} else\n\t\t\treturn nullptr;\n\t}\n}\n\ntemplate\nT QJsonObjectConverter::extract(QVariant variant)\n{\n auto id = qMetaTypeId();\n if(variant.canConvert(id) && variant.convert(id))\n\treturn variant.value();\n else\n\tthrow QJsonSerializationException(QByteArray(\"unable to get QObject pointer from type \") + QMetaType::typeName(id));\n}\n\nQVariant QJsonObjectConverter::toVariant(QObject *object, QMetaType::TypeFlags flags)\n{\n\tif(flags.testFlag(QMetaType::PointerToQObject))\n\t\treturn QVariant::fromValue(object);\n\telse if(flags.testFlag(QMetaType::SharedPointerToQObject)) {\n\t\t\/\/remove parent, as shared pointers and object tree exclude each other\n\t\tif(object)\n\t\t\tobject->setParent(nullptr);\n\t\treturn QVariant::fromValue(QSharedPointer(object));\n\t} else if(flags.testFlag(QMetaType::TrackingPointerToQObject))\n\t\treturn QVariant::fromValue>(object);\n\telse {\n\t\tQ_UNREACHABLE();\n\t\treturn QVariant();\n\t}\n}\n\nbool QJsonObjectConverter::polyMetaObject(QObject *object)\n{\n\tauto meta = object->metaObject();\n\n\t\/\/check the internal property\n\tif(object->dynamicPropertyNames().contains(\"__qt_json_serializer_polymorphic\")) {\n\t\tauto polyProp = object->property(\"__qt_json_serializer_polymorphic\").toBool();\n\t\treturn polyProp;\n\t}\n\n\t\/\/check the class info\n\tauto polyIndex = meta->indexOfClassInfo(\"polymorphic\");\n\tif(polyIndex != -1) {\n\t\tauto info = meta->classInfo(polyIndex);\n\t\tif(info.value() == QByteArray(\"true\"))\n\t\t\treturn true;\/\/ use the object\n\t\telse if(info.value() == QByteArray(\"false\"))\n\t\t\treturn false;\/\/ use the class\n\t\telse\n\t\t\tqWarning() << \"Invalid value for polymorphic classinfo on object type\" << meta->className() << \"ignored\";\n\t}\n\n\t\/\/default: the class\n\treturn false;\/\/ use the class\n}\n<|endoftext|>"} {"text":"#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH\n#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#if HAVE_EIGEN\n #include \n#endif \/\/ HAVE_EIGEN\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/\/! ParameterTree extension for nicer output\n\/\/! \\todo TODO The report method should go into dune-common\nclass ExtendedParameterTree\n : public Dune::ParameterTree {\n\n typedef Dune::ParameterTree BaseType;\n\npublic:\n ExtendedParameterTree();\n ExtendedParameterTree(const std::string filename);\n ExtendedParameterTree(int argc, char** argv, std::string filename);\n ExtendedParameterTree(const Dune::ParameterTree& other);\n\n ExtendedParameterTree& operator=(const Dune::ParameterTree& other);\n\n \/**\n * \\brief adds another Dune::ParameterTree\n *\/\n void add(const Dune::ParameterTree& _other, const std::string _subName = \"\");\n ExtendedParameterTree sub(const std::string& _sub) const;\n\n void report(std::ostream& stream = std::cout, const std::string& prefix = \"\") const;\n void reportNicely(std::ostream& stream = std::cout) const;\n std::string reportString(const std::string& prefix = \"\") const;\n\n std::string get(const std::string& key, const char* defaultValue) const\n {\n return this->get< std::string >(key, std::string(defaultValue));\n }\n\n template< typename T >\n T get(const std::string& key, const T& defaultValue) const\n {\n if (!BaseType::hasKey(key)) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" missing key '\" << key << \"' is replaced by given default value!\" << std::endl;\n }\n return BaseType::get< T >(key, defaultValue);\n }\n\n template< class T >\n T get(const std::string& key) const\n {\n if (!BaseType::hasKey(key))\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" key '\" << key << \"' missing in the following Dune::ParameterTree:\\n\" << reportString(\" \"));\n return BaseType::get< T >(key);\n }\n\n bool hasVector(const std::string& key) const;\n\n template< class T >\n Dune::DynamicVector< T > getDynVector(const std::string& key, const T& def, const size_t minSize) const\n {\n const std::vector< T > vector = getVector< T >(key, def, minSize);\n Dune::DynamicVector< T > ret(vector.size());\n for (size_t ii = 0; ii < vector.size(); ++ii)\n ret[ii] = vector[ii];\n return ret;\n }\n\n template< class T >\n std::vector< T > getVector(const std::string& key, const T& def, const unsigned int minSize) const\n {\n if (!hasKey(key)) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" missing key '\" << key << \"' is replaced by given default value!\" << std::endl;\n return std::vector< T >(minSize, def);\n } else {\n const std::string str = BaseType::get(key, \"meaningless_default_value\");\n if (str.empty()) {\n if (minSize > 0) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" vector '\" << key << \"' was too small (0) and has been enlarged to size \" << minSize << \"!\" << std::endl;\n }\n return std::vector< T >(minSize, def);\n } else if (str.size() < 3) {\n std::vector< T > ret;\n ret.push_back(DSC::fromString< T >(str));\n if (ret.size() < minSize) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" vector '\" << key << \"' was too small (\" << ret.size() << \") and has been enlarged to size \" << minSize << \"!\" << std::endl;\n for (auto i = ret.size(); i < minSize; ++i)\n ret.push_back(def);\n }\n return ret;\n } else {\n \/\/ the dune parametertree strips any leading and trailing whitespace\n \/\/ so we can be sure that the first and last have to be the brackets [] if this is a vector\n std::vector< T > ret;\n if (str.substr(0, 1) == \"[\"\n && str.substr(str.size() - 1, 1) == \"]\") {\n std::vector< std::string > tokens;\n if (str.size() > 2)\n tokens = DSC::tokenize< std::string >(str.substr(1, str.size() - 2), \";\");\n for (unsigned int i = 0; i < tokens.size(); ++i)\n ret.push_back(DSC::fromString< T >(boost::algorithm::trim_copy(tokens[i])));\n for (auto i = ret.size(); i < minSize; ++i)\n ret.push_back(def);\n } else if (str.substr(0, 1) == \"[\"\n || str.substr(str.size() - 1, 1) == \"]\") {\n DUNE_THROW(Dune::RangeError, \"Vectors have to be of the form '[entry_0; entry_1; ... ]'!\");\n } else {\n ret = std::vector< T >(minSize, DSC::fromString< T >(boost::algorithm::trim_copy(str)));\n }\n return ret;\n }\n }\n } \/\/ std::vector< T > getVector(const std::string& key, const T def) const\n\n template< class T >\n Dune::DynamicVector< T > getDynVector(const std::string& _key, const size_t minSize) const\n {\n const std::vector< T > vector = getVector< T >(_key, minSize);\n Dune::DynamicVector< T > ret(vector.size());\n for (size_t ii = 0; ii < vector.size(); ++ii)\n ret[ii] = vector[ii];\n return ret;\n }\n\n template< class T >\n std::vector< T > getVector(const std::string& key, const unsigned int minSize) const\n {\n if (!hasKey(key)) {\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << DSC::colorStringRed(\"ERROR:\")\n << \" key '\" << key << \"' missing in the following Dune::ParameterTree:\\n\" << reportString(\" \"));\n } else {\n std::vector< T > ret;\n const std::string str = BaseType::get< std::string >(key, \"meaningless_default_value\");\n \/\/ the dune parametertree strips any leading and trailing whitespace\n \/\/ so we can be sure that the first and last have to be the brackets [] if this is a vector\n if (str.substr(0, 1) == \"[\" && str.substr(str.size() - 1, 1) == \"]\") {\n const std::vector< std::string > tokens = DSC::tokenize< std::string >(str.substr(1, str.size() - 2), \";\");\n for (unsigned int i = 0; i < tokens.size(); ++i)\n ret.push_back(DSC::fromString< T >(boost::algorithm::trim_copy(tokens[i])));\n } else if (minSize == 1)\n ret.push_back(DSC::fromString< T >(str));\n else\n DUNE_THROW(Dune::RangeError, \"Vectors have to be of the form '[entry_0; entry_1; ... ]'!\");\n if (ret.size() < minSize)\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << DSC::colorStringRed(\"ERROR:\")\n << \" vector '\" << key\n << \"' too short (is \" << ret.size() << \", should be at least \" << minSize\n << \") in the following Dune::ParameterTree :\\n\" << reportString(\" \"));\n return ret;\n }\n } \/\/ std::vector< T > getVector(const std::string& key, const T def) const\n\n#if HAVE_EIGEN\n template< class T >\n Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& key,\n const T& def,\n const unsigned int minSize) const\n {\n \/\/ get correspongin vector\n std::vector< T > vec = getVector< T >(key, def, minSize);\n \/\/ create eigen vector and return\n Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());\n for (unsigned int i = 0; i < vec.size(); ++i)\n ret(i) = vec[i];\n return ret;\n }\n\n template< class T >\n Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& key, const unsigned int minSize) const\n {\n \/\/ get correspongin vector\n std::vector< T > vec = getVector< T >(key, minSize);\n \/\/ create eigen vector and return\n Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());\n for (unsigned int i = 0; i < vec.size(); ++i)\n ret(i) = vec[i];\n return ret;\n }\n#endif \/\/ HAVE_EIGEN\n\n void assertKey(const std::string& key) const;\n void assertSub(const std::string& _sub) const;\n\n \/**\n \\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.\n \\param[in] argc\n From \\c main()\n \\param[in] argv\n From \\c main()\n \\return The Dune::ParameterTree that is to be filled.\n **\/\n static ParameterTree init(int argc, char** argv, std::string filename);\n static ParameterTree init(const std::string filename);\n\nprivate:\n void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const;\n std::string findCommonPrefix(const BaseType& sub, const std::string previousPrefix = \"\") const;\n void reportFlatly(const BaseType& sub, const std::string& prefix = \"\", std::ostream& stream = std::cout) const;\n}; \/\/ class ExtendedParameterTree\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_COMMON_PARAMETER_TREE_HH\n\n\/** Copyright (c) 2012, Rene Milk, Felix Albrecht\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n[dune.stuff.common.parameter] fixed typo#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH\n#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#if HAVE_EIGEN\n #include \n#endif \/\/ HAVE_EIGEN\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/\/! ParameterTree extension for nicer output\n\/\/! \\todo TODO The report method should go into dune-common\nclass ExtendedParameterTree\n : public Dune::ParameterTree {\n\n typedef Dune::ParameterTree BaseType;\n\npublic:\n ExtendedParameterTree();\n ExtendedParameterTree(const std::string filename);\n ExtendedParameterTree(int argc, char** argv, std::string filename);\n ExtendedParameterTree(const Dune::ParameterTree& other);\n\n ExtendedParameterTree& operator=(const Dune::ParameterTree& other);\n\n \/**\n * \\brief adds another Dune::ParameterTree\n *\/\n void add(const Dune::ParameterTree& _other, const std::string _subName = \"\");\n ExtendedParameterTree sub(const std::string& _sub) const;\n\n void report(std::ostream& stream = std::cout, const std::string& prefix = \"\") const;\n void reportNicely(std::ostream& stream = std::cout) const;\n std::string reportString(const std::string& prefix = \"\") const;\n\n std::string get(const std::string& key, const char* defaultValue) const\n {\n return this->get< std::string >(key, std::string(defaultValue));\n }\n\n template< typename T >\n T get(const std::string& key, const T& defaultValue) const\n {\n if (!BaseType::hasKey(key)) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" missing key '\" << key << \"' is replaced by given default value!\" << std::endl;\n }\n return BaseType::get< T >(key, defaultValue);\n }\n\n template< class T >\n T get(const std::string& key) const\n {\n if (!BaseType::hasKey(key))\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" key '\" << key << \"' missing in the following Dune::ParameterTree:\\n\" << reportString(\" \"));\n return BaseType::get< T >(key);\n }\n\n bool hasVector(const std::string& key) const;\n\n template< class T >\n Dune::DynamicVector< T > getDynVector(const std::string& key, const T& def, const size_t minSize) const\n {\n const std::vector< T > vector = getVector< T >(key, def, minSize);\n Dune::DynamicVector< T > ret(vector.size());\n for (size_t ii = 0; ii < vector.size(); ++ii)\n ret[ii] = vector[ii];\n return ret;\n }\n\n template< class T >\n std::vector< T > getVector(const std::string& key, const T& def, const unsigned int minSize) const\n {\n if (!hasKey(key)) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" missing key '\" << key << \"' is replaced by given default value!\" << std::endl;\n return std::vector< T >(minSize, def);\n } else {\n const std::string str = BaseType::get(key, \"meaningless_default_value\");\n if (str.empty()) {\n if (minSize > 0) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" vector '\" << key << \"' was too small (0) and has been enlarged to size \" << minSize << \"!\" << std::endl;\n }\n return std::vector< T >(minSize, def);\n } else if (str.size() < 3) {\n std::vector< T > ret;\n ret.push_back(DSC::fromString< T >(str));\n if (ret.size() < minSize) {\n DSC::Logger().debug() << DSC::colorString(\"WARNING:\") << \" vector '\" << key << \"' was too small (\" << ret.size() << \") and has been enlarged to size \" << minSize << \"!\" << std::endl;\n for (auto i = ret.size(); i < minSize; ++i)\n ret.push_back(def);\n }\n return ret;\n } else {\n \/\/ the dune parametertree strips any leading and trailing whitespace\n \/\/ so we can be sure that the first and last have to be the brackets [] if this is a vector\n std::vector< T > ret;\n if (str.substr(0, 1) == \"[\"\n && str.substr(str.size() - 1, 1) == \"]\") {\n std::vector< std::string > tokens;\n if (str.size() > 2)\n tokens = DSC::tokenize< std::string >(str.substr(1, str.size() - 2), \";\");\n for (unsigned int i = 0; i < tokens.size(); ++i)\n ret.push_back(DSC::fromString< T >(boost::algorithm::trim_copy(tokens[i])));\n for (auto i = ret.size(); i < minSize; ++i)\n ret.push_back(def);\n } else if (str.substr(0, 1) == \"[\"\n || str.substr(str.size() - 1, 1) == \"]\") {\n DUNE_THROW(Dune::RangeError, \"Vectors have to be of the form '[entry_0; entry_1; ... ]'!\");\n } else {\n ret = std::vector< T >(minSize, DSC::fromString< T >(boost::algorithm::trim_copy(str)));\n }\n return ret;\n }\n }\n } \/\/ std::vector< T > getVector(const std::string& key, const T def) const\n\n template< class T >\n Dune::DynamicVector< T > getDynVector(const std::string& _key, const size_t minSize) const\n {\n const std::vector< T > vector = getVector< T >(_key, minSize);\n Dune::DynamicVector< T > ret(vector.size());\n for (size_t ii = 0; ii < vector.size(); ++ii)\n ret[ii] = vector[ii];\n return ret;\n }\n\n template< class T >\n std::vector< T > getVector(const std::string& key, const unsigned int minSize) const\n {\n if (!hasKey(key)) {\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << DSC::colorStringRed(\"ERROR:\")\n << \" key '\" << key << \"' missing in the following Dune::ParameterTree:\\n\" << reportString(\" \"));\n } else {\n std::vector< T > ret;\n const std::string str = BaseType::get< std::string >(key, \"meaningless_default_value\");\n \/\/ the dune parametertree strips any leading and trailing whitespace\n \/\/ so we can be sure that the first and last have to be the brackets [] if this is a vector\n if (str.substr(0, 1) == \"[\" && str.substr(str.size() - 1, 1) == \"]\") {\n const std::vector< std::string > tokens = DSC::tokenize< std::string >(str.substr(1, str.size() - 2), \";\");\n for (unsigned int i = 0; i < tokens.size(); ++i)\n ret.push_back(DSC::fromString< T >(boost::algorithm::trim_copy(tokens[i])));\n } else if (minSize == 1)\n ret.push_back(DSC::fromString< T >(str));\n else\n DUNE_THROW(Dune::RangeError, \"Vectors have to be of the form '[entry_0; entry_1; ... ]'!\");\n if (ret.size() < minSize)\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << DSC::colorStringRed(\"ERROR:\")\n << \" vector '\" << key\n << \"' too short (is \" << ret.size() << \", should be at least \" << minSize\n << \") in the following Dune::ParameterTree :\\n\" << reportString(\" \"));\n return ret;\n }\n } \/\/ std::vector< T > getVector(const std::string& key, const T def) const\n\n#if HAVE_EIGEN\n template< class T >\n Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& key,\n const T& def,\n const unsigned int minSize) const\n {\n \/\/ get corresponding vector\n std::vector< T > vec = getVector< T >(key, def, minSize);\n \/\/ create eigen vector and return\n Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());\n for (unsigned int i = 0; i < vec.size(); ++i)\n ret(i) = vec[i];\n return ret;\n }\n\n template< class T >\n Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& key, const unsigned int minSize) const\n {\n \/\/ get corresponding vector\n std::vector< T > vec = getVector< T >(key, minSize);\n \/\/ create eigen vector and return\n Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());\n for (unsigned int i = 0; i < vec.size(); ++i)\n ret(i) = vec[i];\n return ret;\n }\n#endif \/\/ HAVE_EIGEN\n\n void assertKey(const std::string& key) const;\n void assertSub(const std::string& _sub) const;\n\n \/**\n \\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.\n \\param[in] argc\n From \\c main()\n \\param[in] argv\n From \\c main()\n \\return The Dune::ParameterTree that is to be filled.\n **\/\n static ParameterTree init(int argc, char** argv, std::string filename);\n static ParameterTree init(const std::string filename);\n\nprivate:\n void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const;\n std::string findCommonPrefix(const BaseType& sub, const std::string previousPrefix = \"\") const;\n void reportFlatly(const BaseType& sub, const std::string& prefix = \"\", std::ostream& stream = std::cout) const;\n}; \/\/ class ExtendedParameterTree\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_COMMON_PARAMETER_TREE_HH\n\n\/** Copyright (c) 2012, Rene Milk, Felix Albrecht\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n<|endoftext|>"} {"text":"\/* rsspp - Copyright (C) 2008-2009 Andreas Krennmair \n * Licensed under the MIT\/X Consortium License. See file LICENSE\n * for more information.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace newsbeuter;\n\nstatic size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {\n\tstd::string * pbuf = static_cast(userp);\n\tpbuf->append(static_cast(buffer), size * nmemb);\n\treturn size * nmemb;\n}\n\nnamespace rsspp {\n\nparser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) \n\t: to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) {\n}\n\nparser::~parser() {\n\tif (doc)\n\t\txmlFreeDoc(doc);\n}\n\nstruct header_values {\n\ttime_t lastmodified;\n\tstd::string etag;\n};\n\nstatic size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) {\n\tchar * header = new char[size*nmemb + 1];\n\theader_values * values = (header_values *)data;\n\n\tmemcpy(header, ptr, size*nmemb);\n\theader[size*nmemb] = '\\0';\n\n\tif (!strncasecmp(\"Last-Modified:\", header, 14)) {\n\t\tvalues->lastmodified = curl_getdate(header+14, NULL);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got last-modified %s (%d)\", header+14, values->lastmodified);\n\t} else if (!strncasecmp(\"ETag:\",header, 5)) {\n\t\tvalues->etag = std::string(header+5);\n\t\tutils::trim(values->etag);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got etag %s\", values->etag.c_str());\n\t}\n\n\tdelete[] header;\n\n\treturn size * nmemb;\n}\n\nfeed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag) {\n\tstd::string buf;\n\tCURLcode ret;\n\n\tCURL * easyhandle = curl_easy_init();\n\tif (!easyhandle) {\n\t\tthrow exception(_(\"couldn't initialize libcurl\"));\n\t}\n\n\tif (ua) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);\n\t}\n\tcurl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());\n\tcurl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);\n\tcurl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_ENCODING, \"gzip, deflate\");\n\tif (to != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);\n\n\tif (prx)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);\n\n\tif (prxauth)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);\n\n\theader_values hdrs = { 0, \"\" };\n\n\tcurl_slist * custom_headers = NULL;\n\n\tif (lastmodified != 0) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\tif (etag.length() > 0) {\n\t\tcustom_headers = curl_slist_append(custom_headers, utils::strprintf(\"If-None-Match: %s\", etag.c_str()).c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\n\tret = curl_easy_perform(easyhandle);\n\n\tlm = hdrs.lastmodified;\n\tet = hdrs.etag;\n\n\tif (custom_headers) {\n\t\tcurl_slist_free_all(custom_headers);\n\t}\n\n\tLOG(LOG_DEBUG, \"rsspp::parser::parse_url: ret = %d\", ret);\n\n\tlong status;\n\tcurl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);\n\n\tif (status >= 400) {\n\t\tLOG(LOG_USERERROR, _(\"Error: trying to download feed `%s' returned HTTP status code %ld.\"), url.c_str(), status);\n\t}\n\n\tcurl_easy_cleanup(easyhandle);\n\n\tif (ret != 0) {\n\t\tLOG(LOG_ERROR, \"rsspp::parser::parse_url: curl_easy_perform returned err %d: %s\", ret, curl_easy_strerror(ret));\n\t\tthrow exception(curl_easy_strerror(ret));\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_url: retrieved data for %s: %s\", url.c_str(), buf.c_str());\n\n\tif (buf.length() > 0) {\n\t\tLOG(LOG_DEBUG, \"parser::parse_url: handing over data to parse_buffer()\");\n\t\treturn parse_buffer(buf.c_str(), buf.length());\n\t}\n\n\treturn feed();\n}\n\nfeed parser::parse_buffer(const char * buffer, size_t size, const char * url) {\n\tdoc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse buffer\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_buffer: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_file(const std::string& filename) {\n\tdoc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse file\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_file: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_xmlnode(xmlNode* node) {\n\tfeed f;\n\n\tif (node) {\n\t\tif (node->name && node->type == XML_ELEMENT_NODE) {\n\t\t\tif (strcmp((const char *)node->name, \"rss\")==0) {\n\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\tif (!version) {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"no RSS version\"));\n\t\t\t\t}\n\t\t\t\tif (strcmp(version, \"0.91\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_91;\n\t\t\t\telse if (strcmp(version, \"0.92\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_92;\n\t\t\t\telse if (strcmp(version, \"2.0\")==0)\n\t\t\t\t\tf.rss_version = RSS_2_0;\n\t\t\t\telse {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"invalid RSS version\"));\n\t\t\t\t}\n\t\t\t\txmlFree((void *)version);\n\t\t\t} else if (strcmp((const char *)node->name, \"RDF\")==0) {\n\t\t\t\tf.rss_version = RSS_1_0;\n\t\t\t} else if (strcmp((const char *)node->name, \"feed\")==0) {\n\t\t\t\tif (node->ns && node->ns->href) {\n\t\t\t\t\tif (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_0_3;\n\t\t\t\t\t} else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_1_0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow exception(_(\"no Atom version\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::tr1::shared_ptr parser = rss_parser_factory::get_object(f, doc);\n\n\t\t\ttry {\n\t\t\t\tparser->parse_feed(f, node);\n\t\t\t} catch (exception& e) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\t}\n\n\treturn f;\n}\n\nvoid parser::global_init() {\n\tLIBXML_TEST_VERSION\n\tcurl_global_init(CURL_GLOBAL_ALL);\n}\n\nvoid parser::global_cleanup() {\n\txmlCleanupParser();\n\tcurl_global_cleanup();\n}\n\n\n}\nadded missing argument.\/* rsspp - Copyright (C) 2008-2009 Andreas Krennmair \n * Licensed under the MIT\/X Consortium License. See file LICENSE\n * for more information.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace newsbeuter;\n\nstatic size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {\n\tstd::string * pbuf = static_cast(userp);\n\tpbuf->append(static_cast(buffer), size * nmemb);\n\treturn size * nmemb;\n}\n\nnamespace rsspp {\n\nparser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) \n\t: to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) {\n}\n\nparser::~parser() {\n\tif (doc)\n\t\txmlFreeDoc(doc);\n}\n\nstruct header_values {\n\ttime_t lastmodified;\n\tstd::string etag;\n};\n\nstatic size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) {\n\tchar * header = new char[size*nmemb + 1];\n\theader_values * values = (header_values *)data;\n\n\tmemcpy(header, ptr, size*nmemb);\n\theader[size*nmemb] = '\\0';\n\n\tif (!strncasecmp(\"Last-Modified:\", header, 14)) {\n\t\tvalues->lastmodified = curl_getdate(header+14, NULL);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got last-modified %s (%d)\", header+14, values->lastmodified);\n\t} else if (!strncasecmp(\"ETag:\",header, 5)) {\n\t\tvalues->etag = std::string(header+5);\n\t\tutils::trim(values->etag);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got etag %s\", values->etag.c_str());\n\t}\n\n\tdelete[] header;\n\n\treturn size * nmemb;\n}\n\nfeed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag) {\n\tstd::string buf;\n\tCURLcode ret;\n\n\tCURL * easyhandle = curl_easy_init();\n\tif (!easyhandle) {\n\t\tthrow exception(_(\"couldn't initialize libcurl\"));\n\t}\n\n\tif (ua) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);\n\t}\n\tcurl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());\n\tcurl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);\n\tcurl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_ENCODING, \"gzip, deflate\");\n\tif (to != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);\n\n\tif (prx)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);\n\n\tif (prxauth)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);\n\n\theader_values hdrs = { 0, \"\" };\n\n\tcurl_slist * custom_headers = NULL;\n\n\tif (lastmodified != 0) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\tif (etag.length() > 0) {\n\t\tcustom_headers = curl_slist_append(custom_headers, utils::strprintf(\"If-None-Match: %s\", etag.c_str()).c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\n\tret = curl_easy_perform(easyhandle);\n\n\tlm = hdrs.lastmodified;\n\tet = hdrs.etag;\n\n\tif (custom_headers) {\n\t\tcurl_slist_free_all(custom_headers);\n\t}\n\n\tLOG(LOG_DEBUG, \"rsspp::parser::parse_url: ret = %d\", ret);\n\n\tlong status;\n\tcurl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);\n\n\tif (status >= 400) {\n\t\tLOG(LOG_USERERROR, _(\"Error: trying to download feed `%s' returned HTTP status code %ld.\"), url.c_str(), status);\n\t}\n\n\tcurl_easy_cleanup(easyhandle);\n\n\tif (ret != 0) {\n\t\tLOG(LOG_ERROR, \"rsspp::parser::parse_url: curl_easy_perform returned err %d: %s\", ret, curl_easy_strerror(ret));\n\t\tthrow exception(curl_easy_strerror(ret));\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_url: retrieved data for %s: %s\", url.c_str(), buf.c_str());\n\n\tif (buf.length() > 0) {\n\t\tLOG(LOG_DEBUG, \"parser::parse_url: handing over data to parse_buffer()\");\n\t\treturn parse_buffer(buf.c_str(), buf.length(), url.c_str());\n\t}\n\n\treturn feed();\n}\n\nfeed parser::parse_buffer(const char * buffer, size_t size, const char * url) {\n\tdoc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse buffer\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_buffer: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_file(const std::string& filename) {\n\tdoc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse file\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_file: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_xmlnode(xmlNode* node) {\n\tfeed f;\n\n\tif (node) {\n\t\tif (node->name && node->type == XML_ELEMENT_NODE) {\n\t\t\tif (strcmp((const char *)node->name, \"rss\")==0) {\n\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\tif (!version) {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"no RSS version\"));\n\t\t\t\t}\n\t\t\t\tif (strcmp(version, \"0.91\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_91;\n\t\t\t\telse if (strcmp(version, \"0.92\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_92;\n\t\t\t\telse if (strcmp(version, \"2.0\")==0)\n\t\t\t\t\tf.rss_version = RSS_2_0;\n\t\t\t\telse {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"invalid RSS version\"));\n\t\t\t\t}\n\t\t\t\txmlFree((void *)version);\n\t\t\t} else if (strcmp((const char *)node->name, \"RDF\")==0) {\n\t\t\t\tf.rss_version = RSS_1_0;\n\t\t\t} else if (strcmp((const char *)node->name, \"feed\")==0) {\n\t\t\t\tif (node->ns && node->ns->href) {\n\t\t\t\t\tif (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_0_3;\n\t\t\t\t\t} else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_1_0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow exception(_(\"no Atom version\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::tr1::shared_ptr parser = rss_parser_factory::get_object(f, doc);\n\n\t\t\ttry {\n\t\t\t\tparser->parse_feed(f, node);\n\t\t\t} catch (exception& e) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\t}\n\n\treturn f;\n}\n\nvoid parser::global_init() {\n\tLIBXML_TEST_VERSION\n\tcurl_global_init(CURL_GLOBAL_ALL);\n}\n\nvoid parser::global_cleanup() {\n\txmlCleanupParser();\n\tcurl_global_cleanup();\n}\n\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015 Sebastian Geisler\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file LICENSE or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include \n#include \n\n#include \"ByteArray.h\"\n#include \"Crypto.h\"\n#include \"Conversions.h\"\n\nByteArray::ByteArray(const Byte *data, size_t len)\n: vector(len)\n{\n memcpy(&this->[0], data, len);\n}\n\nvoid ByteArray::operator+=(const ByteArray &other)\n{\n this->insert(this->end(), other.begin(), other.end());\n}\n\nvoid ByteArray::operator+=(const Byte &other)\n{\n this->push_back(other);\n}\n\nByteArray ByteArray::operator+(const ByteArray &other) const\n{\n ByteArray ret;\n ret.insert(ret.end(), this->begin(), this->end());\n ret.insert(ret.end(), other.begin(), other.end());\n return ret;\n}\n\nByteArray ByteArray::operator+(const Byte other) const\n{\n ByteArray ret;\n ret.insert(ret.end(), this->begin(), this->end());\n ret.insert(ret.end(), other);\n return ret;\n}\n\nstd::string ByteArray::toHex() const\n{\n return Conversions::toHex(*this);\n}\n\nstd::string ByteArray::toBase58() const\n{\n return Conversions::toBase58(*this);\n}\n\nstd::string ByteArray::toBase58Check(Byte version) const\n{\n return Conversions::toBase58Check(*this, version);\n}\n\nByteArray ByteArray::sha256() const\n{\n return Crypto::sha256(*this);\n}\n\nByteArray ByteArray::ripemd160() const\n{\n return Crypto::ripemd160(*this);\n}\n\nByteArray ByteArray::getSection(ByteArray::size_type begin, ByteArray::size_type len)\n{\n if (begin + len > size())\n throw std::range_error(\"section not in bounds of ByteArray\");\n\n if (len == 0)\n return ByteArray();\n\n ByteArray ret;\n ret.insert(ret.end(), this->begin() + begin, this->begin() + (begin + len));\n\n return ret;\n}\n\nuint16_t ByteArray::toUInt16()\n{\n return Conversions::toUInt16(*this);\n}\n\nuint32_t ByteArray::toUInt32()\n{\n return Conversions::toUInt32(*this);\n}\n\nuint64_t ByteArray::toUInt64()\n{\n return Conversions::toUInt64(*this);\n}\nfixed syntax error\/\/ Copyright (c) 2015 Sebastian Geisler\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file LICENSE or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include \n#include \n\n#include \"ByteArray.h\"\n#include \"Crypto.h\"\n#include \"Conversions.h\"\n\nByteArray::ByteArray(const Byte *data, size_t len)\n: vector(len)\n{\n memcpy(&(*this)[0], data, len);\n}\n\nvoid ByteArray::operator+=(const ByteArray &other)\n{\n this->insert(this->end(), other.begin(), other.end());\n}\n\nvoid ByteArray::operator+=(const Byte &other)\n{\n this->push_back(other);\n}\n\nByteArray ByteArray::operator+(const ByteArray &other) const\n{\n ByteArray ret;\n ret.insert(ret.end(), this->begin(), this->end());\n ret.insert(ret.end(), other.begin(), other.end());\n return ret;\n}\n\nByteArray ByteArray::operator+(const Byte other) const\n{\n ByteArray ret;\n ret.insert(ret.end(), this->begin(), this->end());\n ret.insert(ret.end(), other);\n return ret;\n}\n\nstd::string ByteArray::toHex() const\n{\n return Conversions::toHex(*this);\n}\n\nstd::string ByteArray::toBase58() const\n{\n return Conversions::toBase58(*this);\n}\n\nstd::string ByteArray::toBase58Check(Byte version) const\n{\n return Conversions::toBase58Check(*this, version);\n}\n\nByteArray ByteArray::sha256() const\n{\n return Crypto::sha256(*this);\n}\n\nByteArray ByteArray::ripemd160() const\n{\n return Crypto::ripemd160(*this);\n}\n\nByteArray ByteArray::getSection(ByteArray::size_type begin, ByteArray::size_type len)\n{\n if (begin + len > size())\n throw std::range_error(\"section not in bounds of ByteArray\");\n\n if (len == 0)\n return ByteArray();\n\n ByteArray ret;\n ret.insert(ret.end(), this->begin() + begin, this->begin() + (begin + len));\n\n return ret;\n}\n\nuint16_t ByteArray::toUInt16()\n{\n return Conversions::toUInt16(*this);\n}\n\nuint32_t ByteArray::toUInt32()\n{\n return Conversions::toUInt32(*this);\n}\n\nuint64_t ByteArray::toUInt64()\n{\n return Conversions::toUInt64(*this);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017 Immo Software\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * o Redistributions of source code must retain the above copyright notice, this list\n * of conditions and the following disclaimer.\n *\n * o Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * o Neither the name of the copyright holder nor the names of its contributors may\n * be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"sampler_voice.h\"\n#include \"reader_thread.h\"\n#include \"ui.h\"\n#include \"debug_log.h\"\n#include \"utility.h\"\n\nusing namespace slab;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Code\n\/\/------------------------------------------------------------------------------\n\nSampleBufferManager::SampleBufferManager()\n: _number(0),\n _fullBuffers(),\n _emptyBuffers(),\n _primeMutex(),\n _currentBuffer(nullptr),\n _activeBufferCount(0),\n _totalSamples(0),\n _startSample(0),\n _samplesPlayed(0),\n _samplesRead(0),\n _samplesQueued(0),\n _didReadFileStart(false),\n _waitingForFileStart(true),\n _isReady(false)\n{\n}\n\nvoid SampleBufferManager::init(SamplerVoice * voice, int16_t * buffer)\n{\n _voice = voice;\n _number = voice->get_number();\n _primeMutex.init(\"prime\");\n\n uint32_t i;\n for (i = 0; i < kBufferCount; ++i)\n {\n _buffer[i].number = i;\n _buffer[i].state = SampleBuffer::State::kUnused;\n _buffer[i].data = &buffer[i * kBufferSize];\n _buffer[i].startFrame = 0;\n _buffer[i].frameCount = kBufferSize;\n _buffer[i].readHead = 0;\n _buffer[i].reread = false;\n }\n}\n\nvoid SampleBufferManager::set_file(uint32_t totalFrames)\n{\n _startSample = 0;\n _totalSamples = totalFrames;\n _endSample = totalFrames;\n _activeBufferCount = min(round_up_div(_totalSamples, kBufferSize), kBufferCount);\n _samplesPlayed = 0;\n _samplesRead = 0;\n _samplesQueued = 0;\n _didReadFileStart = false;\n _waitingForFileStart = true;\n _isReady = false;\n}\n\nvoid SampleBufferManager::prime()\n{\n Ar::Mutex::Guard guard(_primeMutex);\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: start prime\\r\\n\", _number);\n\n \/\/ Reset state.\n _samplesPlayed = _startSample;\n _samplesRead = _didReadFileStart ? kBufferSize : _startSample;\n _samplesQueued = _samplesRead;\n\n \/\/ Clear buffers queues.\n ReaderThread::get()->clear_voice_queue(_voice);\n _fullBuffers.clear();\n _emptyBuffers.clear();\n\n \/\/ Playing will start from the file start buffer.\n _currentBuffer = &_buffer[0];\n _buffer[0].readHead = 0;\n\n \/\/ Queue up the rest of the available buffers to be filled.\n uint32_t i = _didReadFileStart ? 1 : 0;\n for (; i < _activeBufferCount; ++i)\n {\n \/\/ If the buffer is currently being filled by the reader thread, then we can't touch\n \/\/ it. So just flag it for requeuing when it's finished. This will be handled in\n \/\/ enqueue_full_buffer().\n if (_buffer[i].state == SampleBuffer::State::kReading)\n {\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: prime: marking b%lu for reread\\r\\n\", _number, i);\n _buffer[i].reread = true;\n }\n else\n {\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: prime: queuing b%lu for read\\r\\n\", _number, i);\n queue_buffer_for_read(&_buffer[i]);\n }\n }\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: end prime\\r\\n\", _number);\n}\n\nSampleBuffer * SampleBufferManager::get_current_buffer()\n{\n if (!_currentBuffer)\n {\n _currentBuffer = dequeue_next_buffer();\n }\n return _currentBuffer;\n}\n\nvoid SampleBufferManager::queue_buffer_for_read(SampleBuffer * buffer)\n{\n buffer->startFrame = _samplesQueued;\n buffer->frameCount = min(kBufferSize, _endSample - _samplesQueued);\n buffer->reread = false;\n buffer->state = SampleBuffer::State::kFree;\n\n _emptyBuffers.put(buffer);\n ReaderThread::get()->enqueue(_voice);\n\n _samplesQueued += buffer->frameCount;\n}\n\nSampleBuffer * SampleBufferManager::get_empty_buffer()\n{\n Ar::Mutex::Guard guard(_primeMutex);\n\n SampleBuffer * buffer;\n if (_emptyBuffers.get(buffer))\n {\n buffer->state = SampleBuffer::State::kReading;\n return buffer;\n }\n else\n {\n return nullptr;\n }\n}\n\nvoid SampleBufferManager::retire_buffer(SampleBuffer * buffer)\n{\n _samplesPlayed += buffer->frameCount;\n\n if (_samplesPlayed >= _endSample)\n {\n DEBUG_PRINTF(RETIRE_MASK, \"V%lu: retiring b%d; played %lu (done)\\r\\n\", _number, buffer->number, _samplesPlayed);\n\n _voice->playing_did_finish();\n }\n else\n {\n DEBUG_PRINTF(RETIRE_MASK, \"V%lu: retiring b%d; played %lu\\r\\n\", _number, buffer->number, _samplesPlayed);\n\n \/\/ Don't queue up file start buffer for reading, and don't queue more than the active\n \/\/ number of samples.\n if (buffer != &_buffer[0] && _samplesQueued < _endSample)\n {\n DEBUG_PRINTF(RETIRE_MASK|QUEUE_MASK, \"V%lu: retire: queue b%d to read @ %lu\\r\\n\", _number, buffer->number, _samplesPlayed);\n queue_buffer_for_read(buffer);\n }\n\n dequeue_next_buffer();\n }\n}\n\nSampleBuffer * SampleBufferManager::dequeue_next_buffer()\n{\n SampleBuffer * buffer;\n if (_fullBuffers.get(buffer))\n {\n DEBUG_PRINTF(CURBUF_MASK, \"V%lu: current buffer = %d\\r\\n\", _number, buffer->number);\n _currentBuffer = buffer;\n buffer->state = SampleBuffer::State::kPlaying;\n }\n else\n {\n DEBUG_PRINTF(ERROR_MASK, \"V%lu: *** NO READY BUFFERS ***\\r\\n\", _number);\n Ar::_halt();\n _currentBuffer = nullptr;\n }\n return _currentBuffer;\n}\n\nvoid SampleBufferManager::enqueue_full_buffer(SampleBuffer * buffer)\n{\n assert(buffer);\n if (buffer == &_buffer[0])\n {\n _didReadFileStart = true;\n if (_waitingForFileStart)\n {\n _waitingForFileStart = false;\n _isReady = true;\n }\n _samplesRead += buffer->frameCount;\n buffer->state = SampleBuffer::State::kReady;\n }\n else\n {\n if (buffer->reread)\n {\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: queuing b%d for reread\\r\\n\", _number, buffer->number);\n queue_buffer_for_read(buffer);\n }\n else\n {\n _samplesRead += buffer->frameCount;\n\n buffer->state = SampleBuffer::State::kReady;\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: queuing b%d for play\\r\\n\", _number, buffer->number);\n _fullBuffers.put(buffer);\n }\n }\n}\n\nvoid SampleBufferManager::set_start_sample(uint32_t start)\n{\n \/\/ Voice must not be playing.\n assert(!_voice->is_playing());\n\n _isReady = false;\n _didReadFileStart = false;\n _waitingForFileStart = true;\n _startSample = start;\n if (_endSample < _startSample)\n {\n _endSample = _startSample;\n }\n\n _activeBufferCount = min(round_up_div(get_active_samples(), kBufferSize), kBufferCount);\n\n prime();\n}\n\nvoid SampleBufferManager::set_end_sample(uint32_t end)\n{\n \/\/ Voice must not be playing.\n assert(!_voice->is_playing());\n assert(end >= _startSample);\n\n _endSample = end;\n\n _activeBufferCount = min(round_up_div(get_active_samples(), kBufferSize), kBufferCount);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\nSamplerVoice::SamplerVoice()\n: _wav(),\n _data(),\n _manager(),\n _isPlaying(false),\n _turnOnLedNextBuffer(false),\n _lastBufferLastSample(0),\n _fraction(0.0f),\n _gain(1.0f),\n _pitch(1.0f)\n{\n}\n\nvoid SamplerVoice::init(uint32_t n, int16_t * buffer)\n{\n _number = n;\n _manager.init(this, buffer);\n}\n\nvoid SamplerVoice::set_file(WaveFile& file)\n{\n _wav = file;\n _data = _wav.get_audio_data();\n _isPlaying = false;\n _manager.set_file(_data.get_frames());\n}\n\nvoid SamplerVoice::_reset_voice()\n{\n _isPlaying = false;\n _fraction = 0.0f;\n _lastBufferLastSample = 0.0f;\n}\n\nvoid SamplerVoice::prime()\n{\n _reset_voice();\n _manager.prime();\n}\n\nvoid SamplerVoice::trigger()\n{\n \/\/ Ignore the trigger if the manager isn't ready to play.\n if (!_manager.is_ready())\n {\n return;\n }\n\n \/\/ Handle re-triggering while sample is already playing.\n if (_isPlaying)\n {\n DEBUG_PRINTF(RETRIG_MASK, \"V%lu: retrigger (@%lu)\\r\\n\", _number, _manager.get_samples_played());\n\n \/\/ Start playing over from file start.\n prime();\n\n UI::get().set_voice_playing(_number, false);\n _turnOnLedNextBuffer = true;\n }\n else\n {\n UI::get().set_voice_playing(_number, true);\n }\n _isPlaying = true;\n}\n\nvoid SamplerVoice::playing_did_finish()\n{\n UI::get().set_voice_playing(_number, false);\n prime();\n}\n\nvoid SamplerVoice::render(int16_t * data, uint32_t frameCount)\n{\n uint32_t i;\n\n \/\/ Get the current buffer if playing.\n SampleBuffer * voiceBuffer = nullptr;\n if (is_valid() && is_playing())\n {\n voiceBuffer = _manager.get_current_buffer();\n }\n\n \/\/ If not playing, just fill with silence.\n if (!voiceBuffer)\n {\n for (i = 0; i < frameCount; ++i)\n {\n *data = 0;\n data += 2;\n }\n return;\n }\n\n float rate = _pitch;\n int16_t * bufferData = voiceBuffer->data;\n uint32_t readHead = voiceBuffer->readHead;\n uint32_t bufferFrameCount = voiceBuffer->frameCount;\n float s0 = 0.0f;\n float s1 = 0.0f;\n\n \/\/ Special case for unmodified pitch.\n if (rate == 1.0f)\n {\n uint32_t framesRemainingInBuffer = bufferFrameCount - readHead;\n uint32_t framesFromBuffer = min(framesRemainingInBuffer, frameCount);\n\n \/\/ Render sample data into the output buffer.\n for (i = 0; i < framesFromBuffer; ++i)\n {\n s1 = float(bufferData[readHead++]);\n\n \/\/ Apply the gain.\n float s = s1 * _gain;\n *data = int16_t(s);\n data += 2;\n }\n }\n else\n {\n float readHeadFraction = _fraction;\n s1 = _lastBufferLastSample;\n\n \/\/ Render sample data into the output buffer at the specified playback rate.\n for (i = 0; i < frameCount; ++i)\n {\n readHeadFraction += rate;\n if (readHeadFraction >= 1.0f)\n {\n uint32_t index = uint32_t(readHeadFraction);\n readHeadFraction -= index;\n readHead += index;\n\n \/\/ Check if we reached the end of this sample buffer.\n if (readHead >= bufferFrameCount)\n {\n _manager.retire_buffer(voiceBuffer);\n\n \/\/ If we're no longer playing, exit this loop.\n if (!_isPlaying)\n {\n \/\/ Set some variables used outside the loop below.\n readHead = voiceBuffer->readHead;\n readHeadFraction = 0.0f;\n s1 = 0.0f;\n break;\n }\n\n \/\/ Get the next buffer and update locals.\n voiceBuffer = _manager.get_current_buffer();\n bufferData = voiceBuffer->data;\n readHead = voiceBuffer->readHead + (bufferFrameCount - readHead);\n bufferFrameCount = voiceBuffer->frameCount;\n }\n\n s0 = s1;\n s1 = float(bufferData[readHead]);\n }\n\n \/\/ Perform simple linear interpolation, then apply the gain.\n float s = (s0 + readHeadFraction * (s1 - s0)) * _gain;\n *data = int16_t(s);\n data += 2;\n }\n\n _fraction = readHeadFraction;\n }\n\n voiceBuffer->readHead = readHead;\n _lastBufferLastSample = s1;\n\n \/\/ Fill any leftover frames with silence.\n for (; i < frameCount; ++i)\n {\n *data = 0;\n data += 2;\n }\n\n \/\/ Did we finish this buffer?\n if (readHead >= bufferFrameCount)\n {\n _manager.retire_buffer(voiceBuffer);\n }\n\n if (_turnOnLedNextBuffer)\n {\n _turnOnLedNextBuffer = false;\n UI::get().set_voice_playing(_number, true);\n }\n}\n\nvoid SamplerVoice::set_sample_start(float start)\n{\n \/\/ Stop playing and turn off LED.\n _reset_voice();\n UI::get().set_voice_playing(_number, false);\n\n \/\/ Tell sample manager to set and load new start point.\n uint32_t sample = uint32_t(float(_manager.get_total_samples()) * start);\n _manager.set_start_sample(sample);\n}\n\nvoid SamplerVoice::set_sample_end(float end)\n{\n \/\/ Stop playing and turn off LED.\n _reset_voice();\n UI::get().set_voice_playing(_number, false);\n\n uint32_t startSample = _manager.get_start_sample();\n uint32_t s = _manager.get_total_samples() - startSample;\n uint32_t sample = startSample + uint32_t(float(s) * end);\n _manager.set_end_sample(sample);\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ EOF\n\/\/------------------------------------------------------------------------------\nFixed _samplesRead value set in SampleBufferManager::prime().\/*\n * Copyright (c) 2017 Immo Software\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * o Redistributions of source code must retain the above copyright notice, this list\n * of conditions and the following disclaimer.\n *\n * o Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * o Neither the name of the copyright holder nor the names of its contributors may\n * be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"sampler_voice.h\"\n#include \"reader_thread.h\"\n#include \"ui.h\"\n#include \"debug_log.h\"\n#include \"utility.h\"\n\nusing namespace slab;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Code\n\/\/------------------------------------------------------------------------------\n\nSampleBufferManager::SampleBufferManager()\n: _number(0),\n _fullBuffers(),\n _emptyBuffers(),\n _primeMutex(),\n _currentBuffer(nullptr),\n _activeBufferCount(0),\n _totalSamples(0),\n _startSample(0),\n _samplesPlayed(0),\n _samplesRead(0),\n _samplesQueued(0),\n _didReadFileStart(false),\n _waitingForFileStart(true),\n _isReady(false)\n{\n}\n\nvoid SampleBufferManager::init(SamplerVoice * voice, int16_t * buffer)\n{\n _voice = voice;\n _number = voice->get_number();\n _primeMutex.init(\"prime\");\n\n uint32_t i;\n for (i = 0; i < kBufferCount; ++i)\n {\n _buffer[i].number = i;\n _buffer[i].state = SampleBuffer::State::kUnused;\n _buffer[i].data = &buffer[i * kBufferSize];\n _buffer[i].startFrame = 0;\n _buffer[i].frameCount = kBufferSize;\n _buffer[i].readHead = 0;\n _buffer[i].reread = false;\n }\n}\n\nvoid SampleBufferManager::set_file(uint32_t totalFrames)\n{\n _startSample = 0;\n _totalSamples = totalFrames;\n _endSample = totalFrames;\n _activeBufferCount = min(round_up_div(_totalSamples, kBufferSize), kBufferCount);\n _samplesPlayed = 0;\n _samplesRead = 0;\n _samplesQueued = 0;\n _didReadFileStart = false;\n _waitingForFileStart = true;\n _isReady = false;\n}\n\nvoid SampleBufferManager::prime()\n{\n Ar::Mutex::Guard guard(_primeMutex);\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: start prime\\r\\n\", _number);\n\n \/\/ Reset state.\n _samplesPlayed = _startSample;\n _samplesRead = _didReadFileStart ? _startSample + kBufferSize : _startSample;\n _samplesQueued = _samplesRead;\n\n \/\/ Clear buffers queues.\n ReaderThread::get()->clear_voice_queue(_voice);\n _fullBuffers.clear();\n _emptyBuffers.clear();\n\n \/\/ Playing will start from the file start buffer.\n _currentBuffer = &_buffer[0];\n _buffer[0].readHead = 0;\n\n \/\/ Queue up the rest of the available buffers to be filled.\n uint32_t i = _didReadFileStart ? 1 : 0;\n for (; i < _activeBufferCount; ++i)\n {\n \/\/ If the buffer is currently being filled by the reader thread, then we can't touch\n \/\/ it. So just flag it for requeuing when it's finished. This will be handled in\n \/\/ enqueue_full_buffer().\n if (_buffer[i].state == SampleBuffer::State::kReading)\n {\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: prime: marking b%lu for reread\\r\\n\", _number, i);\n _buffer[i].reread = true;\n }\n else\n {\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: prime: queuing b%lu for read\\r\\n\", _number, i);\n queue_buffer_for_read(&_buffer[i]);\n }\n }\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: end prime\\r\\n\", _number);\n}\n\nSampleBuffer * SampleBufferManager::get_current_buffer()\n{\n if (!_currentBuffer)\n {\n _currentBuffer = dequeue_next_buffer();\n }\n return _currentBuffer;\n}\n\nvoid SampleBufferManager::queue_buffer_for_read(SampleBuffer * buffer)\n{\n buffer->startFrame = _samplesQueued;\n buffer->frameCount = min(kBufferSize, _endSample - _samplesQueued);\n buffer->reread = false;\n buffer->state = SampleBuffer::State::kFree;\n\n _emptyBuffers.put(buffer);\n ReaderThread::get()->enqueue(_voice);\n\n _samplesQueued += buffer->frameCount;\n}\n\nSampleBuffer * SampleBufferManager::get_empty_buffer()\n{\n Ar::Mutex::Guard guard(_primeMutex);\n\n SampleBuffer * buffer;\n if (_emptyBuffers.get(buffer))\n {\n buffer->state = SampleBuffer::State::kReading;\n return buffer;\n }\n else\n {\n return nullptr;\n }\n}\n\nvoid SampleBufferManager::retire_buffer(SampleBuffer * buffer)\n{\n _samplesPlayed += buffer->frameCount;\n\n if (_samplesPlayed >= _endSample)\n {\n DEBUG_PRINTF(RETIRE_MASK, \"V%lu: retiring b%d; played %lu (done)\\r\\n\", _number, buffer->number, _samplesPlayed);\n\n _voice->playing_did_finish();\n }\n else\n {\n DEBUG_PRINTF(RETIRE_MASK, \"V%lu: retiring b%d; played %lu\\r\\n\", _number, buffer->number, _samplesPlayed);\n\n \/\/ Don't queue up file start buffer for reading, and don't queue more than the active\n \/\/ number of samples.\n if (buffer != &_buffer[0] && _samplesQueued < _endSample)\n {\n DEBUG_PRINTF(RETIRE_MASK|QUEUE_MASK, \"V%lu: retire: queue b%d to read @ %lu\\r\\n\", _number, buffer->number, _samplesPlayed);\n queue_buffer_for_read(buffer);\n }\n\n dequeue_next_buffer();\n }\n}\n\nSampleBuffer * SampleBufferManager::dequeue_next_buffer()\n{\n SampleBuffer * buffer;\n if (_fullBuffers.get(buffer))\n {\n DEBUG_PRINTF(CURBUF_MASK, \"V%lu: current buffer = %d\\r\\n\", _number, buffer->number);\n _currentBuffer = buffer;\n buffer->state = SampleBuffer::State::kPlaying;\n }\n else\n {\n DEBUG_PRINTF(ERROR_MASK, \"V%lu: *** NO READY BUFFERS ***\\r\\n\", _number);\n Ar::_halt();\n _currentBuffer = nullptr;\n }\n return _currentBuffer;\n}\n\nvoid SampleBufferManager::enqueue_full_buffer(SampleBuffer * buffer)\n{\n assert(buffer);\n if (buffer == &_buffer[0])\n {\n _didReadFileStart = true;\n if (_waitingForFileStart)\n {\n _waitingForFileStart = false;\n _isReady = true;\n }\n _samplesRead += buffer->frameCount;\n buffer->state = SampleBuffer::State::kReady;\n }\n else\n {\n if (buffer->reread)\n {\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: queuing b%d for reread\\r\\n\", _number, buffer->number);\n queue_buffer_for_read(buffer);\n }\n else\n {\n _samplesRead += buffer->frameCount;\n\n buffer->state = SampleBuffer::State::kReady;\n DEBUG_PRINTF(QUEUE_MASK, \"V%lu: queuing b%d for play\\r\\n\", _number, buffer->number);\n _fullBuffers.put(buffer);\n }\n }\n}\n\nvoid SampleBufferManager::set_start_sample(uint32_t start)\n{\n \/\/ Voice must not be playing.\n assert(!_voice->is_playing());\n\n _isReady = false;\n _didReadFileStart = false;\n _waitingForFileStart = true;\n _startSample = start;\n if (_endSample < _startSample)\n {\n _endSample = _startSample;\n }\n\n _activeBufferCount = min(round_up_div(get_active_samples(), kBufferSize), kBufferCount);\n\n prime();\n}\n\nvoid SampleBufferManager::set_end_sample(uint32_t end)\n{\n \/\/ Voice must not be playing.\n assert(!_voice->is_playing());\n assert(end >= _startSample);\n\n _endSample = end;\n\n _activeBufferCount = min(round_up_div(get_active_samples(), kBufferSize), kBufferCount);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\nSamplerVoice::SamplerVoice()\n: _wav(),\n _data(),\n _manager(),\n _isPlaying(false),\n _turnOnLedNextBuffer(false),\n _lastBufferLastSample(0),\n _fraction(0.0f),\n _gain(1.0f),\n _pitch(1.0f)\n{\n}\n\nvoid SamplerVoice::init(uint32_t n, int16_t * buffer)\n{\n _number = n;\n _manager.init(this, buffer);\n}\n\nvoid SamplerVoice::set_file(WaveFile& file)\n{\n _wav = file;\n _data = _wav.get_audio_data();\n _isPlaying = false;\n _manager.set_file(_data.get_frames());\n}\n\nvoid SamplerVoice::_reset_voice()\n{\n _isPlaying = false;\n _fraction = 0.0f;\n _lastBufferLastSample = 0.0f;\n}\n\nvoid SamplerVoice::prime()\n{\n _reset_voice();\n _manager.prime();\n}\n\nvoid SamplerVoice::trigger()\n{\n \/\/ Ignore the trigger if the manager isn't ready to play.\n if (!_manager.is_ready())\n {\n return;\n }\n\n \/\/ Handle re-triggering while sample is already playing.\n if (_isPlaying)\n {\n DEBUG_PRINTF(RETRIG_MASK, \"V%lu: retrigger (@%lu)\\r\\n\", _number, _manager.get_samples_played());\n\n \/\/ Start playing over from file start.\n prime();\n\n UI::get().set_voice_playing(_number, false);\n _turnOnLedNextBuffer = true;\n }\n else\n {\n UI::get().set_voice_playing(_number, true);\n }\n _isPlaying = true;\n}\n\nvoid SamplerVoice::playing_did_finish()\n{\n UI::get().set_voice_playing(_number, false);\n prime();\n}\n\nvoid SamplerVoice::render(int16_t * data, uint32_t frameCount)\n{\n uint32_t i;\n\n \/\/ Get the current buffer if playing.\n SampleBuffer * voiceBuffer = nullptr;\n if (is_valid() && is_playing())\n {\n voiceBuffer = _manager.get_current_buffer();\n }\n\n \/\/ If not playing, just fill with silence.\n if (!voiceBuffer)\n {\n for (i = 0; i < frameCount; ++i)\n {\n *data = 0;\n data += 2;\n }\n return;\n }\n\n float rate = _pitch;\n int16_t * bufferData = voiceBuffer->data;\n uint32_t readHead = voiceBuffer->readHead;\n uint32_t bufferFrameCount = voiceBuffer->frameCount;\n float s0 = 0.0f;\n float s1 = 0.0f;\n\n \/\/ Special case for unmodified pitch.\n if (rate == 1.0f)\n {\n uint32_t framesRemainingInBuffer = bufferFrameCount - readHead;\n uint32_t framesFromBuffer = min(framesRemainingInBuffer, frameCount);\n\n \/\/ Render sample data into the output buffer.\n for (i = 0; i < framesFromBuffer; ++i)\n {\n s1 = float(bufferData[readHead++]);\n\n \/\/ Apply the gain.\n float s = s1 * _gain;\n *data = int16_t(s);\n data += 2;\n }\n }\n else\n {\n float readHeadFraction = _fraction;\n s1 = _lastBufferLastSample;\n\n \/\/ Render sample data into the output buffer at the specified playback rate.\n for (i = 0; i < frameCount; ++i)\n {\n readHeadFraction += rate;\n if (readHeadFraction >= 1.0f)\n {\n uint32_t index = uint32_t(readHeadFraction);\n readHeadFraction -= index;\n readHead += index;\n\n \/\/ Check if we reached the end of this sample buffer.\n if (readHead >= bufferFrameCount)\n {\n _manager.retire_buffer(voiceBuffer);\n\n \/\/ If we're no longer playing, exit this loop.\n if (!_isPlaying)\n {\n \/\/ Set some variables used outside the loop below.\n readHead = voiceBuffer->readHead;\n readHeadFraction = 0.0f;\n s1 = 0.0f;\n break;\n }\n\n \/\/ Get the next buffer and update locals.\n voiceBuffer = _manager.get_current_buffer();\n bufferData = voiceBuffer->data;\n readHead = voiceBuffer->readHead + (bufferFrameCount - readHead);\n bufferFrameCount = voiceBuffer->frameCount;\n }\n\n s0 = s1;\n s1 = float(bufferData[readHead]);\n }\n\n \/\/ Perform simple linear interpolation, then apply the gain.\n float s = (s0 + readHeadFraction * (s1 - s0)) * _gain;\n *data = int16_t(s);\n data += 2;\n }\n\n _fraction = readHeadFraction;\n }\n\n voiceBuffer->readHead = readHead;\n _lastBufferLastSample = s1;\n\n \/\/ Fill any leftover frames with silence.\n for (; i < frameCount; ++i)\n {\n *data = 0;\n data += 2;\n }\n\n \/\/ Did we finish this buffer?\n if (readHead >= bufferFrameCount)\n {\n _manager.retire_buffer(voiceBuffer);\n }\n\n if (_turnOnLedNextBuffer)\n {\n _turnOnLedNextBuffer = false;\n UI::get().set_voice_playing(_number, true);\n }\n}\n\nvoid SamplerVoice::set_sample_start(float start)\n{\n \/\/ Stop playing and turn off LED.\n _reset_voice();\n UI::get().set_voice_playing(_number, false);\n\n \/\/ Tell sample manager to set and load new start point.\n uint32_t sample = uint32_t(float(_manager.get_total_samples()) * start);\n _manager.set_start_sample(sample);\n}\n\nvoid SamplerVoice::set_sample_end(float end)\n{\n \/\/ Stop playing and turn off LED.\n _reset_voice();\n UI::get().set_voice_playing(_number, false);\n\n uint32_t startSample = _manager.get_start_sample();\n uint32_t s = _manager.get_total_samples() - startSample;\n uint32_t sample = startSample + uint32_t(float(s) * end);\n _manager.set_end_sample(sample);\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ EOF\n\/\/------------------------------------------------------------------------------\n<|endoftext|>"} {"text":"\/\/ This program is free software licenced under MIT Licence. You can\n\/\/ find a copy of this licence in LICENCE.txt in the top directory of\n\/\/ source code.\n\/\/\n\n\/\/ Self\n#include \"GreedyRoundStrategy.h\"\n\n\/\/ Project\n#include \"globals.h\"\n#include \"World.h\"\n#include \"Region.h\"\n#include \"SuperRegion.h\"\n#include \"common\/ScoreComputer.h\"\n\n\/\/ C++\n#include \n#include \n#include \n\n\nnamespace warlightAi {\n\nGreedyRoundStrategy::GreedyRoundStrategy(const World &world,\n int availableArmies)\n : RoundStrategy(world, availableArmies)\n{\n using common::ScoreComputer;\n\n auto pq_cmp = [](const auto &lhs, const auto &rhs) -> bool {\n return lhs.first < rhs.first;\n };\n std::priority_queue<\n std::pair,\n std::vector>,\n decltype(pq_cmp)\n > pq(pq_cmp);\n std::unordered_set supers;\n\n for (auto &myReg : world.getRegionsOwnedBy(Player::ME))\n for (auto &neigh : myReg->getNeighbors()) {\n if (supers.count(neigh->getSuperRegion()))\n continue;\n\n pq.emplace(\n ScoreComputer::wastelandsBasedScore(neigh->getSuperRegion()),\n neigh->getSuperRegion()\n );\n supers.emplace(neigh->getSuperRegion());\n }\n\n std::unordered_set addedRegs;\n VecOfRegionPtrs neighs;\n while (!pq.empty()) {\n auto superReg = pq.top().second;\n pq.pop();\n\n for (auto ® : superReg->getSubRegions()) {\n if (reg->getOwner() == Player::ME || addedRegs.count(reg))\n continue;\n\n for (auto ®Neigh : reg->getNeighbors())\n if (regNeigh->getOwner() == Player::ME) {\n addedRegs.emplace(reg);\n neighs.emplace_back(reg);\n break;\n }\n }\n }\n\n for (auto &neigh : neighs) {\n if (availableArmies <= 0)\n break;\n\n auto biggestReg = static_cast(nullptr);\n auto maxArmies = std::numeric_limits::min();\n for (auto &mine : neigh->getNeighbors()) {\n if (mine->getOwner() != Player::ME)\n continue;\n\n if (mine->getArmies() > maxArmies) {\n maxArmies = mine->getArmies();\n biggestReg = mine;\n }\n }\n\n auto armiesNeeded = ScoreComputer::armiesNeeded(neigh->getArmies(), 0.7) + 1;\n auto diff = armiesNeeded - maxArmies;\n if (diff > availableArmies) {\n continue;\n } else if (diff > 0) {\n biggestReg->setArmies(biggestReg->getArmies() + diff);\n m_deployments.emplace_back(biggestReg, diff);\n availableArmies -= diff;\n }\n\n m_attacks.emplace_back(biggestReg, neigh, biggestReg->getArmies() - 1);\n biggestReg->setArmies(1);\n }\n\n if (availableArmies && m_attacks.size()) {\n m_deployments.emplace_back(std::get<0>(m_attacks.front()), availableArmies);\n std::get<2>(m_attacks.front()) += availableArmies;\n } else if (availableArmies) {\n auto maxArmies = std::numeric_limits::min();\n auto maxReg = static_cast(nullptr);\n for (auto &mine : world.getRegionsOwnedBy(Player::ME))\n if (mine->getArmies() > maxArmies) {\n maxArmies = mine->getArmies();\n maxReg = mine;\n }\n\n m_deployments.emplace_back(maxReg, availableArmies);\n }\n\n computeMigrations();\n}\n\nVecOfPairs GreedyRoundStrategy::getDeployments() const\n{\n return m_deployments;\n}\n\nVecOfTuples GreedyRoundStrategy::getAttacks() const\n{\n return m_attacks;\n}\n\nvoid GreedyRoundStrategy::computeMigrations()\n{\n auto visitedRegs = getRegionsOnBorder();\n std::queue Q;\n\n for (auto ® : visitedRegs)\n Q.emplace(reg);\n\n while (!Q.empty()) {\n auto nextReg = Q.front();\n Q.pop();\n\n for (auto &neigh : nextReg->getNeighbors()) {\n if (neigh->getOwner() != Player::ME || visitedRegs.count(neigh))\n continue;\n\n visitedRegs.emplace(neigh);\n Q.emplace(neigh);\n if (neigh->getArmies() > 1)\n m_attacks.emplace_back(neigh, nextReg, neigh->getArmies() - 1);\n }\n }\n}\n\nstd::unordered_set GreedyRoundStrategy::getRegionsOnBorder()\n{\n std::unordered_set regsOnBorder;\n\n for (auto &mine : m_world.getRegionsOwnedBy(Player::ME)) {\n auto isOnBorder = false;\n for (auto &neigh : mine->getNeighbors())\n if (neigh->getOwner() != Player::ME) {\n isOnBorder = true;\n break;\n }\n\n if (isOnBorder)\n regsOnBorder.emplace(mine);\n }\n\n return regsOnBorder;\n}\n\n} \/\/ namespace warlightAi\nReverse attacks order\/\/ This program is free software licenced under MIT Licence. You can\n\/\/ find a copy of this licence in LICENCE.txt in the top directory of\n\/\/ source code.\n\/\/\n\n\/\/ Self\n#include \"GreedyRoundStrategy.h\"\n\n\/\/ Project\n#include \"globals.h\"\n#include \"World.h\"\n#include \"Region.h\"\n#include \"SuperRegion.h\"\n#include \"common\/ScoreComputer.h\"\n\n\/\/ C++\n#include \n#include \n#include \n\n\nnamespace warlightAi {\n\nGreedyRoundStrategy::GreedyRoundStrategy(const World &world,\n int availableArmies)\n : RoundStrategy(world, availableArmies)\n{\n using common::ScoreComputer;\n\n auto pq_cmp = [](const auto &lhs, const auto &rhs) -> bool {\n return lhs.first < rhs.first;\n };\n std::priority_queue<\n std::pair,\n std::vector>,\n decltype(pq_cmp)\n > pq(pq_cmp);\n std::unordered_set supers;\n\n for (auto &myReg : world.getRegionsOwnedBy(Player::ME))\n for (auto &neigh : myReg->getNeighbors()) {\n if (supers.count(neigh->getSuperRegion()))\n continue;\n\n pq.emplace(\n ScoreComputer::wastelandsBasedScore(neigh->getSuperRegion()),\n neigh->getSuperRegion()\n );\n supers.emplace(neigh->getSuperRegion());\n }\n\n std::unordered_set addedRegs;\n VecOfRegionPtrs neighs;\n while (!pq.empty()) {\n auto superReg = pq.top().second;\n pq.pop();\n\n for (auto ® : superReg->getSubRegions()) {\n if (reg->getOwner() == Player::ME || addedRegs.count(reg))\n continue;\n\n for (auto ®Neigh : reg->getNeighbors())\n if (regNeigh->getOwner() == Player::ME) {\n addedRegs.emplace(reg);\n neighs.emplace_back(reg);\n break;\n }\n }\n }\n\n for (auto &neigh : neighs) {\n if (availableArmies <= 0)\n break;\n\n auto biggestReg = static_cast(nullptr);\n auto maxArmies = std::numeric_limits::min();\n for (auto &mine : neigh->getNeighbors()) {\n if (mine->getOwner() != Player::ME)\n continue;\n\n if (mine->getArmies() > maxArmies) {\n maxArmies = mine->getArmies();\n biggestReg = mine;\n }\n }\n\n auto armiesNeeded = ScoreComputer::armiesNeeded(neigh->getArmies(), 0.7) + 1;\n auto diff = armiesNeeded - maxArmies;\n if (diff > availableArmies) {\n continue;\n } else if (diff > 0) {\n biggestReg->setArmies(biggestReg->getArmies() + diff);\n m_deployments.emplace_back(biggestReg, diff);\n availableArmies -= diff;\n }\n\n m_attacks.emplace_back(biggestReg, neigh, biggestReg->getArmies() - 1);\n biggestReg->setArmies(1);\n }\n\n if (availableArmies && m_attacks.size()) {\n m_deployments.emplace_back(std::get<0>(m_attacks.front()), availableArmies);\n std::get<2>(m_attacks.front()) += availableArmies;\n } else if (availableArmies) {\n auto maxArmies = std::numeric_limits::min();\n auto maxReg = static_cast(nullptr);\n for (auto &mine : world.getRegionsOwnedBy(Player::ME))\n if (mine->getArmies() > maxArmies) {\n maxArmies = mine->getArmies();\n maxReg = mine;\n }\n\n m_deployments.emplace_back(maxReg, availableArmies);\n }\n\n computeMigrations();\n}\n\nVecOfPairs GreedyRoundStrategy::getDeployments() const\n{\n return m_deployments;\n}\n\nVecOfTuples GreedyRoundStrategy::getAttacks() const\n{\n std::reverse(m_attacks.begin(), m_attacks.end());\n return m_attacks;\n}\n\nvoid GreedyRoundStrategy::computeMigrations()\n{\n auto visitedRegs = getRegionsOnBorder();\n std::queue Q;\n\n for (auto ® : visitedRegs)\n Q.emplace(reg);\n\n while (!Q.empty()) {\n auto nextReg = Q.front();\n Q.pop();\n\n for (auto &neigh : nextReg->getNeighbors()) {\n if (neigh->getOwner() != Player::ME || visitedRegs.count(neigh))\n continue;\n\n visitedRegs.emplace(neigh);\n Q.emplace(neigh);\n if (neigh->getArmies() > 1)\n m_attacks.emplace_back(neigh, nextReg, neigh->getArmies() - 1);\n }\n }\n}\n\nstd::unordered_set GreedyRoundStrategy::getRegionsOnBorder()\n{\n std::unordered_set regsOnBorder;\n\n for (auto &mine : m_world.getRegionsOwnedBy(Player::ME)) {\n auto isOnBorder = false;\n for (auto &neigh : mine->getNeighbors())\n if (neigh->getOwner() != Player::ME) {\n isOnBorder = true;\n break;\n }\n\n if (isOnBorder)\n regsOnBorder.emplace(mine);\n }\n\n return regsOnBorder;\n}\n\n} \/\/ namespace warlightAi\n<|endoftext|>"} {"text":"#include \"Symbol.h\"\n#include \"Shadow.h\"\n#include \"config.h\"\n#include \"FileIO.h\"\n\n#include \n\n#include \n#include \n\nnamespace eshadow\n{\n\nSymbol::Symbol()\n{\n\tm_shadow = new Shadow(SOFT_SHADOW_RADIUS);\n}\n\nSymbol::~Symbol()\n{\n\tif (m_shadow) {\n\t\tm_shadow->RemoveReference();\n\t}\n}\n\nvoid Symbol::Draw(const s2::RenderParams& params, const s2::Sprite* spr) const\n{\n\ts2::RenderParams p = params;\n\tif (spr) {\n\t\tp.mt = spr->GetLocalMat() * params.mt;\n\t\tp.color = spr->GetColor() * params.color;\n\t}\n\tif (m_shadow) {\n\t\tm_shadow->Draw(p.mt, p.color.mul.a);\n\t}\n}\n\nsm::rect Symbol::GetBounding(const s2::Sprite* spr) const\n{\n\tif (m_shadow) {\n\t\treturn m_shadow->GetRegion();\n\t} else {\n\t\treturn sm::rect(sm::vec2(0, 0), 200, 200);\n\t}\n}\n\nbool Symbol::LoadResources()\n{\n\tif (!gum::FilepathHelper::Exists(m_filepath)) {\n\t\treturn false;\n\t}\n\tFileIO::LoadFromFile(m_filepath.c_str(), this);\n\treturn true;\n}\n\n}[FIXED] compile#include \"Symbol.h\"\n#include \"Shadow.h\"\n#include \"config.h\"\n#include \"FileIO.h\"\n\n#include \n\n#include \n#include \n\nnamespace eshadow\n{\n\nSymbol::Symbol()\n{\n\tm_shadow = new Shadow(SOFT_SHADOW_RADIUS);\n}\n\nSymbol::~Symbol()\n{\n\tif (m_shadow) {\n\t\tm_shadow->RemoveReference();\n\t}\n}\n\nvoid Symbol::Draw(const s2::RenderParams& params, const s2::Sprite* spr) const\n{\n\ts2::RenderParams p = params;\n\tif (spr) {\n\t\tp.mt = spr->GetLocalMat() * params.mt;\n\t\tp.color = spr->GetColor() * params.color;\n\t}\n\tif (m_shadow) {\n\t\tm_shadow->Draw(p.mt, p.color.GetMul().a);\n\t}\n}\n\nsm::rect Symbol::GetBounding(const s2::Sprite* spr) const\n{\n\tif (m_shadow) {\n\t\treturn m_shadow->GetRegion();\n\t} else {\n\t\treturn sm::rect(sm::vec2(0, 0), 200, 200);\n\t}\n}\n\nbool Symbol::LoadResources()\n{\n\tif (!gum::FilepathHelper::Exists(m_filepath)) {\n\t\treturn false;\n\t}\n\tFileIO::LoadFromFile(m_filepath.c_str(), this);\n\treturn true;\n}\n\n}<|endoftext|>"} {"text":"#include \"cppbencode.h\"\n#include \n#include \n\nvoid verify(const ben::Value &value, const char *s)\n{\n\tstd::ostringstream ss;\n\tvalue.write(ss);\n\n\tassert(ss.str() == s);\n\n\tstd::istringstream parser(ss.str());\n\tben::Value value2;\n\tvalue2.load_all(parser);\n\n\tassert(value == value2);\n}\n\nvoid verify_error(const char *s, const char *error)\n{\n\tben::Value val;\n\tstd::istringstream ss(s);\n\ttry {\n\t\tval.load(ss);\n\t\t\/* should always raise an exception *\/\n\t\tassert(0);\n\t} catch (const ben::decode_error &e) {\n\t\tassert(e.what() == std::string(error));\n\t}\n}\n\nint main()\n{\n\tverify(0, \"i0e\");\n\tverify(1234, \"i1234e\");\n\tverify(-1234, \"i-1234e\");\n\tverify(std::string(\"foobar\"), \"6:foobar\");\n\tverify(std::string(\"\"), \"0:\");\n\tverify(true, \"b1\");\n\tverify(false, \"b0\");\n\n\tstd::vector arr;\n\tarr.push_back(std::string(\"foo\"));\n\tarr.push_back(1234);\n\tarr.push_back(true);\n\tverify(arr, \"l3:fooi1234eb1e\");\n\n\tben::dict_map_t dict;\n\tdict.insert(std::make_pair(\"bar\", arr));\n\tdict.insert(std::make_pair(\"foo\", std::string(\"test\")));\n\tverify(dict, \"d3:barl3:fooi1234eb1e3:foo4:teste\");\n\n\tverify_error(\"i1234\", \"Expected 'e'\");\n\tverify_error(\"dx\", \"Expected a digit\");\n\tverify_error(\"d-5\", \"Expected a digit\");\n\tverify_error(\"d123\", \"Expected ':'\");\n\tverify_error(\"i\", \"Unexpected end of input\");\n\tverify_error(\"i 1e\", \"Expected a digit or '-'\");\n\tverify_error(\"i1111111111111111111111e\", \"Invalid integer\");\n\tverify_error(\"i- 1e\", \"Invalid integer\");\n\tverify_error(\"i-0e\", \"Zero with a minus sign\");\n\tverify_error(\"i05e\", \"Integer has leading zeroes\");\n\tverify_error(\"06:foobar\", \"String length has leading zeroes\");\n\tverify_error(\"123\", \"Expected ':'\");\n\tverify_error(\"5:foo\", \"Unexpected end of input\");\n\tverify_error(\"l\", \"Unexpected end of input\");\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123ee\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got null\"));\n\t}\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123e3:foob1e\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got boolean\"));\n\t}\n\n\tprintf(\"ok\\n\");\n\treturn 0;\n}\ntest: Add comments [DOCUMENTATION]#include \"cppbencode.h\"\n#include \n#include \n\nvoid verify(const ben::Value &value, const char *encoded)\n{\n\t\/* verify that the encoder produces the expected output *\/\n\tstd::ostringstream ss;\n\tvalue.write(ss);\n\tassert(ss.str() == encoded);\n\n\t\/* try to load the bencoded string, and check that it is equal *\/\n\tstd::istringstream parser(ss.str());\n\tben::Value value2;\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n}\n\nvoid verify_error(const char *s, const char *error)\n{\n\tben::Value val;\n\tstd::istringstream ss(s);\n\ttry {\n\t\tval.load(ss);\n\t\t\/* should always raise an exception *\/\n\t\tassert(0);\n\t} catch (const ben::decode_error &e) {\n\t\tassert(e.what() == std::string(error));\n\t}\n}\n\nint main()\n{\n\tverify(0, \"i0e\");\n\tverify(1234, \"i1234e\");\n\tverify(-1234, \"i-1234e\");\n\tverify(std::string(\"foobar\"), \"6:foobar\");\n\tverify(std::string(\"\"), \"0:\");\n\tverify(true, \"b1\");\n\tverify(false, \"b0\");\n\n\tstd::vector arr;\n\tarr.push_back(std::string(\"foo\"));\n\tarr.push_back(1234);\n\tarr.push_back(true);\n\tverify(arr, \"l3:fooi1234eb1e\");\n\n\tben::dict_map_t dict;\n\tdict.insert(std::make_pair(\"bar\", arr));\n\tdict.insert(std::make_pair(\"foo\", std::string(\"test\")));\n\tverify(dict, \"d3:barl3:fooi1234eb1e3:foo4:teste\");\n\n\tverify_error(\"i1234\", \"Expected 'e'\");\n\tverify_error(\"dx\", \"Expected a digit\");\n\tverify_error(\"d-5\", \"Expected a digit\");\n\tverify_error(\"d123\", \"Expected ':'\");\n\tverify_error(\"i\", \"Unexpected end of input\");\n\tverify_error(\"i 1e\", \"Expected a digit or '-'\");\n\tverify_error(\"i1111111111111111111111e\", \"Invalid integer\");\n\tverify_error(\"i- 1e\", \"Invalid integer\");\n\tverify_error(\"i-0e\", \"Zero with a minus sign\");\n\tverify_error(\"i05e\", \"Integer has leading zeroes\");\n\tverify_error(\"06:foobar\", \"String length has leading zeroes\");\n\tverify_error(\"123\", \"Expected ':'\");\n\tverify_error(\"5:foo\", \"Unexpected end of input\");\n\tverify_error(\"l\", \"Unexpected end of input\");\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123ee\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got null\"));\n\t}\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123e3:foob1e\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got boolean\"));\n\t}\n\n\tprintf(\"ok\\n\");\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file help.cpp\n\/\/\/ @brief help() and version() functions of the primesieve\n\/\/\/ console application.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace {\n\nconst string helpMenu(\n \"Usage: primesieve [START] STOP [OPTION]...\\n\"\n \"Use the segmented sieve of Eratosthenes to generate the primes and\\n\"\n \"prime k-tuplets in the interval [START, STOP] < 2^64\\n\"\n \"\\n\"\n \"Options:\\n\"\n \" -c, --count= Count primes and prime k-tuplets, 1 <= N <= 7\\n\"\n \" 1=primes, 2=twins, 3=triplets, ...\\n\"\n \" -h, --help Print this help menu\\n\"\n \" -n, --nthprime Calculate the nth prime\\n\"\n \" e.g. 1 100 -n finds the first prime >= 100\\n\"\n \" -o, --offset= Sieve the interval [START, START + N]\\n\"\n \" -p, --print= Print primes or prime k-tuplets, 1 <= N <= 7\\n\"\n \" 1=primes, 2=twins, 3=triplets, ...\\n\"\n \" -q, --quiet Quiet mode, prints less output\\n\"\n \" -s, --size= Set the sieve size in kilobytes, 1 <= N <= 2048\\n\"\n \" --test Run various sieving tests and exit\\n\"\n \" -t, --threads= Set the number of threads, 1 <= N <= CPU cores\\n\"\n \" -v, --version Print version and license information\\n\"\n \"\\n\"\n \"Example:\\n\"\n \" Count the primes and print the twin primes below 1000\\n\"\n \" > primesieve 1000 --count=1 -p2\"\n);\n\nconst string versionInfo(\n \"primesieve \" PRIMESIEVE_VERSION \", \\n\"\n \"Copyright (C) 2014 Kim Walisch\\n\"\n \"BSD 2-Clause License \"\n);\n\n} \/\/ end namespace\n\nvoid help()\n{\n cout << helpMenu << endl;\n exit(1);\n}\n\nvoid version()\n{\n cout << versionInfo << endl;\n exit(1);\n}\nUpdate help.cpp\/\/\/\n\/\/\/ @file help.cpp\n\/\/\/ @brief help() and version() functions of the primesieve\n\/\/\/ console application.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace {\n\nconst string helpMenu(\n \"Usage: primesieve [START] STOP [OPTION]...\\n\"\n \"Use the segmented sieve of Eratosthenes to generate the primes and\\n\"\n \"prime k-tuplets in the interval [START, STOP] < 2^64\\n\"\n \"\\n\"\n \"Options:\\n\"\n \" -c, --count= Count primes and prime k-tuplets, 1 <= N <= 7\\n\"\n \" 1=primes, 2=twins, 3=triplets, ...\\n\"\n \" -h, --help Print this help menu\\n\"\n \" -n, --nthprime Calculate the nth prime\\n\"\n \" e.g. 1 100 -n finds the first prime > 100\\n\"\n \" -o, --offset= Sieve the interval [START, START + N]\\n\"\n \" -p, --print= Print primes or prime k-tuplets, 1 <= N <= 7\\n\"\n \" 1=primes, 2=twins, 3=triplets, ...\\n\"\n \" -q, --quiet Quiet mode, prints less output\\n\"\n \" -s, --size= Set the sieve size in kilobytes, 1 <= N <= 2048\\n\"\n \" --test Run various sieving tests and exit\\n\"\n \" -t, --threads= Set the number of threads, 1 <= N <= CPU cores\\n\"\n \" -v, --version Print version and license information\\n\"\n \"\\n\"\n \"Example:\\n\"\n \" Print and count the twin primes below 1000000\\n\"\n \" > primesieve 10**6 --print=2 -c2\"\n);\n\nconst string versionInfo(\n \"primesieve \" PRIMESIEVE_VERSION \", \\n\"\n \"Copyright (C) 2014 Kim Walisch\\n\"\n \"BSD 2-Clause License \"\n);\n\n} \/\/ end namespace\n\nvoid help()\n{\n cout << helpMenu << endl;\n exit(1);\n}\n\nvoid version()\n{\n cout << versionInfo << endl;\n exit(1);\n}\n<|endoftext|>"} {"text":"\/*\n * This class implmentats callbacks function that are called by ATS\n * AUTHORS:\n * Vmon: May 2013, moving Bill's code to C++\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \nusing namespace std;\n\n#include \n\/\/to retrieve the client ip\n#include \n#include \n#include \n\n\/\/to run fail2ban-client\n#include \n\n#include \"banjax.h\"\n#include \"banjax_continuation.h\"\n#include \"transaction_muncher.h\"\n#include \"regex_manager.h\"\n#include \"challenge_manager.h\"\n#include \"swabber_interface.h\"\n#include \"ats_event_handler.h\"\n\n\/*the glabal_cont the global continuation that is generated by\n by the banjax object.*\/\n\/\/TSCont Banjax::global_contp;\n\/\/extern TSMutex Banjax::regex_mutex;\nbool ATSEventHandler::banjax_active_queues[BanjaxFilter::TOTAL_NO_OF_QUEUES];\n\n\/\/Banjax* ATSEventHandler::banjax = NULL;\n\nint\nATSEventHandler::banjax_global_eventhandler(TSCont contp, TSEvent event, void *edata)\n{\n TSHttpTxn txnp = (TSHttpTxn) edata;\n BanjaxContinuation *cd;\n\n switch (event) {\n case TS_EVENT_HTTP_TXN_START:\n \/\/If we are here it means this is the global continuation\n \/\/we never subscribe subsequent continuations to this event\n handle_txn_start((TSHttpTxn) edata);\n \/*if (banjax_active_queues[HTTP_START])\n handle_task_queue(HTTP_START, (BanjaxContinuation *) TSContDataGet(contp));*\/\n\n return 0;\n\n case TS_EVENT_HTTP_READ_REQUEST_HDR:\n if(contp != Banjax::global_contp)\n handle_request((BanjaxContinuation *) TSContDataGet(contp));\n return 0;\n\n case TS_EVENT_HTTP_READ_CACHE_HDR:\n \/* on hit we don't do anything for now\n lack of miss means hit to me \n if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation *) TSContDataGet(contp);\n cd->hit = 1;\n }*\/\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return 0;\n\n case TS_EVENT_HTTP_SEND_REQUEST_HDR:\n TSDebug(BANJAX_PLUGIN_NAME, \"miss\");\n if (contp != Banjax::global_contp) {\n\t cd = (BanjaxContinuation *) TSContDataGet(contp);\n\t cd->transaction_muncher.miss();\n }\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return 0;\n\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR:\n \/\/TSDebug(BANJAX_PLUGIN_NAME, \"response\" );\n if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation*) TSContDataGet(contp);\n handle_response(cd);\n }\n return 0;\n\n case TS_EVENT_HTTP_TXN_CLOSE:\n TSDebug(BANJAX_PLUGIN_NAME, \"txn close\" );\n if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation *) TSContDataGet(contp); \n if (banjax_active_queues[BanjaxFilter::HTTP_CLOSE])\n handle_task_queue(banjax->task_queues[BanjaxFilter::HTTP_CLOSE], cd);\n\n \/\/killing the continuation\n cd->~BanjaxContinuation(); \/\/leave mem manage to ATS\n \/\/TSfree(cd); I think TS is taking care of this\n destroy_continuation(contp);\n }\n break;\n\n case TS_EVENT_TIMEOUT:\n \/\/TODO: This code does not make sense and needs to be revisited\n TSDebug(\"banjaxtimeout\", \"timeout\" );\n \/* when mutex lock is not acquired and continuation is rescheduled,\n the plugin is called back with TS_EVENT_TIMEOUT with a NULL\n edata. We need to decide, in which function did the MutexLock\n failed and call that function again *\/\n \/*if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation *) TSContDataGet(contp);\n switch (cd->cf) {\n case BanjaxContinuation::HANDLE_REQUEST:\n handle_request(cd);\n return 0;\n default:\n TSDebug(BANJAX_PLUGIN_NAME, \"This event was unexpected: %d\\n\", event);\n break;\n\t }\n } else {\n \/\/regardless, it even doesn't make sense to read the list here\n \/\/read_regex_list(contp);\n return 0;\n }*\/\n\n default:\n TSDebug(BANJAX_PLUGIN_NAME, \"Unsolicitated event call?\" );\n break;\n }\n\n return 0;\n\n}\n\nvoid\nATSEventHandler::handle_request(BanjaxContinuation* cd)\n{\n \/\/retreiving part of header requested by the filters\n const TransactionParts& cur_trans_parts = cd->transaction_muncher.retrieve_parts(banjax->which_parts_are_requested());\n\n bool continue_filtering = true;\n for(Banjax::TaskQueue::iterator cur_task = banjax->task_queues[BanjaxFilter::HTTP_REQUEST].begin(); continue_filtering && cur_task != banjax->task_queues[BanjaxFilter::HTTP_REQUEST].end(); cur_task++) {\n FilterResponse cur_filter_result = ((*(cur_task->filter)).*(cur_task->task))(cur_trans_parts);\n switch (cur_filter_result.response_type) \n {\n case FilterResponse::GO_AHEAD_NO_COMMENT:\n continue;\n \n case FilterResponse::NO_WORRIES_SERVE_IMMIDIATELY: \n \/\/This is when the requester is white listed\n continue_filtering = false;\n break;\n\n case FilterResponse::I_RESPOND:\n \/\/ from here on, cur_filter_result is owned by the continuation data.\n cd->response_info = cur_filter_result;\n cd->responding_filter = cur_task->filter;\n \/\/ TODO(oschaaf): commented this. @vmon: we already hook this globally,\n \/\/ is there a reason we need to hook it again here?\n \/\/TSHttpTxnHookAdd(cd->txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cd->contp);\n TSHttpTxnReenable(cd->txnp, TS_EVENT_HTTP_ERROR);\n return;\n\n default:\n \/\/Not implemeneted, hence ignoe\n break;\n \n }\n }\n \n \/\/TODO: it is imaginable that a filter needs to be \n \/\/called during response but does not need to influnence\n \/\/the response, e.g. botbanger hence we need to get the \n \/\/response hook while continuing with the flow\n \/\/destroy_continuation(cd->txnp, cd->contp);\n TSHttpTxnReenable(cd->txnp, TS_EVENT_HTTP_CONTINUE);\n\n}\n\nvoid\nATSEventHandler::handle_response(BanjaxContinuation* cd)\n{\n \/\/we need to retrieve response parts for any filter who requested it.\n cd->transaction_muncher.retrieve_response_parts(banjax->which_response_parts_are_requested());\n\n if (cd->response_info.response_type == FilterResponse::I_RESPOND) {\n cd->transaction_muncher.set_status(TS_HTTP_STATUS_FORBIDDEN);\n std::string buf = (((cd->responding_filter)->*(((FilterExtendedResponse*)cd->response_info.response_data)->response_generator)))(cd->transaction_muncher.retrieve_parts(banjax->all_filters_requested_part), cd->response_info);\n\n cd->transaction_muncher.set_status(\n (TSHttpStatus)(((FilterExtendedResponse*)cd->response_info.response_data))->response_code);\n \n if ((((FilterExtendedResponse*)cd->response_info.response_data))->set_cookie_header.size()) {\n cd->transaction_muncher.append_header(\n \"Set-Cookie\", (((FilterExtendedResponse*)cd->response_info.response_data))->set_cookie_header.c_str());\n }\n if (buf.size() == 0) {\n \/\/ When we get here, no valid response body was generated somehow.\n \/\/ Insert one, to prevent triggering an assert in TSHttpTxnErrorBodySet\n buf.append(\"Not authorized\");\n }\n char* b = (char*) TSmalloc(buf.size());\n memcpy(b, buf.data(), buf.size());\n TSHttpTxnErrorBodySet(cd->txnp, b, buf.size(),\n (((FilterExtendedResponse*)cd->response_info.response_data))->get_and_release_content_type());\n }\n \/\/Now we should take care of registerd filters in the queue these are not\n \/\/going to generate the response at least that is the plan\n if (banjax_active_queues[BanjaxFilter::HTTP_START])\n handle_task_queue(banjax->task_queues[BanjaxFilter::HTTP_RESPONSE], cd);\n\n TSHttpTxnReenable(cd->txnp, TS_EVENT_HTTP_CONTINUE);\n\n}\n\n\/**\n @param global_contp contains the global continuation and is sent here\n , so the new continuation gets the main banjax object\n *\/\nvoid\nATSEventHandler::handle_txn_start(TSHttpTxn txnp)\n{\n TSDebug(BANJAX_PLUGIN_NAME, \"txn start\" );\n\n TSCont txn_contp;\n BanjaxContinuation *cd;\n\n \/\/retreive the banjax obej\n txn_contp = TSContCreate((TSEventFunc) banjax_global_eventhandler, TSMutexCreate());\n \/* create the data that'll be associated with the continuation *\/\n cd = (BanjaxContinuation *) TSmalloc(sizeof(BanjaxContinuation));\n cd = new(cd) BanjaxContinuation(txnp);\n \/\/TSDebug(BANJAX_PLUGIN_NAME, \"New continuation data at %lu\", (unsigned long)cd);\n TSContDataSet(txn_contp, cd);\n\n cd->contp = txn_contp;\n\n TSHttpTxnHookAdd(txnp, TS_HTTP_READ_REQUEST_HDR_HOOK, txn_contp);\n TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_REQUEST_HDR_HOOK, txn_contp);\n TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, txn_contp);\n TSHttpTxnHookAdd(txnp, TS_HTTP_TXN_CLOSE_HOOK, txn_contp);\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n\n}\n\n\/**\n runs if a filter is registered to run a function during an event\n*\/\nvoid \nATSEventHandler::handle_task_queue(Banjax::TaskQueue& current_queue, BanjaxContinuation* cd)\n{\n const TransactionParts& cur_trans_parts = cd->transaction_muncher.retrieve_parts(banjax->which_parts_are_requested());\n\n for(Banjax::TaskQueue::iterator cur_task = current_queue.begin(); cur_task != current_queue.end(); cur_task++)\n \/*For now we have no plan on doing anything with the result\n in future we need to receive the filter instruction for \n the rest of transation but for the moment only it matters\n at the begining of the transaction to interfere with the \n transaction.\n\n FilterResponse cur_filter_result =\n *\/ \n ((*(cur_task->filter)).*(cur_task->task))(cur_trans_parts);\n \n}\n\nvoid\nATSEventHandler::destroy_continuation(TSCont contp)\n{\n BanjaxContinuation *cd = NULL;\n\n cd = (BanjaxContinuation *) TSContDataGet(contp);\n\n \/\/save the txn before destroying the continuation so we can continue\n TSHttpTxn txn_keeper = cd->txnp;\n TSContDestroy(contp);\n TSHttpTxnReenable(txn_keeper, TS_EVENT_HTTP_CONTINUE);\n\n if (cd != NULL) {\n TSfree(cd);\n \/\/ delete cd;\n }\n}\nfree the cont data before destroying the cont\/*\n * This class implmentats callbacks function that are called by ATS\n * AUTHORS:\n * Vmon: May 2013, moving Bill's code to C++\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \nusing namespace std;\n\n#include \n\/\/to retrieve the client ip\n#include \n#include \n#include \n\n\/\/to run fail2ban-client\n#include \n\n#include \"banjax.h\"\n#include \"banjax_continuation.h\"\n#include \"transaction_muncher.h\"\n#include \"regex_manager.h\"\n#include \"challenge_manager.h\"\n#include \"swabber_interface.h\"\n#include \"ats_event_handler.h\"\n\n\/*the glabal_cont the global continuation that is generated by\n by the banjax object.*\/\n\/\/TSCont Banjax::global_contp;\n\/\/extern TSMutex Banjax::regex_mutex;\nbool ATSEventHandler::banjax_active_queues[BanjaxFilter::TOTAL_NO_OF_QUEUES];\n\n\/\/Banjax* ATSEventHandler::banjax = NULL;\n\nint\nATSEventHandler::banjax_global_eventhandler(TSCont contp, TSEvent event, void *edata)\n{\n TSHttpTxn txnp = (TSHttpTxn) edata;\n BanjaxContinuation *cd;\n\n switch (event) {\n case TS_EVENT_HTTP_TXN_START:\n \/\/If we are here it means this is the global continuation\n \/\/we never subscribe subsequent continuations to this event\n handle_txn_start((TSHttpTxn) edata);\n \/*if (banjax_active_queues[HTTP_START])\n handle_task_queue(HTTP_START, (BanjaxContinuation *) TSContDataGet(contp));*\/\n\n return 0;\n\n case TS_EVENT_HTTP_READ_REQUEST_HDR:\n if(contp != Banjax::global_contp)\n handle_request((BanjaxContinuation *) TSContDataGet(contp));\n return 0;\n\n case TS_EVENT_HTTP_READ_CACHE_HDR:\n \/* on hit we don't do anything for now\n lack of miss means hit to me \n if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation *) TSContDataGet(contp);\n cd->hit = 1;\n }*\/\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return 0;\n\n case TS_EVENT_HTTP_SEND_REQUEST_HDR:\n TSDebug(BANJAX_PLUGIN_NAME, \"miss\");\n if (contp != Banjax::global_contp) {\n\t cd = (BanjaxContinuation *) TSContDataGet(contp);\n\t cd->transaction_muncher.miss();\n }\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return 0;\n\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR:\n \/\/TSDebug(BANJAX_PLUGIN_NAME, \"response\" );\n if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation*) TSContDataGet(contp);\n handle_response(cd);\n }\n return 0;\n\n case TS_EVENT_HTTP_TXN_CLOSE:\n TSDebug(BANJAX_PLUGIN_NAME, \"txn close\" );\n if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation *) TSContDataGet(contp); \n if (banjax_active_queues[BanjaxFilter::HTTP_CLOSE])\n handle_task_queue(banjax->task_queues[BanjaxFilter::HTTP_CLOSE], cd);\n\n \/\/killing the continuation\n cd->~BanjaxContinuation(); \/\/leave mem manage to ATS\n \/\/TSfree(cd); I think TS is taking care of this\n destroy_continuation(contp);\n }\n break;\n\n case TS_EVENT_TIMEOUT:\n \/\/TODO: This code does not make sense and needs to be revisited\n TSDebug(\"banjaxtimeout\", \"timeout\" );\n \/* when mutex lock is not acquired and continuation is rescheduled,\n the plugin is called back with TS_EVENT_TIMEOUT with a NULL\n edata. We need to decide, in which function did the MutexLock\n failed and call that function again *\/\n \/*if (contp != Banjax::global_contp) {\n cd = (BanjaxContinuation *) TSContDataGet(contp);\n switch (cd->cf) {\n case BanjaxContinuation::HANDLE_REQUEST:\n handle_request(cd);\n return 0;\n default:\n TSDebug(BANJAX_PLUGIN_NAME, \"This event was unexpected: %d\\n\", event);\n break;\n\t }\n } else {\n \/\/regardless, it even doesn't make sense to read the list here\n \/\/read_regex_list(contp);\n return 0;\n }*\/\n\n default:\n TSDebug(BANJAX_PLUGIN_NAME, \"Unsolicitated event call?\" );\n break;\n }\n\n return 0;\n\n}\n\nvoid\nATSEventHandler::handle_request(BanjaxContinuation* cd)\n{\n \/\/retreiving part of header requested by the filters\n const TransactionParts& cur_trans_parts = cd->transaction_muncher.retrieve_parts(banjax->which_parts_are_requested());\n\n bool continue_filtering = true;\n for(Banjax::TaskQueue::iterator cur_task = banjax->task_queues[BanjaxFilter::HTTP_REQUEST].begin(); continue_filtering && cur_task != banjax->task_queues[BanjaxFilter::HTTP_REQUEST].end(); cur_task++) {\n FilterResponse cur_filter_result = ((*(cur_task->filter)).*(cur_task->task))(cur_trans_parts);\n switch (cur_filter_result.response_type) \n {\n case FilterResponse::GO_AHEAD_NO_COMMENT:\n continue;\n \n case FilterResponse::NO_WORRIES_SERVE_IMMIDIATELY: \n \/\/This is when the requester is white listed\n continue_filtering = false;\n break;\n\n case FilterResponse::I_RESPOND:\n \/\/ from here on, cur_filter_result is owned by the continuation data.\n cd->response_info = cur_filter_result;\n cd->responding_filter = cur_task->filter;\n \/\/ TODO(oschaaf): commented this. @vmon: we already hook this globally,\n \/\/ is there a reason we need to hook it again here?\n \/\/TSHttpTxnHookAdd(cd->txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cd->contp);\n TSHttpTxnReenable(cd->txnp, TS_EVENT_HTTP_ERROR);\n return;\n\n default:\n \/\/Not implemeneted, hence ignoe\n break;\n \n }\n }\n \n \/\/TODO: it is imaginable that a filter needs to be \n \/\/called during response but does not need to influnence\n \/\/the response, e.g. botbanger hence we need to get the \n \/\/response hook while continuing with the flow\n \/\/destroy_continuation(cd->txnp, cd->contp);\n TSHttpTxnReenable(cd->txnp, TS_EVENT_HTTP_CONTINUE);\n\n}\n\nvoid\nATSEventHandler::handle_response(BanjaxContinuation* cd)\n{\n \/\/we need to retrieve response parts for any filter who requested it.\n cd->transaction_muncher.retrieve_response_parts(banjax->which_response_parts_are_requested());\n\n if (cd->response_info.response_type == FilterResponse::I_RESPOND) {\n cd->transaction_muncher.set_status(TS_HTTP_STATUS_FORBIDDEN);\n std::string buf = (((cd->responding_filter)->*(((FilterExtendedResponse*)cd->response_info.response_data)->response_generator)))(cd->transaction_muncher.retrieve_parts(banjax->all_filters_requested_part), cd->response_info);\n\n cd->transaction_muncher.set_status(\n (TSHttpStatus)(((FilterExtendedResponse*)cd->response_info.response_data))->response_code);\n \n if ((((FilterExtendedResponse*)cd->response_info.response_data))->set_cookie_header.size()) {\n cd->transaction_muncher.append_header(\n \"Set-Cookie\", (((FilterExtendedResponse*)cd->response_info.response_data))->set_cookie_header.c_str());\n }\n if (buf.size() == 0) {\n \/\/ When we get here, no valid response body was generated somehow.\n \/\/ Insert one, to prevent triggering an assert in TSHttpTxnErrorBodySet\n buf.append(\"Not authorized\");\n }\n char* b = (char*) TSmalloc(buf.size());\n memcpy(b, buf.data(), buf.size());\n TSHttpTxnErrorBodySet(cd->txnp, b, buf.size(),\n (((FilterExtendedResponse*)cd->response_info.response_data))->get_and_release_content_type());\n }\n \/\/Now we should take care of registerd filters in the queue these are not\n \/\/going to generate the response at least that is the plan\n if (banjax_active_queues[BanjaxFilter::HTTP_START])\n handle_task_queue(banjax->task_queues[BanjaxFilter::HTTP_RESPONSE], cd);\n\n TSHttpTxnReenable(cd->txnp, TS_EVENT_HTTP_CONTINUE);\n\n}\n\n\/**\n @param global_contp contains the global continuation and is sent here\n , so the new continuation gets the main banjax object\n *\/\nvoid\nATSEventHandler::handle_txn_start(TSHttpTxn txnp)\n{\n TSDebug(BANJAX_PLUGIN_NAME, \"txn start\" );\n\n TSCont txn_contp;\n BanjaxContinuation *cd;\n\n \/\/retreive the banjax obej\n txn_contp = TSContCreate((TSEventFunc) banjax_global_eventhandler, TSMutexCreate());\n \/* create the data that'll be associated with the continuation *\/\n cd = (BanjaxContinuation *) TSmalloc(sizeof(BanjaxContinuation));\n cd = new(cd) BanjaxContinuation(txnp);\n \/\/TSDebug(BANJAX_PLUGIN_NAME, \"New continuation data at %lu\", (unsigned long)cd);\n TSContDataSet(txn_contp, cd);\n\n cd->contp = txn_contp;\n\n TSHttpTxnHookAdd(txnp, TS_HTTP_READ_REQUEST_HDR_HOOK, txn_contp);\n TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_REQUEST_HDR_HOOK, txn_contp);\n TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, txn_contp);\n TSHttpTxnHookAdd(txnp, TS_HTTP_TXN_CLOSE_HOOK, txn_contp);\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n\n}\n\n\/**\n runs if a filter is registered to run a function during an event\n*\/\nvoid \nATSEventHandler::handle_task_queue(Banjax::TaskQueue& current_queue, BanjaxContinuation* cd)\n{\n const TransactionParts& cur_trans_parts = cd->transaction_muncher.retrieve_parts(banjax->which_parts_are_requested());\n\n for(Banjax::TaskQueue::iterator cur_task = current_queue.begin(); cur_task != current_queue.end(); cur_task++)\n \/*For now we have no plan on doing anything with the result\n in future we need to receive the filter instruction for \n the rest of transation but for the moment only it matters\n at the begining of the transaction to interfere with the \n transaction.\n\n FilterResponse cur_filter_result =\n *\/ \n ((*(cur_task->filter)).*(cur_task->task))(cur_trans_parts);\n \n}\n\nvoid\nATSEventHandler::destroy_continuation(TSCont contp)\n{\n BanjaxContinuation *cd = NULL;\n\n cd = (BanjaxContinuation *) TSContDataGet(contp);\n\n \/\/save the txn before destroying the continuation so we can continue\n TSHttpTxn txn_keeper = cd->txnp;\n TSfree(cd);\n\n TSContDestroy(contp);\n TSHttpTxnReenable(txn_keeper, TS_EVENT_HTTP_CONTINUE);\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2020 The Android Open Source Project\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 \"src\/trace_processor\/util\/gzip_utils.h\"\n\n\/\/ For bazel build.\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/compiler.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n#include \n#else\nstruct z_stream_s {};\n#endif\n\nnamespace perfetto {\nnamespace trace_processor {\nnamespace util {\n\nbool IsGzipSupported() {\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n return true;\n#else\n return false;\n#endif\n}\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\nGzipDecompressor::GzipDecompressor() : z_stream_(new z_stream()) {\n z_stream_->zalloc = nullptr;\n z_stream_->zfree = nullptr;\n z_stream_->opaque = nullptr;\n inflateInit2(z_stream_.get(), 32 + 15);\n}\n#else\nGzipDecompressor::GzipDecompressor() = default;\n#endif\n\nGzipDecompressor::~GzipDecompressor() {\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n \/\/ Ensure the call to inflateEnd to prevent leaks of internal state.\n inflateEnd(z_stream_.get());\n#endif\n}\n\nvoid GzipDecompressor::Reset() {\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n inflateReset(z_stream_.get());\n#endif\n}\n\nvoid GzipDecompressor::SetInput(const uint8_t* data, size_t size) {\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n \/\/ This const_cast is not harmfull as zlib will not modify the data in this\n \/\/ pointer. This is only necessary because of the build flags we use to be\n \/\/ compatible with other embedders.\n z_stream_->next_in = const_cast(data);\n z_stream_->avail_in = static_cast(size);\n#else\n base::ignore_result(data);\n base::ignore_result(size);\n#endif\n}\n\nGzipDecompressor::Result GzipDecompressor::Decompress(uint8_t* out,\n size_t out_size) {\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n if (z_stream_->avail_in == 0)\n return Result{ResultCode::kNeedsMoreInput, 0};\n\n z_stream_->next_out = out;\n z_stream_->avail_out = static_cast(out_size);\n\n int ret = inflate(z_stream_.get(), Z_NO_FLUSH);\n switch (ret) {\n case Z_NEED_DICT:\n case Z_DATA_ERROR:\n case Z_MEM_ERROR:\n \/\/ Ignore inflateEnd error as we will error out anyway.\n inflateEnd(z_stream_.get());\n return Result{ResultCode::kError, 0};\n case Z_STREAM_END:\n return Result{ResultCode::kEof, out_size - z_stream_->avail_out};\n case Z_BUF_ERROR:\n return Result{ResultCode::kNoProgress, 0};\n default:\n return Result{ResultCode::kOk, out_size - z_stream_->avail_out};\n }\n#else\n base::ignore_result(out);\n base::ignore_result(out_size);\n return Result{ResultCode::kError, 0};\n#endif\n}\n\n} \/\/ namespace util\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\nImprove Readability of gzip_utils.cc\/*\n * Copyright (C) 2020 The Android Open Source Project\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 \"src\/trace_processor\/util\/gzip_utils.h\"\n\n\/\/ For bazel build.\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/compiler.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n#include \n#else\nstruct z_stream_s {};\n#endif\n\nnamespace perfetto {\nnamespace trace_processor {\nnamespace util {\n\nbool IsGzipSupported() {\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n return true;\n#else\n return false;\n#endif\n}\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB) \/\/ Real Implementation\n\nGzipDecompressor::GzipDecompressor() : z_stream_(new z_stream()) {\n z_stream_->zalloc = nullptr;\n z_stream_->zfree = nullptr;\n z_stream_->opaque = nullptr;\n \/\/ TODO(mohitms): Should we instead use `32 + MAX_WBITS` here to make\n \/\/ it more readable ?\n inflateInit2(z_stream_.get(), 32 + 15);\n}\n\nGzipDecompressor::~GzipDecompressor() {\n inflateEnd(z_stream_.get());\n}\n\nvoid GzipDecompressor::Reset() {\n inflateReset(z_stream_.get());\n}\n\nvoid GzipDecompressor::SetInput(const uint8_t* data, size_t size) {\n \/\/ This const_cast is not harmfull as zlib will not modify the data in this\n \/\/ pointer. This is only necessary because of the build flags we use to be\n \/\/ compatible with other embedders.\n z_stream_->next_in = const_cast(data);\n z_stream_->avail_in = static_cast(size);\n}\n\nGzipDecompressor::Result GzipDecompressor::Decompress(uint8_t* out,\n size_t out_size) {\n if (z_stream_->avail_in == 0)\n return Result{ResultCode::kNeedsMoreInput, 0};\n\n z_stream_->next_out = out;\n z_stream_->avail_out = static_cast(out_size);\n\n int ret = inflate(z_stream_.get(), Z_NO_FLUSH);\n switch (ret) {\n case Z_NEED_DICT:\n case Z_DATA_ERROR:\n case Z_MEM_ERROR:\n \/\/ Ignore inflateEnd error as we will error out anyway.\n inflateEnd(z_stream_.get());\n return Result{ResultCode::kError, 0};\n case Z_STREAM_END:\n return Result{ResultCode::kEof, out_size - z_stream_->avail_out};\n case Z_BUF_ERROR:\n return Result{ResultCode::kNoProgress, 0};\n default:\n return Result{ResultCode::kOk, out_size - z_stream_->avail_out};\n }\n}\n\n#else \/\/ Dummy Implementation\n\nGzipDecompressor::GzipDecompressor() = default;\nGzipDecompressor::~GzipDecompressor() = default;\nvoid GzipDecompressor::Reset() {}\nvoid GzipDecompressor::SetInput(const uint8_t*, size_t) {}\nGzipDecompressor::Result GzipDecompressor::Decompress(uint8_t*, size_t) {\n Result{ResultCode::kError, 0};\n}\n\n#endif \/\/ PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n\n} \/\/ namespace util\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2022 The Android Open Source Project\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 \"src\/trace_processor\/util\/zip_reader.h\"\n\n#include \n\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/utils.h\"\n#include \"src\/trace_processor\/util\/gzip_utils.h\"\n#include \"src\/trace_processor\/util\/streaming_line_reader.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n#include \/\/ For crc32().\n#endif\n\nnamespace perfetto {\nnamespace trace_processor {\nnamespace util {\n\nnamespace {\n\n\/\/ Entry signatures.\nconst uint32_t kFileHeaderSig = 0x04034b50;\nconst uint32_t kCentralDirectorySig = 0x02014b50;\n\n\/\/ Compression flags.\nconst uint16_t kNoCompression = 0;\nconst uint16_t kDeflate = 8;\n\ntemplate \nT ReadAndAdvance(const uint8_t** ptr) {\n T res{};\n memcpy(base::AssumeLittleEndian(&res), *ptr, sizeof(T));\n *ptr += sizeof(T);\n return res;\n}\n\n} \/\/ namespace\n\nZipReader::ZipReader() = default;\nZipReader::~ZipReader() = default;\n\nbase::Status ZipReader::Parse(const void* data, size_t len) {\n const uint8_t* input = static_cast(data);\n const uint8_t* const input_begin = input;\n const uint8_t* const input_end = input + len;\n auto input_avail = [&] { return static_cast(input_end - input); };\n\n \/\/ .zip file sequence:\n \/\/ [ File 1 header (30 bytes) ]\n \/\/ [ File 1 name ]\n \/\/ [ File 1 extra fields (optional) ]\n \/\/ [ File 1 compressed payload ]\n \/\/\n \/\/ [ File 2 header (30 bytes) ]\n \/\/ [ File 2 name ]\n \/\/ [ File 2 extra fields (optional) ]\n \/\/ [ File 2 compressed payload ]\n \/\/\n \/\/ [ Central directory (ignored) ]\n while (input < input_end) {\n \/\/ Initial state, we are building up the file header.\n if (cur_.raw_hdr_size < kZipFileHdrSize) {\n size_t copy_size =\n std::min(input_avail(), kZipFileHdrSize - cur_.raw_hdr_size);\n memcpy(&cur_.raw_hdr[cur_.raw_hdr_size], input, copy_size);\n cur_.raw_hdr_size += copy_size;\n input += copy_size;\n\n \/\/ If we got all the kZipFileHdrSize bytes, parse the zip file header now.\n if (cur_.raw_hdr_size == kZipFileHdrSize) {\n const uint8_t* hdr_it = &cur_.raw_hdr[0];\n cur_.hdr.signature = ReadAndAdvance(&hdr_it);\n if (cur_.hdr.signature == kCentralDirectorySig) {\n \/\/ We reached the central directory at the end of file.\n \/\/ We don't make any use here of the central directory, so we just\n \/\/ ignore everything else after this point.\n \/\/ Here we abuse the ZipFile class a bit. The Central Directory header\n \/\/ has a different layout. The first 4 bytes (signature) match, the\n \/\/ rest don't but the sizeof(central dir) is >> sizeof(file header) so\n \/\/ we are fine.\n \/\/ We do this rather than retuning because we could have further\n \/\/ Parse() calls (imagine parsing bytes one by one), and we need a way\n \/\/ to keep track of the \"keep eating input without doing anything\".\n cur_.ignore_bytes_after_fname = std::numeric_limits::max();\n input = input_end;\n break;\n }\n if (cur_.hdr.signature != kFileHeaderSig) {\n return base::ErrStatus(\n \"Invalid signature found at offset 0x%zx. Actual=%x, expected=%x\",\n static_cast(input - input_begin) - kZipFileHdrSize,\n cur_.hdr.signature, kFileHeaderSig);\n }\n\n cur_.hdr.version = ReadAndAdvance(&hdr_it);\n cur_.hdr.flags = ReadAndAdvance(&hdr_it);\n cur_.hdr.compression = ReadAndAdvance(&hdr_it);\n cur_.hdr.mtime = ReadAndAdvance(&hdr_it);\n cur_.hdr.mdate = ReadAndAdvance(&hdr_it);\n cur_.hdr.crc32 = ReadAndAdvance(&hdr_it);\n cur_.hdr.compressed_size = ReadAndAdvance(&hdr_it);\n cur_.hdr.uncompressed_size = ReadAndAdvance(&hdr_it);\n cur_.hdr.fname_len = ReadAndAdvance(&hdr_it);\n cur_.hdr.extra_field_len = ReadAndAdvance(&hdr_it);\n PERFETTO_DCHECK(static_cast(hdr_it - cur_.raw_hdr) ==\n kZipFileHdrSize);\n\n \/\/ We support only up to version 2.0 (20). Higher versions define\n \/\/ more advanced features that we don't support (zip64 extensions,\n \/\/ encryption).\n \/\/ Flag bits 1,2 define the compression strength for deflating (which\n \/\/ zlib supports transparently). Other bits define other compression\n \/\/ methods that we don't support.\n if ((cur_.hdr.version > 20) || (cur_.hdr.flags & ~3) != 0) {\n return base::ErrStatus(\n \"Unsupported zip features at offset 0x%zx. version=%x, flags=%x\",\n static_cast(input - input_begin) - kZipFileHdrSize,\n cur_.hdr.version, cur_.hdr.flags);\n }\n cur_.compressed_data.reset(new uint8_t[cur_.hdr.compressed_size]);\n cur_.ignore_bytes_after_fname = cur_.hdr.extra_field_len;\n }\n continue;\n }\n\n \/\/ Build up the file name.\n if (cur_.hdr.fname.size() < cur_.hdr.fname_len) {\n size_t name_left = cur_.hdr.fname_len - cur_.hdr.fname.size();\n size_t copy_size = std::min(name_left, input_avail());\n cur_.hdr.fname.append(reinterpret_cast(input), copy_size);\n input += copy_size;\n continue;\n }\n\n \/\/ Skip any bytes if extra fields were present.\n if (cur_.ignore_bytes_after_fname > 0) {\n size_t skip_size = std::min(input_avail(), cur_.ignore_bytes_after_fname);\n cur_.ignore_bytes_after_fname -= skip_size;\n input += skip_size;\n continue;\n }\n\n \/\/ Build up the compressed payload\n if (cur_.compressed_data_written < cur_.hdr.compressed_size) {\n size_t needed = cur_.hdr.compressed_size - cur_.compressed_data_written;\n size_t copy_size = std::min(needed, input_avail());\n memcpy(&cur_.compressed_data[cur_.compressed_data_written], input,\n copy_size);\n cur_.compressed_data_written += copy_size;\n input += copy_size;\n continue;\n }\n\n \/\/ We have accumulated the whole header, file name and compressed payload.\n PERFETTO_DCHECK(cur_.raw_hdr_size == kZipFileHdrSize);\n PERFETTO_DCHECK(cur_.hdr.fname.size() == cur_.hdr.fname_len);\n PERFETTO_DCHECK(cur_.compressed_data_written == cur_.hdr.compressed_size);\n PERFETTO_DCHECK(cur_.ignore_bytes_after_fname == 0);\n\n files_.emplace_back();\n files_.back().hdr_ = std::move(cur_.hdr);\n files_.back().compressed_data_ = std::move(cur_.compressed_data);\n cur_ = FileParseState(); \/\/ Reset the parsing state for the next file.\n\n } \/\/ while (input < input_end)\n\n \/\/ At this point we must have consumed all input.\n PERFETTO_DCHECK(input_avail() == 0);\n return base::OkStatus();\n}\n\nZipFile::ZipFile() = default;\nZipFile::~ZipFile() = default;\nZipFile::ZipFile(ZipFile&& other) noexcept = default;\nZipFile& ZipFile::operator=(ZipFile&& other) noexcept = default;\n\nbase::Status ZipFile::Decompress(std::vector* out_data) const {\n out_data->clear();\n\n auto res = DoDecompressionChecks();\n if (!res.ok())\n return res;\n\n if (hdr_.compression == kNoCompression) {\n const uint8_t* data = compressed_data_.get();\n out_data->insert(out_data->end(), data, data + hdr_.compressed_size);\n return base::OkStatus();\n }\n\n if (hdr_.uncompressed_size == 0)\n return base::OkStatus();\n\n PERFETTO_DCHECK(hdr_.compression == kDeflate);\n GzipDecompressor dec(GzipDecompressor::InputMode::kRawDeflate);\n dec.Feed(compressed_data_.get(), hdr_.compressed_size);\n\n out_data->resize(hdr_.uncompressed_size);\n auto dec_res = dec.ExtractOutput(out_data->data(), out_data->size());\n if (dec_res.ret != GzipDecompressor::ResultCode::kEof) {\n return base::ErrStatus(\"Zip decompression error (%d) on %s (c=%u, u=%u)\",\n static_cast(dec_res.ret), hdr_.fname.c_str(),\n hdr_.compressed_size, hdr_.uncompressed_size);\n }\n out_data->resize(dec_res.bytes_written);\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n const auto* crc_data = reinterpret_cast(out_data->data());\n auto crc_len = static_cast<::uInt>(out_data->size());\n auto actual_crc32 = static_cast(::crc32(0u, crc_data, crc_len));\n if (actual_crc32 != hdr_.crc32) {\n return base::ErrStatus(\"Zip CRC32 failure on %s (actual: %x, expected: %x)\",\n hdr_.fname.c_str(), actual_crc32, hdr_.crc32);\n }\n#endif\n\n return base::OkStatus();\n}\n\nbase::Status ZipFile::DecompressLines(LinesCallback callback) const {\n using ResultCode = GzipDecompressor::ResultCode;\n\n auto res = DoDecompressionChecks();\n if (!res.ok())\n return res;\n\n StreamingLineReader line_reader(callback);\n\n if (hdr_.compression == kNoCompression) {\n line_reader.Tokenize(\n base::StringView(reinterpret_cast(compressed_data_.get()),\n hdr_.compressed_size));\n return base::OkStatus();\n }\n\n PERFETTO_DCHECK(hdr_.compression == kDeflate);\n GzipDecompressor dec(GzipDecompressor::InputMode::kRawDeflate);\n dec.Feed(compressed_data_.get(), hdr_.compressed_size);\n\n static constexpr size_t kChunkSize = 32768;\n GzipDecompressor::Result dec_res;\n do {\n auto* wptr = reinterpret_cast(line_reader.BeginWrite(kChunkSize));\n dec_res = dec.ExtractOutput(wptr, kChunkSize);\n if (dec_res.ret == ResultCode::kError ||\n dec_res.ret == ResultCode::kNeedsMoreInput)\n return base::ErrStatus(\"zlib decompression error on %s (%d)\",\n name().c_str(), static_cast(dec_res.ret));\n PERFETTO_DCHECK(dec_res.bytes_written <= kChunkSize);\n line_reader.EndWrite(dec_res.bytes_written);\n } while (dec_res.ret == ResultCode::kOk);\n return base::OkStatus();\n}\n\n\/\/ Common logic for both Decompress() and DecompressLines().\nbase::Status ZipFile::DoDecompressionChecks() const {\n PERFETTO_DCHECK(compressed_data_);\n\n if (hdr_.compression == kNoCompression) {\n PERFETTO_CHECK(hdr_.compressed_size == hdr_.uncompressed_size);\n return base::OkStatus();\n }\n\n if (hdr_.compression != kDeflate) {\n return base::ErrStatus(\"Zip compression mode not supported (%u)\",\n hdr_.compression);\n }\n\n if (!IsGzipSupported()) {\n return base::ErrStatus(\n \"Cannot open zip file. Gzip is not enabled in the current build. \"\n \"Rebuild with enable_perfetto_zlib=true\");\n }\n\n return base::OkStatus();\n}\n\n\/\/ Returns a 64-bit version of time_t, that is, the num seconds since the Epoch.\nuint64_t ZipFile::GetDatetime() const {\n \/\/ Date: 7 bits year, 4 bits month, 5 bits day.\n \/\/ Time: 5 bits hour, 6 bits minute, 5 bits second.\n struct tm mdt {};\n \/\/ As per man 3 mktime, `tm_year` is relative to 1900 not Epoch. Go figure.\n mdt.tm_year = 1980 + (hdr_.mdate >> (16 - 7)) - 1900;\n\n \/\/ As per the man page, the month ranges 0 to 11 (Jan = 0).\n mdt.tm_mon = ((hdr_.mdate >> (16 - 7 - 4)) & 0x0f) - 1;\n\n \/\/ However, still according to the same man page, the day starts from 1.\n mdt.tm_mday = hdr_.mdate & 0x1f;\n\n mdt.tm_hour = hdr_.mtime >> (16 - 5);\n mdt.tm_min = (hdr_.mtime >> (16 - 5 - 6)) & 0x3f;\n mdt.tm_sec = hdr_.mtime & 0x1f;\n return static_cast(mktime(&mdt));\n}\n\nstd::string ZipFile::GetDatetimeStr() const {\n char buf[32]{};\n time_t secs = static_cast(GetDatetime());\n strftime(buf, sizeof(buf), \"%Y-%m-%d %H:%M\", gmtime(&secs));\n buf[sizeof(buf) - 1] = '\\0';\n return buf;\n}\n\n} \/\/ namespace util\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\nTraceProcessor: use UTC in ZipReader\/*\n * Copyright (C) 2022 The Android Open Source Project\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 \"src\/trace_processor\/util\/zip_reader.h\"\n\n#include \n\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/utils.h\"\n#include \"src\/trace_processor\/util\/gzip_utils.h\"\n#include \"src\/trace_processor\/util\/streaming_line_reader.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n#include \/\/ For crc32().\n#endif\n\nnamespace perfetto {\nnamespace trace_processor {\nnamespace util {\n\nnamespace {\n\n\/\/ Entry signatures.\nconst uint32_t kFileHeaderSig = 0x04034b50;\nconst uint32_t kCentralDirectorySig = 0x02014b50;\n\n\/\/ Compression flags.\nconst uint16_t kNoCompression = 0;\nconst uint16_t kDeflate = 8;\n\ntemplate \nT ReadAndAdvance(const uint8_t** ptr) {\n T res{};\n memcpy(base::AssumeLittleEndian(&res), *ptr, sizeof(T));\n *ptr += sizeof(T);\n return res;\n}\n\n} \/\/ namespace\n\nZipReader::ZipReader() = default;\nZipReader::~ZipReader() = default;\n\nbase::Status ZipReader::Parse(const void* data, size_t len) {\n const uint8_t* input = static_cast(data);\n const uint8_t* const input_begin = input;\n const uint8_t* const input_end = input + len;\n auto input_avail = [&] { return static_cast(input_end - input); };\n\n \/\/ .zip file sequence:\n \/\/ [ File 1 header (30 bytes) ]\n \/\/ [ File 1 name ]\n \/\/ [ File 1 extra fields (optional) ]\n \/\/ [ File 1 compressed payload ]\n \/\/\n \/\/ [ File 2 header (30 bytes) ]\n \/\/ [ File 2 name ]\n \/\/ [ File 2 extra fields (optional) ]\n \/\/ [ File 2 compressed payload ]\n \/\/\n \/\/ [ Central directory (ignored) ]\n while (input < input_end) {\n \/\/ Initial state, we are building up the file header.\n if (cur_.raw_hdr_size < kZipFileHdrSize) {\n size_t copy_size =\n std::min(input_avail(), kZipFileHdrSize - cur_.raw_hdr_size);\n memcpy(&cur_.raw_hdr[cur_.raw_hdr_size], input, copy_size);\n cur_.raw_hdr_size += copy_size;\n input += copy_size;\n\n \/\/ If we got all the kZipFileHdrSize bytes, parse the zip file header now.\n if (cur_.raw_hdr_size == kZipFileHdrSize) {\n const uint8_t* hdr_it = &cur_.raw_hdr[0];\n cur_.hdr.signature = ReadAndAdvance(&hdr_it);\n if (cur_.hdr.signature == kCentralDirectorySig) {\n \/\/ We reached the central directory at the end of file.\n \/\/ We don't make any use here of the central directory, so we just\n \/\/ ignore everything else after this point.\n \/\/ Here we abuse the ZipFile class a bit. The Central Directory header\n \/\/ has a different layout. The first 4 bytes (signature) match, the\n \/\/ rest don't but the sizeof(central dir) is >> sizeof(file header) so\n \/\/ we are fine.\n \/\/ We do this rather than retuning because we could have further\n \/\/ Parse() calls (imagine parsing bytes one by one), and we need a way\n \/\/ to keep track of the \"keep eating input without doing anything\".\n cur_.ignore_bytes_after_fname = std::numeric_limits::max();\n input = input_end;\n break;\n }\n if (cur_.hdr.signature != kFileHeaderSig) {\n return base::ErrStatus(\n \"Invalid signature found at offset 0x%zx. Actual=%x, expected=%x\",\n static_cast(input - input_begin) - kZipFileHdrSize,\n cur_.hdr.signature, kFileHeaderSig);\n }\n\n cur_.hdr.version = ReadAndAdvance(&hdr_it);\n cur_.hdr.flags = ReadAndAdvance(&hdr_it);\n cur_.hdr.compression = ReadAndAdvance(&hdr_it);\n cur_.hdr.mtime = ReadAndAdvance(&hdr_it);\n cur_.hdr.mdate = ReadAndAdvance(&hdr_it);\n cur_.hdr.crc32 = ReadAndAdvance(&hdr_it);\n cur_.hdr.compressed_size = ReadAndAdvance(&hdr_it);\n cur_.hdr.uncompressed_size = ReadAndAdvance(&hdr_it);\n cur_.hdr.fname_len = ReadAndAdvance(&hdr_it);\n cur_.hdr.extra_field_len = ReadAndAdvance(&hdr_it);\n PERFETTO_DCHECK(static_cast(hdr_it - cur_.raw_hdr) ==\n kZipFileHdrSize);\n\n \/\/ We support only up to version 2.0 (20). Higher versions define\n \/\/ more advanced features that we don't support (zip64 extensions,\n \/\/ encryption).\n \/\/ Flag bits 1,2 define the compression strength for deflating (which\n \/\/ zlib supports transparently). Other bits define other compression\n \/\/ methods that we don't support.\n if ((cur_.hdr.version > 20) || (cur_.hdr.flags & ~3) != 0) {\n return base::ErrStatus(\n \"Unsupported zip features at offset 0x%zx. version=%x, flags=%x\",\n static_cast(input - input_begin) - kZipFileHdrSize,\n cur_.hdr.version, cur_.hdr.flags);\n }\n cur_.compressed_data.reset(new uint8_t[cur_.hdr.compressed_size]);\n cur_.ignore_bytes_after_fname = cur_.hdr.extra_field_len;\n }\n continue;\n }\n\n \/\/ Build up the file name.\n if (cur_.hdr.fname.size() < cur_.hdr.fname_len) {\n size_t name_left = cur_.hdr.fname_len - cur_.hdr.fname.size();\n size_t copy_size = std::min(name_left, input_avail());\n cur_.hdr.fname.append(reinterpret_cast(input), copy_size);\n input += copy_size;\n continue;\n }\n\n \/\/ Skip any bytes if extra fields were present.\n if (cur_.ignore_bytes_after_fname > 0) {\n size_t skip_size = std::min(input_avail(), cur_.ignore_bytes_after_fname);\n cur_.ignore_bytes_after_fname -= skip_size;\n input += skip_size;\n continue;\n }\n\n \/\/ Build up the compressed payload\n if (cur_.compressed_data_written < cur_.hdr.compressed_size) {\n size_t needed = cur_.hdr.compressed_size - cur_.compressed_data_written;\n size_t copy_size = std::min(needed, input_avail());\n memcpy(&cur_.compressed_data[cur_.compressed_data_written], input,\n copy_size);\n cur_.compressed_data_written += copy_size;\n input += copy_size;\n continue;\n }\n\n \/\/ We have accumulated the whole header, file name and compressed payload.\n PERFETTO_DCHECK(cur_.raw_hdr_size == kZipFileHdrSize);\n PERFETTO_DCHECK(cur_.hdr.fname.size() == cur_.hdr.fname_len);\n PERFETTO_DCHECK(cur_.compressed_data_written == cur_.hdr.compressed_size);\n PERFETTO_DCHECK(cur_.ignore_bytes_after_fname == 0);\n\n files_.emplace_back();\n files_.back().hdr_ = std::move(cur_.hdr);\n files_.back().compressed_data_ = std::move(cur_.compressed_data);\n cur_ = FileParseState(); \/\/ Reset the parsing state for the next file.\n\n } \/\/ while (input < input_end)\n\n \/\/ At this point we must have consumed all input.\n PERFETTO_DCHECK(input_avail() == 0);\n return base::OkStatus();\n}\n\nZipFile::ZipFile() = default;\nZipFile::~ZipFile() = default;\nZipFile::ZipFile(ZipFile&& other) noexcept = default;\nZipFile& ZipFile::operator=(ZipFile&& other) noexcept = default;\n\nbase::Status ZipFile::Decompress(std::vector* out_data) const {\n out_data->clear();\n\n auto res = DoDecompressionChecks();\n if (!res.ok())\n return res;\n\n if (hdr_.compression == kNoCompression) {\n const uint8_t* data = compressed_data_.get();\n out_data->insert(out_data->end(), data, data + hdr_.compressed_size);\n return base::OkStatus();\n }\n\n if (hdr_.uncompressed_size == 0)\n return base::OkStatus();\n\n PERFETTO_DCHECK(hdr_.compression == kDeflate);\n GzipDecompressor dec(GzipDecompressor::InputMode::kRawDeflate);\n dec.Feed(compressed_data_.get(), hdr_.compressed_size);\n\n out_data->resize(hdr_.uncompressed_size);\n auto dec_res = dec.ExtractOutput(out_data->data(), out_data->size());\n if (dec_res.ret != GzipDecompressor::ResultCode::kEof) {\n return base::ErrStatus(\"Zip decompression error (%d) on %s (c=%u, u=%u)\",\n static_cast(dec_res.ret), hdr_.fname.c_str(),\n hdr_.compressed_size, hdr_.uncompressed_size);\n }\n out_data->resize(dec_res.bytes_written);\n\n#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)\n const auto* crc_data = reinterpret_cast(out_data->data());\n auto crc_len = static_cast<::uInt>(out_data->size());\n auto actual_crc32 = static_cast(::crc32(0u, crc_data, crc_len));\n if (actual_crc32 != hdr_.crc32) {\n return base::ErrStatus(\"Zip CRC32 failure on %s (actual: %x, expected: %x)\",\n hdr_.fname.c_str(), actual_crc32, hdr_.crc32);\n }\n#endif\n\n return base::OkStatus();\n}\n\nbase::Status ZipFile::DecompressLines(LinesCallback callback) const {\n using ResultCode = GzipDecompressor::ResultCode;\n\n auto res = DoDecompressionChecks();\n if (!res.ok())\n return res;\n\n StreamingLineReader line_reader(callback);\n\n if (hdr_.compression == kNoCompression) {\n line_reader.Tokenize(\n base::StringView(reinterpret_cast(compressed_data_.get()),\n hdr_.compressed_size));\n return base::OkStatus();\n }\n\n PERFETTO_DCHECK(hdr_.compression == kDeflate);\n GzipDecompressor dec(GzipDecompressor::InputMode::kRawDeflate);\n dec.Feed(compressed_data_.get(), hdr_.compressed_size);\n\n static constexpr size_t kChunkSize = 32768;\n GzipDecompressor::Result dec_res;\n do {\n auto* wptr = reinterpret_cast(line_reader.BeginWrite(kChunkSize));\n dec_res = dec.ExtractOutput(wptr, kChunkSize);\n if (dec_res.ret == ResultCode::kError ||\n dec_res.ret == ResultCode::kNeedsMoreInput)\n return base::ErrStatus(\"zlib decompression error on %s (%d)\",\n name().c_str(), static_cast(dec_res.ret));\n PERFETTO_DCHECK(dec_res.bytes_written <= kChunkSize);\n line_reader.EndWrite(dec_res.bytes_written);\n } while (dec_res.ret == ResultCode::kOk);\n return base::OkStatus();\n}\n\n\/\/ Common logic for both Decompress() and DecompressLines().\nbase::Status ZipFile::DoDecompressionChecks() const {\n PERFETTO_DCHECK(compressed_data_);\n\n if (hdr_.compression == kNoCompression) {\n PERFETTO_CHECK(hdr_.compressed_size == hdr_.uncompressed_size);\n return base::OkStatus();\n }\n\n if (hdr_.compression != kDeflate) {\n return base::ErrStatus(\"Zip compression mode not supported (%u)\",\n hdr_.compression);\n }\n\n if (!IsGzipSupported()) {\n return base::ErrStatus(\n \"Cannot open zip file. Gzip is not enabled in the current build. \"\n \"Rebuild with enable_perfetto_zlib=true\");\n }\n\n return base::OkStatus();\n}\n\n\/\/ Returns a 64-bit version of time_t, that is, the num seconds since the Epoch.\nuint64_t ZipFile::GetDatetime() const {\n \/\/ Date: 7 bits year, 4 bits month, 5 bits day.\n \/\/ Time: 5 bits hour, 6 bits minute, 5 bits second.\n struct tm mdt {};\n \/\/ As per man 3 mktime, `tm_year` is relative to 1900 not Epoch. Go figure.\n mdt.tm_year = 1980 + (hdr_.mdate >> (16 - 7)) - 1900;\n\n \/\/ As per the man page, the month ranges 0 to 11 (Jan = 0).\n mdt.tm_mon = ((hdr_.mdate >> (16 - 7 - 4)) & 0x0f) - 1;\n\n \/\/ However, still according to the same man page, the day starts from 1.\n mdt.tm_mday = hdr_.mdate & 0x1f;\n\n mdt.tm_hour = hdr_.mtime >> (16 - 5);\n mdt.tm_min = (hdr_.mtime >> (16 - 5 - 6)) & 0x3f;\n mdt.tm_sec = hdr_.mtime & 0x1f;\n return static_cast(timegm(&mdt));\n}\n\nstd::string ZipFile::GetDatetimeStr() const {\n char buf[32]{};\n time_t secs = static_cast(GetDatetime());\n strftime(buf, sizeof(buf), \"%Y-%m-%d %H:%M\", gmtime(&secs));\n buf[sizeof(buf) - 1] = '\\0';\n return buf;\n}\n\n} \/\/ namespace util\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/**\n * This code is released under the\n * Apache License Version 2.0 http:\/\/www.apache.org\/licenses\/.\n *\n *\/\n\n\n#include \n#include \"synthetic.h\"\n#include \"timer.h\"\n#include \"intersection.h\"\n\n\/\/ https:\/\/code.google.com\/p\/likwid\/wiki\/LikwidPerfCtr#Using_the_marker_API\n#ifdef LIKWID_MARKERS \/\/ see 'make likwidintersection' for compiler flags\n#include \n#endif\n\n\/**\n * Goal: have the largest array count about 4M terms (this\n * matches our experiments), and vary the size of the\n * smallest array vary from 1*4M to 1\/1000*4M (or so).\n *\n * Set the size of the intersection to 30% of the lesser\n * array. (Again, this matches our real data...)\n *\n * To match our clueweb, we use a range of values in [0,2**26).\n *\/\ntemplate \npair, vector> getNaivePair(generator gen, uint32_t minlength, uint32_t Max, float sizeratio,\nfloat intersectionratio) {\n if (sizeratio < 1) throw runtime_error(\"sizeratio should be larger or equal to 1\");\n if (intersectionratio < 0) throw runtime_error(\"intersectionratio should be positive\");\n if (intersectionratio > 1) throw runtime_error(\"intersectionratio cannot be larger than 1\");\n const uint32_t maxlenth = static_cast(round(static_cast(minlength) * sizeratio));\n if (maxlenth > Max) throw runtime_error(\"I can't generate an array so large in such a small range.\");\n if (maxlenth < minlength) throw runtime_error(\"something went wrong, possibly an overflow.\");\n \/\/ we basically assume that, if we do nothing, intersections are very small\n const uint32_t intersize = static_cast(round(static_cast(minlength) * intersectionratio));\n\n vector inter = gen.generate(intersize, Max);\n vector smallest = unite(gen.generate(static_cast(minlength - inter.size()), Max), inter);\n vector largest = unite(gen.generate(static_cast(maxlenth - inter.size()), Max), inter);\n vector intersection = intersect(smallest, largest);\n if (largest.size() > smallest.size())\n return pair, vector>(smallest, largest);\n return pair, vector>(largest, smallest);\n\n}\n\n\n\nvoid printusage() {\n#ifdef LIKWID_MARKERS\n cout << \"example: likwid -m -C 1 -g BRANCH .\/likwidintersection -u > uniform.out\" << endl;\n#else\n cout << \" -u switches to uniform distribution\" << endl;\n#endif\n}\n\nint main(int argc, char **argv) {\n size_t howmany = 0;\n size_t loop = 3;\n bool uniform = false;\n uint32_t Big = 22;\n float intersectionratio = 0.3f;\n uint32_t MaxBit = 26;\n int c;\n while ((c = getopt(argc, argv, \"uns:m:R:M:S:l:h\")) != -1)\n switch (c) {\n case 'h':\n printusage();\n return 0;\n case 'S':\n Big = atoi(optarg);\n break;\n case 'R':\n intersectionratio = atof(optarg);\n break;\n case 'M':\n intersectionratio = atoi(optarg);\n if (MaxBit < 1) {\n printusage();\n return -1;\n }\n break;\n case 'm':\n howmany = atoi(optarg);\n if (howmany < 1) {\n printusage();\n return -1;\n }\n break;\n case 'l':\n loop = atoi(optarg);\n if (loop < 1) {\n printusage();\n return -1;\n }\n break;\n case 'u':\n uniform = true;\n break;\n default:\n abort();\n }\n if (howmany == 0) {\n howmany = 5;\n }\n cout << \"# howmany : \" << howmany << endl;\n cout << \"# loop : \" << loop << endl;\n cout << \"# distribution : \" << (uniform ? \"uniform\" : \"clustered\") << endl;\n cout << \"# Big : \" << Big << endl;\n cout << \"# intersectionratio : \" << intersectionratio << endl;\n cout << \"# MaxBit : \" << MaxBit << endl;\n UniformDataGenerator udg;\n ClusteredDataGenerator cdg;\n WallClockTimer z;\n size_t bogus = 0;\n vector buffer(2 * (1U << Big));\n#ifdef LIKWID_MARKERS\n char currentMarker[64];\n likwid_markerInit();\n#endif\n\n cout << \"# size-ratio\\t\";\n for (string intername : IntersectionFactory::allNames()) {\n cout << intername << \"\\t\";\n }\n cout << \"relative-intersection-size \" << endl;\n\n for (float ir = 1.001; ir <= 10000; ir = ir * sqrt(1.9)) {\n vector , vector>> data(howmany);\n uint32_t smallsize = static_cast(round(static_cast(1 << Big) \/ ir));\n cout << \"#generating data...\";\n cout.flush();\n for (size_t k = 0; k < howmany; ++k) {\n data[k] = uniform ? getNaivePair(udg , smallsize, 1U << MaxBit, ir, intersectionratio)\n : getNaivePair(cdg , smallsize, 1U << MaxBit, ir, intersectionratio);\n }\n cout << \"ok.\" << endl;\n cout << ir << \"\\t\";\n float aratio = 0.0f;\n for (string intername : IntersectionFactory::allNames()) {\n intersectionfunction interfnc = IntersectionFactory::getFromName(intername);\n size_t volume = 0;\n#ifdef LIKWID_MARKERS\n snprintf(currentMarker, sizeof(currentMarker), \"%s %.2f\", intername.c_str(), ir);\n likwid_markerStartRegion(currentMarker);\n#endif\n z.reset();\n for (size_t k = 0; k < data.size(); ++k) {\n volume += (data[k].first.size() + data[k].second.size()) * loop;\n for (size_t L = 0; L < loop; ++L) {\n aratio = interfnc(data[k].first.data(),\n (data[k].first).size(), data[k].second.data(),\n (data[k].second).size(), buffer.data());\n bogus += aratio;\n }\n }\n cout << setw(10) << setprecision(5) << (volume \/ (static_cast(z.split()))) << \"\\t\";\n#ifdef LIKWID_MARKERS\n likwid_markerStopRegion(currentMarker);\n#endif\n }\n cout << \"\\t\\t\" << aratio \/ smallsize;\n cout << endl;\n\n }\n#ifdef LIKWID_MARKERS\n likwid_markerClose();\n#endif\n\n cout << \"# bogus = \" << bogus << endl;\n}\nFixing minor typo\/**\n * This code is released under the\n * Apache License Version 2.0 http:\/\/www.apache.org\/licenses\/.\n *\n *\/\n\n\n#include \n#include \"synthetic.h\"\n#include \"timer.h\"\n#include \"intersection.h\"\n\n\/\/ https:\/\/code.google.com\/p\/likwid\/wiki\/LikwidPerfCtr#Using_the_marker_API\n#ifdef LIKWID_MARKERS \/\/ see 'make likwidintersection' for compiler flags\n#include \n#endif\n\n\/**\n * Goal: have the largest array count about 4M terms (this\n * matches our experiments), and vary the size of the\n * smallest array vary from 1*4M to 1\/1000*4M (or so).\n *\n * Set the size of the intersection to 30% of the lesser\n * array. (Again, this matches our real data...)\n *\n * To match our clueweb, we use a range of values in [0,2**26).\n *\/\ntemplate \npair, vector> getNaivePair(generator gen, uint32_t minlength, uint32_t Max, float sizeratio,\nfloat intersectionratio) {\n if (sizeratio < 1) throw runtime_error(\"sizeratio should be larger or equal to 1\");\n if (intersectionratio < 0) throw runtime_error(\"intersectionratio should be positive\");\n if (intersectionratio > 1) throw runtime_error(\"intersectionratio cannot be larger than 1\");\n const uint32_t maxlenth = static_cast(round(static_cast(minlength) * sizeratio));\n if (maxlenth > Max) throw runtime_error(\"I can't generate an array so large in such a small range.\");\n if (maxlenth < minlength) throw runtime_error(\"something went wrong, possibly an overflow.\");\n \/\/ we basically assume that, if we do nothing, intersections are very small\n const uint32_t intersize = static_cast(round(static_cast(minlength) * intersectionratio));\n\n vector inter = gen.generate(intersize, Max);\n vector smallest = unite(gen.generate(static_cast(minlength - inter.size()), Max), inter);\n vector largest = unite(gen.generate(static_cast(maxlenth - inter.size()), Max), inter);\n vector intersection = intersect(smallest, largest);\n if (largest.size() > smallest.size())\n return pair, vector>(smallest, largest);\n return pair, vector>(largest, smallest);\n\n}\n\n\n\nvoid printusage() {\n#ifdef LIKWID_MARKERS\n cout << \"example: likwid -m -C 1 -g BRANCH .\/likwidintersection -u > uniform.out\" << endl;\n#else\n cout << \" -u switches to uniform distribution\" << endl;\n#endif\n}\n\nint main(int argc, char **argv) {\n size_t howmany = 0;\n size_t loop = 3;\n bool uniform = false;\n uint32_t Big = 22;\n float intersectionratio = 0.3f;\n uint32_t MaxBit = 26;\n int c;\n while ((c = getopt(argc, argv, \"uns:m:R:M:S:l:h\")) != -1)\n switch (c) {\n case 'h':\n printusage();\n return 0;\n case 'S':\n Big = atoi(optarg);\n break;\n case 'R':\n intersectionratio = atof(optarg);\n break;\n case 'M':\n MaxBit = atoi(optarg);\n if (MaxBit < 1) {\n printusage();\n return -1;\n }\n break;\n case 'm':\n howmany = atoi(optarg);\n if (howmany < 1) {\n printusage();\n return -1;\n }\n break;\n case 'l':\n loop = atoi(optarg);\n if (loop < 1) {\n printusage();\n return -1;\n }\n break;\n case 'u':\n uniform = true;\n break;\n default:\n abort();\n }\n if (howmany == 0) {\n howmany = 5;\n }\n cout << \"# howmany : \" << howmany << endl;\n cout << \"# loop : \" << loop << endl;\n cout << \"# distribution : \" << (uniform ? \"uniform\" : \"clustered\") << endl;\n cout << \"# Big : \" << Big << endl;\n cout << \"# intersectionratio : \" << intersectionratio << endl;\n cout << \"# MaxBit : \" << MaxBit << endl;\n UniformDataGenerator udg;\n ClusteredDataGenerator cdg;\n WallClockTimer z;\n size_t bogus = 0;\n vector buffer(2 * (1U << Big));\n#ifdef LIKWID_MARKERS\n char currentMarker[64];\n likwid_markerInit();\n#endif\n\n cout << \"# size-ratio\\t\";\n for (string intername : IntersectionFactory::allNames()) {\n cout << intername << \"\\t\";\n }\n cout << \"relative-intersection-size \" << endl;\n\n for (float ir = 1.001; ir <= 10000; ir = ir * sqrt(1.9)) {\n vector , vector>> data(howmany);\n uint32_t smallsize = static_cast(round(static_cast(1 << Big) \/ ir));\n cout << \"#generating data...\";\n cout.flush();\n for (size_t k = 0; k < howmany; ++k) {\n data[k] = uniform ? getNaivePair(udg , smallsize, 1U << MaxBit, ir, intersectionratio)\n : getNaivePair(cdg , smallsize, 1U << MaxBit, ir, intersectionratio);\n }\n cout << \"ok.\" << endl;\n cout << ir << \"\\t\";\n float aratio = 0.0f;\n for (string intername : IntersectionFactory::allNames()) {\n intersectionfunction interfnc = IntersectionFactory::getFromName(intername);\n size_t volume = 0;\n#ifdef LIKWID_MARKERS\n snprintf(currentMarker, sizeof(currentMarker), \"%s %.2f\", intername.c_str(), ir);\n likwid_markerStartRegion(currentMarker);\n#endif\n z.reset();\n for (size_t k = 0; k < data.size(); ++k) {\n volume += (data[k].first.size() + data[k].second.size()) * loop;\n for (size_t L = 0; L < loop; ++L) {\n aratio = interfnc(data[k].first.data(),\n (data[k].first).size(), data[k].second.data(),\n (data[k].second).size(), buffer.data());\n bogus += aratio;\n }\n }\n cout << setw(10) << setprecision(5) << (volume \/ (static_cast(z.split()))) << \"\\t\";\n#ifdef LIKWID_MARKERS\n likwid_markerStopRegion(currentMarker);\n#endif\n }\n cout << \"\\t\\t\" << aratio \/ smallsize;\n cout << endl;\n\n }\n#ifdef LIKWID_MARKERS\n likwid_markerClose();\n#endif\n\n cout << \"# bogus = \" << bogus << endl;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef NEKTAR_USE_EXPRESSION_TEMPLATES\n#define NEKTAR_USE_EXPRESSION_TEMPLATES\n#endif \/\/NEKTAR_USE_EXPRESSION_TEMPLATES\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nektar\n{\n namespace UnitTests\n {\n BOOST_AUTO_TEST_CASE(TestMatrixSizeConstantNode)\n {\n typedef NekMatrix Matrix;\n typedef NekVector Vector;\n\n typedef Node LhsNode; \n typedef Node RhsNode;\n typedef Node Expression;\n typedef Expression::Indices Indices;\n\n double m_buf[] = {1, 4, 2, 5, 3, 6};\n double v_buf[] = {1, 2, 3};\n Matrix m(2, 3, m_buf);\n Vector v(3, v_buf);\n\n Expression e = m*v;\n \n boost::tuple sizes = \n MatrixSize::GetRequiredSize(e.GetData());\n\n unsigned int rows = sizes.get<0>();\n unsigned int cols = sizes.get<1>();\n unsigned int bufferSize = sizes.get<2>();\n \n BOOST_CHECK_EQUAL(rows, 2u);\n BOOST_CHECK_EQUAL(cols, 3u);\n BOOST_CHECK_EQUAL(bufferSize, rows*cols);\n \n rows = 0;\n cols = 0;\n bufferSize = 0;\n sizes = MatrixSize::GetRequiredSize(e.GetData());\n rows = sizes.get<0>();\n cols = sizes.get<1>();\n bufferSize = sizes.get<2>();\n \n BOOST_CHECK_EQUAL(rows, 3u);\n BOOST_CHECK_EQUAL(cols, 1u);\n BOOST_CHECK_EQUAL(bufferSize, rows*cols);\n\n sizes = MatrixSize::GetRequiredSize(e.GetData());\n rows = sizes.get<0>();\n cols = sizes.get<1>();\n bufferSize = sizes.get<2>();\n BOOST_CHECK_EQUAL(rows, 2u);\n BOOST_CHECK_EQUAL(cols, 1u);\n BOOST_CHECK_EQUAL(bufferSize, rows*cols);\n }\n\n \n BOOST_AUTO_TEST_CASE(TestConstantConstantTree)\n {\n typedef Node > LhsNode;\n BOOST_MPL_ASSERT(( boost::is_same > ));\n BOOST_MPL_ASSERT(( boost::is_same&> ));\n \n typedef Node > RhsNode;\n typedef Node Expression;\n typedef Expression::Indices Indices;\n\n typedef RemoveUnecessaryTemporaries::TransformedNodeType TransformedNodeType;\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n typedef RemoveUnecessaryTemporaries::TransformedIndices TransformedIndices;\n BOOST_STATIC_ASSERT(( boost::mpl::size::type::value == 2 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 0 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 1 ));\n\n typedef boost::fusion::vector2&, const CountedObject&> ExpectedListType;\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n CountedObject lhs(3);\n CountedObject rhs(17);\n CountedObject::ClearCounters();\n\n Expression e = lhs + rhs;\n CountedObject::Check(0, 0, 0, 0, 0, 0);\n CountedObject result = lhs + rhs;\n CountedObject::Check(0, 0, 0, 0, 0, 0);\n BOOST_CHECK_EQUAL( CountedObject::numberOfExpressionConstructions, 1 );\n BOOST_CHECK_EQUAL( CountedObject::numberOfExpressionAssignments, 0 );\n\n BOOST_CHECK_EQUAL(result.value, lhs.value + rhs.value);\n }\n\n BOOST_AUTO_TEST_CASE(TestConstantConstantTreeVaryDataType)\n {\n typedef NekMatrix Matrix;\n typedef NekVector Vector;\n\n typedef Node LhsNode;\n BOOST_MPL_ASSERT(( boost::is_same ));\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n typedef Node RhsNode;\n typedef Node Expression;\n typedef Expression::Indices Indices;\n\n typedef RemoveUnecessaryTemporaries::TransformedNodeType TransformedNodeType;\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n typedef RemoveUnecessaryTemporaries::TransformedIndices TransformedIndices;\n BOOST_STATIC_ASSERT(( boost::mpl::size::type::value == 2 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 0 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 1 ));\n\n typedef boost::fusion::vector2 ExpectedListType;\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n double m_buf[] = {1, 4, 2, 5, 3, 6};\n double v_buf[] = {1, 2, 3};\n Matrix m(2, 3, m_buf);\n Vector v(3, v_buf);\n\n Expression e = m*v;\n Vector result = m*v;\n\n double expected_result_buf[] = {1+4+9, 4+10+18};\n Vector expected_result(2, expected_result_buf); \n BOOST_CHECK_EQUAL(result, expected_result);\n }\n\n }\n\n BOOST_AUTO_TEST_CASE(TestBinaryBinaryMatrixTree)\n {\n typedef NekMatrix Matrix;\n double m_buf[] = {1, 4, 2, 5};\n Matrix m1(2, 2, m_buf);\n Matrix m2(2, 2, m_buf);\n Matrix m3(2, 2, m_buf);\n Matrix m4(2, 2, m_buf);\n\n Array gmat;\n\n Matrix result = m1*m2 + m3*m4;\n \/\/Matrix result1 = (gmat[0][0]*gmat[0][0]+gmat[2][0]*gmat[2][0]+gmat[4][0]*gmat[4][0])* (m1) + \n \/\/ (gmat[0][0]*gmat[1][0] + gmat[2][0]*gmat[3][0] + gmat[4][0]*gmat[5][0])*(m2 + Transpose(m2)) +\n \/\/ (gmat[1][0]*gmat[1][0] + gmat[3][0]*gmat[3][0] + gmat[5][0]*gmat[5][0])* (m3);\n \/\/Matrix result2 = (1.0)*(m1) + (2.0)*(m2) + (3.0)*(m3);\n \n \/\/Matrix result3 = m1*m1 + m2*m2 + m3*m3;\n typedef Node, MultiplyOp, Node > T;\n typedef Node Lhs;\n typedef T Rhs;\n typedef Node ExpressionType;\n ExpressionType e = m1*m1 + m2*m2 + m3*m3;\n typedef ExpressionType::Indices Indices;\n\n \/\/typedef RemoveUnecessaryTemporaries::TransformedNodeType TransformedNodeType;\n typedef RemoveUnecessaryTemporaries::TransformedIndices TransformedIndices;\n }\n}\nBoost version-dependent fix for ExpressionTemplates unit tests.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef NEKTAR_USE_EXPRESSION_TEMPLATES\n#define NEKTAR_USE_EXPRESSION_TEMPLATES\n#endif \/\/NEKTAR_USE_EXPRESSION_TEMPLATES\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nektar\n{\n namespace UnitTests\n {\n BOOST_AUTO_TEST_CASE(TestMatrixSizeConstantNode)\n {\n typedef NekMatrix Matrix;\n typedef NekVector Vector;\n\n typedef Node LhsNode; \n typedef Node RhsNode;\n typedef Node Expression;\n typedef Expression::Indices Indices;\n\n double m_buf[] = {1, 4, 2, 5, 3, 6};\n double v_buf[] = {1, 2, 3};\n Matrix m(2, 3, m_buf);\n Vector v(3, v_buf);\n\n Expression e = m*v;\n \n boost::tuple sizes = \n MatrixSize::GetRequiredSize(e.GetData());\n\n unsigned int rows = sizes.get<0>();\n unsigned int cols = sizes.get<1>();\n unsigned int bufferSize = sizes.get<2>();\n \n BOOST_CHECK_EQUAL(rows, 2u);\n BOOST_CHECK_EQUAL(cols, 3u);\n BOOST_CHECK_EQUAL(bufferSize, rows*cols);\n \n rows = 0;\n cols = 0;\n bufferSize = 0;\n sizes = MatrixSize::GetRequiredSize(e.GetData());\n rows = sizes.get<0>();\n cols = sizes.get<1>();\n bufferSize = sizes.get<2>();\n \n BOOST_CHECK_EQUAL(rows, 3u);\n BOOST_CHECK_EQUAL(cols, 1u);\n BOOST_CHECK_EQUAL(bufferSize, rows*cols);\n\n sizes = MatrixSize::GetRequiredSize(e.GetData());\n rows = sizes.get<0>();\n cols = sizes.get<1>();\n bufferSize = sizes.get<2>();\n BOOST_CHECK_EQUAL(rows, 2u);\n BOOST_CHECK_EQUAL(cols, 1u);\n BOOST_CHECK_EQUAL(bufferSize, rows*cols);\n }\n\n \n BOOST_AUTO_TEST_CASE(TestConstantConstantTree)\n {\n typedef Node > LhsNode;\n BOOST_MPL_ASSERT(( boost::is_same > ));\n BOOST_MPL_ASSERT(( boost::is_same&> ));\n \n typedef Node > RhsNode;\n typedef Node Expression;\n typedef Expression::Indices Indices;\n\n typedef RemoveUnecessaryTemporaries::TransformedNodeType TransformedNodeType;\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n typedef RemoveUnecessaryTemporaries::TransformedIndices TransformedIndices;\n BOOST_STATIC_ASSERT(( boost::mpl::size::type::value == 2 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 0 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 1 ));\n\n#if BOOST_VERSION < 104200\n typedef boost::fusion::vector&, const CountedObject&> ExpectedListType;\n#else\n typedef boost::fusion::vector2&, const CountedObject&> ExpectedListType;\n#endif\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n CountedObject lhs(3);\n CountedObject rhs(17);\n CountedObject::ClearCounters();\n\n Expression e = lhs + rhs;\n CountedObject::Check(0, 0, 0, 0, 0, 0);\n CountedObject result = lhs + rhs;\n CountedObject::Check(0, 0, 0, 0, 0, 0);\n BOOST_CHECK_EQUAL( CountedObject::numberOfExpressionConstructions, 1 );\n BOOST_CHECK_EQUAL( CountedObject::numberOfExpressionAssignments, 0 );\n\n BOOST_CHECK_EQUAL(result.value, lhs.value + rhs.value);\n }\n\n BOOST_AUTO_TEST_CASE(TestConstantConstantTreeVaryDataType)\n {\n typedef NekMatrix Matrix;\n typedef NekVector Vector;\n\n typedef Node LhsNode;\n BOOST_MPL_ASSERT(( boost::is_same ));\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n typedef Node RhsNode;\n typedef Node Expression;\n typedef Expression::Indices Indices;\n\n typedef RemoveUnecessaryTemporaries::TransformedNodeType TransformedNodeType;\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n typedef RemoveUnecessaryTemporaries::TransformedIndices TransformedIndices;\n BOOST_STATIC_ASSERT(( boost::mpl::size::type::value == 2 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 0 ));\n BOOST_STATIC_ASSERT(( boost::mpl::at_c::type::value == 1 ));\n\n#if BOOST_VERSION < 104200\n typedef boost::fusion::vector ExpectedListType;\n#else\n typedef boost::fusion::vector2 ExpectedListType;\n#endif\n BOOST_MPL_ASSERT(( boost::is_same ));\n \n double m_buf[] = {1, 4, 2, 5, 3, 6};\n double v_buf[] = {1, 2, 3};\n Matrix m(2, 3, m_buf);\n Vector v(3, v_buf);\n\n Expression e = m*v;\n Vector result = m*v;\n\n double expected_result_buf[] = {1+4+9, 4+10+18};\n Vector expected_result(2, expected_result_buf); \n BOOST_CHECK_EQUAL(result, expected_result);\n }\n\n }\n\n BOOST_AUTO_TEST_CASE(TestBinaryBinaryMatrixTree)\n {\n typedef NekMatrix Matrix;\n double m_buf[] = {1, 4, 2, 5};\n Matrix m1(2, 2, m_buf);\n Matrix m2(2, 2, m_buf);\n Matrix m3(2, 2, m_buf);\n Matrix m4(2, 2, m_buf);\n\n Array gmat;\n\n Matrix result = m1*m2 + m3*m4;\n \/\/Matrix result1 = (gmat[0][0]*gmat[0][0]+gmat[2][0]*gmat[2][0]+gmat[4][0]*gmat[4][0])* (m1) + \n \/\/ (gmat[0][0]*gmat[1][0] + gmat[2][0]*gmat[3][0] + gmat[4][0]*gmat[5][0])*(m2 + Transpose(m2)) +\n \/\/ (gmat[1][0]*gmat[1][0] + gmat[3][0]*gmat[3][0] + gmat[5][0]*gmat[5][0])* (m3);\n \/\/Matrix result2 = (1.0)*(m1) + (2.0)*(m2) + (3.0)*(m3);\n \n \/\/Matrix result3 = m1*m1 + m2*m2 + m3*m3;\n typedef Node, MultiplyOp, Node > T;\n typedef Node Lhs;\n typedef T Rhs;\n typedef Node ExpressionType;\n ExpressionType e = m1*m1 + m2*m2 + m3*m3;\n typedef ExpressionType::Indices Indices;\n\n \/\/typedef RemoveUnecessaryTemporaries::TransformedNodeType TransformedNodeType;\n typedef RemoveUnecessaryTemporaries::TransformedIndices TransformedIndices;\n }\n}\n<|endoftext|>"} {"text":"#ifndef _SDD_MANAGER_HH_\n#define _SDD_MANAGER_HH_\n\n#include \/\/ runtime_error\n\n#include \"sdd\/internal_manager.hh\"\n#include \"sdd\/values_manager.hh\"\n\nnamespace sdd {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief This class represents the global context of the library.\n\/\/\/\n\/\/\/ It can only be created by the init() function. It is safe to use the library as long as the\n\/\/\/ instance returned by manager::init() exists.\ntemplate \nclass manager final\n{\n \/\/ Can't copy a manager.\n manager(const manager&) = delete;\n manager& operator=(const manager&) = delete;\n\nprivate:\n\n \/\/\/ @brief The type of a set of values.\n using values_type = typename C::Values;\n\n \/\/\/ @brief Keep the configuration.\n const C conf_;\n\n \/\/\/ @brief The manager of Values.\n values_manager* values_;\n\n \/\/\/ @brief The manager of SDD and homomorphisms.\n internal_manager* m_;\n\n \/\/\/ @brief Construct a manager from an internal manager.\n manager(const C& conf, values_manager* v, internal_manager* m)\n : conf_(conf), values_(v), m_(m)\n {}\n\npublic:\n\n \/\/\/ @brief Initialize the library for a specific configuration.\n \/\/\/ @tparam C The configuration type.\n \/\/\/ @param configuration An instance of the configuration with some parameters set.\n \/\/\/ @throw std::runtime_error if the library was already configured.\n \/\/\/\n \/\/\/ It must be the first function called before any other call to the library.\n static\n manager\n init(const C& configuration = C())\n {\n if (*global_ptr() == nullptr and *global_ptr() == nullptr)\n {\n values_manager* v = new values_manager(configuration);\n if (not v)\n {\n throw std::runtime_error(\"Can't allocate values manager.\");\n }\n\n *global_values_ptr() = v;\n\n internal_manager* g = new internal_manager(configuration);\n if (not g)\n {\n delete v;\n throw std::runtime_error(\"Can't allocate internal manager.\");\n }\n *global_ptr() = g;\n\n return manager(configuration, v, g);\n }\n else\n {\n throw std::runtime_error(\"Library already initialized.\");\n }\n }\n\n \/\/\/ @brief Destructor.\n ~manager()\n {\n if (m_)\n {\n *global_ptr() = nullptr;\n if (conf_.final_cleanup)\n {\n delete m_;\n }\n }\n if (values_)\n {\n *global_values_ptr() = nullptr;\n if (conf_.final_cleanup)\n {\n delete values_;\n }\n }\n }\n\n \/\/\/ @brief Reset homomorphisms evaluation cache.\n void\n reset_hom_cache()\n {\n m_->hom_context.clear();\n }\n\n \/\/\/ @brief Get the statistics for SDDs.\n mem::unique_table_statistics\n sdd_stats()\n const noexcept\n {\n return m_->sdd_unique_table.stats();\n }\n\n \/\/\/ @brief Get the statistics for homomorphisms.\n mem::unique_table_statistics\n hom_stats()\n const noexcept\n {\n return m_->hom_unique_table.stats();\n }\n\n \/\/\/ @brief Default move constructor.\n manager(manager&&) = default;\n\n \/\/\/ @brief Default move operator.\n manager& operator=(manager&&) = default;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\n#endif \/\/ _SDD_MANAGER_HH_\nStatistics are internal stuff.#ifndef _SDD_MANAGER_HH_\n#define _SDD_MANAGER_HH_\n\n#include \/\/ runtime_error\n\n#include \"sdd\/internal_manager.hh\"\n#include \"sdd\/values_manager.hh\"\n\nnamespace sdd {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief This class represents the global context of the library.\n\/\/\/\n\/\/\/ It can only be created by the init() function. It is safe to use the library as long as the\n\/\/\/ instance returned by manager::init() exists.\ntemplate \nclass manager final\n{\n \/\/ Can't copy a manager.\n manager(const manager&) = delete;\n manager& operator=(const manager&) = delete;\n\nprivate:\n\n \/\/\/ @brief The type of a set of values.\n using values_type = typename C::Values;\n\n \/\/\/ @brief Keep the configuration.\n const C conf_;\n\n \/\/\/ @brief The manager of Values.\n values_manager* values_;\n\n \/\/\/ @brief The manager of SDD and homomorphisms.\n internal_manager* m_;\n\n \/\/\/ @brief Construct a manager from an internal manager.\n manager(const C& conf, values_manager* v, internal_manager* m)\n : conf_(conf), values_(v), m_(m)\n {}\n\npublic:\n\n \/\/\/ @brief Initialize the library for a specific configuration.\n \/\/\/ @tparam C The configuration type.\n \/\/\/ @param configuration An instance of the configuration with some parameters set.\n \/\/\/ @throw std::runtime_error if the library was already configured.\n \/\/\/\n \/\/\/ It must be the first function called before any other call to the library.\n static\n manager\n init(const C& configuration = C())\n {\n if (*global_ptr() == nullptr and *global_ptr() == nullptr)\n {\n values_manager* v = new values_manager(configuration);\n if (not v)\n {\n throw std::runtime_error(\"Can't allocate values manager.\");\n }\n\n *global_values_ptr() = v;\n\n internal_manager* g = new internal_manager(configuration);\n if (not g)\n {\n delete v;\n throw std::runtime_error(\"Can't allocate internal manager.\");\n }\n *global_ptr() = g;\n\n return manager(configuration, v, g);\n }\n else\n {\n throw std::runtime_error(\"Library already initialized.\");\n }\n }\n\n \/\/\/ @brief Destructor.\n ~manager()\n {\n if (m_)\n {\n *global_ptr() = nullptr;\n if (conf_.final_cleanup)\n {\n delete m_;\n }\n }\n if (values_)\n {\n *global_values_ptr() = nullptr;\n if (conf_.final_cleanup)\n {\n delete values_;\n }\n }\n }\n\n \/\/\/ @brief Default move constructor.\n manager(manager&&) = default;\n\n \/\/\/ @brief Default move operator.\n manager& operator=(manager&&) = default;\n\n \/\/\/ @brief Reset homomorphisms evaluation cache.\n void\n reset_hom_cache()\n {\n m_->hom_context.clear();\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get the statistics for SDDs.\n mem::unique_table_statistics\n sdd_stats()\n const noexcept\n {\n return m_->sdd_unique_table.stats();\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get the statistics for homomorphisms.\n mem::unique_table_statistics\n hom_stats()\n const noexcept\n {\n return m_->hom_unique_table.stats();\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\n#endif \/\/ _SDD_MANAGER_HH_\n<|endoftext|>"} {"text":"\/**\n * @file hoeffding_tree_main.cpp\n * @author Ryan Curtin\n *\n * A command-line executable that can build a streaming decision tree.\n *\/\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::data;\n\nPARAM_STRING(\"training_file\", \"Training dataset file.\", \"t\", \"\");\nPARAM_STRING(\"labels_file\", \"Labels for training dataset.\", \"l\", \"\");\n\nPARAM_DOUBLE(\"confidence\", \"Confidence before splitting (between 0 and 1).\",\n \"c\", 0.95);\nPARAM_INT(\"max_samples\", \"Maximum number of samples before splitting.\", \"n\",\n 5000);\n\nPARAM_STRING(\"input_model_file\", \"File to load trained tree from.\", \"m\", \"\");\nPARAM_STRING(\"output_model_file\", \"File to save trained tree to.\", \"M\", \"\");\n\nPARAM_STRING(\"test_file\", \"File of testing data.\", \"T\", \"\");\nPARAM_STRING(\"predictions_file\", \"File to output label predictions for test \"\n \"data into.\", \"p\", \"\");\nPARAM_STRING(\"probabilities_file\", \"In addition to predicting labels, provide \"\n \"prediction probabilities in this file.\", \"P\", \"\");\n\nPARAM_STRING(\"numeric_split_strategy\", \"The splitting strategy to use for \"\n \"numeric features: 'domingos' or 'binary'.\", \"N\", \"binary\");\nPARAM_FLAG(\"batch_mode\", \"If true, samples will be considered in batch instead \"\n \"of as a stream. This generally results in better trees but at the cost of\"\n \" memory usage and runtime.\", \"b\");\nPARAM_FLAG(\"info_gain\", \"If set, information gain is used instead of Gini \"\n \"impurity for calculating Hoeffding bounds.\", \"i\");\nPARAM_INT(\"passes\", \"Number of passes to take over the dataset.\", \"s\", 1);\n\nPARAM_INT(\"bins\", \"If the 'domingos' split strategy is used, this specifies \"\n \"the number of bins for each numeric split.\", \"B\", 10);\nPARAM_INT(\"observations_before_binning\", \"If the 'domingos' split strategy is \"\n \"used, this specifies the number of samples observed before binning is \"\n \"performed.\", \"o\", 100);\n\n\/\/ Helper function for once we have chosen a tree type.\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit =\n typename TreeType::NumericSplit(0));\n\nint main(int argc, char** argv)\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Check input parameters for validity.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n const string numericSplitStrategy =\n CLI::GetParam(\"numeric_split_strategy\");\n\n if ((!predictionsFile.empty() || !probabilitiesFile.empty()) &&\n testFile.empty())\n Log::Fatal << \"--test_file must be specified if --predictions_file or \"\n << \"--probabilities_file is specified.\" << endl;\n\n if (trainingFile.empty() && inputModelFile.empty())\n Log::Fatal << \"One of --training_file or --input_model_file must be \"\n << \"specified!\" << endl;\n\n if (!trainingFile.empty() && labelsFile.empty())\n Log::Fatal << \"If --training_file is specified, --labels_file must be \"\n << \"specified too!\" << endl;\n\n if (trainingFile.empty() && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored; no training set provided.\" << endl;\n\n if (CLI::HasParam(\"passes\") && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored because --passes was specified.\"\n << endl;\n\n if (CLI::HasParam(\"info_gain\"))\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n else\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n}\n\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit)\n{\n \/\/ Load necessary parameters.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const double confidence = CLI::GetParam(\"confidence\");\n const size_t maxSamples = (size_t) CLI::GetParam(\"max_samples\");\n const size_t minSamples = (size_t) CLI::GetParam(\"min_samples\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string outputModelFile = CLI::GetParam(\"output_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n bool batchTraining = CLI::HasParam(\"batch_mode\");\n const size_t passes = (size_t) CLI::GetParam(\"passes\");\n if (passes > 1)\n batchTraining = false; \/\/ We already warned about this earlier.\n\n TreeType* tree = NULL;\n DatasetInfo datasetInfo;\n if (inputModelFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n\n tree = new TreeType(trainingSet, datasetInfo, labels, max(labels) + 1,\n batchTraining, confidence, maxSamples, 100, minSamples,\n typename TreeType::CategoricalSplit(0, 0), numericSplit);\n\n for (size_t i = 1; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n Timer::Stop(\"tree_training\");\n }\n else\n {\n tree = new TreeType(datasetInfo, 1, 1);\n data::Load(inputModelFile, \"streamingDecisionTree\", *tree, true);\n\n if (!trainingFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n {\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n for (size_t i = 0; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n }\n else\n {\n tree->Train(trainingSet, labels, batchTraining);\n }\n Timer::Stop(\"tree_training\");\n }\n }\n\n \/\/ The tree is trained or loaded. Now do any testing if we need.\n if (!testFile.empty())\n {\n arma::mat testSet;\n data::Load(testFile, testSet, datasetInfo, true);\n\n arma::Row predictions;\n arma::rowvec probabilities;\n\n Timer::Start(\"tree_testing\");\n tree->Classify(testSet, predictions, probabilities);\n Timer::Stop(\"tree_testing\");\n\n if (!predictionsFile.empty())\n data::Save(predictionsFile, predictions);\n\n if (!probabilitiesFile.empty())\n data::Save(probabilitiesFile, probabilities);\n }\n\n \/\/ Check the accuracy on the training set.\n if (!outputModelFile.empty())\n data::Save(outputModelFile, \"streamingDecisionTree\", tree, true);\n\n \/\/ Clean up memory.\n delete tree;\n}\nAdd min_samples option.\/**\n * @file hoeffding_tree_main.cpp\n * @author Ryan Curtin\n *\n * A command-line executable that can build a streaming decision tree.\n *\/\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::data;\n\nPARAM_STRING(\"training_file\", \"Training dataset file.\", \"t\", \"\");\nPARAM_STRING(\"labels_file\", \"Labels for training dataset.\", \"l\", \"\");\n\nPARAM_DOUBLE(\"confidence\", \"Confidence before splitting (between 0 and 1).\",\n \"c\", 0.95);\nPARAM_INT(\"max_samples\", \"Maximum number of samples before splitting.\", \"n\",\n 5000);\nPARAM_INT(\"min_samples\", \"Minimum number of samples before splitting.\", \"I\",\n 100);\n\nPARAM_STRING(\"input_model_file\", \"File to load trained tree from.\", \"m\", \"\");\nPARAM_STRING(\"output_model_file\", \"File to save trained tree to.\", \"M\", \"\");\n\nPARAM_STRING(\"test_file\", \"File of testing data.\", \"T\", \"\");\nPARAM_STRING(\"predictions_file\", \"File to output label predictions for test \"\n \"data into.\", \"p\", \"\");\nPARAM_STRING(\"probabilities_file\", \"In addition to predicting labels, provide \"\n \"prediction probabilities in this file.\", \"P\", \"\");\n\nPARAM_STRING(\"numeric_split_strategy\", \"The splitting strategy to use for \"\n \"numeric features: 'domingos' or 'binary'.\", \"N\", \"binary\");\nPARAM_FLAG(\"batch_mode\", \"If true, samples will be considered in batch instead \"\n \"of as a stream. This generally results in better trees but at the cost of\"\n \" memory usage and runtime.\", \"b\");\nPARAM_FLAG(\"info_gain\", \"If set, information gain is used instead of Gini \"\n \"impurity for calculating Hoeffding bounds.\", \"i\");\nPARAM_INT(\"passes\", \"Number of passes to take over the dataset.\", \"s\", 1);\n\nPARAM_INT(\"bins\", \"If the 'domingos' split strategy is used, this specifies \"\n \"the number of bins for each numeric split.\", \"B\", 10);\nPARAM_INT(\"observations_before_binning\", \"If the 'domingos' split strategy is \"\n \"used, this specifies the number of samples observed before binning is \"\n \"performed.\", \"o\", 100);\n\n\/\/ Helper function for once we have chosen a tree type.\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit =\n typename TreeType::NumericSplit(0));\n\nint main(int argc, char** argv)\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Check input parameters for validity.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n const string numericSplitStrategy =\n CLI::GetParam(\"numeric_split_strategy\");\n\n if ((!predictionsFile.empty() || !probabilitiesFile.empty()) &&\n testFile.empty())\n Log::Fatal << \"--test_file must be specified if --predictions_file or \"\n << \"--probabilities_file is specified.\" << endl;\n\n if (trainingFile.empty() && inputModelFile.empty())\n Log::Fatal << \"One of --training_file or --input_model_file must be \"\n << \"specified!\" << endl;\n\n if (!trainingFile.empty() && labelsFile.empty())\n Log::Fatal << \"If --training_file is specified, --labels_file must be \"\n << \"specified too!\" << endl;\n\n if (trainingFile.empty() && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored; no training set provided.\" << endl;\n\n if (CLI::HasParam(\"passes\") && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored because --passes was specified.\"\n << endl;\n\n if (CLI::HasParam(\"info_gain\"))\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n else\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n}\n\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit)\n{\n \/\/ Load necessary parameters.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const double confidence = CLI::GetParam(\"confidence\");\n const size_t maxSamples = (size_t) CLI::GetParam(\"max_samples\");\n const size_t minSamples = (size_t) CLI::GetParam(\"min_samples\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string outputModelFile = CLI::GetParam(\"output_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n bool batchTraining = CLI::HasParam(\"batch_mode\");\n const size_t passes = (size_t) CLI::GetParam(\"passes\");\n if (passes > 1)\n batchTraining = false; \/\/ We already warned about this earlier.\n\n TreeType* tree = NULL;\n DatasetInfo datasetInfo;\n if (inputModelFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n\n tree = new TreeType(trainingSet, datasetInfo, labels, max(labels) + 1,\n batchTraining, confidence, maxSamples, 100, minSamples,\n typename TreeType::CategoricalSplit(0, 0), numericSplit);\n\n for (size_t i = 1; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n Timer::Stop(\"tree_training\");\n }\n else\n {\n tree = new TreeType(datasetInfo, 1, 1);\n data::Load(inputModelFile, \"streamingDecisionTree\", *tree, true);\n\n if (!trainingFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n {\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n for (size_t i = 0; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n }\n else\n {\n tree->Train(trainingSet, labels, batchTraining);\n }\n Timer::Stop(\"tree_training\");\n }\n }\n\n \/\/ The tree is trained or loaded. Now do any testing if we need.\n if (!testFile.empty())\n {\n arma::mat testSet;\n data::Load(testFile, testSet, datasetInfo, true);\n\n arma::Row predictions;\n arma::rowvec probabilities;\n\n Timer::Start(\"tree_testing\");\n tree->Classify(testSet, predictions, probabilities);\n Timer::Stop(\"tree_testing\");\n\n if (!predictionsFile.empty())\n data::Save(predictionsFile, predictions);\n\n if (!probabilitiesFile.empty())\n data::Save(probabilitiesFile, probabilities);\n }\n\n \/\/ Check the accuracy on the training set.\n if (!outputModelFile.empty())\n data::Save(outputModelFile, \"streamingDecisionTree\", tree, true);\n\n \/\/ Clean up memory.\n delete tree;\n}\n<|endoftext|>"} {"text":"\/**\n * @file hoeffding_tree_main.cpp\n * @author Ryan Curtin\n *\n * A command-line executable that can build a streaming decision tree.\n *\/\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::data;\n\nPARAM_STRING(\"training_file\", \"Training dataset file.\", \"t\", \"\");\nPARAM_STRING(\"labels_file\", \"Labels for training dataset.\", \"l\", \"\");\n\nPARAM_DOUBLE(\"confidence\", \"Confidence before splitting (between 0 and 1).\",\n \"c\", 0.95);\nPARAM_INT(\"max_samples\", \"Maximum number of samples before splitting.\", \"n\",\n 5000);\nPARAM_INT(\"min_samples\", \"Minimum number of samples before splitting.\", \"I\",\n 100);\n\nPARAM_STRING(\"input_model_file\", \"File to load trained tree from.\", \"m\", \"\");\nPARAM_STRING(\"output_model_file\", \"File to save trained tree to.\", \"M\", \"\");\n\nPARAM_STRING(\"test_file\", \"File of testing data.\", \"T\", \"\");\nPARAM_STRING(\"test_labels_file\", \"Labels of test data.\", \"L\", \"\");\nPARAM_STRING(\"predictions_file\", \"File to output label predictions for test \"\n \"data into.\", \"p\", \"\");\nPARAM_STRING(\"probabilities_file\", \"In addition to predicting labels, provide \"\n \"prediction probabilities in this file.\", \"P\", \"\");\n\nPARAM_STRING(\"numeric_split_strategy\", \"The splitting strategy to use for \"\n \"numeric features: 'domingos' or 'binary'.\", \"N\", \"binary\");\nPARAM_FLAG(\"batch_mode\", \"If true, samples will be considered in batch instead \"\n \"of as a stream. This generally results in better trees but at the cost of\"\n \" memory usage and runtime.\", \"b\");\nPARAM_FLAG(\"info_gain\", \"If set, information gain is used instead of Gini \"\n \"impurity for calculating Hoeffding bounds.\", \"i\");\nPARAM_INT(\"passes\", \"Number of passes to take over the dataset.\", \"s\", 1);\n\nPARAM_INT(\"bins\", \"If the 'domingos' split strategy is used, this specifies \"\n \"the number of bins for each numeric split.\", \"B\", 10);\nPARAM_INT(\"observations_before_binning\", \"If the 'domingos' split strategy is \"\n \"used, this specifies the number of samples observed before binning is \"\n \"performed.\", \"o\", 100);\n\n\/\/ Helper function for once we have chosen a tree type.\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit =\n typename TreeType::NumericSplit(0));\n\nint main(int argc, char** argv)\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Check input parameters for validity.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n const string numericSplitStrategy =\n CLI::GetParam(\"numeric_split_strategy\");\n\n if ((!predictionsFile.empty() || !probabilitiesFile.empty()) &&\n testFile.empty())\n Log::Fatal << \"--test_file must be specified if --predictions_file or \"\n << \"--probabilities_file is specified.\" << endl;\n\n if (trainingFile.empty() && inputModelFile.empty())\n Log::Fatal << \"One of --training_file or --input_model_file must be \"\n << \"specified!\" << endl;\n\n if (!trainingFile.empty() && labelsFile.empty())\n Log::Fatal << \"If --training_file is specified, --labels_file must be \"\n << \"specified too!\" << endl;\n\n if (trainingFile.empty() && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored; no training set provided.\" << endl;\n\n if (CLI::HasParam(\"passes\") && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored because --passes was specified.\"\n << endl;\n\n if (CLI::HasParam(\"info_gain\"))\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n else\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n}\n\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit)\n{\n \/\/ Load necessary parameters.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const double confidence = CLI::GetParam(\"confidence\");\n const size_t maxSamples = (size_t) CLI::GetParam(\"max_samples\");\n const size_t minSamples = (size_t) CLI::GetParam(\"min_samples\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string outputModelFile = CLI::GetParam(\"output_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n bool batchTraining = CLI::HasParam(\"batch_mode\");\n const size_t passes = (size_t) CLI::GetParam(\"passes\");\n if (passes > 1)\n batchTraining = false; \/\/ We already warned about this earlier.\n\n TreeType* tree = NULL;\n DatasetInfo datasetInfo;\n if (inputModelFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n\n tree = new TreeType(trainingSet, datasetInfo, labels, max(labels) + 1,\n batchTraining, confidence, maxSamples, 100, minSamples,\n typename TreeType::CategoricalSplit(0, 0), numericSplit);\n\n for (size_t i = 1; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n Timer::Stop(\"tree_training\");\n }\n else\n {\n tree = new TreeType(datasetInfo, 1, 1);\n data::Load(inputModelFile, \"streamingDecisionTree\", *tree, true);\n\n if (!trainingFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n {\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n for (size_t i = 0; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n }\n else\n {\n tree->Train(trainingSet, labels, batchTraining);\n }\n Timer::Stop(\"tree_training\");\n }\n }\n\n if (!trainingFile.empty())\n {\n \/\/ Get training error.\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n arma::Row predictions;\n tree->Classify(trainingSet, predictions);\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n size_t correct = 0;\n for (size_t i = 0; i < labels.n_elem; ++i)\n if (labels[i] == predictions[i])\n ++correct;\n\n Log::Info << correct << \" out of \" << labels.n_elem << \" correct \"\n << \"on training set (\" << double(correct) \/ double(labels.n_elem) *\n 100.0 << \").\" << endl;\n\n }\n\n \/\/ The tree is trained or loaded. Now do any testing if we need.\n if (!testFile.empty())\n {\n arma::mat testSet;\n data::Load(testFile, testSet, datasetInfo, true);\n\n arma::Row predictions;\n arma::rowvec probabilities;\n\n Timer::Start(\"tree_testing\");\n tree->Classify(testSet, predictions, probabilities);\n Timer::Stop(\"tree_testing\");\n\n if (CLI::HasParam(\"test_labels_file\"))\n {\n string testLabelsFile = CLI::GetParam(\"test_labels_file\");\n arma::Col testLabelsIn;\n data::Load(testLabelsFile, testLabelsIn, true, false);\n arma::Row testLabels = testLabelsIn.t();\n\n size_t correct = 0;\n for (size_t i = 0; i < testLabels.n_elem; ++i)\n {\n if (predictions[i] == testLabels[i])\n ++correct;\n }\n Log::Info << correct << \" out of \" << testLabels.n_elem << \" correct \"\n << \"on test set (\" << double(correct) \/ double(testLabels.n_elem) *\n 100.0 << \").\" << endl;\n }\n\n if (!predictionsFile.empty())\n data::Save(predictionsFile, predictions);\n\n if (!probabilitiesFile.empty())\n data::Save(probabilitiesFile, probabilities);\n }\n\n \/\/ Check the accuracy on the training set.\n if (!outputModelFile.empty())\n data::Save(outputModelFile, \"streamingDecisionTree\", tree, true);\n\n \/\/ Clean up memory.\n delete tree;\n}\nPrint the number of nodes in the tree.\/**\n * @file hoeffding_tree_main.cpp\n * @author Ryan Curtin\n *\n * A command-line executable that can build a streaming decision tree.\n *\/\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::data;\n\nPARAM_STRING(\"training_file\", \"Training dataset file.\", \"t\", \"\");\nPARAM_STRING(\"labels_file\", \"Labels for training dataset.\", \"l\", \"\");\n\nPARAM_DOUBLE(\"confidence\", \"Confidence before splitting (between 0 and 1).\",\n \"c\", 0.95);\nPARAM_INT(\"max_samples\", \"Maximum number of samples before splitting.\", \"n\",\n 5000);\nPARAM_INT(\"min_samples\", \"Minimum number of samples before splitting.\", \"I\",\n 100);\n\nPARAM_STRING(\"input_model_file\", \"File to load trained tree from.\", \"m\", \"\");\nPARAM_STRING(\"output_model_file\", \"File to save trained tree to.\", \"M\", \"\");\n\nPARAM_STRING(\"test_file\", \"File of testing data.\", \"T\", \"\");\nPARAM_STRING(\"test_labels_file\", \"Labels of test data.\", \"L\", \"\");\nPARAM_STRING(\"predictions_file\", \"File to output label predictions for test \"\n \"data into.\", \"p\", \"\");\nPARAM_STRING(\"probabilities_file\", \"In addition to predicting labels, provide \"\n \"prediction probabilities in this file.\", \"P\", \"\");\n\nPARAM_STRING(\"numeric_split_strategy\", \"The splitting strategy to use for \"\n \"numeric features: 'domingos' or 'binary'.\", \"N\", \"binary\");\nPARAM_FLAG(\"batch_mode\", \"If true, samples will be considered in batch instead \"\n \"of as a stream. This generally results in better trees but at the cost of\"\n \" memory usage and runtime.\", \"b\");\nPARAM_FLAG(\"info_gain\", \"If set, information gain is used instead of Gini \"\n \"impurity for calculating Hoeffding bounds.\", \"i\");\nPARAM_INT(\"passes\", \"Number of passes to take over the dataset.\", \"s\", 1);\n\nPARAM_INT(\"bins\", \"If the 'domingos' split strategy is used, this specifies \"\n \"the number of bins for each numeric split.\", \"B\", 10);\nPARAM_INT(\"observations_before_binning\", \"If the 'domingos' split strategy is \"\n \"used, this specifies the number of samples observed before binning is \"\n \"performed.\", \"o\", 100);\n\n\/\/ Helper function for once we have chosen a tree type.\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit =\n typename TreeType::NumericSplit(0));\n\nint main(int argc, char** argv)\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Check input parameters for validity.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n const string numericSplitStrategy =\n CLI::GetParam(\"numeric_split_strategy\");\n\n if ((!predictionsFile.empty() || !probabilitiesFile.empty()) &&\n testFile.empty())\n Log::Fatal << \"--test_file must be specified if --predictions_file or \"\n << \"--probabilities_file is specified.\" << endl;\n\n if (trainingFile.empty() && inputModelFile.empty())\n Log::Fatal << \"One of --training_file or --input_model_file must be \"\n << \"specified!\" << endl;\n\n if (!trainingFile.empty() && labelsFile.empty())\n Log::Fatal << \"If --training_file is specified, --labels_file must be \"\n << \"specified too!\" << endl;\n\n if (trainingFile.empty() && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored; no training set provided.\" << endl;\n\n if (CLI::HasParam(\"passes\") && CLI::HasParam(\"batch_mode\"))\n Log::Warn << \"--batch_mode (-b) ignored because --passes was specified.\"\n << endl;\n\n if (CLI::HasParam(\"info_gain\"))\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n else\n {\n if (numericSplitStrategy == \"domingos\")\n {\n const size_t bins = (size_t) CLI::GetParam(\"bins\");\n const size_t observationsBeforeBinning = (size_t)\n CLI::GetParam(\"observations_before_binning\");\n HoeffdingDoubleNumericSplit ns(0, bins,\n observationsBeforeBinning);\n PerformActions>(ns);\n }\n else if (numericSplitStrategy == \"binary\")\n {\n PerformActions>();\n }\n else\n {\n Log::Fatal << \"Unrecognized numeric split strategy (\"\n << numericSplitStrategy << \")! Must be 'domingos' or 'binary'.\"\n << endl;\n }\n }\n}\n\ntemplate\nvoid PerformActions(const typename TreeType::NumericSplit& numericSplit)\n{\n \/\/ Load necessary parameters.\n const string trainingFile = CLI::GetParam(\"training_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const double confidence = CLI::GetParam(\"confidence\");\n const size_t maxSamples = (size_t) CLI::GetParam(\"max_samples\");\n const size_t minSamples = (size_t) CLI::GetParam(\"min_samples\");\n const string inputModelFile = CLI::GetParam(\"input_model_file\");\n const string outputModelFile = CLI::GetParam(\"output_model_file\");\n const string testFile = CLI::GetParam(\"test_file\");\n const string predictionsFile = CLI::GetParam(\"predictions_file\");\n const string probabilitiesFile = CLI::GetParam(\"probabilities_file\");\n bool batchTraining = CLI::HasParam(\"batch_mode\");\n const size_t passes = (size_t) CLI::GetParam(\"passes\");\n if (passes > 1)\n batchTraining = false; \/\/ We already warned about this earlier.\n\n TreeType* tree = NULL;\n DatasetInfo datasetInfo;\n if (inputModelFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n\n tree = new TreeType(trainingSet, datasetInfo, labels, max(labels) + 1,\n batchTraining, confidence, maxSamples, 100, minSamples,\n typename TreeType::CategoricalSplit(0, 0), numericSplit);\n\n for (size_t i = 1; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n Timer::Stop(\"tree_training\");\n }\n else\n {\n tree = new TreeType(datasetInfo, 1, 1);\n data::Load(inputModelFile, \"streamingDecisionTree\", *tree, true);\n\n if (!trainingFile.empty())\n {\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n for (size_t i = 0; i < trainingSet.n_rows; ++i)\n Log::Info << datasetInfo.NumMappings(i) << \" mappings in dimension \"\n << i << \".\" << endl;\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n \/\/ Now create the decision tree.\n Timer::Start(\"tree_training\");\n if (passes > 1)\n {\n Log::Info << \"Taking \" << passes << \" passes over the dataset.\" << endl;\n for (size_t i = 0; i < passes; ++i)\n tree->Train(trainingSet, labels, false);\n }\n else\n {\n tree->Train(trainingSet, labels, batchTraining);\n }\n Timer::Stop(\"tree_training\");\n }\n }\n\n if (!trainingFile.empty())\n {\n \/\/ Get training error.\n arma::mat trainingSet;\n data::Load(trainingFile, trainingSet, datasetInfo, true);\n arma::Row predictions;\n tree->Classify(trainingSet, predictions);\n\n arma::Col labelsIn;\n data::Load(labelsFile, labelsIn, true, false);\n arma::Row labels = labelsIn.t();\n\n size_t correct = 0;\n for (size_t i = 0; i < labels.n_elem; ++i)\n if (labels[i] == predictions[i])\n ++correct;\n\n Log::Info << correct << \" out of \" << labels.n_elem << \" correct \"\n << \"on training set (\" << double(correct) \/ double(labels.n_elem) *\n 100.0 << \").\" << endl;\n }\n\n \/\/ Get the number of nods in the tree.\n std::queue queue;\n queue.push(tree);\n size_t nodes = 0;\n while (!queue.empty())\n {\n TreeType* node = queue.front();\n queue.pop();\n ++nodes;\n\n for (size_t i = 0; i < node->NumChildren(); ++i)\n queue.push(&node->Child(i));\n }\n Log::Info << nodes << \" nodes in the tree.\" << endl;\n\n \/\/ The tree is trained or loaded. Now do any testing if we need.\n if (!testFile.empty())\n {\n arma::mat testSet;\n data::Load(testFile, testSet, datasetInfo, true);\n\n arma::Row predictions;\n arma::rowvec probabilities;\n\n Timer::Start(\"tree_testing\");\n tree->Classify(testSet, predictions, probabilities);\n Timer::Stop(\"tree_testing\");\n\n if (CLI::HasParam(\"test_labels_file\"))\n {\n string testLabelsFile = CLI::GetParam(\"test_labels_file\");\n arma::Col testLabelsIn;\n data::Load(testLabelsFile, testLabelsIn, true, false);\n arma::Row testLabels = testLabelsIn.t();\n\n size_t correct = 0;\n for (size_t i = 0; i < testLabels.n_elem; ++i)\n {\n if (predictions[i] == testLabels[i])\n ++correct;\n }\n Log::Info << correct << \" out of \" << testLabels.n_elem << \" correct \"\n << \"on test set (\" << double(correct) \/ double(testLabels.n_elem) *\n 100.0 << \").\" << endl;\n }\n\n if (!predictionsFile.empty())\n data::Save(predictionsFile, predictions);\n\n if (!probabilitiesFile.empty())\n data::Save(probabilitiesFile, probabilities);\n }\n\n \/\/ Check the accuracy on the training set.\n if (!outputModelFile.empty())\n data::Save(outputModelFile, \"streamingDecisionTree\", tree, true);\n\n \/\/ Clean up memory.\n delete tree;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: OptionList.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"OptionList.h\"\n\nOptionList::OptionList(int argc, char* argv[])\n{\n std::string tag ;\n std::string value ;\n \n int arg_type = 1 ;\n int prev_arg_type = 0 ;\n\n int index = 1 ;\n while (index < argc)\n {\n if (argv[index][0] == '-' && argv[index][1] == '-')\n {\n \/\/ tag\n tag = argv[index] ;\n tag = tag.erase(0, 2) ; \/\/ remove '--' \n } \n else\n {\n \/\/ value \n value = argv[index] ;\n m_Map.insert(std::make_pair(tag, value)) ;\n }\n index++ ;\n }\n}\n\nint OptionList::GetOption(std::string option_tag, StringVector* values)\n{\n values->clear() ;\n typedef OptionMap::const_iterator CI ;\n std::pair bound = m_Map.equal_range(option_tag) ;\n int count = 0 ;\n \n for (CI i = bound.first ; i != bound.second ; ++i)\n {\n values->push_back(i->second) ;\n count++ ;\n }\n return count ;\n}\n\n\nint OptionList::DumpOption(std::string option_tag, bool withTag,\n bool withNewLine)\n{\n typedef OptionMap::const_iterator CI ;\n std::pair bound = m_Map.equal_range(option_tag) ;\n int count = 0 ;\n\n if (bound.first != bound.second)\n {\n if (withTag)\n std::cout << \"--\" << option_tag << \" \" ;\n \n for (CI i = bound.first ; i != bound.second ; ++i)\n {\n std::cout << i->second << \" \" ;\n count++ ;\n }\n \n if (withNewLine)\n std::cout << std::endl ;\n \n return count++ ;\n }\n\n return 0 ;\n}\n\n\nint OptionList::GetMultiDoubleOption(std::string tag, \n std::vector* args, \n bool required)\n throw (RequiredOptionMissing) \n{\n args->clear() ;\n \n StringVector temp_args ;\n int arg_no = this->GetOption(tag, &temp_args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return -1 ;\n \n if (temp_args[0] == \"-\")\n return -2 ;\n \n for (int i = 0 ; i < arg_no ; i++)\n {\n args->push_back( atof(temp_args[i].c_str()) ) ;\n }\n \n return arg_no ;\n}\n\ndouble OptionList::GetDoubleOption(std::string tag, double default_value,\n bool required)\n throw (RequiredOptionMissing) \n{\n StringVector temp_args ;\n int arg_no = this->GetOption(tag, &temp_args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return default_value ;\n \n return atof(temp_args[0].c_str()) ;\n}\n\nbool OptionList::GetBooleanOption(std::string tag, bool default_value, bool required)\n throw (RequiredOptionMissing) \n{\n StringVector args ;\n int arg_no = this->GetOption(tag, &args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return default_value ;\n \n if (args[0] == \"yes\")\n {\n return true ;\n }\n else\n {\n return false ;\n }\n}\n\nint OptionList::GetMultiIntOption(std::string tag, \n std::vector* args, \n bool required)\n throw (RequiredOptionMissing) \n{\n args->clear() ;\n \n StringVector temp_args ;\n int arg_no = this->GetOption(tag, &temp_args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return -1 ;\n \n if (temp_args[0] == \"-\")\n return -2 ;\n \n for (int i = 0 ; i < arg_no ; i++)\n {\n args->push_back( atoi(temp_args[i].c_str()) ) ;\n }\n \n return arg_no ;\n}\n\nint OptionList::GetIntOption(std::string tag, int default_value, bool required)\n throw (RequiredOptionMissing) \n{\n StringVector args ;\n int arg_no = this->GetOption(tag, &args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return default_value ;\n \n return atoi(args[0].c_str()) ;\n}\n\nint OptionList::GetStringOption(std::string tag, \n std::string* ret, \n bool required)\n throw (RequiredOptionMissing) \n{\n StringVector args ;\n int arg_no = this->GetOption(tag, &args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return -1 ;\n \n *ret = args[0] ;\n return arg_no ;\n}\n\nSTYLE: removed unused variables to remove SGI warnings\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: OptionList.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"OptionList.h\"\n\nOptionList::OptionList(int argc, char* argv[])\n{\n std::string tag ;\n std::string value ;\n \n int index = 1 ;\n while (index < argc)\n {\n if (argv[index][0] == '-' && argv[index][1] == '-')\n {\n \/\/ tag\n tag = argv[index] ;\n tag = tag.erase(0, 2) ; \/\/ remove '--' \n } \n else\n {\n \/\/ value \n value = argv[index] ;\n m_Map.insert(std::make_pair(tag, value)) ;\n }\n index++ ;\n }\n}\n\nint OptionList::GetOption(std::string option_tag, StringVector* values)\n{\n values->clear() ;\n typedef OptionMap::const_iterator CI ;\n std::pair bound = m_Map.equal_range(option_tag) ;\n int count = 0 ;\n \n for (CI i = bound.first ; i != bound.second ; ++i)\n {\n values->push_back(i->second) ;\n count++ ;\n }\n return count ;\n}\n\n\nint OptionList::DumpOption(std::string option_tag, bool withTag,\n bool withNewLine)\n{\n typedef OptionMap::const_iterator CI ;\n std::pair bound = m_Map.equal_range(option_tag) ;\n int count = 0 ;\n\n if (bound.first != bound.second)\n {\n if (withTag)\n std::cout << \"--\" << option_tag << \" \" ;\n \n for (CI i = bound.first ; i != bound.second ; ++i)\n {\n std::cout << i->second << \" \" ;\n count++ ;\n }\n \n if (withNewLine)\n std::cout << std::endl ;\n \n return count++ ;\n }\n\n return 0 ;\n}\n\n\nint OptionList::GetMultiDoubleOption(std::string tag, \n std::vector* args, \n bool required)\n throw (RequiredOptionMissing) \n{\n args->clear() ;\n \n StringVector temp_args ;\n int arg_no = this->GetOption(tag, &temp_args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return -1 ;\n \n if (temp_args[0] == \"-\")\n return -2 ;\n \n for (int i = 0 ; i < arg_no ; i++)\n {\n args->push_back( atof(temp_args[i].c_str()) ) ;\n }\n \n return arg_no ;\n}\n\ndouble OptionList::GetDoubleOption(std::string tag, double default_value,\n bool required)\n throw (RequiredOptionMissing) \n{\n StringVector temp_args ;\n int arg_no = this->GetOption(tag, &temp_args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return default_value ;\n \n return atof(temp_args[0].c_str()) ;\n}\n\nbool OptionList::GetBooleanOption(std::string tag, bool default_value, bool required)\n throw (RequiredOptionMissing) \n{\n StringVector args ;\n int arg_no = this->GetOption(tag, &args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return default_value ;\n \n if (args[0] == \"yes\")\n {\n return true ;\n }\n else\n {\n return false ;\n }\n}\n\nint OptionList::GetMultiIntOption(std::string tag, \n std::vector* args, \n bool required)\n throw (RequiredOptionMissing) \n{\n args->clear() ;\n \n StringVector temp_args ;\n int arg_no = this->GetOption(tag, &temp_args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return -1 ;\n \n if (temp_args[0] == \"-\")\n return -2 ;\n \n for (int i = 0 ; i < arg_no ; i++)\n {\n args->push_back( atoi(temp_args[i].c_str()) ) ;\n }\n \n return arg_no ;\n}\n\nint OptionList::GetIntOption(std::string tag, int default_value, bool required)\n throw (RequiredOptionMissing) \n{\n StringVector args ;\n int arg_no = this->GetOption(tag, &args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return default_value ;\n \n return atoi(args[0].c_str()) ;\n}\n\nint OptionList::GetStringOption(std::string tag, \n std::string* ret, \n bool required)\n throw (RequiredOptionMissing) \n{\n StringVector args ;\n int arg_no = this->GetOption(tag, &args) ;\n \n if (required && arg_no == 0)\n throw RequiredOptionMissing(tag) ;\n \n if (arg_no == 0)\n return -1 ;\n \n *ret = args[0] ;\n return arg_no ;\n}\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"kitinformationconfigwidget.h\"\n\n#include \"devicesupport\/devicemanager.h\"\n#include \"devicesupport\/devicemanagermodel.h\"\n#include \"devicesupport\/idevicefactory.h\"\n#include \"projectexplorerconstants.h\"\n#include \"kit.h\"\n#include \"kitinformation.h\"\n#include \"toolchain.h\"\n#include \"toolchainmanager.h\"\n#include \"environmentwidget.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Core;\n\nnamespace ProjectExplorer {\nnamespace Internal {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ SysRootInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nSysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChange(false)\n{\n m_chooser = new Utils::PathChooser;\n m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);\n m_chooser->setHistoryCompleter(QLatin1String(\"PE.SysRoot.History\"));\n m_chooser->setFileName(SysRootKitInformation::sysRoot(k));\n connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));\n}\n\nSysRootInformationConfigWidget::~SysRootInformationConfigWidget()\n{\n delete m_chooser;\n}\n\nQString SysRootInformationConfigWidget::displayName() const\n{\n return tr(\"Sysroot:\");\n}\n\nQString SysRootInformationConfigWidget::toolTip() const\n{\n return tr(\"The root directory of the system image to use.
\"\n \"Leave empty when building for the desktop.\");\n}\n\nvoid SysRootInformationConfigWidget::refresh()\n{\n if (!m_ignoreChange)\n m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit));\n}\n\nvoid SysRootInformationConfigWidget::makeReadOnly()\n{\n m_chooser->setReadOnly(true);\n}\n\nQWidget *SysRootInformationConfigWidget::mainWidget() const\n{\n return m_chooser->lineEdit();\n}\n\nQWidget *SysRootInformationConfigWidget::buttonWidget() const\n{\n return m_chooser->buttonAtIndex(0);\n}\n\nvoid SysRootInformationConfigWidget::pathWasChanged()\n{\n m_ignoreChange = true;\n SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName());\n m_ignoreChange = false;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ToolChainInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChanges(false),\n m_isReadOnly(false)\n{\n m_comboBox = new QComboBox;\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n m_manageButton->setContentsMargins(0, 0, 0, 0);\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));\n}\n\nToolChainInformationConfigWidget::~ToolChainInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_manageButton;\n}\n\nQString ToolChainInformationConfigWidget::displayName() const\n{\n return tr(\"Compiler:\");\n}\n\nQString ToolChainInformationConfigWidget::toolTip() const\n{\n return tr(\"The compiler to use for building.
\"\n \"Make sure the compiler will produce binaries compatible with the target device, \"\n \"Qt version and other libraries used.\");\n}\n\nvoid ToolChainInformationConfigWidget::refresh()\n{\n m_ignoreChanges = true;\n m_comboBox->clear();\n foreach (ToolChain *tc, ToolChainManager::toolChains())\n m_comboBox->addItem(tc->displayName(), tc->id());\n\n if (m_comboBox->count() == 0) {\n m_comboBox->addItem(tr(\"\"), QString());\n m_comboBox->setEnabled(false);\n } else {\n m_comboBox->setEnabled(m_comboBox->count() > 1 && !m_isReadOnly);\n }\n\n m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));\n m_ignoreChanges = false;\n}\n\nvoid ToolChainInformationConfigWidget::makeReadOnly()\n{\n m_isReadOnly = true;\n m_comboBox->setEnabled(false);\n}\n\nQWidget *ToolChainInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQWidget *ToolChainInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid ToolChainInformationConfigWidget::manageToolChains()\n{\n ICore::showOptionsDialog(Constants::TOOLCHAIN_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid ToolChainInformationConfigWidget::currentToolChainChanged(int idx)\n{\n if (m_ignoreChanges)\n return;\n\n const QString id = m_comboBox->itemData(idx).toString();\n ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id));\n}\n\nint ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)\n{\n const QString id = tc ? tc->id() : QString();\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (id == m_comboBox->itemData(i).toString())\n return i;\n }\n return -1;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceTypeInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox)\n{\n QList factories\n = ExtensionSystem::PluginManager::getObjects();\n foreach (IDeviceFactory *factory, factories) {\n foreach (Id id, factory->availableCreationIds())\n m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());\n }\n\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));\n}\n\nDeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget()\n{\n delete m_comboBox;\n}\n\nQWidget *DeviceTypeInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceTypeInformationConfigWidget::displayName() const\n{\n return tr(\"Device type:\");\n}\n\nQString DeviceTypeInformationConfigWidget::toolTip() const\n{\n return tr(\"The type of device to run applications on.\");\n}\n\nvoid DeviceTypeInformationConfigWidget::refresh()\n{\n Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);\n if (!devType.isValid())\n m_comboBox->setCurrentIndex(-1);\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) {\n m_comboBox->setCurrentIndex(i);\n break;\n }\n }\n}\n\nvoid DeviceTypeInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nvoid DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)\n{\n Id type = idx < 0 ? Id() : Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());\n DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_isReadOnly(false),\n m_ignoreChange(false),\n m_comboBox(new QComboBox),\n m_model(new DeviceManagerModel(DeviceManager::instance()))\n{\n m_comboBox->setModel(m_model);\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n\n refresh();\n m_comboBox->setToolTip(toolTip());\n\n connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));\n connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));\n}\n\nDeviceInformationConfigWidget::~DeviceInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_model;\n delete m_manageButton;\n}\n\nQWidget *DeviceInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceInformationConfigWidget::displayName() const\n{\n return tr(\"Device:\");\n}\n\nQString DeviceInformationConfigWidget::toolTip() const\n{\n return tr(\"The device to run the applications on.\");\n}\n\nvoid DeviceInformationConfigWidget::refresh()\n{\n m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));\n m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit)));\n}\n\nvoid DeviceInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nQWidget *DeviceInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid DeviceInformationConfigWidget::manageDevices()\n{\n ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid DeviceInformationConfigWidget::modelAboutToReset()\n{\n m_selectedId = m_model->deviceId(m_comboBox->currentIndex());\n m_ignoreChange = true;\n}\n\nvoid DeviceInformationConfigWidget::modelReset()\n{\n m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId));\n m_ignoreChange = false;\n}\n\nvoid DeviceInformationConfigWidget::currentDeviceChanged()\n{\n if (m_ignoreChange)\n return;\n DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex()));\n}\n\n\/\/ --------------------------------------------------------------------\n\/\/ KitEnvironmentConfigWidget:\n\/\/ --------------------------------------------------------------------\n\nKitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_summaryLabel(new QLabel),\n m_manageButton(new QPushButton),\n m_dialog(0),\n m_editor(0)\n{\n refresh();\n m_manageButton->setText(tr(\"Change...\"));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges()));\n}\n\nQWidget *KitEnvironmentConfigWidget::mainWidget() const\n{\n return m_summaryLabel;\n}\n\nQString KitEnvironmentConfigWidget::displayName() const\n{\n return tr(\"Environment:\");\n}\n\nQString KitEnvironmentConfigWidget::toolTip() const\n{\n return tr(\"Additional environment settings when using this kit.\");\n}\n\nvoid KitEnvironmentConfigWidget::refresh()\n{\n QList changes = EnvironmentKitInformation::environmentChanges(m_kit);\n Utils::sort(changes, [](const Utils::EnvironmentItem &lhs, const Utils::EnvironmentItem &rhs)\n { return QString::localeAwareCompare(lhs.name, rhs.name) < 0; });\n QString shortSummary = Utils::EnvironmentItem::toStringList(changes).join(QLatin1String(\"; \"));\n QFontMetrics fm(m_summaryLabel->font());\n shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width());\n m_summaryLabel->setText(shortSummary.isEmpty() ? tr(\"No changes to apply.\") : shortSummary);\n if (m_editor)\n m_editor->setPlainText(Utils::EnvironmentItem::toStringList(changes).join(QLatin1Char('\\n')));\n}\n\nvoid KitEnvironmentConfigWidget::makeReadOnly()\n{\n m_manageButton->setEnabled(false);\n if (m_dialog)\n m_dialog->reject();\n}\n\nvoid KitEnvironmentConfigWidget::editEnvironmentChanges()\n{\n if (m_dialog) {\n m_dialog->activateWindow();\n m_dialog->raise();\n return;\n }\n\n QTC_ASSERT(!m_editor, return);\n\n m_dialog = new QDialog(m_summaryLabel);\n m_dialog->setWindowTitle(tr(\"Edit Environment Changes\"));\n QVBoxLayout *layout = new QVBoxLayout(m_dialog);\n m_editor = new QPlainTextEdit;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel);\n\n layout->addWidget(m_editor);\n layout->addWidget(buttons);\n\n connect(buttons, SIGNAL(accepted()), m_dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), m_dialog, SLOT(reject()));\n connect(m_dialog, SIGNAL(accepted()), this, SLOT(acceptChangesDialog()));\n connect(m_dialog, SIGNAL(rejected()), this, SLOT(closeChangesDialog()));\n connect(buttons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyChanges()));\n\n refresh();\n m_dialog->show();\n}\n\nvoid KitEnvironmentConfigWidget::applyChanges()\n{\n QTC_ASSERT(m_editor, return);\n auto changes = Utils::EnvironmentItem::fromStringList(m_editor->toPlainText().split(QLatin1Char('\\n')));\n EnvironmentKitInformation::setEnvironmentChanges(m_kit, changes);\n}\n\nvoid KitEnvironmentConfigWidget::closeChangesDialog()\n{\n m_dialog->deleteLater();\n m_dialog = 0;\n m_editor = 0;\n}\n\nvoid KitEnvironmentConfigWidget::acceptChangesDialog()\n{\n applyChanges();\n closeChangesDialog();\n}\n\nQWidget *KitEnvironmentConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ProjectExplorer\nKits: Replace use of Id::fromUniqueId() and Id::toUniqueId()\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"kitinformationconfigwidget.h\"\n\n#include \"devicesupport\/devicemanager.h\"\n#include \"devicesupport\/devicemanagermodel.h\"\n#include \"devicesupport\/idevicefactory.h\"\n#include \"projectexplorerconstants.h\"\n#include \"kit.h\"\n#include \"kitinformation.h\"\n#include \"toolchain.h\"\n#include \"toolchainmanager.h\"\n#include \"environmentwidget.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Core;\n\nnamespace ProjectExplorer {\nnamespace Internal {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ SysRootInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nSysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChange(false)\n{\n m_chooser = new Utils::PathChooser;\n m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);\n m_chooser->setHistoryCompleter(QLatin1String(\"PE.SysRoot.History\"));\n m_chooser->setFileName(SysRootKitInformation::sysRoot(k));\n connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));\n}\n\nSysRootInformationConfigWidget::~SysRootInformationConfigWidget()\n{\n delete m_chooser;\n}\n\nQString SysRootInformationConfigWidget::displayName() const\n{\n return tr(\"Sysroot:\");\n}\n\nQString SysRootInformationConfigWidget::toolTip() const\n{\n return tr(\"The root directory of the system image to use.
\"\n \"Leave empty when building for the desktop.\");\n}\n\nvoid SysRootInformationConfigWidget::refresh()\n{\n if (!m_ignoreChange)\n m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit));\n}\n\nvoid SysRootInformationConfigWidget::makeReadOnly()\n{\n m_chooser->setReadOnly(true);\n}\n\nQWidget *SysRootInformationConfigWidget::mainWidget() const\n{\n return m_chooser->lineEdit();\n}\n\nQWidget *SysRootInformationConfigWidget::buttonWidget() const\n{\n return m_chooser->buttonAtIndex(0);\n}\n\nvoid SysRootInformationConfigWidget::pathWasChanged()\n{\n m_ignoreChange = true;\n SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName());\n m_ignoreChange = false;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ToolChainInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChanges(false),\n m_isReadOnly(false)\n{\n m_comboBox = new QComboBox;\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n m_manageButton->setContentsMargins(0, 0, 0, 0);\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));\n}\n\nToolChainInformationConfigWidget::~ToolChainInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_manageButton;\n}\n\nQString ToolChainInformationConfigWidget::displayName() const\n{\n return tr(\"Compiler:\");\n}\n\nQString ToolChainInformationConfigWidget::toolTip() const\n{\n return tr(\"The compiler to use for building.
\"\n \"Make sure the compiler will produce binaries compatible with the target device, \"\n \"Qt version and other libraries used.\");\n}\n\nvoid ToolChainInformationConfigWidget::refresh()\n{\n m_ignoreChanges = true;\n m_comboBox->clear();\n foreach (ToolChain *tc, ToolChainManager::toolChains())\n m_comboBox->addItem(tc->displayName(), tc->id());\n\n if (m_comboBox->count() == 0) {\n m_comboBox->addItem(tr(\"\"), QString());\n m_comboBox->setEnabled(false);\n } else {\n m_comboBox->setEnabled(m_comboBox->count() > 1 && !m_isReadOnly);\n }\n\n m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));\n m_ignoreChanges = false;\n}\n\nvoid ToolChainInformationConfigWidget::makeReadOnly()\n{\n m_isReadOnly = true;\n m_comboBox->setEnabled(false);\n}\n\nQWidget *ToolChainInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQWidget *ToolChainInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid ToolChainInformationConfigWidget::manageToolChains()\n{\n ICore::showOptionsDialog(Constants::TOOLCHAIN_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid ToolChainInformationConfigWidget::currentToolChainChanged(int idx)\n{\n if (m_ignoreChanges)\n return;\n\n const QString id = m_comboBox->itemData(idx).toString();\n ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id));\n}\n\nint ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)\n{\n const QString id = tc ? tc->id() : QString();\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (id == m_comboBox->itemData(i).toString())\n return i;\n }\n return -1;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceTypeInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox)\n{\n QList factories\n = ExtensionSystem::PluginManager::getObjects();\n foreach (IDeviceFactory *factory, factories) {\n foreach (Id id, factory->availableCreationIds())\n m_comboBox->addItem(factory->displayNameForId(id), id.toSetting());\n }\n\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));\n}\n\nDeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget()\n{\n delete m_comboBox;\n}\n\nQWidget *DeviceTypeInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceTypeInformationConfigWidget::displayName() const\n{\n return tr(\"Device type:\");\n}\n\nQString DeviceTypeInformationConfigWidget::toolTip() const\n{\n return tr(\"The type of device to run applications on.\");\n}\n\nvoid DeviceTypeInformationConfigWidget::refresh()\n{\n Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);\n if (!devType.isValid())\n m_comboBox->setCurrentIndex(-1);\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (m_comboBox->itemData(i) == devType.toSetting()) {\n m_comboBox->setCurrentIndex(i);\n break;\n }\n }\n}\n\nvoid DeviceTypeInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nvoid DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)\n{\n Id type = idx < 0 ? Id() : Id::fromSetting(m_comboBox->itemData(idx));\n DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_isReadOnly(false),\n m_ignoreChange(false),\n m_comboBox(new QComboBox),\n m_model(new DeviceManagerModel(DeviceManager::instance()))\n{\n m_comboBox->setModel(m_model);\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n\n refresh();\n m_comboBox->setToolTip(toolTip());\n\n connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));\n connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));\n}\n\nDeviceInformationConfigWidget::~DeviceInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_model;\n delete m_manageButton;\n}\n\nQWidget *DeviceInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceInformationConfigWidget::displayName() const\n{\n return tr(\"Device:\");\n}\n\nQString DeviceInformationConfigWidget::toolTip() const\n{\n return tr(\"The device to run the applications on.\");\n}\n\nvoid DeviceInformationConfigWidget::refresh()\n{\n m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));\n m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit)));\n}\n\nvoid DeviceInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nQWidget *DeviceInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid DeviceInformationConfigWidget::manageDevices()\n{\n ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid DeviceInformationConfigWidget::modelAboutToReset()\n{\n m_selectedId = m_model->deviceId(m_comboBox->currentIndex());\n m_ignoreChange = true;\n}\n\nvoid DeviceInformationConfigWidget::modelReset()\n{\n m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId));\n m_ignoreChange = false;\n}\n\nvoid DeviceInformationConfigWidget::currentDeviceChanged()\n{\n if (m_ignoreChange)\n return;\n DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex()));\n}\n\n\/\/ --------------------------------------------------------------------\n\/\/ KitEnvironmentConfigWidget:\n\/\/ --------------------------------------------------------------------\n\nKitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_summaryLabel(new QLabel),\n m_manageButton(new QPushButton),\n m_dialog(0),\n m_editor(0)\n{\n refresh();\n m_manageButton->setText(tr(\"Change...\"));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges()));\n}\n\nQWidget *KitEnvironmentConfigWidget::mainWidget() const\n{\n return m_summaryLabel;\n}\n\nQString KitEnvironmentConfigWidget::displayName() const\n{\n return tr(\"Environment:\");\n}\n\nQString KitEnvironmentConfigWidget::toolTip() const\n{\n return tr(\"Additional environment settings when using this kit.\");\n}\n\nvoid KitEnvironmentConfigWidget::refresh()\n{\n QList changes = EnvironmentKitInformation::environmentChanges(m_kit);\n Utils::sort(changes, [](const Utils::EnvironmentItem &lhs, const Utils::EnvironmentItem &rhs)\n { return QString::localeAwareCompare(lhs.name, rhs.name) < 0; });\n QString shortSummary = Utils::EnvironmentItem::toStringList(changes).join(QLatin1String(\"; \"));\n QFontMetrics fm(m_summaryLabel->font());\n shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width());\n m_summaryLabel->setText(shortSummary.isEmpty() ? tr(\"No changes to apply.\") : shortSummary);\n if (m_editor)\n m_editor->setPlainText(Utils::EnvironmentItem::toStringList(changes).join(QLatin1Char('\\n')));\n}\n\nvoid KitEnvironmentConfigWidget::makeReadOnly()\n{\n m_manageButton->setEnabled(false);\n if (m_dialog)\n m_dialog->reject();\n}\n\nvoid KitEnvironmentConfigWidget::editEnvironmentChanges()\n{\n if (m_dialog) {\n m_dialog->activateWindow();\n m_dialog->raise();\n return;\n }\n\n QTC_ASSERT(!m_editor, return);\n\n m_dialog = new QDialog(m_summaryLabel);\n m_dialog->setWindowTitle(tr(\"Edit Environment Changes\"));\n QVBoxLayout *layout = new QVBoxLayout(m_dialog);\n m_editor = new QPlainTextEdit;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel);\n\n layout->addWidget(m_editor);\n layout->addWidget(buttons);\n\n connect(buttons, SIGNAL(accepted()), m_dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), m_dialog, SLOT(reject()));\n connect(m_dialog, SIGNAL(accepted()), this, SLOT(acceptChangesDialog()));\n connect(m_dialog, SIGNAL(rejected()), this, SLOT(closeChangesDialog()));\n connect(buttons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyChanges()));\n\n refresh();\n m_dialog->show();\n}\n\nvoid KitEnvironmentConfigWidget::applyChanges()\n{\n QTC_ASSERT(m_editor, return);\n auto changes = Utils::EnvironmentItem::fromStringList(m_editor->toPlainText().split(QLatin1Char('\\n')));\n EnvironmentKitInformation::setEnvironmentChanges(m_kit, changes);\n}\n\nvoid KitEnvironmentConfigWidget::closeChangesDialog()\n{\n m_dialog->deleteLater();\n m_dialog = 0;\n m_editor = 0;\n}\n\nvoid KitEnvironmentConfigWidget::acceptChangesDialog()\n{\n applyChanges();\n closeChangesDialog();\n}\n\nQWidget *KitEnvironmentConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"\/** \n @file unix.c\n @brief ENet Unix system specific functions\n*\/\n#ifndef WIN32\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ENET_BUILDING_LIB 1\n#include \"enet\/enet.h\"\n\n#ifdef __APPLE__\n#undef HAS_POLL\n#ifndef HAS_SOCKLEN_T \n#define HAS_SOCKLEN_T\n#endif\n#ifndef HAS_FCNTL\n#define HAS_FCNTL\n#endif\n#endif\n\n#ifdef HAS_FCNTL\n#include \n#endif\n\n#ifdef HAS_POLL\n#include \n#endif\n\n#if defined(__socklen_t_defined) && !defined(HAS_SOCKLEN_T)\n#define HAS_SOCKLEN_T\n#endif\n\n#ifndef HAS_SOCKLEN_T\ntypedef int socklen_t;\n#endif\n\n#ifndef MSG_NOSIGNAL\n#define MSG_NOSIGNAL 0\n#endif\n\nstatic enet_uint32 timeBase = 0;\n\nint\nenet_initialize (void)\n{\n return 0;\n}\n\nvoid\nenet_deinitialize (void)\n{\n}\n\nenet_uint32\nenet_time_get (void)\n{\n struct timeval timeVal;\n\n gettimeofday (& timeVal, NULL);\n\n return timeVal.tv_sec * 1000 + timeVal.tv_usec \/ 1000 - timeBase;\n}\n\nvoid\nenet_time_set (enet_uint32 newTimeBase)\n{\n struct timeval timeVal;\n\n gettimeofday (& timeVal, NULL);\n \n timeBase = timeVal.tv_sec * 1000 + timeVal.tv_usec \/ 1000 - newTimeBase;\n}\n\nint\nenet_address_set_host (ENetAddress * address, const char * name)\n{\n struct hostent * hostEntry = NULL;\n#ifdef HAS_GETHOSTBYNAME_R\n struct hostent hostData;\n char buffer [2048];\n int errnum;\n\n#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)\n gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum);\n#else\n hostEntry = gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & errnum);\n#endif\n#else\n hostEntry = gethostbyname (name);\n#endif\n\n if (hostEntry == NULL ||\n hostEntry -> h_addrtype != AF_INET)\n {\n#ifdef HAS_INET_PTON\n if (! inet_pton (AF_INET, name, & address -> host))\n#else\n if (! inet_aton (name, (struct in_addr *) & address -> host))\n#endif\n return -1;\n return 0;\n }\n\n address -> host = * (enet_uint32 *) hostEntry -> h_addr_list [0];\n\n return 0;\n}\n\nint\nenet_address_get_host_ip (const ENetAddress * address, char * name, size_t nameLength)\n{\n#ifdef HAS_INET_NTOP\n if (inet_ntop (AF_INET, & address -> host, name, nameLength) == NULL)\n#else\n char * addr = inet_ntoa (* (struct in_addr *) & address -> host);\n if (addr != NULL)\n strncpy (name, addr, nameLength);\n else\n#endif\n return -1;\n return 0;\n}\n\nint\nenet_address_get_host (const ENetAddress * address, char * name, size_t nameLength)\n{\n struct in_addr in;\n struct hostent * hostEntry = NULL;\n#ifdef HAS_GETHOSTBYADDR_R\n struct hostent hostData;\n char buffer [2048];\n int errnum;\n\n in.s_addr = address -> host;\n\n#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)\n gethostbyaddr_r ((char *) & in, sizeof (struct in_addr), AF_INET, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum);\n#else\n hostEntry = gethostbyaddr_r ((char *) & in, sizeof (struct in_addr), AF_INET, & hostData, buffer, sizeof (buffer), & errnum);\n#endif\n#else\n in.s_addr = address -> host;\n\n hostEntry = gethostbyaddr ((char *) & in, sizeof (struct in_addr), AF_INET);\n#endif\n\n if (hostEntry == NULL)\n return enet_address_get_host_ip (address, name, nameLength);\n\n strncpy (name, hostEntry -> h_name, nameLength);\n\n return 0;\n}\n\nint\nenet_socket_bind (ENetSocket socket, const ENetAddress * address)\n{\n struct sockaddr_in sin;\n\n memset (& sin, 0, sizeof (struct sockaddr_in));\n\n sin.sin_family = AF_INET;\n\n if (address != NULL)\n {\n sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);\n sin.sin_addr.s_addr = address -> host;\n }\n else\n {\n sin.sin_port = 0;\n sin.sin_addr.s_addr = INADDR_ANY;\n }\n\n return bind (socket,\n (struct sockaddr *) & sin,\n sizeof (struct sockaddr_in)); \n}\n\nint \nenet_socket_listen (ENetSocket socket, int backlog)\n{\n return listen (socket, backlog < 0 ? SOMAXCONN : backlog);\n}\n\nENetSocket\nenet_socket_create (ENetSocketType type)\n{\n ENetSocket sd = socket (PF_INET, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);\n \n \/\/ disable any sig pipe exceptions \n if (sd) {\n int set = 1;\n setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));\n }\n return sd;\n}\n\nint\nenet_socket_set_option (ENetSocket socket, ENetSocketOption option, int value)\n{\n int result = -1;\n switch (option)\n {\n case ENET_SOCKOPT_NONBLOCK:\n#ifdef HAS_FCNTL\n result = fcntl (socket, F_SETFL, O_NONBLOCK | fcntl (socket, F_GETFL));\n#else\n result = ioctl (socket, FIONBIO, & value);\n#endif\n break;\n\n case ENET_SOCKOPT_BROADCAST:\n result = setsockopt (socket, SOL_SOCKET, SO_BROADCAST, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_REUSEADDR:\n result = setsockopt (socket, SOL_SOCKET, SO_REUSEADDR, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_RCVBUF:\n result = setsockopt (socket, SOL_SOCKET, SO_RCVBUF, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_SNDBUF:\n result = setsockopt (socket, SOL_SOCKET, SO_SNDBUF, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_RCVTIMEO:\n result = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_SNDTIMEO:\n result = setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & value, sizeof (int));\n break;\n\n default:\n break;\n }\n return result == -1 ? -1 : 0;\n}\n\nint\nenet_socket_connect (ENetSocket socket, const ENetAddress * address)\n{\n struct sockaddr_in sin;\n\n memset (& sin, 0, sizeof (struct sockaddr_in));\n\n sin.sin_family = AF_INET;\n sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);\n sin.sin_addr.s_addr = address -> host;\n\n return connect (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in));\n}\n\nENetSocket\nenet_socket_accept (ENetSocket socket, ENetAddress * address)\n{\n int result;\n struct sockaddr_in sin;\n socklen_t sinLength = sizeof (struct sockaddr_in);\n\n result = accept (socket, \n address != NULL ? (struct sockaddr *) & sin : NULL, \n address != NULL ? & sinLength : NULL);\n \n if (result == -1)\n return ENET_SOCKET_NULL;\n\n if (address != NULL)\n {\n address -> host = (enet_uint32) sin.sin_addr.s_addr;\n address -> port = ENET_NET_TO_HOST_16 (sin.sin_port);\n }\n\n return result;\n} \n \nvoid\nenet_socket_destroy (ENetSocket socket)\n{\n close (socket);\n}\n\nint\nenet_socket_send (ENetSocket socket,\n const ENetAddress * address,\n const ENetBuffer * buffers,\n size_t bufferCount)\n{\n struct msghdr msgHdr;\n struct sockaddr_in sin;\n int sentLength;\n\n memset (& msgHdr, 0, sizeof (struct msghdr));\n\n if (address != NULL)\n {\n memset (& sin, 0, sizeof (struct sockaddr_in));\n\n sin.sin_family = AF_INET;\n sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);\n sin.sin_addr.s_addr = address -> host;\n\n msgHdr.msg_name = & sin;\n msgHdr.msg_namelen = sizeof (struct sockaddr_in);\n }\n\n msgHdr.msg_iov = (struct iovec *) buffers;\n msgHdr.msg_iovlen = bufferCount;\n\n sentLength = sendmsg (socket, & msgHdr, MSG_NOSIGNAL);\n \n if (sentLength == -1)\n {\n if (errno == EWOULDBLOCK)\n return 0;\n\n return -1;\n }\n\n return sentLength;\n}\n\nint\nenet_socket_receive (ENetSocket socket,\n ENetAddress * address,\n ENetBuffer * buffers,\n size_t bufferCount)\n{\n struct msghdr msgHdr;\n struct sockaddr_in sin;\n int recvLength;\n\n memset (& msgHdr, 0, sizeof (struct msghdr));\n\n if (address != NULL)\n {\n msgHdr.msg_name = & sin;\n msgHdr.msg_namelen = sizeof (struct sockaddr_in);\n }\n\n msgHdr.msg_iov = (struct iovec *) buffers;\n msgHdr.msg_iovlen = bufferCount;\n\n recvLength = recvmsg (socket, & msgHdr, MSG_NOSIGNAL);\n\n if (recvLength == -1)\n {\n if (errno == EWOULDBLOCK)\n return 0;\n\n return -1;\n }\n\n#ifdef HAS_MSGHDR_FLAGS\n if (msgHdr.msg_flags & MSG_TRUNC)\n return -1;\n#endif\n\n if (address != NULL)\n {\n address -> host = (enet_uint32) sin.sin_addr.s_addr;\n address -> port = ENET_NET_TO_HOST_16 (sin.sin_port);\n }\n\n return recvLength;\n}\n\nint\nenet_socketset_select (ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout)\n{\n struct timeval timeVal;\n\n timeVal.tv_sec = timeout \/ 1000;\n timeVal.tv_usec = (timeout % 1000) * 1000;\n\n return select (maxSocket + 1, readSet, writeSet, NULL, & timeVal);\n}\n\nint\nenet_socket_wait (ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout)\n{\n#ifdef HAS_POLL\n struct pollfd pollSocket;\n int pollCount;\n \n pollSocket.fd = socket;\n pollSocket.events = 0;\n\n if (* condition & ENET_SOCKET_WAIT_SEND)\n pollSocket.events |= POLLOUT;\n\n if (* condition & ENET_SOCKET_WAIT_RECEIVE)\n pollSocket.events |= POLLIN;\n\n pollCount = poll (& pollSocket, 1, timeout);\n\n if (pollCount < 0)\n return -1;\n\n * condition = ENET_SOCKET_WAIT_NONE;\n\n if (pollCount == 0)\n return 0;\n\n if (pollSocket.revents & POLLOUT)\n * condition |= ENET_SOCKET_WAIT_SEND;\n \n if (pollSocket.revents & POLLIN)\n * condition |= ENET_SOCKET_WAIT_RECEIVE;\n\n return 0;\n#else\n fd_set readSet, writeSet;\n struct timeval timeVal;\n int selectCount;\n\n timeVal.tv_sec = timeout \/ 1000;\n timeVal.tv_usec = (timeout % 1000) * 1000;\n\n FD_ZERO (& readSet);\n FD_ZERO (& writeSet);\n\n if (* condition & ENET_SOCKET_WAIT_SEND)\n FD_SET (socket, & writeSet);\n\n if (* condition & ENET_SOCKET_WAIT_RECEIVE)\n FD_SET (socket, & readSet);\n\n selectCount = select (socket + 1, & readSet, & writeSet, NULL, & timeVal);\n\n if (selectCount < 0)\n return -1;\n\n * condition = ENET_SOCKET_WAIT_NONE;\n\n if (selectCount == 0)\n return 0;\n\n if (FD_ISSET (socket, & writeSet))\n * condition |= ENET_SOCKET_WAIT_SEND;\n\n if (FD_ISSET (socket, & readSet))\n * condition |= ENET_SOCKET_WAIT_RECEIVE;\n\n return 0;\n#endif\n}\n\n#endif\n\nfix for platform that don't have SO_NOSIGPIPE\/** \n @file unix.c\n @brief ENet Unix system specific functions\n*\/\n#ifndef WIN32\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ENET_BUILDING_LIB 1\n#include \"enet\/enet.h\"\n\n#ifdef __APPLE__\n#undef HAS_POLL\n#ifndef HAS_SOCKLEN_T \n#define HAS_SOCKLEN_T\n#endif\n#ifndef HAS_FCNTL\n#define HAS_FCNTL\n#endif\n#endif\n\n#ifdef HAS_FCNTL\n#include \n#endif\n\n#ifdef HAS_POLL\n#include \n#endif\n\n#if defined(__socklen_t_defined) && !defined(HAS_SOCKLEN_T)\n#define HAS_SOCKLEN_T\n#endif\n\n#ifndef HAS_SOCKLEN_T\ntypedef int socklen_t;\n#endif\n\n#ifndef MSG_NOSIGNAL\n#define MSG_NOSIGNAL 0\n#endif\n\nstatic enet_uint32 timeBase = 0;\n\nint\nenet_initialize (void)\n{\n return 0;\n}\n\nvoid\nenet_deinitialize (void)\n{\n}\n\nenet_uint32\nenet_time_get (void)\n{\n struct timeval timeVal;\n\n gettimeofday (& timeVal, NULL);\n\n return timeVal.tv_sec * 1000 + timeVal.tv_usec \/ 1000 - timeBase;\n}\n\nvoid\nenet_time_set (enet_uint32 newTimeBase)\n{\n struct timeval timeVal;\n\n gettimeofday (& timeVal, NULL);\n \n timeBase = timeVal.tv_sec * 1000 + timeVal.tv_usec \/ 1000 - newTimeBase;\n}\n\nint\nenet_address_set_host (ENetAddress * address, const char * name)\n{\n struct hostent * hostEntry = NULL;\n#ifdef HAS_GETHOSTBYNAME_R\n struct hostent hostData;\n char buffer [2048];\n int errnum;\n\n#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)\n gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum);\n#else\n hostEntry = gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & errnum);\n#endif\n#else\n hostEntry = gethostbyname (name);\n#endif\n\n if (hostEntry == NULL ||\n hostEntry -> h_addrtype != AF_INET)\n {\n#ifdef HAS_INET_PTON\n if (! inet_pton (AF_INET, name, & address -> host))\n#else\n if (! inet_aton (name, (struct in_addr *) & address -> host))\n#endif\n return -1;\n return 0;\n }\n\n address -> host = * (enet_uint32 *) hostEntry -> h_addr_list [0];\n\n return 0;\n}\n\nint\nenet_address_get_host_ip (const ENetAddress * address, char * name, size_t nameLength)\n{\n#ifdef HAS_INET_NTOP\n if (inet_ntop (AF_INET, & address -> host, name, nameLength) == NULL)\n#else\n char * addr = inet_ntoa (* (struct in_addr *) & address -> host);\n if (addr != NULL)\n strncpy (name, addr, nameLength);\n else\n#endif\n return -1;\n return 0;\n}\n\nint\nenet_address_get_host (const ENetAddress * address, char * name, size_t nameLength)\n{\n struct in_addr in;\n struct hostent * hostEntry = NULL;\n#ifdef HAS_GETHOSTBYADDR_R\n struct hostent hostData;\n char buffer [2048];\n int errnum;\n\n in.s_addr = address -> host;\n\n#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)\n gethostbyaddr_r ((char *) & in, sizeof (struct in_addr), AF_INET, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum);\n#else\n hostEntry = gethostbyaddr_r ((char *) & in, sizeof (struct in_addr), AF_INET, & hostData, buffer, sizeof (buffer), & errnum);\n#endif\n#else\n in.s_addr = address -> host;\n\n hostEntry = gethostbyaddr ((char *) & in, sizeof (struct in_addr), AF_INET);\n#endif\n\n if (hostEntry == NULL)\n return enet_address_get_host_ip (address, name, nameLength);\n\n strncpy (name, hostEntry -> h_name, nameLength);\n\n return 0;\n}\n\nint\nenet_socket_bind (ENetSocket socket, const ENetAddress * address)\n{\n struct sockaddr_in sin;\n\n memset (& sin, 0, sizeof (struct sockaddr_in));\n\n sin.sin_family = AF_INET;\n\n if (address != NULL)\n {\n sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);\n sin.sin_addr.s_addr = address -> host;\n }\n else\n {\n sin.sin_port = 0;\n sin.sin_addr.s_addr = INADDR_ANY;\n }\n\n return bind (socket,\n (struct sockaddr *) & sin,\n sizeof (struct sockaddr_in)); \n}\n\nint \nenet_socket_listen (ENetSocket socket, int backlog)\n{\n return listen (socket, backlog < 0 ? SOMAXCONN : backlog);\n}\n\nENetSocket\nenet_socket_create (ENetSocketType type)\n{\n ENetSocket sd = socket (PF_INET, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);\n \n \/\/ disable any sig pipe exceptions \n#ifdef SO_NOSIGPIPE\n if (sd) {\n int set = 1;\n setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));\n }\n#endif\n return sd;\n}\n\nint\nenet_socket_set_option (ENetSocket socket, ENetSocketOption option, int value)\n{\n int result = -1;\n switch (option)\n {\n case ENET_SOCKOPT_NONBLOCK:\n#ifdef HAS_FCNTL\n result = fcntl (socket, F_SETFL, O_NONBLOCK | fcntl (socket, F_GETFL));\n#else\n result = ioctl (socket, FIONBIO, & value);\n#endif\n break;\n\n case ENET_SOCKOPT_BROADCAST:\n result = setsockopt (socket, SOL_SOCKET, SO_BROADCAST, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_REUSEADDR:\n result = setsockopt (socket, SOL_SOCKET, SO_REUSEADDR, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_RCVBUF:\n result = setsockopt (socket, SOL_SOCKET, SO_RCVBUF, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_SNDBUF:\n result = setsockopt (socket, SOL_SOCKET, SO_SNDBUF, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_RCVTIMEO:\n result = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & value, sizeof (int));\n break;\n\n case ENET_SOCKOPT_SNDTIMEO:\n result = setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & value, sizeof (int));\n break;\n\n default:\n break;\n }\n return result == -1 ? -1 : 0;\n}\n\nint\nenet_socket_connect (ENetSocket socket, const ENetAddress * address)\n{\n struct sockaddr_in sin;\n\n memset (& sin, 0, sizeof (struct sockaddr_in));\n\n sin.sin_family = AF_INET;\n sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);\n sin.sin_addr.s_addr = address -> host;\n\n return connect (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in));\n}\n\nENetSocket\nenet_socket_accept (ENetSocket socket, ENetAddress * address)\n{\n int result;\n struct sockaddr_in sin;\n socklen_t sinLength = sizeof (struct sockaddr_in);\n\n result = accept (socket, \n address != NULL ? (struct sockaddr *) & sin : NULL, \n address != NULL ? & sinLength : NULL);\n \n if (result == -1)\n return ENET_SOCKET_NULL;\n\n if (address != NULL)\n {\n address -> host = (enet_uint32) sin.sin_addr.s_addr;\n address -> port = ENET_NET_TO_HOST_16 (sin.sin_port);\n }\n\n return result;\n} \n \nvoid\nenet_socket_destroy (ENetSocket socket)\n{\n close (socket);\n}\n\nint\nenet_socket_send (ENetSocket socket,\n const ENetAddress * address,\n const ENetBuffer * buffers,\n size_t bufferCount)\n{\n struct msghdr msgHdr;\n struct sockaddr_in sin;\n int sentLength;\n\n memset (& msgHdr, 0, sizeof (struct msghdr));\n\n if (address != NULL)\n {\n memset (& sin, 0, sizeof (struct sockaddr_in));\n\n sin.sin_family = AF_INET;\n sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);\n sin.sin_addr.s_addr = address -> host;\n\n msgHdr.msg_name = & sin;\n msgHdr.msg_namelen = sizeof (struct sockaddr_in);\n }\n\n msgHdr.msg_iov = (struct iovec *) buffers;\n msgHdr.msg_iovlen = bufferCount;\n\n sentLength = sendmsg (socket, & msgHdr, MSG_NOSIGNAL);\n \n if (sentLength == -1)\n {\n if (errno == EWOULDBLOCK)\n return 0;\n\n return -1;\n }\n\n return sentLength;\n}\n\nint\nenet_socket_receive (ENetSocket socket,\n ENetAddress * address,\n ENetBuffer * buffers,\n size_t bufferCount)\n{\n struct msghdr msgHdr;\n struct sockaddr_in sin;\n int recvLength;\n\n memset (& msgHdr, 0, sizeof (struct msghdr));\n\n if (address != NULL)\n {\n msgHdr.msg_name = & sin;\n msgHdr.msg_namelen = sizeof (struct sockaddr_in);\n }\n\n msgHdr.msg_iov = (struct iovec *) buffers;\n msgHdr.msg_iovlen = bufferCount;\n\n recvLength = recvmsg (socket, & msgHdr, MSG_NOSIGNAL);\n\n if (recvLength == -1)\n {\n if (errno == EWOULDBLOCK)\n return 0;\n\n return -1;\n }\n\n#ifdef HAS_MSGHDR_FLAGS\n if (msgHdr.msg_flags & MSG_TRUNC)\n return -1;\n#endif\n\n if (address != NULL)\n {\n address -> host = (enet_uint32) sin.sin_addr.s_addr;\n address -> port = ENET_NET_TO_HOST_16 (sin.sin_port);\n }\n\n return recvLength;\n}\n\nint\nenet_socketset_select (ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout)\n{\n struct timeval timeVal;\n\n timeVal.tv_sec = timeout \/ 1000;\n timeVal.tv_usec = (timeout % 1000) * 1000;\n\n return select (maxSocket + 1, readSet, writeSet, NULL, & timeVal);\n}\n\nint\nenet_socket_wait (ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout)\n{\n#ifdef HAS_POLL\n struct pollfd pollSocket;\n int pollCount;\n \n pollSocket.fd = socket;\n pollSocket.events = 0;\n\n if (* condition & ENET_SOCKET_WAIT_SEND)\n pollSocket.events |= POLLOUT;\n\n if (* condition & ENET_SOCKET_WAIT_RECEIVE)\n pollSocket.events |= POLLIN;\n\n pollCount = poll (& pollSocket, 1, timeout);\n\n if (pollCount < 0)\n return -1;\n\n * condition = ENET_SOCKET_WAIT_NONE;\n\n if (pollCount == 0)\n return 0;\n\n if (pollSocket.revents & POLLOUT)\n * condition |= ENET_SOCKET_WAIT_SEND;\n \n if (pollSocket.revents & POLLIN)\n * condition |= ENET_SOCKET_WAIT_RECEIVE;\n\n return 0;\n#else\n fd_set readSet, writeSet;\n struct timeval timeVal;\n int selectCount;\n\n timeVal.tv_sec = timeout \/ 1000;\n timeVal.tv_usec = (timeout % 1000) * 1000;\n\n FD_ZERO (& readSet);\n FD_ZERO (& writeSet);\n\n if (* condition & ENET_SOCKET_WAIT_SEND)\n FD_SET (socket, & writeSet);\n\n if (* condition & ENET_SOCKET_WAIT_RECEIVE)\n FD_SET (socket, & readSet);\n\n selectCount = select (socket + 1, & readSet, & writeSet, NULL, & timeVal);\n\n if (selectCount < 0)\n return -1;\n\n * condition = ENET_SOCKET_WAIT_NONE;\n\n if (selectCount == 0)\n return 0;\n\n if (FD_ISSET (socket, & writeSet))\n * condition |= ENET_SOCKET_WAIT_SEND;\n\n if (FD_ISSET (socket, & readSet))\n * condition |= ENET_SOCKET_WAIT_RECEIVE;\n\n return 0;\n#endif\n}\n\n#endif\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \"emmintrin.h\"\n#include \"include\/perf.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ninline bool exists_image(const std::string& name) {\n struct stat buffer; \n return (stat (name.c_str(), &buffer) == 0); \n}\n\n#ifdef COUNT_FLOPS\n struct global_op_count __GLOBAL_OP_COUNT;\n#endif\n\n#ifdef COUNT_DETAIL_CYCLES\n struct global_function_cycle_count __COUNT_DETAIL_CYCLES;\n#endif\nvoid init_counting_flops(){\n#ifdef COUNT_FLOPS\n __GLOBAL_OP_COUNT.int_adds=0;\n __GLOBAL_OP_COUNT.int_mults=0;\n __GLOBAL_OP_COUNT.fp_adds=0;\n __GLOBAL_OP_COUNT.fp_mults=0;\n#endif\n}\n\nvoid init_counting_cycles(){\n#ifdef COUNT_DETAIL_CYCLES\n __COUNT_DETAIL_CYCLES.get_average_pixel_cycles=0;\n __COUNT_DETAIL_CYCLES.get_error_cycles=0;\n __COUNT_DETAIL_CYCLES.get_scale_factor_cycles=0;\n __COUNT_DETAIL_CYCLES.down_sample_cycles=0;\n __COUNT_DETAIL_CYCLES.ifs_transformation_execute_cycles=0;\n#endif\n}\nvoid print_detailed_cycles(){\n#ifdef COUNT_DETAIL_CYCLES\n cout<<\"get_average_pixel_cycles: \"<<__COUNT_DETAIL_CYCLES.get_average_pixel_cycles<\\n\";\n return ERR_NO_IMAGE_PATH;\n }\n\n if (!exists_image(image_path.c_str())) {\n std::cout << \"Provided image does not exist\\n\";\n return ERR_NO_IMAGE_PATH;\n }\n\n perf_init();\n\n BMPImage img(image_path.c_str());\n img.Load();\n\n \/\/ Encoding part\n Encoder enc;\n Transforms transforms;\n ifs_trans_init_transformations(&transforms, img.GetChannels());\n init_counting_flops();\n init_counting_cycles();\n cycles_count_start();\n\n enc.Encode(img, &transforms, threshold);\n\n int64_t encodeCycles = cycles_count_stop ();\n print_detailed_cycles();\n print_op_count(\"encoder\");\n\n printf(\"Image height: %d, width: %d\\n\", img.GetHeight(), img.GetWidth());\n\n \/\/ Decoder part\n int64_t decodeCycles=0;\n if(decode){\n BMPImage result(outputFile, img.GetHeight(), img.GetWidth(), transforms.channels);\n Decoder dec;\n init_counting_flops();\n cycles_count_start ();\n dec.Decode(&transforms, result, maxphases);\n decodeCycles = cycles_count_stop ();\n print_op_count(\"decoder\");\n result.Save();\n }\n\n \/\/ Calculate compression ratio\n int64_t transformationsSize=0;\n int64_t transformationNumber=0;\n for(int i=0;iAdded printf value#include \n#include \n#include \"emmintrin.h\"\n#include \"include\/perf.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ninline bool exists_image(const std::string& name) {\n struct stat buffer; \n return (stat (name.c_str(), &buffer) == 0); \n}\n\n#ifdef COUNT_FLOPS\n struct global_op_count __GLOBAL_OP_COUNT;\n#endif\n\n#ifdef COUNT_DETAIL_CYCLES\n struct global_function_cycle_count __COUNT_DETAIL_CYCLES;\n#endif\nvoid init_counting_flops(){\n#ifdef COUNT_FLOPS\n __GLOBAL_OP_COUNT.int_adds=0;\n __GLOBAL_OP_COUNT.int_mults=0;\n __GLOBAL_OP_COUNT.fp_adds=0;\n __GLOBAL_OP_COUNT.fp_mults=0;\n#endif\n}\n\nvoid init_counting_cycles(){\n#ifdef COUNT_DETAIL_CYCLES\n __COUNT_DETAIL_CYCLES.get_average_pixel_cycles=0;\n __COUNT_DETAIL_CYCLES.get_error_cycles=0;\n __COUNT_DETAIL_CYCLES.get_scale_factor_cycles=0;\n __COUNT_DETAIL_CYCLES.down_sample_cycles=0;\n __COUNT_DETAIL_CYCLES.ifs_transformation_execute_cycles=0;\n#endif\n}\nvoid print_detailed_cycles(){\n#ifdef COUNT_DETAIL_CYCLES\n cout<<\"get_average_pixel_cycles: \"<<__COUNT_DETAIL_CYCLES.get_average_pixel_cycles<\\n\";\n return ERR_NO_IMAGE_PATH;\n }\n\n if (!exists_image(image_path.c_str())) {\n std::cout << \"Provided image does not exist\\n\";\n return ERR_NO_IMAGE_PATH;\n }\n\n perf_init();\n\n BMPImage img(image_path.c_str());\n img.Load();\n\n \/\/ Encoding part\n Encoder enc;\n Transforms transforms;\n ifs_trans_init_transformations(&transforms, img.GetChannels());\n init_counting_flops();\n init_counting_cycles();\n cycles_count_start();\n\n enc.Encode(img, &transforms, threshold);\n\n int64_t encodeCycles = cycles_count_stop ();\n print_detailed_cycles();\n print_op_count(\"encoder\");\n\n printf(\"Image height: %d, width: %d\\n\", img.GetHeight(), img.GetWidth());\n\n \/\/ Decoder part\n int64_t decodeCycles=0;\n if(decode){\n BMPImage result(outputFile, img.GetHeight(), img.GetWidth(), transforms.channels);\n Decoder dec;\n init_counting_flops();\n cycles_count_start ();\n dec.Decode(&transforms, result, maxphases);\n decodeCycles = cycles_count_stop ();\n print_op_count(\"decoder\");\n result.Save();\n }else{\n cout<<\"Not running decoding\"<"} {"text":"#include \n#include \n#include \n#include \n\n#include \"vtrc-common\/vtrc-thread-pool.h\"\n#include \"vtrc-client-base\/vtrc-client.h\"\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n\n#include \n#include \n\nvoid on_connect( const boost::system::error_code &err )\n{\n std::cout << \"connected \"\n << err.value( ) << \" \"\n << err.message( ) << \"\\n\";\n}\n\nusing namespace vtrc;\n\n\nint main( )\n{\n\n common::thread_pool tp(4);\n client::vtrc_client cl( tp.get_io_service( ) );\n\n cl.connect( \"127.0.0.1\", \"44667\" );\n \/\/\/cl.async_connect( \"127.0.0.1\", \"44667\", on_connect );\n\n sleep( 2 );\n\n vtrc_rpc_lowlevel::test_rpc::Stub s( cl.get_channel( ).get( ) );\n\n vtrc_rpc_lowlevel::message_info mi;\n\n for( int i=0; i<10000000; ++i ) {\n s.test( NULL, &mi, &mi, NULL );\n std::cout << \"response: \" << mi.message_type( ) << \"\\n\";\n }\n\n tp.join_all( );\n\n return 0;\n\n}\nprotocol#include \n#include \n#include \n#include \n\n#include \"vtrc-common\/vtrc-thread-pool.h\"\n#include \"vtrc-client-base\/vtrc-client.h\"\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n\n#include \n#include \n\nvoid on_connect( const boost::system::error_code &err )\n{\n std::cout << \"connected \"\n << err.value( ) << \" \"\n << err.message( ) << \"\\n\";\n}\n\nusing namespace vtrc;\n\nint main( )\n{\n\n common::thread_pool tp(4);\n client::vtrc_client cl( tp.get_io_service( ) );\n\n cl.connect( \"127.0.0.1\", \"44667\" );\n \/\/\/cl.async_connect( \"127.0.0.1\", \"44667\", on_connect );\n\n sleep( 2 );\n\n vtrc_rpc_lowlevel::test_rpc::Stub s( cl.get_channel( ).get( ) );\n\n vtrc_rpc_lowlevel::message_info mi;\n\n for( int i=0; i<10000000; ++i ) {\n s.test( NULL, &mi, &mi, NULL );\n std::cout << \"response: \" << mi.message_type( ) << \"\\n\";\n }\n\n tp.join_all( );\n\n return 0;\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 Mirants Lu. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"voyager\/core\/timerlist.h\"\n#include \"voyager\/util\/logging.h\"\n#include \"voyager\/util\/timeops.h\"\n\n\nnamespace voyager {\n\nclass Timer {\n private:\n friend class TimerList;\n\n Timer(uint64_t value, uint64_t interval, const TimerProcCallback& cb)\n : micros_value(value),\n micros_interval(interval),\n timerproc_cb(cb),\n repeat(false) {\n if (micros_interval > 0) {\n repeat = true;\n }\n }\n\n Timer(uint64_t value, uint64_t interval, TimerProcCallback&& cb)\n : micros_value(value),\n micros_interval(interval),\n timerproc_cb(std::move(cb)),\n repeat(false) {\n if (micros_interval > 0) {\n repeat = true;\n }\n }\n\n ~Timer() {\n }\n\n uint64_t micros_value;\n uint64_t micros_interval;\n TimerProcCallback timerproc_cb;\n bool repeat;\n};\n\nTimerList::TimerList(EventLoop* ev)\n : eventloop_(CHECK_NOTNULL(ev)) {\n}\n\nTimerList::~TimerList() {\n for (auto& t : timer_ptrs_) {\n delete t;\n }\n}\n\nTimerId TimerList::Insert(uint64_t micros_value,\n uint64_t micros_interval,\n const TimerProcCallback& cb) {\n TimerId timer(micros_value, new Timer(micros_value, micros_interval, cb));\n eventloop_->RunInLoop([this, timer]() {\n InsertInLoop(timer);\n });\n return timer;\n}\n\nTimerId TimerList::Insert(uint64_t micros_value,\n uint64_t micros_interval,\n TimerProcCallback&& cb) {\n TimerId timer(micros_value,\n new Timer(micros_value, micros_interval, std::move(cb)));\n eventloop_->RunInLoop([this, timer]() {\n InsertInLoop(timer);\n });\n return timer;\n}\n\nvoid TimerList::Erase(TimerId timer) {\n eventloop_->RunInLoop([this, timer]() {\n EraseInLoop(timer);\n });\n}\n\nvoid TimerList::InsertInLoop(TimerId timer) {\n eventloop_->AssertInMyLoop();\n timers_.insert(timer);\n timer_ptrs_.insert(timer.second);\n}\n\nvoid TimerList::EraseInLoop(TimerId timer) {\n eventloop_->AssertInMyLoop();\n std::set::iterator it = timer_ptrs_.find(timer.second);\n if (it != timer_ptrs_.end()) {\n timer.first = timer.second->micros_value;\n timers_.erase(timer);\n delete *it;\n timer_ptrs_.erase(it);\n }\n}\n\nuint64_t TimerList::TimeoutMicros() const {\n eventloop_->AssertInMyLoop();\n if (timers_.empty()) {\n return -1;\n }\n std::set::iterator it = timers_.begin();\n if (it->first < timeops::NowMicros()) {\n return 0;\n } else {\n return (it->first - timeops::NowMicros());\n }\n}\n\nvoid TimerList::RunTimerProcs() {\n eventloop_->AssertInMyLoop();\n if (timers_.empty()) {\n return;\n }\n\n uint64_t micros_now = timeops::NowMicros();\n std::set::iterator it;\n while (true) {\n it = timers_.begin();\n if (it != timers_.end() && it->first <= micros_now) {\n Timer* t = it->second;\n timers_.erase(it);\n t->timerproc_cb();\n if (t->repeat) {\n t->micros_value += t->micros_interval;\n TimerId timer(t->micros_value, t);\n timers_.insert(timer);\n } else {\n delete t;\n timer_ptrs_.erase(t);\n }\n } else {\n break;\n }\n }\n}\n\n} \/\/ namespace voyager\nfix timer\/\/ Copyright (c) 2016 Mirants Lu. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"voyager\/core\/timerlist.h\"\n#include \"voyager\/util\/logging.h\"\n#include \"voyager\/util\/timeops.h\"\n\n\nnamespace voyager {\n\nclass Timer {\n private:\n friend class TimerList;\n\n Timer(uint64_t value, uint64_t interval, const TimerProcCallback& cb)\n : micros_value(value),\n micros_interval(interval),\n timerproc_cb(cb),\n repeat(false) {\n if (micros_interval > 0) {\n repeat = true;\n }\n }\n\n Timer(uint64_t value, uint64_t interval, TimerProcCallback&& cb)\n : micros_value(value),\n micros_interval(interval),\n timerproc_cb(std::move(cb)),\n repeat(false) {\n if (micros_interval > 0) {\n repeat = true;\n }\n }\n\n ~Timer() {\n }\n\n uint64_t micros_value;\n uint64_t micros_interval;\n TimerProcCallback timerproc_cb;\n bool repeat;\n};\n\nTimerList::TimerList(EventLoop* ev)\n : eventloop_(CHECK_NOTNULL(ev)) {\n}\n\nTimerList::~TimerList() {\n for (auto& t : timer_ptrs_) {\n delete t;\n }\n}\n\nTimerId TimerList::Insert(uint64_t micros_value,\n uint64_t micros_interval,\n const TimerProcCallback& cb) {\n TimerId timer(micros_value, new Timer(micros_value, micros_interval, cb));\n eventloop_->RunInLoop([this, timer]() {\n InsertInLoop(timer);\n });\n return timer;\n}\n\nTimerId TimerList::Insert(uint64_t micros_value,\n uint64_t micros_interval,\n TimerProcCallback&& cb) {\n TimerId timer(micros_value,\n new Timer(micros_value, micros_interval, std::move(cb)));\n eventloop_->RunInLoop([this, timer]() {\n InsertInLoop(timer);\n });\n return timer;\n}\n\nvoid TimerList::Erase(TimerId timer) {\n eventloop_->RunInLoop([this, timer]() {\n EraseInLoop(timer);\n });\n}\n\nvoid TimerList::InsertInLoop(TimerId timer) {\n eventloop_->AssertInMyLoop();\n timers_.insert(timer);\n timer_ptrs_.insert(timer.second);\n}\n\nvoid TimerList::EraseInLoop(TimerId timer) {\n eventloop_->AssertInMyLoop();\n std::set::iterator it = timer_ptrs_.find(timer.second);\n if (it != timer_ptrs_.end()) {\n timer.first = timer.second->micros_value;\n timers_.erase(timer);\n delete *it;\n timer_ptrs_.erase(it);\n }\n}\n\nuint64_t TimerList::TimeoutMicros() const {\n eventloop_->AssertInMyLoop();\n if (timers_.empty()) {\n return -1;\n }\n std::set::iterator it = timers_.begin();\n uint64_t now = timeops::NowMicros();\n if (it->first <= now) {\n return 0;\n } else {\n return (it->first - now);\n }\n}\n\nvoid TimerList::RunTimerProcs() {\n eventloop_->AssertInMyLoop();\n if (timers_.empty()) {\n return;\n }\n\n uint64_t micros_now = timeops::NowMicros();\n std::set::iterator it;\n while (true) {\n it = timers_.begin();\n if (it != timers_.end() && it->first <= micros_now) {\n Timer* t = it->second;\n timers_.erase(it);\n TimerProcCallback cb = t->timerproc_cb;\n if (t->repeat) {\n t->micros_value += t->micros_interval;\n TimerId timer(t->micros_value, t);\n timers_.insert(timer);\n } else {\n delete t;\n timer_ptrs_.erase(t);\n }\n \/\/ 为了避免周期定时无法移除定时器的问题。\n cb();\n } else {\n break;\n }\n }\n}\n\n} \/\/ namespace voyager\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n\n#include \"dwr.h\"\n#include \"widgets.h\"\n\nCheckBox::CheckBox(const char flag, const QString &text, QWidget *parent) :\n QCheckBox(text, parent)\n{\n this->flag = flag;\n}\n\nchar CheckBox::getFlag()\n{\n if (this->isChecked()) {\n return this->flag;\n }\n return NO_FLAG;\n}\n\nvoid CheckBox::stateChanged(int state)\n{\n super::stateChanged(state);\n}\n\nbool CheckBox::updateState(QString flags)\n{\n bool checked = flags.indexOf(QChar(this->flag)) >= 0;\n this->setChecked(checked);\n return checked;\n}\n\nLevelComboBox::LevelComboBox(QWidget *parent) : QComboBox(parent)\n{\n this->addItem(\"Normal\");\n this->addItem(\"Fast\");\n this->addItem(\"Very Fast\");\n}\n\nchar LevelComboBox::getFlag()\n{\n switch(this->currentIndex()) {\n case 1:\n return 'f';\n case 2:\n return 'F';\n default:\n return NO_FLAG;\n }\n}\n\nbool LevelComboBox::updateState(QString flags)\n{\n if (flags.indexOf(QChar('f')) >= 0) {\n this->setCurrentIndex(1);\n return true;\n } else {\n if (flags.indexOf(QChar('F')) >= 0) {\n this->setCurrentIndex(2);\n return true;\n }\n }\n this->setCurrentIndex(0);\n return false;\n}\n\nButtonEntry::ButtonEntry(QWidget *parent) :\n QWidget(parent)\n{\n QVBoxLayout *vbox = new QVBoxLayout();\n QHBoxLayout *hbox = new QHBoxLayout();\n this->textBox = new QLineEdit(this);\n this->button = new QPushButton(\"Click\", this);\n this->label = new QLabel(\"\", this);\n vbox->addWidget(this->label);\n hbox->addWidget(this->textBox);\n hbox->addWidget(this->button);\n vbox->addLayout(hbox);\n this->setLayout(vbox);\n connect(this->button, SIGNAL(clicked()), this, SLOT(handleButton()));\n connect(this->textBox, SIGNAL(textEdited(QString)), this, SLOT(handleEdit(QString)));\n}\n\n\nQString ButtonEntry::text()\n{\n return this->textBox->text();\n}\n\nvoid ButtonEntry::setText(QString text)\n{\n this->textBox->setText(text);\n}\n\nFileEntry::FileEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Browse...\");\n this->label->setText(\"ROM File\");\n}\n\nvoid FileEntry::handleButton()\n{\n QString filename = QFileDialog::getOpenFileName(\n this, \"Choose the ROM file\", \".\/\", \"NES ROM Files (*.nes)\");\n this->textBox->setText(filename);\n}\n\nDirEntry::DirEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Browse...\");\n#ifdef _WIN32\n this->label->setText(\"Output Folder\");\n#else\n this->label->setText(\"Output Directory\");\n#endif\n}\n\nvoid DirEntry::handleButton()\n{\n QString dirName = QFileDialog::getExistingDirectory(this,\n#ifdef _WIN32\n \"Choose the output folder\",\n#else\n \"Choose the output directory\",\n#endif\n \".\/\");\n this->textBox->setText(dirName);\n}\n\nSeedEntry::SeedEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Random\");\n this->label->setText(\"Seed\");\n this->handleButton();\n}\n\nvoid SeedEntry::handleButton()\n{\n uint64_t seed;\n char seedString[21];\n srand(time(NULL));\n seed = ((uint64_t)rand() << 32) | ((uint64_t)rand() & 0xffffffffL);\n snprintf(seedString, 21, \"%\" PRIu64, seed);\n this->textBox->setText(QString(seedString));\n}\n\nuint64_t SeedEntry::getSeed()\n{\n uint64_t seed;\n sscanf(this->textBox->text().toLatin1().constData(), \"%\"PRIu64, &seed);\n return seed;\n}\n\nFlagEntry::FlagEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Defaults\");\n this->label->setText(\"Flags\");\n}\n\nvoid FlagEntry::handleButton()\n{\n this->setText(DEFAULT_FLAGS);\n this->textBox->textEdited(this->text());\n}\n\nvoid FlagEntry::handleEdit(QString text)\n{\n this->textEdited(text);\n}\n\nFixed a compile error on OSX\n#include \n#include \n#include \n#include \n#include \n\n#include \"dwr.h\"\n#include \"widgets.h\"\n\nCheckBox::CheckBox(const char flag, const QString &text, QWidget *parent) :\n QCheckBox(text, parent)\n{\n this->flag = flag;\n}\n\nchar CheckBox::getFlag()\n{\n if (this->isChecked()) {\n return this->flag;\n }\n return NO_FLAG;\n}\n\nvoid CheckBox::stateChanged(int state)\n{\n super::stateChanged(state);\n}\n\nbool CheckBox::updateState(QString flags)\n{\n bool checked = flags.indexOf(QChar(this->flag)) >= 0;\n this->setChecked(checked);\n return checked;\n}\n\nLevelComboBox::LevelComboBox(QWidget *parent) : QComboBox(parent)\n{\n this->addItem(\"Normal\");\n this->addItem(\"Fast\");\n this->addItem(\"Very Fast\");\n}\n\nchar LevelComboBox::getFlag()\n{\n switch(this->currentIndex()) {\n case 1:\n return 'f';\n case 2:\n return 'F';\n default:\n return NO_FLAG;\n }\n}\n\nbool LevelComboBox::updateState(QString flags)\n{\n if (flags.indexOf(QChar('f')) >= 0) {\n this->setCurrentIndex(1);\n return true;\n } else {\n if (flags.indexOf(QChar('F')) >= 0) {\n this->setCurrentIndex(2);\n return true;\n }\n }\n this->setCurrentIndex(0);\n return false;\n}\n\nButtonEntry::ButtonEntry(QWidget *parent) :\n QWidget(parent)\n{\n QVBoxLayout *vbox = new QVBoxLayout();\n QHBoxLayout *hbox = new QHBoxLayout();\n this->textBox = new QLineEdit(this);\n this->button = new QPushButton(\"Click\", this);\n this->label = new QLabel(\"\", this);\n vbox->addWidget(this->label);\n hbox->addWidget(this->textBox);\n hbox->addWidget(this->button);\n vbox->addLayout(hbox);\n this->setLayout(vbox);\n connect(this->button, SIGNAL(clicked()), this, SLOT(handleButton()));\n connect(this->textBox, SIGNAL(textEdited(QString)), this, SLOT(handleEdit(QString)));\n}\n\n\nQString ButtonEntry::text()\n{\n return this->textBox->text();\n}\n\nvoid ButtonEntry::setText(QString text)\n{\n this->textBox->setText(text);\n}\n\nFileEntry::FileEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Browse...\");\n this->label->setText(\"ROM File\");\n}\n\nvoid FileEntry::handleButton()\n{\n QString filename = QFileDialog::getOpenFileName(\n this, \"Choose the ROM file\", \".\/\", \"NES ROM Files (*.nes)\");\n this->textBox->setText(filename);\n}\n\nDirEntry::DirEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Browse...\");\n#ifdef _WIN32\n this->label->setText(\"Output Folder\");\n#else\n this->label->setText(\"Output Directory\");\n#endif\n}\n\nvoid DirEntry::handleButton()\n{\n QString dirName = QFileDialog::getExistingDirectory(this,\n#ifdef _WIN32\n \"Choose the output folder\",\n#else\n \"Choose the output directory\",\n#endif\n \".\/\");\n this->textBox->setText(dirName);\n}\n\nSeedEntry::SeedEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Random\");\n this->label->setText(\"Seed\");\n this->handleButton();\n}\n\nvoid SeedEntry::handleButton()\n{\n uint64_t seed;\n char seedString[21];\n srand(time(NULL));\n seed = ((uint64_t)rand() << 32) | ((uint64_t)rand() & 0xffffffffL);\n snprintf(seedString, 21, \"%\" PRIu64, seed);\n this->textBox->setText(QString(seedString));\n}\n\nuint64_t SeedEntry::getSeed()\n{\n uint64_t seed;\n sscanf(this->textBox->text().toLatin1().constData(), \"%\" PRIu64, &seed);\n return seed;\n}\n\nFlagEntry::FlagEntry(QWidget *parent) : ButtonEntry(parent)\n{\n this->button->setText(\"Defaults\");\n this->label->setText(\"Flags\");\n}\n\nvoid FlagEntry::handleButton()\n{\n this->setText(DEFAULT_FLAGS);\n this->textBox->textEdited(this->text());\n}\n\nvoid FlagEntry::handleEdit(QString text)\n{\n this->textEdited(text);\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"drake\/core\/Gradient.h\"\n#include \"drake\/util\/drakeGeometryUtil.h\"\n#include \"drake\/util\/eigen_matrix_compare.h\"\n#include \"drake\/util\/testUtil.h\"\n#include \"gtest\/gtest.h\"\n\nusing Eigen::Isometry3d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\nusing Eigen::Dynamic;\nusing Eigen::Quaterniond;\nusing Eigen::Translation3d;\nusing std::default_random_engine;\nusing drake::util::MatrixCompareType;\nusing Drake::initializeAutoDiff;\n\nnamespace drake {\nnamespace util {\nnamespace {\n\nvoid testExpmap2quat(const Vector4d &quat);\n\nvoid testRotationConversionFunctions() {\n int ntests = 100;\n default_random_engine generator;\n \/\/ quat2axis, axis2quat\n for (int i = 0; i < ntests; i++) {\n Vector4d q = uniformlyRandomQuat(generator);\n auto a = quat2axis(q);\n auto q_back = axis2quat(a);\n valuecheck(acos(std::abs(q.transpose() * q_back)), 0.0, 1e-6);\n }\n \/\/ quat2rotmat, rotmat2quat\n for (int i = 0; i < ntests; i++) {\n Vector4d q = uniformlyRandomQuat(generator);\n Matrix3d R = quat2rotmat(q);\n Vector4d q_back = rotmat2quat(R);\n valuecheck(acos(std::abs(q.transpose() * q_back)), 0.0, 1e-6);\n }\n \/\/ quat2rpy, rpy2quat\n for (int i = 0; i < ntests; i++) {\n Vector4d q = uniformlyRandomQuat(generator);\n Vector3d rpy = quat2rpy(q);\n Vector4d q_back = rpy2quat(rpy);\n valuecheck(acos(std::abs(q.transpose() * q_back)), 0.0, 1e-6);\n }\n \/\/ rotmat2axis, axis2rotmat\n for (int i = 0; i < ntests; i++) {\n Matrix3d R = uniformlyRandomRotmat(generator);\n Vector4d a = rotmat2axis(R);\n Matrix3d R_back = axis2rotmat(a);\n EXPECT_TRUE(CompareMatrices(R, R_back, 1e-6, MatrixCompareType::absolute));\n }\n \/\/ rotmat2rpy, rpy2rotmat\n for (int i = 0; i < ntests; i++) {\n Matrix3d R = uniformlyRandomRotmat(generator);\n Vector3d rpy = rotmat2rpy(R);\n Matrix3d R_back = rpy2rotmat(rpy);\n EXPECT_TRUE(CompareMatrices(R, R_back, 1e-6, MatrixCompareType::absolute));\n }\n \/\/ rpy2axis, axis2rpy\n for (int i = 0; i < ntests; i++) {\n Vector3d rpy = uniformlyRandomRPY(generator);\n Vector4d axis = rpy2axis(rpy);\n Vector3d rpy_back = axis2rpy(axis);\n EXPECT_TRUE(\n CompareMatrices(rpy, rpy_back, 1e-6, MatrixCompareType::absolute));\n }\n \/\/ expmap2quat, quat2expmap\n Vector4d quat_degenerate = Vector4d::Zero();\n quat_degenerate(0) = 1.0;\n testExpmap2quat(quat_degenerate);\n quat_degenerate(0) = -1.0;\n testExpmap2quat(quat_degenerate);\n for (int i = 0; i < ntests; i++) {\n Vector4d quat = uniformlyRandomQuat(generator);\n testExpmap2quat(quat);\n }\n \/\/ quat2eigenQuaternion\n Vector4d quat = uniformlyRandomQuat(generator);\n Quaterniond eigenQuat = quat2eigenQuaternion(quat);\n Matrix3d R_expected = quat2rotmat(quat);\n Matrix3d R_eigen = eigenQuat.matrix();\n EXPECT_TRUE(\n CompareMatrices(R_expected, R_eigen, 1e-6, MatrixCompareType::absolute));\n}\n\nvoid testDHomogTrans(int ntests) {\n Isometry3d T;\n std::default_random_engine generator;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n T = Quaterniond(q(0), q(1), q(2), q(3));\n \/\/ T.setIdentity();\n \/\/ T = AngleAxisd(M_PI_2, Vector3d(1.0, 0.0, 0.0));\n\n const int nv = 6;\n const int nq = 7;\n\n auto S = Matrix::Random(6, nv).eval();\n \/\/ setLinearIndices(S);\n \/\/ S.setIdentity();\n \/\/ std::cout << S << \"\\n\\n\";\n\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n \/\/ setLinearIndices(qdot_to_v);\n \/\/ std::cout << qdot_to_v << \"\\n\\n\";\n\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n volatile auto vol = dT;\n \/\/ std::cout << dT << std::endl << std::endl;\n }\n}\n\nvoid testDHomogTransInv(int ntests, bool check) {\n Isometry3d T;\n std::default_random_engine generator;\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n \/\/ T = Quaterniond(q(0), q(1), q(2), q(3)) *\n \/\/ Translation3d(Vector3d::Random());\n T = Quaterniond(q(0), q(1), q(2), q(3));\n\n const int nv = 6;\n const int nq = 7;\n\n auto S = Matrix::Random(6, nv).eval();\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n auto dTInv = dHomogTransInv(T, dT);\n volatile auto vol = dTInv;\n\n if (check) {\n auto dTInvInv = dHomogTransInv(T.inverse(), dTInv);\n\n if (!dT.matrix().isApprox(dTInvInv.matrix(), 1e-10)) {\n std::cout << \"dTInv:\\n\" << dTInv << \"\\n\\n\";\n std::cout << \"dT:\\n\" << dT << \"\\n\\n\";\n std::cout << \"dTInvInv:\\n\" << dTInvInv << \"\\n\\n\";\n std::cout << \"dTInvInv - dT:\\n\" << dTInvInv - dT << \"\\n\\n\";\n\n throw std::runtime_error(\"wrong\");\n }\n }\n }\n}\n\nvoid testDTransformAdjoint(int ntests) {\n const int nv = 6;\n const int nq = 34;\n const int cols_X = 3;\n\n Isometry3d T;\n std::default_random_engine generator;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n auto S = Matrix::Random(6, nv).eval();\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n auto X = Matrix::Random(6, cols_X).eval();\n auto dX = MatrixXd::Random(X.size(), nq).eval();\n \/\/ auto dX = Matrix::Random().eval();\n auto dAdT_times_X = dTransformSpatialMotion(T, X, dT, dX).eval();\n volatile auto vol = dAdT_times_X;\n }\n}\n\nvoid testDTransformAdjointTranspose(int ntests) {\n const int nv = 6;\n const int nq = 34;\n const int cols_X = 3;\n\n Isometry3d T;\n std::default_random_engine generator;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n auto S = Matrix::Random(6, nv).eval();\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n auto X = Matrix::Random(6, cols_X).eval();\n auto dX = MatrixXd::Random(X.size(), nq).eval();\n \/\/ auto dX = Matrix::Random().eval();\n auto dAdTtranspose_times_X = dTransformSpatialForce(T, X, dT, dX).eval();\n volatile auto vol = dAdTtranspose_times_X;\n }\n}\n\nvoid testNormalizeVec(int ntests) {\n const int x_rows = 4;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n auto x = Matrix::Random().eval();\n Matrix x_norm;\n Matrix dx_norm;\n Matrix ddx_norm;\n normalizeVec(x, x_norm, &dx_norm, &ddx_norm);\n \/\/ std::cout << \"gradientNumRows: \" << gradientNumRows(x_rows, x_rows, 1)\n \/\/ << std::endl;\n\n volatile auto volx_norm = x_norm;\n volatile auto voldx_norm = dx_norm;\n volatile auto volddx_norm = ddx_norm;\n\n \/\/ std::cout << \"x_norm:\\n\" << x_norm << std::endl << std::endl;\n \/\/ std::cout << \"dx_norm:\\n\" << dx_norm << std::endl << std::endl;\n \/\/ std::cout << \"ddx_norm:\\n\" << ddx_norm << std::endl << std::endl;\n }\n}\n\nvoid testSpatialCrossProduct() {\n auto a = (Matrix::Random()).eval();\n auto b = (Matrix::Identity()).eval();\n auto a_crm_b = crossSpatialMotion(a, b);\n auto a_crf_b = crossSpatialForce(a, b);\n EXPECT_TRUE(CompareMatrices(a_crf_b, -a_crm_b.transpose(), 1e-8,\n MatrixCompareType::absolute));\n}\n\nvoid testdrpy2rotmat() {\n default_random_engine generator;\n Vector3d rpy = uniformlyRandomRPY(generator);\n Matrix3d R = rpy2rotmat(rpy);\n Matrix dR = drpy2rotmat(rpy);\n Matrix dR_num = Matrix::Zero();\n for (int i = 0; i < 3; i++) {\n Vector3d err = Vector3d::Zero();\n err(i) = 1e-7;\n Vector3d rpyi = rpy + err;\n Matrix3d Ri = rpy2rotmat(rpyi);\n Matrix3d Ri_err = (Ri - R) \/ err(i);\n for (int j = 0; j < 9; j++) {\n dR_num(j, i) = Ri_err(j);\n valuecheck(dR(j, i), dR_num(j, i), 1e-3);\n }\n }\n}\n\nvoid testExpmap2quat(const Vector4d &quat) {\n auto quat_autodiff = initializeAutoDiff(quat);\n auto expmap_autodiff = quat2expmap(quat_autodiff);\n auto expmap = autoDiffToValueMatrix(expmap_autodiff);\n auto expmap_grad = autoDiffToGradientMatrix(expmap_autodiff);\n auto quat_back_autodiff = expmap2quat(initializeAutoDiff(expmap));\n auto quat_back = autoDiffToValueMatrix(quat_back_autodiff);\n auto quat_back_grad = autoDiffToGradientMatrix(quat_back_autodiff);\n valuecheck(std::abs((quat.transpose() * quat_back).value()), 1.0, 1e-8);\n Matrix3d identity = Matrix3d::Identity();\n EXPECT_TRUE(CompareMatrices((expmap_grad * quat_back_grad).eval(), identity,\n 1e-10, MatrixCompareType::absolute));\n}\n\nTEST(drakeGeometryUtilTest, AllTests) {\n testRotationConversionFunctions();\n\n int ntests = 100000;\n std::cout << \"testDHomogTrans elapsed time: \"\n << measure<>::execution(testDHomogTrans, ntests) << std::endl;\n std::cout << \"testDHomogTransInv elapsed time: \"\n << measure<>::execution(testDHomogTransInv, ntests, false)\n << std::endl;\n std::cout << \"testDTransformAdjoint elapsed time: \"\n << measure<>::execution(testDTransformAdjoint, ntests) << std::endl;\n std::cout << \"testDTransformAdjointTranspose elapsed time: \"\n << measure<>::execution(testDTransformAdjointTranspose, ntests)\n << std::endl;\n std::cout << \"testNormalizeVec elapsed time: \"\n << measure<>::execution(testNormalizeVec, ntests) << std::endl;\n\n testDHomogTransInv(1000, true);\n testSpatialCrossProduct();\n testdrpy2rotmat();\n}\n\n} \/\/ namespace\n} \/\/ namespace util\n} \/\/ namespace drake\nPer Issue #2055: * set 'ntests = 1' everywhere -- forget doing any kind of benchmarking here, and just run every test loop for one iteration; * turn calls to individual test functions into actual gtest test functions, instead of glomming them all into a single \"AllTests\" gtest function.#include \n#include \n#include \n#include \"drake\/core\/Gradient.h\"\n#include \"drake\/util\/drakeGeometryUtil.h\"\n#include \"drake\/util\/eigen_matrix_compare.h\"\n#include \"drake\/util\/testUtil.h\"\n#include \"gtest\/gtest.h\"\n\nusing Eigen::Isometry3d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\nusing Eigen::Dynamic;\nusing Eigen::Quaterniond;\nusing Eigen::Translation3d;\nusing std::default_random_engine;\nusing drake::util::MatrixCompareType;\nusing Drake::initializeAutoDiff;\n\nnamespace drake {\nnamespace util {\nnamespace {\n\nvoid testExpmap2quat(const Vector4d &quat);\n\nTEST(DrakeGeometryUtilTest, RotationConversionFunctions) {\n int ntests = 1;\n default_random_engine generator;\n \/\/ quat2axis, axis2quat\n for (int i = 0; i < ntests; i++) {\n Vector4d q = uniformlyRandomQuat(generator);\n auto a = quat2axis(q);\n auto q_back = axis2quat(a);\n valuecheck(acos(std::abs(q.transpose() * q_back)), 0.0, 1e-6);\n }\n \/\/ quat2rotmat, rotmat2quat\n for (int i = 0; i < ntests; i++) {\n Vector4d q = uniformlyRandomQuat(generator);\n Matrix3d R = quat2rotmat(q);\n Vector4d q_back = rotmat2quat(R);\n valuecheck(acos(std::abs(q.transpose() * q_back)), 0.0, 1e-6);\n }\n \/\/ quat2rpy, rpy2quat\n for (int i = 0; i < ntests; i++) {\n Vector4d q = uniformlyRandomQuat(generator);\n Vector3d rpy = quat2rpy(q);\n Vector4d q_back = rpy2quat(rpy);\n valuecheck(acos(std::abs(q.transpose() * q_back)), 0.0, 1e-6);\n }\n \/\/ rotmat2axis, axis2rotmat\n for (int i = 0; i < ntests; i++) {\n Matrix3d R = uniformlyRandomRotmat(generator);\n Vector4d a = rotmat2axis(R);\n Matrix3d R_back = axis2rotmat(a);\n EXPECT_TRUE(CompareMatrices(R, R_back, 1e-6, MatrixCompareType::absolute));\n }\n \/\/ rotmat2rpy, rpy2rotmat\n for (int i = 0; i < ntests; i++) {\n Matrix3d R = uniformlyRandomRotmat(generator);\n Vector3d rpy = rotmat2rpy(R);\n Matrix3d R_back = rpy2rotmat(rpy);\n EXPECT_TRUE(CompareMatrices(R, R_back, 1e-6, MatrixCompareType::absolute));\n }\n \/\/ rpy2axis, axis2rpy\n for (int i = 0; i < ntests; i++) {\n Vector3d rpy = uniformlyRandomRPY(generator);\n Vector4d axis = rpy2axis(rpy);\n Vector3d rpy_back = axis2rpy(axis);\n EXPECT_TRUE(\n CompareMatrices(rpy, rpy_back, 1e-6, MatrixCompareType::absolute));\n }\n \/\/ expmap2quat, quat2expmap\n Vector4d quat_degenerate = Vector4d::Zero();\n quat_degenerate(0) = 1.0;\n testExpmap2quat(quat_degenerate);\n quat_degenerate(0) = -1.0;\n testExpmap2quat(quat_degenerate);\n for (int i = 0; i < ntests; i++) {\n Vector4d quat = uniformlyRandomQuat(generator);\n testExpmap2quat(quat);\n }\n \/\/ quat2eigenQuaternion\n Vector4d quat = uniformlyRandomQuat(generator);\n Quaterniond eigenQuat = quat2eigenQuaternion(quat);\n Matrix3d R_expected = quat2rotmat(quat);\n Matrix3d R_eigen = eigenQuat.matrix();\n EXPECT_TRUE(\n CompareMatrices(R_expected, R_eigen, 1e-6, MatrixCompareType::absolute));\n}\n\nTEST(DrakeGeometryUtilTest, DHomogTrans) {\n const int ntests = 1;\n Isometry3d T;\n std::default_random_engine generator;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n T = Quaterniond(q(0), q(1), q(2), q(3));\n \/\/ T.setIdentity();\n \/\/ T = AngleAxisd(M_PI_2, Vector3d(1.0, 0.0, 0.0));\n\n const int nv = 6;\n const int nq = 7;\n\n auto S = Matrix::Random(6, nv).eval();\n \/\/ setLinearIndices(S);\n \/\/ S.setIdentity();\n \/\/ std::cout << S << \"\\n\\n\";\n\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n \/\/ setLinearIndices(qdot_to_v);\n \/\/ std::cout << qdot_to_v << \"\\n\\n\";\n\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n volatile auto vol = dT;\n \/\/ std::cout << dT << std::endl << std::endl;\n }\n}\n\nTEST(DrakeGeometryUtilTest, DHomogTransInv) {\n const int ntests = 1;\n const bool check = true;\n Isometry3d T;\n std::default_random_engine generator;\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n \/\/ T = Quaterniond(q(0), q(1), q(2), q(3)) *\n \/\/ Translation3d(Vector3d::Random());\n T = Quaterniond(q(0), q(1), q(2), q(3));\n\n const int nv = 6;\n const int nq = 7;\n\n auto S = Matrix::Random(6, nv).eval();\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n auto dTInv = dHomogTransInv(T, dT);\n volatile auto vol = dTInv;\n\n if (check) {\n auto dTInvInv = dHomogTransInv(T.inverse(), dTInv);\n\n if (!dT.matrix().isApprox(dTInvInv.matrix(), 1e-10)) {\n std::cout << \"dTInv:\\n\" << dTInv << \"\\n\\n\";\n std::cout << \"dT:\\n\" << dT << \"\\n\\n\";\n std::cout << \"dTInvInv:\\n\" << dTInvInv << \"\\n\\n\";\n std::cout << \"dTInvInv - dT:\\n\" << dTInvInv - dT << \"\\n\\n\";\n\n throw std::runtime_error(\"wrong\");\n }\n }\n }\n}\n\nTEST(DrakeGeometryUtilTest, DTransformAdjoint) {\n const int ntests = 1;\n const int nv = 6;\n const int nq = 34;\n const int cols_X = 3;\n\n Isometry3d T;\n std::default_random_engine generator;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n auto S = Matrix::Random(6, nv).eval();\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n auto X = Matrix::Random(6, cols_X).eval();\n auto dX = MatrixXd::Random(X.size(), nq).eval();\n \/\/ auto dX = Matrix::Random().eval();\n auto dAdT_times_X = dTransformSpatialMotion(T, X, dT, dX).eval();\n volatile auto vol = dAdT_times_X;\n }\n}\n\nTEST(DrakeGeometryUtilTest, DTransformAdjointTranspose) {\n const int ntests = 1;\n const int nv = 6;\n const int nq = 34;\n const int cols_X = 3;\n\n Isometry3d T;\n std::default_random_engine generator;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n Vector4d q = uniformlyRandomQuat(generator);\n T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n auto S = Matrix::Random(6, nv).eval();\n auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n auto X = Matrix::Random(6, cols_X).eval();\n auto dX = MatrixXd::Random(X.size(), nq).eval();\n \/\/ auto dX = Matrix::Random().eval();\n auto dAdTtranspose_times_X = dTransformSpatialForce(T, X, dT, dX).eval();\n volatile auto vol = dAdTtranspose_times_X;\n }\n}\n\nTEST(DrakeGeometryUtilTest, NormalizeVec) {\n const int ntests = 1;\n const int x_rows = 4;\n\n for (int testnr = 0; testnr < ntests; testnr++) {\n auto x = Matrix::Random().eval();\n Matrix x_norm;\n Matrix dx_norm;\n Matrix ddx_norm;\n normalizeVec(x, x_norm, &dx_norm, &ddx_norm);\n \/\/ std::cout << \"gradientNumRows: \" << gradientNumRows(x_rows, x_rows, 1)\n \/\/ << std::endl;\n\n volatile auto volx_norm = x_norm;\n volatile auto voldx_norm = dx_norm;\n volatile auto volddx_norm = ddx_norm;\n\n \/\/ std::cout << \"x_norm:\\n\" << x_norm << std::endl << std::endl;\n \/\/ std::cout << \"dx_norm:\\n\" << dx_norm << std::endl << std::endl;\n \/\/ std::cout << \"ddx_norm:\\n\" << ddx_norm << std::endl << std::endl;\n }\n}\n\nTEST(DrakeGeometryUtilTest, SpatialCrossProduct) {\n auto a = (Matrix::Random()).eval();\n auto b = (Matrix::Identity()).eval();\n auto a_crm_b = crossSpatialMotion(a, b);\n auto a_crf_b = crossSpatialForce(a, b);\n EXPECT_TRUE(CompareMatrices(a_crf_b, -a_crm_b.transpose(), 1e-8,\n MatrixCompareType::absolute));\n}\n\nTEST(DrakeGeometryUtilTest, drpy2rotmat) {\n default_random_engine generator;\n Vector3d rpy = uniformlyRandomRPY(generator);\n Matrix3d R = rpy2rotmat(rpy);\n Matrix dR = drpy2rotmat(rpy);\n Matrix dR_num = Matrix::Zero();\n for (int i = 0; i < 3; i++) {\n Vector3d err = Vector3d::Zero();\n err(i) = 1e-7;\n Vector3d rpyi = rpy + err;\n Matrix3d Ri = rpy2rotmat(rpyi);\n Matrix3d Ri_err = (Ri - R) \/ err(i);\n for (int j = 0; j < 9; j++) {\n dR_num(j, i) = Ri_err(j);\n valuecheck(dR(j, i), dR_num(j, i), 1e-3);\n }\n }\n}\n\nvoid testExpmap2quat(const Vector4d &quat) {\n auto quat_autodiff = initializeAutoDiff(quat);\n auto expmap_autodiff = quat2expmap(quat_autodiff);\n auto expmap = autoDiffToValueMatrix(expmap_autodiff);\n auto expmap_grad = autoDiffToGradientMatrix(expmap_autodiff);\n auto quat_back_autodiff = expmap2quat(initializeAutoDiff(expmap));\n auto quat_back = autoDiffToValueMatrix(quat_back_autodiff);\n auto quat_back_grad = autoDiffToGradientMatrix(quat_back_autodiff);\n valuecheck(std::abs((quat.transpose() * quat_back).value()), 1.0, 1e-8);\n Matrix3d identity = Matrix3d::Identity();\n EXPECT_TRUE(CompareMatrices((expmap_grad * quat_back_grad).eval(), identity,\n 1e-10, MatrixCompareType::absolute));\n}\n\n} \/\/ namespace\n} \/\/ namespace util\n} \/\/ namespace drake\n<|endoftext|>"} {"text":"\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n\/\/ MOOSE includes\n#include \"MaterialPropertyInterface.h\"\n#include \"MooseApp.h\"\n#include \"Material.h\"\n\ntemplate <>\nInputParameters\nvalidParams()\n{\n InputParameters params = emptyInputParameters();\n params.addPrivateParam(\n \"_material_data_type\"); \/\/ optionally force the type of MaterialData to utilize\n return params;\n}\n\nMaterialPropertyInterface::MaterialPropertyInterface(const MooseObject * moose_object,\n const std::set & block_ids,\n const std::set & boundary_ids)\n : _mi_params(moose_object->parameters()),\n _mi_name(_mi_params.get(\"_object_name\")),\n _mi_feproblem(*_mi_params.getCheckedPointerParam(\"_fe_problem_base\")),\n _mi_tid(_mi_params.get(\"_tid\")),\n _stateful_allowed(true),\n _get_material_property_called(false),\n _mi_boundary_restricted(!boundary_ids.empty() &&\n BoundaryRestrictable::restricted(boundary_ids)),\n _mi_block_ids(block_ids),\n _mi_boundary_ids(boundary_ids)\n{\n\n \/\/ Set the MaterialDataType flag\n if (_mi_params.isParamValid(\"_material_data_type\"))\n _material_data_type = _mi_params.get(\"_material_data_type\");\n\n else if (_mi_boundary_restricted)\n _material_data_type = Moose::BOUNDARY_MATERIAL_DATA;\n\n else\n _material_data_type = Moose::BLOCK_MATERIAL_DATA;\n\n _material_data =\n _mi_feproblem.getMaterialData(_material_data_type, _mi_params.get(\"_tid\"));\n}\n\nstd::string\nMaterialPropertyInterface::deducePropertyName(const std::string & name)\n{\n if (_mi_params.have_parameter(name))\n return _mi_params.get(name);\n else\n return name;\n}\n\ntemplate <>\nconst MaterialProperty *\nMaterialPropertyInterface::defaultMaterialProperty(const std::string & name)\n{\n std::istringstream ss(name);\n Real real_value;\n\n \/\/ check if the string parsed cleanly into a Real number\n if (ss >> real_value && ss.eof())\n {\n _default_real_properties.emplace_back(libmesh_make_unique>());\n auto & default_property = _default_real_properties.back();\n\n \/\/ resize to accomodate maximum number obf qpoints\n auto nqp = _mi_feproblem.getMaxQps();\n default_property->resize(nqp);\n\n \/\/ set values for all qpoints to the given default\n for (decltype(nqp) qp = 0; qp < nqp; ++qp)\n (*default_property)[qp] = real_value;\n\n \/\/ return the raw pointer inside the shared pointer\n return default_property.get();\n }\n\n return nullptr;\n}\n\ntemplate <>\nconst ADMaterialPropertyObject *\nMaterialPropertyInterface::defaultADMaterialProperty(const std::string & name)\n{\n std::istringstream ss(name);\n Real real_value;\n\n \/\/ check if the string parsed cleanly into a Real number\n if (ss >> real_value && ss.eof())\n {\n _default_ad_real_properties.emplace_back(\n libmesh_make_unique>(true));\n auto & default_property = _default_ad_real_properties.back();\n\n \/\/ resize to accomodate maximum number obf qpoints\n auto nqp = _mi_feproblem.getMaxQps();\n default_property->resize(nqp);\n\n \/\/ set values for all qpoints to the given default\n for (decltype(nqp) qp = 0; qp < nqp; ++qp)\n (*default_property)[qp] = real_value;\n\n \/\/ return the raw pointer inside the shared pointer\n return default_property.get();\n }\n\n return nullptr;\n}\n\ntemplate <>\nconst ADMaterialPropertyObject *\nMaterialPropertyInterface::defaultADMaterialProperty(const std::string & name)\n{\n std::istringstream ss(name);\n Real real_value;\n\n \/\/ check if the string parsed cleanly into a Real number\n if (ss >> real_value && ss.eof())\n {\n _default_ad_real_vector_properties.emplace_back(\n libmesh_make_unique>());\n auto & default_property = _default_ad_real_vector_properties.back();\n\n \/\/ resize to accomodate maximum number obf qpoints\n auto nqp = _mi_feproblem.getMaxQps();\n default_property->resize(nqp);\n\n \/\/ set values for all qpoints to the given default\n for (decltype(nqp) qp = 0; qp < nqp; ++qp)\n (*default_property)[qp] = real_value;\n\n \/\/ return the raw pointer inside the shared pointer\n return default_property.get();\n }\n\n return nullptr;\n}\n\nstd::set\nMaterialPropertyInterface::getMaterialPropertyBlocks(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBlocks(name);\n}\n\nstd::vector\nMaterialPropertyInterface::getMaterialPropertyBlockNames(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBlockNames(name);\n}\n\nstd::set\nMaterialPropertyInterface::getMaterialPropertyBoundaryIDs(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBoundaryIDs(name);\n}\n\nstd::vector\nMaterialPropertyInterface::getMaterialPropertyBoundaryNames(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBoundaryNames(name);\n}\n\nvoid\nMaterialPropertyInterface::checkMaterialProperty(const std::string & name)\n{\n \/\/ If the material property is boundary restrictable, add to the list of materials to check\n if (_mi_boundary_restricted)\n for (const auto & bnd_id : _mi_boundary_ids)\n _mi_feproblem.storeBoundaryDelayedCheckMatProp(_mi_name, bnd_id, name);\n\n \/\/ The default is to assume block restrictions\n else\n for (const auto & blk_ids : _mi_block_ids)\n _mi_feproblem.storeSubdomainDelayedCheckMatProp(_mi_name, blk_ids, name);\n}\n\nvoid\nMaterialPropertyInterface::markMatPropRequested(const std::string & name)\n{\n _mi_feproblem.markMatPropRequested(name);\n}\n\nvoid\nMaterialPropertyInterface::statefulPropertiesAllowed(bool stateful_allowed)\n{\n _stateful_allowed = stateful_allowed;\n}\n\nMaterial &\nMaterialPropertyInterface::getMaterial(const std::string & name)\n{\n return getMaterialByName(_mi_params.get(name));\n}\n\nvoid\nMaterialPropertyInterface::checkBlockAndBoundaryCompatibility(std::shared_ptr discrete)\n{\n \/\/ Check block compatibility\n if (!discrete->hasBlocks(_mi_block_ids))\n {\n std::ostringstream oss;\n oss << \"The Material object '\" << discrete->name()\n << \"' is defined on blocks that are incompatible with the retrieving object '\" << _mi_name\n << \"':\\n\";\n oss << \" \" << discrete->name();\n for (const auto & sbd_id : discrete->blockIDs())\n oss << \" \" << sbd_id;\n oss << \"\\n\";\n oss << \" \" << _mi_name;\n for (const auto & block_id : _mi_block_ids)\n oss << \" \" << block_id;\n oss << \"\\n\";\n mooseError(oss.str());\n }\n\n \/\/ Check boundary compatibility\n if (!discrete->hasBoundary(_mi_boundary_ids))\n {\n std::ostringstream oss;\n oss << \"The Material object '\" << discrete->name()\n << \"' is defined on boundaries that are incompatible with the retrieving object '\"\n << _mi_name << \"':\\n\";\n oss << \" \" << discrete->name();\n for (const auto & bnd_id : discrete->boundaryIDs())\n oss << \" \" << bnd_id;\n oss << \"\\n\";\n oss << \" \" << _mi_name;\n for (const auto & bnd_id : _mi_boundary_ids)\n oss << \" \" << bnd_id;\n oss << \"\\n\";\n mooseError(oss.str());\n }\n}\n\nMaterial &\nMaterialPropertyInterface::getMaterialByName(const std::string & name, bool no_warn)\n{\n std::shared_ptr discrete =\n _mi_feproblem.getMaterial(name, _material_data_type, _mi_tid, no_warn);\n checkBlockAndBoundaryCompatibility(discrete);\n return *discrete;\n}\n\ntemplate \nMaterial &\nMaterialPropertyInterface::getMaterial(const std::string & name)\n{\n return getMaterialByName(_mi_params.get(name));\n}\n\ntemplate <>\nMaterial &\nMaterialPropertyInterface::getMaterialByName(const std::string & name, bool no_warn)\n{\n return getMaterialByName(name, no_warn);\n}\n\ntemplate <>\nMaterial &\nMaterialPropertyInterface::getMaterialByName(const std::string & name, bool no_warn)\n{\n std::shared_ptr discrete =\n _mi_feproblem.getMaterial(name + \"_jacobian\", _material_data_type, _mi_tid, no_warn);\n checkBlockAndBoundaryCompatibility(discrete);\n return *discrete;\n}\n\ntemplate Material & MaterialPropertyInterface::getMaterial(const std::string &);\ntemplate Material & MaterialPropertyInterface::getMaterial(const std::string &);\n\nvoid\nMaterialPropertyInterface::checkExecutionStage()\n{\n if (_mi_feproblem.startedInitialSetup())\n mooseError(\"Material properties must be retrieved during object construction to ensure correct \"\n \"problem integrity validation.\");\n}\nWe renamed ADMaterial residual objects\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n\/\/ MOOSE includes\n#include \"MaterialPropertyInterface.h\"\n#include \"MooseApp.h\"\n#include \"Material.h\"\n\ntemplate <>\nInputParameters\nvalidParams()\n{\n InputParameters params = emptyInputParameters();\n params.addPrivateParam(\n \"_material_data_type\"); \/\/ optionally force the type of MaterialData to utilize\n return params;\n}\n\nMaterialPropertyInterface::MaterialPropertyInterface(const MooseObject * moose_object,\n const std::set & block_ids,\n const std::set & boundary_ids)\n : _mi_params(moose_object->parameters()),\n _mi_name(_mi_params.get(\"_object_name\")),\n _mi_feproblem(*_mi_params.getCheckedPointerParam(\"_fe_problem_base\")),\n _mi_tid(_mi_params.get(\"_tid\")),\n _stateful_allowed(true),\n _get_material_property_called(false),\n _mi_boundary_restricted(!boundary_ids.empty() &&\n BoundaryRestrictable::restricted(boundary_ids)),\n _mi_block_ids(block_ids),\n _mi_boundary_ids(boundary_ids)\n{\n\n \/\/ Set the MaterialDataType flag\n if (_mi_params.isParamValid(\"_material_data_type\"))\n _material_data_type = _mi_params.get(\"_material_data_type\");\n\n else if (_mi_boundary_restricted)\n _material_data_type = Moose::BOUNDARY_MATERIAL_DATA;\n\n else\n _material_data_type = Moose::BLOCK_MATERIAL_DATA;\n\n _material_data =\n _mi_feproblem.getMaterialData(_material_data_type, _mi_params.get(\"_tid\"));\n}\n\nstd::string\nMaterialPropertyInterface::deducePropertyName(const std::string & name)\n{\n if (_mi_params.have_parameter(name))\n return _mi_params.get(name);\n else\n return name;\n}\n\ntemplate <>\nconst MaterialProperty *\nMaterialPropertyInterface::defaultMaterialProperty(const std::string & name)\n{\n std::istringstream ss(name);\n Real real_value;\n\n \/\/ check if the string parsed cleanly into a Real number\n if (ss >> real_value && ss.eof())\n {\n _default_real_properties.emplace_back(libmesh_make_unique>());\n auto & default_property = _default_real_properties.back();\n\n \/\/ resize to accomodate maximum number obf qpoints\n auto nqp = _mi_feproblem.getMaxQps();\n default_property->resize(nqp);\n\n \/\/ set values for all qpoints to the given default\n for (decltype(nqp) qp = 0; qp < nqp; ++qp)\n (*default_property)[qp] = real_value;\n\n \/\/ return the raw pointer inside the shared pointer\n return default_property.get();\n }\n\n return nullptr;\n}\n\ntemplate <>\nconst ADMaterialPropertyObject *\nMaterialPropertyInterface::defaultADMaterialProperty(const std::string & name)\n{\n std::istringstream ss(name);\n Real real_value;\n\n \/\/ check if the string parsed cleanly into a Real number\n if (ss >> real_value && ss.eof())\n {\n _default_ad_real_properties.emplace_back(\n libmesh_make_unique>(true));\n auto & default_property = _default_ad_real_properties.back();\n\n \/\/ resize to accomodate maximum number obf qpoints\n auto nqp = _mi_feproblem.getMaxQps();\n default_property->resize(nqp);\n\n \/\/ set values for all qpoints to the given default\n for (decltype(nqp) qp = 0; qp < nqp; ++qp)\n (*default_property)[qp] = real_value;\n\n \/\/ return the raw pointer inside the shared pointer\n return default_property.get();\n }\n\n return nullptr;\n}\n\ntemplate <>\nconst ADMaterialPropertyObject *\nMaterialPropertyInterface::defaultADMaterialProperty(const std::string & name)\n{\n std::istringstream ss(name);\n Real real_value;\n\n \/\/ check if the string parsed cleanly into a Real number\n if (ss >> real_value && ss.eof())\n {\n _default_ad_real_vector_properties.emplace_back(\n libmesh_make_unique>());\n auto & default_property = _default_ad_real_vector_properties.back();\n\n \/\/ resize to accomodate maximum number obf qpoints\n auto nqp = _mi_feproblem.getMaxQps();\n default_property->resize(nqp);\n\n \/\/ set values for all qpoints to the given default\n for (decltype(nqp) qp = 0; qp < nqp; ++qp)\n (*default_property)[qp] = real_value;\n\n \/\/ return the raw pointer inside the shared pointer\n return default_property.get();\n }\n\n return nullptr;\n}\n\nstd::set\nMaterialPropertyInterface::getMaterialPropertyBlocks(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBlocks(name);\n}\n\nstd::vector\nMaterialPropertyInterface::getMaterialPropertyBlockNames(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBlockNames(name);\n}\n\nstd::set\nMaterialPropertyInterface::getMaterialPropertyBoundaryIDs(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBoundaryIDs(name);\n}\n\nstd::vector\nMaterialPropertyInterface::getMaterialPropertyBoundaryNames(const std::string & name)\n{\n return _mi_feproblem.getMaterialPropertyBoundaryNames(name);\n}\n\nvoid\nMaterialPropertyInterface::checkMaterialProperty(const std::string & name)\n{\n \/\/ If the material property is boundary restrictable, add to the list of materials to check\n if (_mi_boundary_restricted)\n for (const auto & bnd_id : _mi_boundary_ids)\n _mi_feproblem.storeBoundaryDelayedCheckMatProp(_mi_name, bnd_id, name);\n\n \/\/ The default is to assume block restrictions\n else\n for (const auto & blk_ids : _mi_block_ids)\n _mi_feproblem.storeSubdomainDelayedCheckMatProp(_mi_name, blk_ids, name);\n}\n\nvoid\nMaterialPropertyInterface::markMatPropRequested(const std::string & name)\n{\n _mi_feproblem.markMatPropRequested(name);\n}\n\nvoid\nMaterialPropertyInterface::statefulPropertiesAllowed(bool stateful_allowed)\n{\n _stateful_allowed = stateful_allowed;\n}\n\nMaterial &\nMaterialPropertyInterface::getMaterial(const std::string & name)\n{\n return getMaterialByName(_mi_params.get(name));\n}\n\nvoid\nMaterialPropertyInterface::checkBlockAndBoundaryCompatibility(std::shared_ptr discrete)\n{\n \/\/ Check block compatibility\n if (!discrete->hasBlocks(_mi_block_ids))\n {\n std::ostringstream oss;\n oss << \"The Material object '\" << discrete->name()\n << \"' is defined on blocks that are incompatible with the retrieving object '\" << _mi_name\n << \"':\\n\";\n oss << \" \" << discrete->name();\n for (const auto & sbd_id : discrete->blockIDs())\n oss << \" \" << sbd_id;\n oss << \"\\n\";\n oss << \" \" << _mi_name;\n for (const auto & block_id : _mi_block_ids)\n oss << \" \" << block_id;\n oss << \"\\n\";\n mooseError(oss.str());\n }\n\n \/\/ Check boundary compatibility\n if (!discrete->hasBoundary(_mi_boundary_ids))\n {\n std::ostringstream oss;\n oss << \"The Material object '\" << discrete->name()\n << \"' is defined on boundaries that are incompatible with the retrieving object '\"\n << _mi_name << \"':\\n\";\n oss << \" \" << discrete->name();\n for (const auto & bnd_id : discrete->boundaryIDs())\n oss << \" \" << bnd_id;\n oss << \"\\n\";\n oss << \" \" << _mi_name;\n for (const auto & bnd_id : _mi_boundary_ids)\n oss << \" \" << bnd_id;\n oss << \"\\n\";\n mooseError(oss.str());\n }\n}\n\nMaterial &\nMaterialPropertyInterface::getMaterialByName(const std::string & name, bool no_warn)\n{\n std::shared_ptr discrete =\n _mi_feproblem.getMaterial(name, _material_data_type, _mi_tid, no_warn);\n checkBlockAndBoundaryCompatibility(discrete);\n return *discrete;\n}\n\ntemplate \nMaterial &\nMaterialPropertyInterface::getMaterial(const std::string & name)\n{\n return getMaterialByName(_mi_params.get(name));\n}\n\ntemplate <>\nMaterial &\nMaterialPropertyInterface::getMaterialByName(const std::string & name, bool no_warn)\n{\n const std::string new_name = name + \"_residual\";\n return getMaterialByName(new_name, no_warn);\n}\n\ntemplate <>\nMaterial &\nMaterialPropertyInterface::getMaterialByName(const std::string & name, bool no_warn)\n{\n const std::string new_name = name + \"_jacobian\";\n return getMaterialByName(new_name, no_warn);\n}\n\ntemplate Material & MaterialPropertyInterface::getMaterial(const std::string &);\ntemplate Material & MaterialPropertyInterface::getMaterial(const std::string &);\n\nvoid\nMaterialPropertyInterface::checkExecutionStage()\n{\n if (_mi_feproblem.startedInitialSetup())\n mooseError(\"Material properties must be retrieved during object construction to ensure correct \"\n \"problem integrity validation.\");\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"vtrc-common\/vtrc-pool-pair.h\"\n\n#include \"vtrc-common\/vtrc-connection-iface.h\"\n#include \"vtrc-common\/vtrc-call-context.h\"\n#include \"vtrc-common\/vtrc-exception.h\"\n#include \"vtrc-common\/vtrc-protocol-layer.h\"\n\n#include \"vtrc-client-base\/vtrc-client.h\"\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n#include \"protocol\/vtrc-service.pb.h\"\n#include \"protocol\/vtrc-errors.pb.h\"\n\n#include \n#include \n\n#include \"vtrc-thread.h\"\n#include \"vtrc-ref.h\"\n#include \"vtrc-bind.h\"\n#include \"vtrc-condition-variable.h\"\n#include \"vtrc-chrono.h\"\n\nusing namespace vtrc;\n\nvoid on_connect( const boost::system::error_code &err )\n{\n std::cout << \"connected \"\n << err.value( ) << \" \"\n << err.message( ) << \"\\n\";\n}\n\nstruct work_time {\n typedef vtrc::chrono::high_resolution_clock::time_point time_point;\n time_point start_;\n work_time( )\n :start_(vtrc::chrono::high_resolution_clock::now( ))\n {}\n ~work_time( )\n {\n time_point::duration stop(\n vtrc::chrono::high_resolution_clock::now( ) - start_);\n std::cout << \"call time: \" << stop << \"\\n\";\n }\n};\n\nclass ping_impl: public vtrc_service::internal {\n\n client::vtrc_client *c_;\n\npublic:\n\n ping_impl( client::vtrc_client *c )\n :c_( c )\n {}\n\n void ping(::google::protobuf::RpcController* controller,\n const ::vtrc_service::ping_req* request,\n ::vtrc_service::pong_res* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder chold(done);\n std::cout << \"ping event rcvd \"\n << c_->connection( )\n ->get_call_context( )\n ->get_lowlevel_message( )->id( )\n << \" \" << vtrc::this_thread::get_id( ) << \" \"\n \/\/<< vtrc::chrono::high_resolution_clock::now( )\n << \"\\n\";\n\n return;\n\n const vtrc::common::call_context *cc =\n vtrc::common::call_context::get( c_->connection( ) );\n\n vtrc::shared_ptr\n ch(c_->create_channel( common::rpc_channel::USE_CONTEXT_CALL ));\n\n vtrc_service::test_message mi;\n vtrc_service::test_rpc::Stub s( ch.get( ) );\n\n s.test2( NULL, &mi, &mi, NULL );\n\n \/\/if( done ) done->Run( );\n }\n};\n\nclass test_ev: public vtrc_service::test_events\n{\n vtrc::common::connection_iface *c_;\npublic:\n test_ev( vtrc::common::connection_iface *c )\n :c_( c )\n {}\n\n void test(::google::protobuf::RpcController* controller,\n const ::vtrc_service::test_message* request,\n ::vtrc_service::test_message* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder ch(done);\n std::cout << \"test event rcvd \"\n << c_->get_call_context( )->get_lowlevel_message( )->id( )\n << \" \" << vtrc::this_thread::get_id( ) << \" \"\n << \"\\n\";\n }\n\n};\n\nvoid run_client( vtrc::shared_ptr cl, bool wait)\n{\n vtrc::shared_ptr\n ch(cl->create_channel( wait ? common::rpc_channel::DISABLE_WAIT\n : common::rpc_channel::DEFAULT ));\n vtrc_service::test_rpc::Stub s( ch.get( ) );\n\n vtrc_service::test_message mi;\n vtrc_service::test_message mir;\n\n size_t last = 0;\n\n std::string ts(1024 * 800, 0);\n\n std::cout << \"this thread: \"\n << vtrc::this_thread::get_id( ) << \" \"\n << \"\\n\";\n\n for( int i=0; i<29999999999; ++i ) {\n try {\n\n if( wait )\n vtrc::this_thread::sleep_for(\n vtrc::chrono::microseconds(500) );\n work_time wt;\n \/\/mi.set_b( ts );\n s.test( NULL, &mi, &mir, NULL );\n last = i; \/\/mir.id( );\n std::cout << \"response: \" << last << \"\\n\";\n \/\/cl.reset( );\n } catch( const vtrc::common::exception &ex ) {\n std::cout << \"call error: \"\n << \" code (\" << ex.code( ) << \")\"\n << \" category (\" << ex.category( ) << \")\"\n << \" what: \" << ex.what( )\n << \" (\" << ex.additional( ) << \")\"\n << \"\\n\";\n \/\/if( i % 100 == 0 )\n std::cout << i << \"\\n\";\n if( ex.category( ) == vtrc_errors::CATEGORY_SYSTEM ) break;\n if( ex.code( ) == vtrc_errors::ERR_COMM ) break;\n } catch( const std::exception &ex ) {\n \/\/std::cout << \"call error: \" << ex.what( ) << \"\\n\";\n }\n }\n}\n\nvoid on_connect( )\n{\n std::cout << \"on_connect\\n\";\n}\n\nvoid on_ready( vtrc::condition_variable &cond )\n{\n std::cout << \"on_ready\\n\";\n cond.notify_all( );\n}\n\nvoid on_disconnect( vtrc::condition_variable &cond )\n{\n std::cout << \"on_disconnect\\n\";\n cond.notify_all( );\n}\n\nint main( )\n{\n common::pool_pair pp(2, 2);\n vtrc::shared_ptr cl(client::vtrc_client::create(pp));\n\n cl->set_session_key( \"1234\" );\n\n vtrc::mutex mut;\n vtrc::condition_variable cond;\n\n cl->get_on_connect( ).connect( boost::bind( on_connect ) );\n cl->get_on_ready( ).connect( boost::bind( on_ready,\n vtrc::ref(cond) ));\n cl->get_on_disconnect( ).connect( boost::bind( on_disconnect,\n vtrc::ref(cond) ));\n\n \/\/cl->connect( \"\/tmp\/test.socket\" );\n \/\/cl->connect( \"192.168.56.101\", \"44667\" );\n \/\/cl->connect( \"\\\\\\\\.\\\\pipe\\\\test_pipe\");\n cl->connect( \"127.0.0.1\", \"44667\" );\n \/\/cl->connect( \"::1\", \"44668\" );\n \/\/\/cl->async_connect( \"127.0.0.1\", \"44667\", on_connect );\n\n cl->assign_rpc_handler( vtrc::shared_ptr(new test_ev(cl->connection( ).get( ))) );\n cl->assign_rpc_handler( vtrc::shared_ptr(new ping_impl(cl.get( ))) );\n\n vtrc::unique_lock lck(mut);\n cond.wait( lck, vtrc::bind( &client::vtrc_client::ready, cl ) );\n\n std::cout << \"start program\\n\";\n\n \/\/vtrc::thread( run_client, cl, true ).detach( );\n \/\/vtrc::thread( run_client, cl, false ).detach( );\n\n vtrc::thread r( run_client, cl, false );\n\n\n \/\/cond.wait( lck );\n r.join( );\n\n pp.stop_all( );\n pp.join_all( );\n\n return 0;\n\n}\nproto#include \n#include \n#include \n#include \n\n#include \"vtrc-common\/vtrc-pool-pair.h\"\n\n#include \"vtrc-common\/vtrc-connection-iface.h\"\n#include \"vtrc-common\/vtrc-call-context.h\"\n#include \"vtrc-common\/vtrc-exception.h\"\n#include \"vtrc-common\/vtrc-protocol-layer.h\"\n\n#include \"vtrc-client-base\/vtrc-client.h\"\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n#include \"protocol\/vtrc-service.pb.h\"\n#include \"protocol\/vtrc-errors.pb.h\"\n\n#include \n#include \n\n#include \"vtrc-thread.h\"\n#include \"vtrc-ref.h\"\n#include \"vtrc-bind.h\"\n#include \"vtrc-condition-variable.h\"\n#include \"vtrc-chrono.h\"\n\nusing namespace vtrc;\n\nvoid on_connect( const boost::system::error_code &err )\n{\n std::cout << \"connected \"\n << err.value( ) << \" \"\n << err.message( ) << \"\\n\";\n}\n\nstruct work_time {\n typedef vtrc::chrono::high_resolution_clock::time_point time_point;\n time_point start_;\n work_time( )\n :start_(vtrc::chrono::high_resolution_clock::now( ))\n {}\n ~work_time( )\n {\n time_point::duration stop(\n vtrc::chrono::high_resolution_clock::now( ) - start_);\n std::cout << \"call time: \" << stop << \"\\n\";\n }\n};\n\nclass ping_impl: public vtrc_service::internal {\n\n client::vtrc_client *c_;\n\npublic:\n\n ping_impl( client::vtrc_client *c )\n :c_( c )\n {}\n\n void ping(::google::protobuf::RpcController* controller,\n const ::vtrc_service::ping_req* request,\n ::vtrc_service::pong_res* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder chold(done);\n std::cout << \"ping event rcvd \"\n << c_->connection( )\n ->get_call_context( )\n ->get_lowlevel_message( )->id( )\n << \" \" << vtrc::this_thread::get_id( ) << \" \"\n \/\/<< vtrc::chrono::high_resolution_clock::now( )\n << \"\\n\";\n\n return;\n\n const vtrc::common::call_context *cc =\n vtrc::common::call_context::get( c_->connection( ) );\n\n vtrc::shared_ptr\n ch(c_->create_channel( common::rpc_channel::USE_CONTEXT_CALL ));\n\n vtrc_service::test_message mi;\n vtrc_service::test_rpc::Stub s( ch.get( ) );\n\n s.test2( NULL, &mi, &mi, NULL );\n\n \/\/if( done ) done->Run( );\n }\n};\n\nclass test_ev: public vtrc_service::test_events\n{\n vtrc::common::connection_iface *c_;\npublic:\n test_ev( vtrc::common::connection_iface *c )\n :c_( c )\n {}\n\n void test(::google::protobuf::RpcController* controller,\n const ::vtrc_service::test_message* request,\n ::vtrc_service::test_message* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder ch(done);\n std::cout << \"test event rcvd \"\n << c_->get_call_context( )->get_lowlevel_message( )->id( )\n << \" \" << vtrc::this_thread::get_id( ) << \" \"\n << \"\\n\";\n }\n\n};\n\nvoid run_client( vtrc::shared_ptr cl, bool wait)\n{\n vtrc::shared_ptr\n ch(cl->create_channel( wait ? common::rpc_channel::DISABLE_WAIT\n : common::rpc_channel::DEFAULT ));\n vtrc_service::test_rpc::Stub s( ch.get( ) );\n\n vtrc_service::test_message mi;\n vtrc_service::test_message mir;\n\n size_t last = 0;\n\n std::string ts(1024 * 800, 0);\n\n std::cout << \"this thread: \"\n << vtrc::this_thread::get_id( ) << \" \"\n << \"\\n\";\n\n for( int i=0; i<29999999999; ++i ) {\n try {\n\n if( wait )\n vtrc::this_thread::sleep_for(\n vtrc::chrono::microseconds(500) );\n work_time wt;\n \/\/mi.set_b( ts );\n s.test( NULL, &mi, &mir, NULL );\n last = i; \/\/mir.id( );\n std::cout << \"response: \" << last << \"\\n\";\n \/\/cl.reset( );\n } catch( const vtrc::common::exception &ex ) {\n std::cout << \"call error: \"\n << \" code (\" << ex.code( ) << \")\"\n << \" category (\" << ex.category( ) << \")\"\n << \" what: \" << ex.what( )\n << \" (\" << ex.additional( ) << \")\"\n << \"\\n\";\n \/\/if( i % 100 == 0 )\n std::cout << i << \"\\n\";\n if( ex.category( ) == vtrc_errors::CATEGORY_SYSTEM ) break;\n if( ex.code( ) == vtrc_errors::ERR_COMM ) break;\n } catch( const std::exception &ex ) {\n \/\/std::cout << \"call error: \" << ex.what( ) << \"\\n\";\n }\n }\n}\n\nvoid on_connect( )\n{\n std::cout << \"on_connect\\n\";\n}\n\nvoid on_ready( vtrc::condition_variable &cond )\n{\n std::cout << \"on_ready\\n\";\n cond.notify_all( );\n}\n\nvoid on_disconnect( vtrc::condition_variable &cond )\n{\n std::cout << \"on_disconnect\\n\";\n cond.notify_all( );\n}\n\nint main( )\n{\n common::pool_pair pp(2, 2);\n vtrc::shared_ptr cl(client::vtrc_client::create(pp));\n\n \/\/cl->set_session_key( \"1234\" );\n\n vtrc::mutex mut;\n vtrc::condition_variable cond;\n\n cl->get_on_connect( ).connect( boost::bind( on_connect ) );\n cl->get_on_ready( ).connect( boost::bind( on_ready, vtrc::ref(cond) ));\n cl->get_on_disconnect( ).connect( boost::bind( on_disconnect, vtrc::ref(cond) ));\n\n \/\/cl->connect( \"\/tmp\/test.socket\" );\n \/\/cl->connect( \"192.168.56.101\", \"44667\" );\n \/\/cl->connect( \"\\\\\\\\.\\\\pipe\\\\test_pipe\");\n cl->connect( \"127.0.0.1\", \"44667\" );\n \/\/cl->connect( \"::1\", \"44668\" );\n \/\/\/cl->async_connect( \"127.0.0.1\", \"44667\", on_connect );\n\n cl->assign_rpc_handler( vtrc::shared_ptr(new test_ev(cl->connection( ).get( ))) );\n cl->assign_rpc_handler( vtrc::shared_ptr(new ping_impl(cl.get( ))) );\n\n vtrc::unique_lock lck(mut);\n cond.wait( lck, vtrc::bind( &client::vtrc_client::ready, cl ) );\n\n std::cout << \"start program\\n\";\n\n \/\/vtrc::thread( run_client, cl, true ).detach( );\n \/\/vtrc::thread( run_client, cl, false ).detach( );\n\n vtrc::thread r( run_client, cl, false );\n\n\n \/\/cond.wait( lck );\n r.join( );\n\n pp.stop_all( );\n pp.join_all( );\n\n return 0;\n\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2017-2020 Hans-Kristian Arntzen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"descriptor_set.hpp\"\n#include \"device.hpp\"\n#include \n\nusing namespace std;\nusing namespace Util;\n\nnamespace Vulkan\n{\nDescriptorSetAllocator::DescriptorSetAllocator(Hash hash, Device *device_, const DescriptorSetLayout &layout, const uint32_t *stages_for_binds)\n\t: IntrusiveHashMapEnabled(hash)\n\t, device(device_)\n\t, table(device_->get_device_table())\n{\n\tbindless = layout.array_size[0] == DescriptorSetLayout::UNSIZED_ARRAY;\n\n\tif (!bindless)\n\t{\n\t\tunsigned count = device_->num_thread_indices;\n\t\tfor (unsigned i = 0; i < count; i++)\n\t\t\tper_thread.emplace_back(new PerThread);\n\t}\n\n\tif (bindless && !device->get_device_features().supports_descriptor_indexing)\n\t{\n\t\tLOGE(\"Cannot support descriptor indexing on this device.\\n\");\n\t\treturn;\n\t}\n\n\tVkDescriptorSetLayoutCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };\n\tVkDescriptorSetLayoutBindingFlagsCreateInfoEXT flags = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT };\n\tvector bindings;\n\tVkDescriptorBindingFlagsEXT binding_flags = 0;\n\n\tif (bindless)\n\t{\n\t\tinfo.flags |= VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT;\n\t\tinfo.pNext = &flags;\n\n\t\tflags.bindingCount = 1;\n\t\tflags.pBindingFlags = &binding_flags;\n\t\tbinding_flags = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT |\n\t\t VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT;\n\n\t\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t\t\tbinding_flags |= VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT;\n\t}\n\n\tfor (unsigned i = 0; i < VULKAN_NUM_BINDINGS; i++)\n\t{\n\t\tauto stages = stages_for_binds[i];\n\t\tif (stages == 0)\n\t\t\tcontinue;\n\n\t\tunsigned array_size = layout.array_size[i];\n\t\tunsigned pool_array_size;\n\t\tif (array_size == DescriptorSetLayout::UNSIZED_ARRAY)\n\t\t{\n\t\t\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t\t\t\tarray_size = VULKAN_NUM_BINDINGS_BINDLESS_VARYING;\n\t\t\telse\n\t\t\t\tarray_size = VULKAN_NUM_BINDINGS_BINDLESS;\n\t\t\tpool_array_size = array_size;\n\t\t}\n\t\telse\n\t\t\tpool_array_size = array_size * VULKAN_NUM_SETS_PER_POOL;\n\n\t\tunsigned types = 0;\n\t\tif (layout.sampled_image_mask & (1u << i))\n\t\t{\n\t\t\tVkSampler sampler = VK_NULL_HANDLE;\n\t\t\tif (has_immutable_sampler(layout, i))\n\t\t\t\tsampler = device->get_stock_sampler(get_immutable_sampler(layout, i)).get_sampler();\n\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, array_size, stages, sampler != VK_NULL_HANDLE ? &sampler : nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.sampled_buffer_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.storage_image_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.uniform_buffer_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.storage_buffer_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.input_attachment_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.separate_image_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.sampler_mask & (1u << i))\n\t\t{\n\t\t\tVkSampler sampler = VK_NULL_HANDLE;\n\t\t\tif (has_immutable_sampler(layout, i))\n\t\t\t\tsampler = device->get_stock_sampler(get_immutable_sampler(layout, i)).get_sampler();\n\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_SAMPLER, array_size, stages, sampler != VK_NULL_HANDLE ? &sampler : nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_SAMPLER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\t(void)types;\n\t\tVK_ASSERT(types <= 1 && \"Descriptor set aliasing!\");\n\t}\n\n\tif (!bindings.empty())\n\t{\n\t\tinfo.bindingCount = bindings.size();\n\t\tinfo.pBindings = bindings.data();\n\n\t\tif (bindless && bindings.size() != 1)\n\t\t{\n\t\t\tLOGE(\"Using bindless but have bindingCount != 1.\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tLOGI(\"Creating descriptor set layout.\\n\");\n\tif (table.vkCreateDescriptorSetLayout(device->get_device(), &info, nullptr, &set_layout) != VK_SUCCESS)\n\t\tLOGE(\"Failed to create descriptor set layout.\");\n#ifdef GRANITE_VULKAN_FOSSILIZE\n\tdevice->register_descriptor_set_layout(set_layout, get_hash(), info);\n#endif\n}\n\nVkDescriptorSet DescriptorSetAllocator::allocate_bindless_set(VkDescriptorPool pool, unsigned num_descriptors)\n{\n\tif (!pool || !bindless)\n\t\treturn VK_NULL_HANDLE;\n\n\tVkDescriptorSetAllocateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };\n\tinfo.descriptorPool = pool;\n\tinfo.descriptorSetCount = 1;\n\tinfo.pSetLayouts = &set_layout;\n\n\tVkDescriptorSetVariableDescriptorCountAllocateInfoEXT count_info =\n\t\t\t{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO_EXT };\n\n\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t{\n\t\tcount_info.descriptorSetCount = 1;\n\t\tuint32_t num_desc = num_descriptors;\n\t\tcount_info.pDescriptorCounts = &num_desc;\n\t\tinfo.pNext = &count_info;\n\t}\n\n\tVkDescriptorSet desc_set = VK_NULL_HANDLE;\n\tif (table.vkAllocateDescriptorSets(device->get_device(), &info, &desc_set) != VK_SUCCESS)\n\t\treturn VK_NULL_HANDLE;\n\n\treturn desc_set;\n}\n\nVkDescriptorPool DescriptorSetAllocator::allocate_bindless_pool(unsigned num_sets, unsigned num_descriptors)\n{\n\tif (!bindless)\n\t\treturn VK_NULL_HANDLE;\n\n\tVkDescriptorPool pool = VK_NULL_HANDLE;\n\tVkDescriptorPoolCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };\n\tinfo.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT;\n\tinfo.maxSets = num_sets;\n\tinfo.poolSizeCount = 1;\n\n\tVkDescriptorPoolSize size = pool_size[0];\n\tif (num_descriptors > size.descriptorCount)\n\t{\n\t\tLOGE(\"Trying to allocate more than max bindless descriptors for descriptor layout.\\n\");\n\t\treturn VK_NULL_HANDLE;\n\t}\n\n\t\/\/ If implementation does not support variable descriptor count, allocate maximum.\n\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t\tsize.descriptorCount = num_descriptors;\n\telse\n\t\tinfo.maxSets = 1;\n\n\tinfo.pPoolSizes = &size;\n\n\tif (table.vkCreateDescriptorPool(device->get_device(), &info, nullptr, &pool) != VK_SUCCESS)\n\t{\n\t\tLOGE(\"Failed to create descriptor pool.\\n\");\n\t\treturn VK_NULL_HANDLE;\n\t}\n\n\treturn pool;\n}\n\nvoid DescriptorSetAllocator::begin_frame()\n{\n\tif (!bindless)\n\t{\n\t\tfor (auto &thr : per_thread)\n\t\t\tthr->should_begin = true;\n\t}\n}\n\npair DescriptorSetAllocator::find(unsigned thread_index, Hash hash)\n{\n\tVK_ASSERT(!bindless);\n\n\tauto &state = *per_thread[thread_index];\n\tif (state.should_begin)\n\t{\n\t\tstate.set_nodes.begin_frame();\n\t\tstate.should_begin = false;\n\t}\n\n\tauto *node = state.set_nodes.request(hash);\n\tif (node)\n\t\treturn { node->set, true };\n\n\tnode = state.set_nodes.request_vacant(hash);\n\tif (node)\n\t\treturn { node->set, false };\n\n\tVkDescriptorPool pool;\n\tVkDescriptorPoolCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };\n\tinfo.maxSets = VULKAN_NUM_SETS_PER_POOL;\n\tif (!pool_size.empty())\n\t{\n\t\tinfo.poolSizeCount = pool_size.size();\n\t\tinfo.pPoolSizes = pool_size.data();\n\t}\n\n\tif (table.vkCreateDescriptorPool(device->get_device(), &info, nullptr, &pool) != VK_SUCCESS)\n\t{\n\t\tLOGE(\"Failed to create descriptor pool.\\n\");\n\t\treturn { VK_NULL_HANDLE, false };\n\t}\n\n\tVkDescriptorSet sets[VULKAN_NUM_SETS_PER_POOL];\n\tVkDescriptorSetLayout layouts[VULKAN_NUM_SETS_PER_POOL];\n\tfill(begin(layouts), end(layouts), set_layout);\n\n\tVkDescriptorSetAllocateInfo alloc = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };\n\talloc.descriptorPool = pool;\n\talloc.descriptorSetCount = VULKAN_NUM_SETS_PER_POOL;\n\talloc.pSetLayouts = layouts;\n\n\tif (table.vkAllocateDescriptorSets(device->get_device(), &alloc, sets) != VK_SUCCESS)\n\t\tLOGE(\"Failed to allocate descriptor sets.\\n\");\n\tstate.pools.push_back(pool);\n\n\tfor (auto set : sets)\n\t\tstate.set_nodes.make_vacant(set);\n\n\treturn { state.set_nodes.request_vacant(hash)->set, false };\n}\n\nvoid DescriptorSetAllocator::clear()\n{\n\tfor (auto &thr : per_thread)\n\t{\n\t\tthr->set_nodes.clear();\n\t\tfor (auto &pool : thr->pools)\n\t\t{\n\t\t\ttable.vkResetDescriptorPool(device->get_device(), pool, 0);\n\t\t\ttable.vkDestroyDescriptorPool(device->get_device(), pool, nullptr);\n\t\t}\n\t\tthr->pools.clear();\n\t}\n}\n\nDescriptorSetAllocator::~DescriptorSetAllocator()\n{\n\tif (set_layout != VK_NULL_HANDLE)\n\t\ttable.vkDestroyDescriptorSetLayout(device->get_device(), set_layout, nullptr);\n\tclear();\n}\n\nBindlessDescriptorPool::BindlessDescriptorPool(Device *device_, DescriptorSetAllocator *allocator_, VkDescriptorPool pool)\n\t: device(device_), allocator(allocator_), desc_pool(pool)\n{\n}\n\nBindlessDescriptorPool::~BindlessDescriptorPool()\n{\n\tif (desc_pool)\n\t{\n\t\tif (internal_sync)\n\t\t\tdevice->destroy_descriptor_pool_nolock(desc_pool);\n\t\telse\n\t\t\tdevice->destroy_descriptor_pool(desc_pool);\n\t}\n}\n\nVkDescriptorSet BindlessDescriptorPool::get_descriptor_set() const\n{\n\treturn desc_set;\n}\n\nbool BindlessDescriptorPool::allocate_descriptors(unsigned count)\n{\n\tdesc_set = allocator->allocate_bindless_set(desc_pool, count);\n\treturn desc_set != VK_NULL_HANDLE;\n}\n\nvoid BindlessDescriptorPool::set_texture(unsigned binding, const ImageView &view)\n{\n\t\/\/ TODO: Deal with integer view for depth-stencil images?\n\tset_texture(binding, view.get_float_view(), view.get_image().get_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));\n}\n\nvoid BindlessDescriptorPool::set_texture_unorm(unsigned binding, const ImageView &view)\n{\n\tset_texture(binding, view.get_unorm_view(), view.get_image().get_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));\n}\n\nvoid BindlessDescriptorPool::set_texture_srgb(unsigned binding, const ImageView &view)\n{\n\tset_texture(binding, view.get_srgb_view(), view.get_image().get_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));\n}\n\nvoid BindlessDescriptorPool::set_texture(unsigned binding, VkImageView view, VkImageLayout layout)\n{\n\tVkWriteDescriptorSet write = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };\n\twrite.descriptorCount = 1;\n\twrite.dstArrayElement = binding;\n\twrite.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;\n\twrite.dstSet = desc_set;\n\n\tconst VkDescriptorImageInfo info = {\n\t\tVK_NULL_HANDLE,\n\t\tview,\n\t\tlayout,\n\t};\n\twrite.pImageInfo = &info;\n\n\tauto &table = device->get_device_table();\n\ttable.vkUpdateDescriptorSets(device->get_device(), 1, &write, 0, nullptr);\n}\n\nvoid BindlessDescriptorPoolDeleter::operator()(BindlessDescriptorPool *pool)\n{\n\tpool->device->handle_pool.bindless_descriptor_pool.free(pool);\n}\n}\nFix stack corruption with variable bindless count.\/* Copyright (c) 2017-2020 Hans-Kristian Arntzen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"descriptor_set.hpp\"\n#include \"device.hpp\"\n#include \n\nusing namespace std;\nusing namespace Util;\n\nnamespace Vulkan\n{\nDescriptorSetAllocator::DescriptorSetAllocator(Hash hash, Device *device_, const DescriptorSetLayout &layout, const uint32_t *stages_for_binds)\n\t: IntrusiveHashMapEnabled(hash)\n\t, device(device_)\n\t, table(device_->get_device_table())\n{\n\tbindless = layout.array_size[0] == DescriptorSetLayout::UNSIZED_ARRAY;\n\n\tif (!bindless)\n\t{\n\t\tunsigned count = device_->num_thread_indices;\n\t\tfor (unsigned i = 0; i < count; i++)\n\t\t\tper_thread.emplace_back(new PerThread);\n\t}\n\n\tif (bindless && !device->get_device_features().supports_descriptor_indexing)\n\t{\n\t\tLOGE(\"Cannot support descriptor indexing on this device.\\n\");\n\t\treturn;\n\t}\n\n\tVkDescriptorSetLayoutCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };\n\tVkDescriptorSetLayoutBindingFlagsCreateInfoEXT flags = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT };\n\tvector bindings;\n\tVkDescriptorBindingFlagsEXT binding_flags = 0;\n\n\tif (bindless)\n\t{\n\t\tinfo.flags |= VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT;\n\t\tinfo.pNext = &flags;\n\n\t\tflags.bindingCount = 1;\n\t\tflags.pBindingFlags = &binding_flags;\n\t\tbinding_flags = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT |\n\t\t VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT;\n\n\t\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t\t\tbinding_flags |= VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT;\n\t}\n\n\tfor (unsigned i = 0; i < VULKAN_NUM_BINDINGS; i++)\n\t{\n\t\tauto stages = stages_for_binds[i];\n\t\tif (stages == 0)\n\t\t\tcontinue;\n\n\t\tunsigned array_size = layout.array_size[i];\n\t\tunsigned pool_array_size;\n\t\tif (array_size == DescriptorSetLayout::UNSIZED_ARRAY)\n\t\t{\n\t\t\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t\t\t\tarray_size = VULKAN_NUM_BINDINGS_BINDLESS_VARYING;\n\t\t\telse\n\t\t\t\tarray_size = VULKAN_NUM_BINDINGS_BINDLESS;\n\t\t\tpool_array_size = array_size;\n\t\t}\n\t\telse\n\t\t\tpool_array_size = array_size * VULKAN_NUM_SETS_PER_POOL;\n\n\t\tunsigned types = 0;\n\t\tif (layout.sampled_image_mask & (1u << i))\n\t\t{\n\t\t\tVkSampler sampler = VK_NULL_HANDLE;\n\t\t\tif (has_immutable_sampler(layout, i))\n\t\t\t\tsampler = device->get_stock_sampler(get_immutable_sampler(layout, i)).get_sampler();\n\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, array_size, stages, sampler != VK_NULL_HANDLE ? &sampler : nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.sampled_buffer_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.storage_image_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.uniform_buffer_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.storage_buffer_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.input_attachment_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.separate_image_mask & (1u << i))\n\t\t{\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, array_size, stages, nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\tif (layout.sampler_mask & (1u << i))\n\t\t{\n\t\t\tVkSampler sampler = VK_NULL_HANDLE;\n\t\t\tif (has_immutable_sampler(layout, i))\n\t\t\t\tsampler = device->get_stock_sampler(get_immutable_sampler(layout, i)).get_sampler();\n\n\t\t\tbindings.push_back({ i, VK_DESCRIPTOR_TYPE_SAMPLER, array_size, stages, sampler != VK_NULL_HANDLE ? &sampler : nullptr });\n\t\t\tpool_size.push_back({ VK_DESCRIPTOR_TYPE_SAMPLER, pool_array_size });\n\t\t\ttypes++;\n\t\t}\n\n\t\t(void)types;\n\t\tVK_ASSERT(types <= 1 && \"Descriptor set aliasing!\");\n\t}\n\n\tif (!bindings.empty())\n\t{\n\t\tinfo.bindingCount = bindings.size();\n\t\tinfo.pBindings = bindings.data();\n\n\t\tif (bindless && bindings.size() != 1)\n\t\t{\n\t\t\tLOGE(\"Using bindless but have bindingCount != 1.\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tLOGI(\"Creating descriptor set layout.\\n\");\n\tif (table.vkCreateDescriptorSetLayout(device->get_device(), &info, nullptr, &set_layout) != VK_SUCCESS)\n\t\tLOGE(\"Failed to create descriptor set layout.\");\n#ifdef GRANITE_VULKAN_FOSSILIZE\n\tdevice->register_descriptor_set_layout(set_layout, get_hash(), info);\n#endif\n}\n\nVkDescriptorSet DescriptorSetAllocator::allocate_bindless_set(VkDescriptorPool pool, unsigned num_descriptors)\n{\n\tif (!pool || !bindless)\n\t\treturn VK_NULL_HANDLE;\n\n\tVkDescriptorSetAllocateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };\n\tinfo.descriptorPool = pool;\n\tinfo.descriptorSetCount = 1;\n\tinfo.pSetLayouts = &set_layout;\n\n\tVkDescriptorSetVariableDescriptorCountAllocateInfoEXT count_info =\n\t\t\t{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO_EXT };\n\n\tuint32_t num_desc = num_descriptors;\n\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t{\n\t\tcount_info.descriptorSetCount = 1;\n\t\tcount_info.pDescriptorCounts = &num_desc;\n\t\tinfo.pNext = &count_info;\n\t}\n\n\tVkDescriptorSet desc_set = VK_NULL_HANDLE;\n\tif (table.vkAllocateDescriptorSets(device->get_device(), &info, &desc_set) != VK_SUCCESS)\n\t\treturn VK_NULL_HANDLE;\n\n\treturn desc_set;\n}\n\nVkDescriptorPool DescriptorSetAllocator::allocate_bindless_pool(unsigned num_sets, unsigned num_descriptors)\n{\n\tif (!bindless)\n\t\treturn VK_NULL_HANDLE;\n\n\tVkDescriptorPool pool = VK_NULL_HANDLE;\n\tVkDescriptorPoolCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };\n\tinfo.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT;\n\tinfo.maxSets = num_sets;\n\tinfo.poolSizeCount = 1;\n\n\tVkDescriptorPoolSize size = pool_size[0];\n\tif (num_descriptors > size.descriptorCount)\n\t{\n\t\tLOGE(\"Trying to allocate more than max bindless descriptors for descriptor layout.\\n\");\n\t\treturn VK_NULL_HANDLE;\n\t}\n\n\t\/\/ If implementation does not support variable descriptor count, allocate maximum.\n\tif (device->get_device_features().descriptor_indexing_features.descriptorBindingVariableDescriptorCount)\n\t\tsize.descriptorCount = num_descriptors;\n\telse\n\t\tinfo.maxSets = 1;\n\n\tinfo.pPoolSizes = &size;\n\n\tif (table.vkCreateDescriptorPool(device->get_device(), &info, nullptr, &pool) != VK_SUCCESS)\n\t{\n\t\tLOGE(\"Failed to create descriptor pool.\\n\");\n\t\treturn VK_NULL_HANDLE;\n\t}\n\n\treturn pool;\n}\n\nvoid DescriptorSetAllocator::begin_frame()\n{\n\tif (!bindless)\n\t{\n\t\tfor (auto &thr : per_thread)\n\t\t\tthr->should_begin = true;\n\t}\n}\n\npair DescriptorSetAllocator::find(unsigned thread_index, Hash hash)\n{\n\tVK_ASSERT(!bindless);\n\n\tauto &state = *per_thread[thread_index];\n\tif (state.should_begin)\n\t{\n\t\tstate.set_nodes.begin_frame();\n\t\tstate.should_begin = false;\n\t}\n\n\tauto *node = state.set_nodes.request(hash);\n\tif (node)\n\t\treturn { node->set, true };\n\n\tnode = state.set_nodes.request_vacant(hash);\n\tif (node)\n\t\treturn { node->set, false };\n\n\tVkDescriptorPool pool;\n\tVkDescriptorPoolCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };\n\tinfo.maxSets = VULKAN_NUM_SETS_PER_POOL;\n\tif (!pool_size.empty())\n\t{\n\t\tinfo.poolSizeCount = pool_size.size();\n\t\tinfo.pPoolSizes = pool_size.data();\n\t}\n\n\tif (table.vkCreateDescriptorPool(device->get_device(), &info, nullptr, &pool) != VK_SUCCESS)\n\t{\n\t\tLOGE(\"Failed to create descriptor pool.\\n\");\n\t\treturn { VK_NULL_HANDLE, false };\n\t}\n\n\tVkDescriptorSet sets[VULKAN_NUM_SETS_PER_POOL];\n\tVkDescriptorSetLayout layouts[VULKAN_NUM_SETS_PER_POOL];\n\tfill(begin(layouts), end(layouts), set_layout);\n\n\tVkDescriptorSetAllocateInfo alloc = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };\n\talloc.descriptorPool = pool;\n\talloc.descriptorSetCount = VULKAN_NUM_SETS_PER_POOL;\n\talloc.pSetLayouts = layouts;\n\n\tif (table.vkAllocateDescriptorSets(device->get_device(), &alloc, sets) != VK_SUCCESS)\n\t\tLOGE(\"Failed to allocate descriptor sets.\\n\");\n\tstate.pools.push_back(pool);\n\n\tfor (auto set : sets)\n\t\tstate.set_nodes.make_vacant(set);\n\n\treturn { state.set_nodes.request_vacant(hash)->set, false };\n}\n\nvoid DescriptorSetAllocator::clear()\n{\n\tfor (auto &thr : per_thread)\n\t{\n\t\tthr->set_nodes.clear();\n\t\tfor (auto &pool : thr->pools)\n\t\t{\n\t\t\ttable.vkResetDescriptorPool(device->get_device(), pool, 0);\n\t\t\ttable.vkDestroyDescriptorPool(device->get_device(), pool, nullptr);\n\t\t}\n\t\tthr->pools.clear();\n\t}\n}\n\nDescriptorSetAllocator::~DescriptorSetAllocator()\n{\n\tif (set_layout != VK_NULL_HANDLE)\n\t\ttable.vkDestroyDescriptorSetLayout(device->get_device(), set_layout, nullptr);\n\tclear();\n}\n\nBindlessDescriptorPool::BindlessDescriptorPool(Device *device_, DescriptorSetAllocator *allocator_, VkDescriptorPool pool)\n\t: device(device_), allocator(allocator_), desc_pool(pool)\n{\n}\n\nBindlessDescriptorPool::~BindlessDescriptorPool()\n{\n\tif (desc_pool)\n\t{\n\t\tif (internal_sync)\n\t\t\tdevice->destroy_descriptor_pool_nolock(desc_pool);\n\t\telse\n\t\t\tdevice->destroy_descriptor_pool(desc_pool);\n\t}\n}\n\nVkDescriptorSet BindlessDescriptorPool::get_descriptor_set() const\n{\n\treturn desc_set;\n}\n\nbool BindlessDescriptorPool::allocate_descriptors(unsigned count)\n{\n\tdesc_set = allocator->allocate_bindless_set(desc_pool, count);\n\treturn desc_set != VK_NULL_HANDLE;\n}\n\nvoid BindlessDescriptorPool::set_texture(unsigned binding, const ImageView &view)\n{\n\t\/\/ TODO: Deal with integer view for depth-stencil images?\n\tset_texture(binding, view.get_float_view(), view.get_image().get_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));\n}\n\nvoid BindlessDescriptorPool::set_texture_unorm(unsigned binding, const ImageView &view)\n{\n\tset_texture(binding, view.get_unorm_view(), view.get_image().get_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));\n}\n\nvoid BindlessDescriptorPool::set_texture_srgb(unsigned binding, const ImageView &view)\n{\n\tset_texture(binding, view.get_srgb_view(), view.get_image().get_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));\n}\n\nvoid BindlessDescriptorPool::set_texture(unsigned binding, VkImageView view, VkImageLayout layout)\n{\n\tVkWriteDescriptorSet write = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };\n\twrite.descriptorCount = 1;\n\twrite.dstArrayElement = binding;\n\twrite.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;\n\twrite.dstSet = desc_set;\n\n\tconst VkDescriptorImageInfo info = {\n\t\tVK_NULL_HANDLE,\n\t\tview,\n\t\tlayout,\n\t};\n\twrite.pImageInfo = &info;\n\n\tauto &table = device->get_device_table();\n\ttable.vkUpdateDescriptorSets(device->get_device(), 1, &write, 0, nullptr);\n}\n\nvoid BindlessDescriptorPoolDeleter::operator()(BindlessDescriptorPool *pool)\n{\n\tpool->device->handle_pool.bindless_descriptor_pool.free(pool);\n}\n}\n<|endoftext|>"} {"text":"#include \n\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nint main(int argc, char*argv[]){\n\n\treturn 0;\n}ejercicio1 sin poder jugar 2 veces#include \n#include \n#include \n\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nvoid Arreglar_Score(int[], int, int);\nvoid llenar_arreglo(int[], int);\n\nint main(int argc, char*argv[]){\n\tsrand(time(NULL));\n\tint Intento_User;\n\tint acum_intentos = 0;\n\tconst int SIZE = 10;\n\tint Score[SIZE];\n\n\tint Azar = (-501 + rand()% 501);\n\tcout << Azar << endl;\n\n\tcout << \"Ingrese un numero: \" << endl;\n\tcin >> Intento_User;\n\tacum_intentos++;\n\n\twhile(Azar != Intento_User){\n\t\tif (Intento_User < Azar){\n\t\t\tcout << \"El numero que ingresaste es menor\" << endl;\n\t\t\tcout << \"Ingrese un numero: \" << endl;\n\t\t\tcin >> Intento_User;\n\t\t} else if (Intento_User > Azar){\n\t\t\tcout << \"El numero que ingresaste es mayor\" << endl;\n\t\t\tcout << \"Ingrese un numero: \" << endl;\n\t\t\tcin >> Intento_User;\n\t\t}\n\t\tacum_intentos++;\n\t}\n\n\tcout << \"Felicidades, has adivinado el numero en: \" << acum_intentos << \" intentos\" << endl;\n\tllenar_arreglo(Score, SIZE);\n\tArreglar_Score(Score, SIZE, acum_intentos);\n\tfor (int i = 0; i < SIZE; i++){\n\t\tcout << Score[i] << endl;\n\t}\n\n\treturn 0;\n}\n\nvoid llenar_arreglo(int Score[], int SIZE){\n\tfor (int i = 0; i < SIZE; i++){\n\t\tScore[i] = 0;\n\t}\n}\n\nvoid Arreglar_Score(int Score[], int SIZE, int acum_intentos){\n\tfor (int i = 0; i < SIZE; i++){\n\t\tif (acum_intentos > Score[i]){\n\t\t\tint mayor = acum_intentos;\n\t\t\tacum_intentos = Score[i + 1];\n\t\t\tScore[i] = mayor;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"#include \"KickEvaluator.hpp\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nREGISTER_CONFIGURABLE(KickEvaluator)\n\n\/\/ 1 \/ sqrt(2*pi)\n#define M_1_SQRT_2_PI 0.3989422\n\nusing namespace std;\nusing namespace Geometry2d;\n\nConfigDouble* KickEvaluator::robot_angle_filter_limit;\nConfigDouble* KickEvaluator::kick_std_dev;\nConfigDouble* KickEvaluator::num_rays;\n\nConfigDouble* KickEvaluator::kernal_width_coefficient;\nConfigDouble* KickEvaluator::distance_coefficient;\n\nvoid KickEvaluator::createConfiguration(Configuration* cfg) {\n robot_angle_filter_limit = new ConfigDouble(\n cfg, \"KickEvaluator\/robot_angle_filter_limit\", 0.35 * M_PI);\n kick_std_dev = new ConfigDouble(cfg, \"KickEvaluator\/kick_std_dev\", 0.08);\n num_rays = new ConfigDouble(cfg, \"KickEvaluator\/num_rays\", 16);\n\n kernal_width_coefficient =\n new ConfigDouble(cfg, \"KickEvaluator\/kernal_width_coefficient\", 2.0);\n distance_coefficient =\n new ConfigDouble(cfg, \"KickEvaluator\/distance_coefficient\", -1.0 \/ 7.0);\n}\n\nKickEvaluator::KickEvaluator(SystemState* systemState) : system(systemState) {}\n\nfloat KickEvaluator::eval_pt_to_pt(Point origin, Point target,\n float targetWidth) {\n vector bots(system->self.size() + system->opp.size());\n\n auto filter_predicate = [&](const Robot* bot) -> bool {\n return bot != nullptr && bot->visible &&\n find(excluded_robots.begin(), excluded_robots.end(), bot) ==\n excluded_robots.end();\n };\n\n auto end_it = copy_if(system->self.begin(), system->self.end(),\n bots.begin(), filter_predicate);\n\n end_it = copy_if(system->opp.begin(), system->opp.end(), end_it,\n filter_predicate);\n\n bots.resize(distance(bots.begin(), end_it));\n\n \/\/ < Dist, Angle >\n vector > bot_locations;\n\n \/\/ Add robots as obstacles\n for_each(bots.begin(), bots.end(),\n [&bot_locations, target, origin, this](Robot* bot) {\n\n tuple polar_coords =\n rect_to_polar(origin, target, bot->pos);\n\n if (good_robot_check(polar_coords, target, origin)) {\n bot_locations.push_back(polar_coords);\n }\n });\n\n \/\/ Add imaginary obstacles\n for_each(hypothetical_robot_locations.begin(),\n hypothetical_robot_locations.end(),\n [&bot_locations, target, origin, this](Point obstacle) {\n\n tuple polar_coords =\n rect_to_polar(origin, target, obstacle);\n\n if (good_robot_check(polar_coords, target, origin)) {\n bot_locations.push_back(polar_coords);\n }\n });\n\n \/\/ Use rays between -3 * std_dev and 3 * std_dev\n float half_std_dev = 1.5f * *kick_std_dev;\n float half_target_width = targetWidth;\n\n \/\/ No bots in the way\n if (bot_locations.size() == 0) {\n \/\/ CDF Estimation\n \/\/ The ray estimations are linearlly related to the true CDF probability\n \/\/ These are found through testing the points and using the best fit\n \/\/ line\n \/\/ with R^2 = 0.998458\n float score =\n 1.1219 * erf(half_target_width \/ (*kick_std_dev * sqrt(2))) +\n 0.0125;\n return min(score, 1.0f);\n }\n\n float total = 0.0f;\n float max_total = 0.0f;\n\n float cur_ray_angle = -1 * half_std_dev;\n float ray_angle_inc = 2 * half_std_dev \/ number_of_rays;\n\n \/\/ For each ray\n while (cur_ray_angle < half_std_dev ||\n nearlyEqual(cur_ray_angle, half_std_dev)) {\n vector scores;\n\n \/\/ For each robot\n for (tuple bot_location : bot_locations) {\n float angle_off_ray = get<1>(bot_location) - cur_ray_angle;\n\n \/\/ Distance from ray\n float u = sin(angle_off_ray) * get<0>(bot_location);\n \/\/ Overal kernal scale\n u *= *kernal_width_coefficient;\n \/\/ Distance from kick point\n u *= exp(get<0>(bot_location) * *distance_coefficient);\n\n u = min(1.0f, u);\n u = max(-1.0f, u);\n\n \/\/ Triweight kernal function\n scores.push_back(1 - (float)max(pow((1 - pow(u, 2)), 3), 0.0));\n }\n\n \/\/ Gets -1, 0, 1 depending on whether abs(cur_ray_angle) is >\n \/\/ half_target_width\n float in_range = copysign(1.0, half_target_width - fabs(cur_ray_angle));\n \/\/ Moves in_range to 0 if outside, 1 if inside the range, 0.5 if on the\n \/\/ edge\n in_range = in_range * 0.5 + 0.5;\n\n \/\/ PDF for Gaussian Distribution, Assume mean = 0\n float ray_offset_scale = M_1_SQRT_2_PI \/ *kick_std_dev;\n ray_offset_scale *=\n fast_exp(-0.5 * pow(cur_ray_angle \/ *kick_std_dev, 2));\n\n float min_score = *min_element(begin(scores), end(scores));\n\n \/\/ Only add to the total if it's within the target range\n total += in_range * min_score * ray_offset_scale;\n\n max_total += ray_offset_scale;\n cur_ray_angle += ray_angle_inc;\n }\n\n return total \/ max_total;\n}\n\nfloat KickEvaluator::eval_pt_to_robot(Geometry2d::Point origin,\n Geometry2d::Point target) {\n return eval_pt_to_pt(origin, target, 2 * Robot_Radius);\n}\n\nfloat KickEvaluator::eval_pt_to_opp_goal(Geometry2d::Point origin) {\n Segment their_goal{\n Point{-Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2,\n Field_Dimensions::Current_Dimensions.Length()},\n Point{Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2,\n Field_Dimensions::Current_Dimensions.Length()}};\n\n return eval_pt_to_seg(origin, their_goal);\n}\n\nfloat KickEvaluator::eval_pt_to_our_goal(Geometry2d::Point origin) {\n Segment our_goal{\n Point{-Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2, 0},\n Point{Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2, 0}};\n\n return eval_pt_to_seg(origin, our_goal);\n}\n\nfloat KickEvaluator::eval_pt_to_seg(Geometry2d::Point origin,\n Geometry2d::Segment target) {\n Point pt1 = target.pt[0] - origin;\n Point pt2 = target.pt[1] - origin;\n double angle = abs(atan2(pt1.y(), pt1.x()) - atan2(pt2.y(), pt2.x()));\n\n return eval_pt_to_pt(origin, target.center(), angle);\n}\n\ntuple KickEvaluator::rect_to_polar(Point origin, Point target,\n Point obstacle) {\n Point dir = obstacle - origin;\n\n return make_tuple(dir.mag(), dir.angleBetween(target - origin));\n}\n\nfloat KickEvaluator::fast_exp(float x) {\n return (24 + x * (24 + x * (12 + x * (4 + x)))) * 0.041666666f;\n}\n\nbool KickEvaluator::good_robot_check(std::tuple polar,\n Geometry2d::Point target,\n Geometry2d::Point origin) {\n float delta_dist = get<0>(polar) - (target - origin).mag();\n\n \/\/ Checks that the robot is within the angle range in front\n \/\/ and not too far behind the target position\n return fabs(get<1>(polar)) < *robot_angle_filter_limit &&\n delta_dist * *kernal_width_coefficient < 1;\n}Cleaner way to deal with 0 blocking robots#include \"KickEvaluator.hpp\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nREGISTER_CONFIGURABLE(KickEvaluator)\n\n\/\/ 1 \/ sqrt(2*pi)\n#define M_1_SQRT_2_PI 0.3989422\n\nusing namespace std;\nusing namespace Geometry2d;\n\nConfigDouble* KickEvaluator::robot_angle_filter_limit;\nConfigDouble* KickEvaluator::kick_std_dev;\nConfigDouble* KickEvaluator::num_rays;\n\nConfigDouble* KickEvaluator::kernal_width_coefficient;\nConfigDouble* KickEvaluator::distance_coefficient;\n\nvoid KickEvaluator::createConfiguration(Configuration* cfg) {\n robot_angle_filter_limit = new ConfigDouble(\n cfg, \"KickEvaluator\/robot_angle_filter_limit\", 0.35 * M_PI);\n kick_std_dev = new ConfigDouble(cfg, \"KickEvaluator\/kick_std_dev\", 0.08);\n num_rays = new ConfigDouble(cfg, \"KickEvaluator\/num_rays\", 16);\n\n kernal_width_coefficient =\n new ConfigDouble(cfg, \"KickEvaluator\/kernal_width_coefficient\", 2.0);\n distance_coefficient =\n new ConfigDouble(cfg, \"KickEvaluator\/distance_coefficient\", -1.0 \/ 7.0);\n}\n\nKickEvaluator::KickEvaluator(SystemState* systemState) : system(systemState) {}\n\nfloat KickEvaluator::eval_pt_to_pt(Point origin, Point target,\n float targetWidth) {\n vector bots(system->self.size() + system->opp.size());\n\n auto filter_predicate = [&](const Robot* bot) -> bool {\n return bot != nullptr && bot->visible &&\n find(excluded_robots.begin(), excluded_robots.end(), bot) ==\n excluded_robots.end();\n };\n\n auto end_it = copy_if(system->self.begin(), system->self.end(),\n bots.begin(), filter_predicate);\n\n end_it = copy_if(system->opp.begin(), system->opp.end(), end_it,\n filter_predicate);\n\n bots.resize(distance(bots.begin(), end_it));\n\n \/\/ < Dist, Angle >\n vector > bot_locations;\n\n \/\/ Add robots as obstacles\n for_each(bots.begin(), bots.end(),\n [&bot_locations, target, origin, this](Robot* bot) {\n\n tuple polar_coords =\n rect_to_polar(origin, target, bot->pos);\n\n if (good_robot_check(polar_coords, target, origin)) {\n bot_locations.push_back(polar_coords);\n }\n });\n\n \/\/ Add imaginary obstacles\n for_each(hypothetical_robot_locations.begin(),\n hypothetical_robot_locations.end(),\n [&bot_locations, target, origin, this](Point obstacle) {\n\n tuple polar_coords =\n rect_to_polar(origin, target, obstacle);\n\n if (good_robot_check(polar_coords, target, origin)) {\n bot_locations.push_back(polar_coords);\n }\n });\n\n \/\/ Use rays between -3 * std_dev and 3 * std_dev\n float half_std_dev = 1.5f * *kick_std_dev;\n float half_target_width = targetWidth;\n\n float total = 0.0f;\n float max_total = 0.0f;\n\n float cur_ray_angle = -1 * half_std_dev;\n float ray_angle_inc = 2 * half_std_dev \/ number_of_rays;\n\n \/\/ For each ray\n while (cur_ray_angle < half_std_dev ||\n nearlyEqual(cur_ray_angle, half_std_dev)) {\n vector scores;\n \/\/ Default to perfect score\n scores.push_back(1);\n\n \/\/ For each robot\n for (tuple bot_location : bot_locations) {\n float angle_off_ray = get<1>(bot_location) - cur_ray_angle;\n\n \/\/ Distance from ray\n float u = sin(angle_off_ray) * get<0>(bot_location);\n \/\/ Overal kernal scale\n u *= *kernal_width_coefficient;\n \/\/ Distance from kick point\n u *= exp(get<0>(bot_location) * *distance_coefficient);\n\n u = min(1.0f, u);\n u = max(-1.0f, u);\n\n \/\/ Triweight kernal function\n scores.push_back(1 - (float)max(pow((1 - pow(u, 2)), 3), 0.0));\n }\n\n \/\/ Gets -1, 0, 1 depending on whether abs(cur_ray_angle) is >\n \/\/ half_target_width\n float in_range = copysign(1.0, half_target_width - fabs(cur_ray_angle));\n \/\/ Moves in_range to 0 if outside, 1 if inside the range, 0.5 if on the\n \/\/ edge\n in_range = in_range * 0.5 + 0.5;\n\n \/\/ PDF for Gaussian Distribution, Assume mean = 0\n float ray_offset_scale = M_1_SQRT_2_PI \/ *kick_std_dev;\n ray_offset_scale *=\n fast_exp(-0.5 * pow(cur_ray_angle \/ *kick_std_dev, 2));\n\n float min_score = *min_element(begin(scores), end(scores));\n\n \/\/ Only add to the total if it's within the target range\n total += in_range * min_score * ray_offset_scale;\n\n max_total += ray_offset_scale;\n cur_ray_angle += ray_angle_inc;\n }\n\n return total \/ max_total;\n}\n\nfloat KickEvaluator::eval_pt_to_robot(Geometry2d::Point origin,\n Geometry2d::Point target) {\n return eval_pt_to_pt(origin, target, 2 * Robot_Radius);\n}\n\nfloat KickEvaluator::eval_pt_to_opp_goal(Geometry2d::Point origin) {\n Segment their_goal{\n Point{-Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2,\n Field_Dimensions::Current_Dimensions.Length()},\n Point{Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2,\n Field_Dimensions::Current_Dimensions.Length()}};\n\n return eval_pt_to_seg(origin, their_goal);\n}\n\nfloat KickEvaluator::eval_pt_to_our_goal(Geometry2d::Point origin) {\n Segment our_goal{\n Point{-Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2, 0},\n Point{Field_Dimensions::Current_Dimensions.GoalWidth() \/ 2, 0}};\n\n return eval_pt_to_seg(origin, our_goal);\n}\n\nfloat KickEvaluator::eval_pt_to_seg(Geometry2d::Point origin,\n Geometry2d::Segment target) {\n Point pt1 = target.pt[0] - origin;\n Point pt2 = target.pt[1] - origin;\n double angle = abs(atan2(pt1.y(), pt1.x()) - atan2(pt2.y(), pt2.x()));\n\n return eval_pt_to_pt(origin, target.center(), angle);\n}\n\ntuple KickEvaluator::rect_to_polar(Point origin, Point target,\n Point obstacle) {\n Point dir = obstacle - origin;\n\n return make_tuple(dir.mag(), dir.angleBetween(target - origin));\n}\n\nfloat KickEvaluator::fast_exp(float x) {\n return (24 + x * (24 + x * (12 + x * (4 + x)))) * 0.041666666f;\n}\n\nbool KickEvaluator::good_robot_check(std::tuple polar,\n Geometry2d::Point target,\n Geometry2d::Point origin) {\n float delta_dist = get<0>(polar) - (target - origin).mag();\n\n \/\/ Checks that the robot is within the angle range in front\n \/\/ and not too far behind the target position\n return fabs(get<1>(polar)) < *robot_angle_filter_limit &&\n delta_dist * *kernal_width_coefficient < 1;\n}<|endoftext|>"} {"text":"#include \n#include \"Producer.h\"\n#include \nusing namespace HighQueue;\n\nProducer::Producer(ConnectionPtr & connection, bool solo)\n: solo_(solo)\n, connection_(connection)\n, header_(connection_->getHeader())\n, entryCount_(header_->entryCount_)\n, waitStrategy_(header_->producerWaitStrategy_)\n, consumerUsesMutex_(header_->consumerWaitStrategy_.mutexUsed_)\n, resolver_(header_)\n, readPosition_(*resolver_.resolve(header_->readPosition_))\n, publishPosition_(*resolver_.resolve(header_->publishPosition_))\n, reservePosition_(resolver_.resolve(header_->reservePosition_)->reservePosition_)\n, reserveSoloPosition_(reinterpret_cast(resolver_.resolve(header_->reservePosition_)->reservePosition_))\n, entryAccessor_(resolver_, header_->entries_, header_->entryCount_)\n, publishable_(0)\n, statFulls_(0)\n, statSkips_(0)\n, statPublishWaits_(0)\n, statPublishes_(0)\n, statSpins_(0)\n, statYields_(0)\n, statSleeps_(0)\n, statWaits_(0)\n{\n ++header_->producersPresent_;\n}\n\nProducer::~Producer()\n{\n --header_->producersPresent_;\n}\n\ninline\nuint64_t Producer::reserve()\n{\n if(solo_)\n {\n return reserveSoloPosition_++;\n }\n return reservePosition_++;\n}\n\nvoid Producer::publish(Message & message)\n{\n bool published = false;\n while(!published)\n {\n auto reserved = reserve();\n if(publishable_ <= reserved)\n {\n publishable_ = readPosition_ + entryCount_;\n if(publishable_ <= reserved)\n {\n ++statFulls_;\n if(header_->discardMessagesIfNoConsumer_ && !header_->consumerPresent_)\n {\n readPosition_ = publishPosition_;\n publishable_ = readPosition_ + entryCount_;\n }\n size_t remainingSpins = waitStrategy_.spinCount_;\n size_t remainingYields = waitStrategy_.yieldCount_;\n size_t remainingSleeps = waitStrategy_.sleepCount_;\n while(publishable_ <= reserved)\n {\n if(remainingSpins > 0)\n {\n ++statSpins_;\n if(remainingSpins != WaitStrategy::FOREVER)\n {\n --remainingSpins;\n }\n std::atomic_thread_fence(std::memory_order::memory_order_consume);\n }\n else if(remainingYields > 0)\n {\n ++statYields_;\n if(remainingYields != WaitStrategy::FOREVER)\n {\n --remainingYields;\n }\n std::this_thread::yield();\n }\n else if(remainingSleeps > 0)\n {\n ++statSleeps_;\n if(remainingSleeps != WaitStrategy::FOREVER)\n {\n --remainingSleeps;\n }\n std::this_thread::sleep_for(waitStrategy_.sleepPeriod_);\n }\n else\n {\n ++statWaits_;\n std::unique_lock guard(header_->waitMutex_);\n publishable_ = readPosition_ + entryCount_;\n if(publishable_ > reserved)\n {\n header_->producerWaiting_ = true;\n if(header_->producerWaitConditionVariable_.wait_for(guard, waitStrategy_.mutexWaitTimeout_)\n == std::cv_status::timeout)\n {\n publishable_ = readPosition_ + entryCount_;\n if(publishable_ <= reserved)\n {\n \/\/ todo: define a better exception\n throw std::runtime_error(\"Producer wait timeout.\");\n }\n }\n }\n }\n publishable_ = readPosition_ + header_->entryCount_;\n }\n\n }\n }\n HighQEntry & entry = entryAccessor_[reserved];\n if(entry.status_ != HighQEntry::Status::SKIP)\n {\n message.moveTo(entry.message_);\n entry.status_ = HighQEntry::Status::OK;\n published = true;\n }\n else\n {\n ++statSkips_;\n }\n while(publishPosition_ < reserved)\n {\n ++statPublishWaits_;\n std::this_thread::yield();\n std::atomic_thread_fence(std::memory_order::memory_order_acquire);\n }\n if(publishPosition_ == reserved)\n {\n ++publishPosition_;\n std::atomic_thread_fence(std::memory_order::memory_order_release);\n if(consumerUsesMutex_)\n {\n std::unique_lock guard(header_->waitMutex_);\n if(header_->consumerWaiting_)\n {\n header_->consumerWaiting_ = false;\n header_->consumerWaitConditionVariable_.notify_all();\n }\n }\n ++statPublishes_;\n }\n }\n}\n\nstd::ostream & Producer::writeStats(std::ostream & out) const\n{\n return out << \"Published \" << statPublishes_\n << \" Full: \" << statFulls_\n << \" Skip: \" << statSkips_\n << \" WaitOtherPublishers: \" << statPublishWaits_\n << \" Spin: \" << statSpins_ \n << \" Yield: \" << statYields_ \n << \" Sleep: \" << statSleeps_ \n << \" Wait: \" << statWaits_\n << \" OK: \" << statPublishes_\n << std::endl;\n\n}\n\n\nProducer: no fence is needed when waiting via mutex.#include \n#include \"Producer.h\"\n#include \nusing namespace HighQueue;\n\nProducer::Producer(ConnectionPtr & connection, bool solo)\n: solo_(solo)\n, connection_(connection)\n, header_(connection_->getHeader())\n, entryCount_(header_->entryCount_)\n, waitStrategy_(header_->producerWaitStrategy_)\n, consumerUsesMutex_(header_->consumerWaitStrategy_.mutexUsed_)\n, resolver_(header_)\n, readPosition_(*resolver_.resolve(header_->readPosition_))\n, publishPosition_(*resolver_.resolve(header_->publishPosition_))\n, reservePosition_(resolver_.resolve(header_->reservePosition_)->reservePosition_)\n, reserveSoloPosition_(reinterpret_cast(resolver_.resolve(header_->reservePosition_)->reservePosition_))\n, entryAccessor_(resolver_, header_->entries_, header_->entryCount_)\n, publishable_(0)\n, statFulls_(0)\n, statSkips_(0)\n, statPublishWaits_(0)\n, statPublishes_(0)\n, statSpins_(0)\n, statYields_(0)\n, statSleeps_(0)\n, statWaits_(0)\n{\n ++header_->producersPresent_;\n}\n\nProducer::~Producer()\n{\n --header_->producersPresent_;\n}\n\ninline\nuint64_t Producer::reserve()\n{\n if(solo_)\n {\n return reserveSoloPosition_++;\n }\n return reservePosition_++;\n}\n\nvoid Producer::publish(Message & message)\n{\n bool published = false;\n while(!published)\n {\n auto reserved = reserve();\n if(publishable_ <= reserved)\n {\n publishable_ = readPosition_ + entryCount_;\n if(publishable_ <= reserved)\n {\n ++statFulls_;\n if(header_->discardMessagesIfNoConsumer_ && !header_->consumerPresent_)\n {\n readPosition_ = publishPosition_;\n publishable_ = readPosition_ + entryCount_;\n }\n size_t remainingSpins = waitStrategy_.spinCount_;\n size_t remainingYields = waitStrategy_.yieldCount_;\n size_t remainingSleeps = waitStrategy_.sleepCount_;\n while(publishable_ <= reserved)\n {\n if(remainingSpins > 0)\n {\n ++statSpins_;\n if(remainingSpins != WaitStrategy::FOREVER)\n {\n --remainingSpins;\n }\n std::atomic_thread_fence(std::memory_order::memory_order_consume);\n }\n else if(remainingYields > 0)\n {\n ++statYields_;\n if(remainingYields != WaitStrategy::FOREVER)\n {\n --remainingYields;\n }\n std::this_thread::yield();\n }\n else if(remainingSleeps > 0)\n {\n ++statSleeps_;\n if(remainingSleeps != WaitStrategy::FOREVER)\n {\n --remainingSleeps;\n }\n std::this_thread::sleep_for(waitStrategy_.sleepPeriod_);\n }\n else\n {\n ++statWaits_;\n std::unique_lock guard(header_->waitMutex_);\n publishable_ = readPosition_ + entryCount_;\n if(publishable_ > reserved)\n {\n header_->producerWaiting_ = true;\n if(header_->producerWaitConditionVariable_.wait_for(guard, waitStrategy_.mutexWaitTimeout_)\n == std::cv_status::timeout)\n {\n publishable_ = readPosition_ + entryCount_;\n if(publishable_ <= reserved)\n {\n \/\/ todo: define a better exception\n throw std::runtime_error(\"Producer wait timeout.\");\n }\n }\n }\n }\n publishable_ = readPosition_ + header_->entryCount_;\n }\n\n }\n }\n HighQEntry & entry = entryAccessor_[reserved];\n if(entry.status_ != HighQEntry::Status::SKIP)\n {\n message.moveTo(entry.message_);\n entry.status_ = HighQEntry::Status::OK;\n published = true;\n }\n else\n {\n ++statSkips_;\n }\n while(publishPosition_ < reserved)\n {\n ++statPublishWaits_;\n std::this_thread::yield();\n std::atomic_thread_fence(std::memory_order::memory_order_acquire);\n }\n if(publishPosition_ == reserved)\n {\n ++publishPosition_;\n ++statPublishes_;\n if(!consumerUsesMutex_)\n {\n std::atomic_thread_fence(std::memory_order::memory_order_release);\n return;\n }\n\n std::unique_lock guard(header_->waitMutex_);\n if(header_->consumerWaiting_)\n {\n header_->consumerWaiting_ = false;\n header_->consumerWaitConditionVariable_.notify_all();\n }\n }\n }\n}\n\nstd::ostream & Producer::writeStats(std::ostream & out) const\n{\n return out << \"Published \" << statPublishes_\n << \" Full: \" << statFulls_\n << \" Skip: \" << statSkips_\n << \" WaitOtherPublishers: \" << statPublishWaits_\n << \" Spin: \" << statSpins_ \n << \" Yield: \" << statYields_ \n << \" Sleep: \" << statSleeps_ \n << \" Wait: \" << statWaits_\n << \" OK: \" << statPublishes_\n << std::endl;\n\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n void LockScreenWithUser(test::ScreenLockerTester* tester,\n const std::string& user) {\n UserManager::Get()->UserLoggedIn(user);\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n if (!tester->IsLocked()) {\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n }\n EXPECT_TRUE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\n\/\/ See http:\/\/crbug.com\/79374\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n\/\/ Temporarily disabling screen locker tests while investigating the\n\/\/ issue crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n ui::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n tester->SetPassword(\"password\");\n EXPECT_EQ(\"password\", tester->GetPassword());\n \/\/ Escape clears the password.\n ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),\n ui::VKEY_ESCAPE, false, false, false, false);\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_EQ(\"\", tester->GetPassword());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\nDisabling TestBasic\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n void LockScreenWithUser(test::ScreenLockerTester* tester,\n const std::string& user) {\n UserManager::Get()->UserLoggedIn(user);\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n if (!tester->IsLocked()) {\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n }\n EXPECT_TRUE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\n\/\/ Temporarily disabling all screen locker tests while investigating the\n\/\/ issue crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n ui::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n tester->SetPassword(\"password\");\n EXPECT_EQ(\"password\", tester->GetPassword());\n \/\/ Escape clears the password.\n ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),\n ui::VKEY_ESCAPE, false, false, false, false);\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_EQ(\"\", tester->GetPassword());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"#include \n\nnamespace legui\n{\n void HorizontalSplitter::setBoundingBox(const sf::FloatRect &box)\n {\n \n }\n void HorizontalSplitter::updateSize()\n {\n \n }\n};\nImplemented the HorizontalSplitter.#include \n#include \n\nnamespace legui\n{\n void HorizontalSplitter::setBoundingBox(const sf::FloatRect &box)\n {\n float offset = 0;\n for(std::size_t i = 0; i < getSize(); ++i)\n {\n if(i % 2 == 0) \/\/Number is even. (left side)\n {\n m_widgets[i]->setBoundingBox(sf::FloatRect(box.left, box.height + offset, box.width \/ 2, Config::getFloat(\"STANDARD_HEIGHT\")));\n }\n else \/\/Number is not even. (right side)\n {\n m_widgets[i]->setBoundingBox(sf::FloatRect(box.left + box.width \/ 2, box.height + offset, box.width \/ 2, Config::getFloat(\"STANDARD_HEIGHT\")));\n \/\/Update the size of the widget.\n m_widgets[i]->updateSize();\n \/\/Increase the y offset based on the height of the last right element.\n offset += m_widgets[i]->getBoundingBox().height;\n }\n }\n }\n void HorizontalSplitter::updateSize()\n {\n m_boundingBox.height = 0;\n for(auto &it : m_widgets)\n {\n it->updateSize();\n m_boundingBox.height += it->getBoundingBox().height;\n }\n }\n};\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\nnamespace bfs = boost::filesystem;\n\nnamespace cctag\n{\n\nCCTagVisualDebug::CCTagVisualDebug()\n{\n}\n\nCCTagVisualDebug::~CCTagVisualDebug()\n{\n}\n\nvoid CCTagVisualDebug::initializeFolders(const boost::filesystem::path & rootPath, const std::string & outputFolder, std::size_t nCrowns)\n{\n#ifdef CCTAG_SERIALIZE\n \/\/ Create inputImagePath\/result if it does not exist\n std::stringstream resultFolderName, localizationFolderName, identificationFolderName, absoluteOutputFolderName;\n \n resultFolderName << rootPath.string();\n \n if( outputFolder != \"\" ) {\n resultFolderName << \"\/\" << outputFolder;\n if (!bfs::exists(resultFolderName.str())) {\n bfs::create_directory(resultFolderName.str());\n }\n }\n \n resultFolderName << \"\/cctag\" << nCrowns << \"CC\";\n \n if (!bfs::exists(resultFolderName.str())) {\n bfs::create_directory(resultFolderName.str());\n }\n \n localizationFolderName << resultFolderName.str() << \"\/localization\";\n identificationFolderName << resultFolderName.str() << \"\/identification\";\n\n if (!bfs::exists(localizationFolderName.str())) {\n bfs::create_directory(localizationFolderName.str());\n }\n\n if (!bfs::exists(identificationFolderName.str())) {\n bfs::create_directory(identificationFolderName.str());\n }\n \n _pathRoot = resultFolderName.str();\n CCTAG_COUT_VAR(_pathRoot);\n#endif\n}\n\nvoid CCTagVisualDebug::setPyramidLevel(int level) {\n#ifdef CCTAG_SERIALIZE\n _pyramidLevel = level;\n#endif\n}\n\nint CCTagVisualDebug::getPyramidLevel() {\n return _pyramidLevel;\n}\n\nstd::string CCTagVisualDebug::getPath() const {\n return _path;\n}\n\nvoid CCTagVisualDebug::setImageFileName(const std::string& imageFileName) {\n#ifdef CCTAG_SERIALIZE\n _imageFileName = imageFileName;\n CCTAG_COUT_VAR(_imageFileName);\n _path = _pathRoot + \"\/\" + imageFileName;\n CCTAG_COUT_VAR(_path);\n if (!bfs::exists(_path)) {\n bfs::create_directory(_path);\n CCTAG_COUT(\"creation done\");\n }\n CCTAG_COUT(\"exit\");\n#endif \n}\n\nvoid CCTagVisualDebug::initBackgroundImage(const cv::Mat & back)\n{\n#ifdef CCTAG_SERIALIZE\n cv::Mat temp; \/\/ todo@Lilian: why do I need to use temp ?\n cvtColor(back, temp, cv::COLOR_GRAY2RGB);\n _backImage = temp.clone();\n#endif\n}\n\nvoid CCTagVisualDebug::newSession(const std::string & sessionName) {\n#ifdef CCTAG_SERIALIZE\n \/\/ Don't erase old sessions\n if (_sessions.find(sessionName) == _sessions.end()) {\n _sessions[sessionName] = _backImage;\n }\n#endif\n}\n\nvoid CCTagVisualDebug::drawText(const cctag::Point2dN & p, const std::string & text, const cctag::Color & color) {\n#ifdef CCTAG_SERIALIZE\n CvFont font1;\n cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);\n\n IplImage iplBack = _backImage;\n cvPutText( &iplBack, text.c_str(),\n cvPoint((int) p.x(), (int) p.y()),\n &font1, CV_RGB(color[0] * 255, color[1] * 255, color[2] * 255));\n#endif\n}\n\nvoid CCTagVisualDebug::drawPoint(const cctag::Point2dN & point, const cctag::Color & color) {\n#ifdef CCTAG_SERIALIZE\n if (point.x() >= 1 && point.x() < _backImage.cols-1 &&\n point.y() >= 1 && point.y() < _backImage.rows-1)\n {\n cv::Vec3b cvColor;\n cvColor.val[0] = 255*color[0];\n cvColor.val[1] = 255*color[1]; \n cvColor.val[2] = 255*color[2]; \n _backImage.at(point.y(),point.x()) = cvColor;\n \/\/cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);\n }\n#endif \/\/ CCTAG_SERIALIZE\n}\n\nvoid CCTagVisualDebug::drawPoint(const cctag::DirectedPoint2d & point, const cctag::Color & color) {\n#ifdef CCTAG_SERIALIZE\n if (point.x() >= 1 && point.x() < _backImage.cols-1 &&\n point.y() >= 1 && point.y() < _backImage.rows-1)\n {\n \/\/cv::Vec3b cvColor;\n \/\/cvColor.val[0] = 255*color[0];\n \/\/cvColor.val[1] = 255*color[1]; \n \/\/cvColor.val[2] = 255*color[2]; \n \/\/_backImage.at(point.y(),point.x()) = cvColor;\n cv::Point p1(point.x(),point.y());\n cv::Point p2(point.x() + point.dX(),point.y() + point.dY());\n cv::arrowedLine( _backImage, p1, p2, cv::Scalar(255*color[0], 255*color[1], 255*color[2]) );\n \n \/\/cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);\n }\n#endif \/\/ CCTAG_SERIALIZE\n}\n\nvoid CCTagVisualDebug::drawPoints(const std::vector > & points, const cctag::Color & color)\n{\n#ifdef CCTAG_SERIALIZE\n BOOST_FOREACH(const cctag::Point2dN & point, points) {\n CCTagVisualDebug::instance().drawPoint(point, cctag::color_red);\n }\n#endif\n}\n\n\/\/ todo templater la function ci-dessus avec celle ci-dessous\nvoid CCTagVisualDebug::drawPoints(const std::vector > & points, const cctag::Color & color)\n{\n#ifdef CCTAG_SERIALIZE\n BOOST_FOREACH(const cctag::Point2dN & point, points) {\n CCTagVisualDebug::instance().drawPoint(cctag::Point2dN(point.x(),point.y()), cctag::color_red);\n }\n#endif\n}\n\nvoid CCTagVisualDebug::drawMarker(const cctag::CCTag& marker, bool drawScaledMarker)\n{\n#ifdef CCTAG_SERIALIZE\n numerical::geometry::Ellipse rescaledOuterEllipse;\n if (drawScaledMarker) {\n rescaledOuterEllipse = marker.rescaledOuterEllipse();\n } else {\n rescaledOuterEllipse = marker.outerEllipse();\n }\n Point2dN & center = rescaledOuterEllipse.center();\n \n \/\/ Display ellipses\n if (drawScaledMarker) {\n rescaledOuterEllipse = marker.rescaledOuterEllipse();\n } else {\n rescaledOuterEllipse = marker.outerEllipse();\n }\n\n cv::Scalar color;\n \/\/ Set the color\n if (marker.getStatus() == status::no_collected_cuts) {\n \/\/ Magenta\n color = cv::Scalar(255,0,255);\n }else if (marker.getStatus() == status::no_selected_cuts) {\n \/\/ Cyan\n color = cv::Scalar(0,255,255);\n }else if(marker.getStatus() == status::opti_has_diverged){\n \/\/ Red\n color = cv::Scalar(255,0,0);\n }else if(marker.getStatus() == status::id_not_reliable){\n \/\/ Cyan\n color = cv::Scalar(0,255,255);\n }else if(marker.getStatus() == status::id_reliable){\n \/\/ Green\n color = cv::Scalar(0,255,0);\n }else if(marker.getStatus() == status::degenerate){\n \/\/ Yellow 1\n color = cv::Scalar(255,255,0);\n }else if(marker.getStatus() == 0 ){\n \/\/ Green\n color = cv::Scalar(0,255,0);\n }\n\n \/\/CCTAT_COUT_VAR(color);\n \n cv::ellipse(_backImage , cv::Point(center.x(),center.y()),\n cv::Size(rescaledOuterEllipse.a(), rescaledOuterEllipse.b()),\n rescaledOuterEllipse.angle()*180\/M_PI, 0, 360, color);\n#endif\n}\n\nvoid CCTagVisualDebug::drawInfos(const cctag::CCTag& marker, bool drawScaledMarker)\n{\n#ifdef CCTAG_SERIALIZE\n CvFont font1;\n cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);\n\n std::string sId = boost::lexical_cast(marker.id() + 1);\n\n int x, y;\n if (drawScaledMarker) {\n x = int (marker.rescaledOuterEllipse().center().x());\n y = int (marker.rescaledOuterEllipse().center().y());\n } else {\n x = int (marker.outerEllipse().center().x());\n y = int (marker.outerEllipse().center().y());\n }\n\n IplImage iplImg = _backImage;\n cvPutText( &iplImg, sId.c_str(),\n cvPoint(x-10, y+10),\n &font1, CV_RGB(255, 140, 0));\n#endif\n}\n\nstd::string CCTagVisualDebug::getImageFileName() const {\n return _imageFileName;\n}\n\nvoid CCTagVisualDebug::out(const std::string & filename) const {\n#ifdef CCTAG_SERIALIZE\n cv::imwrite(filename, _backImage);\n#endif\n}\n\nvoid CCTagVisualDebug::outPutAllSessions() const {\n#ifdef CCTAG_SERIALIZE\n BOOST_FOREACH(const Sessions::const_iterator::value_type & v, _sessions) {\n const std::string filename = _path + \"\/\" + v.first + \".png\";\n cv::imwrite(filename, v.second);\n }\n#endif\n}\n\nvoid CCTagVisualDebug::writeLocalizationView(cctag::CCTag::List& markers) const {\n#ifdef CCTAG_SERIALIZE\n std::stringstream localizationResultFileName;\n localizationResultFileName << \"..\/localization\/\" << _imageFileName;\n CCTagVisualDebug::instance().newSession(localizationResultFileName.str());\n\n BOOST_FOREACH(const cctag::CCTag & marker, markers) {\n CCTagVisualDebug::instance().drawMarker(marker);\n CCTagVisualDebug::instance().drawInfos(marker);\n }\n#endif\n}\n\nvoid CCTagVisualDebug::writeIdentificationView(cctag::CCTag::List& markers) const {\n#ifdef CCTAG_SERIALIZE\n\n std::stringstream identificationResultFileName;\n identificationResultFileName << \"..\/identification\/\" << _imageFileName;\n CCTagVisualDebug::instance().newSession(identificationResultFileName.str());\n\n BOOST_FOREACH(const cctag::CCTag & marker, markers) {\n CCTagVisualDebug::instance().drawMarker(marker);\n CCTagVisualDebug::instance().drawPoints(marker.rescaledOuterEllipsePoints(), cctag::color_red);\n CCTagVisualDebug::instance().drawInfos(marker);\n }\n\n#endif\n}\n\nvoid CCTagVisualDebug::clearSessions() {\n#ifdef CCTAG_SERIALIZE\n _sessions.erase(_sessions.begin(), _sessions.end());\n#endif\n}\n\n} \/\/ namespace cctag\nless debug output unless VISUAL_DEBUG is given#include \n#include \n\n#include \n#include \n\nnamespace bfs = boost::filesystem;\n\nnamespace cctag\n{\n\nCCTagVisualDebug::CCTagVisualDebug()\n{\n}\n\nCCTagVisualDebug::~CCTagVisualDebug()\n{\n}\n\nvoid CCTagVisualDebug::initializeFolders(const boost::filesystem::path & rootPath, const std::string & outputFolder, std::size_t nCrowns)\n{\n#ifdef CCTAG_SERIALIZE\n \/\/ Create inputImagePath\/result if it does not exist\n std::stringstream resultFolderName, localizationFolderName, identificationFolderName, absoluteOutputFolderName;\n \n resultFolderName << rootPath.string();\n \n if( outputFolder != \"\" ) {\n resultFolderName << \"\/\" << outputFolder;\n if (!bfs::exists(resultFolderName.str())) {\n bfs::create_directory(resultFolderName.str());\n }\n }\n \n resultFolderName << \"\/cctag\" << nCrowns << \"CC\";\n \n if (!bfs::exists(resultFolderName.str())) {\n bfs::create_directory(resultFolderName.str());\n }\n \n localizationFolderName << resultFolderName.str() << \"\/localization\";\n identificationFolderName << resultFolderName.str() << \"\/identification\";\n\n if (!bfs::exists(localizationFolderName.str())) {\n bfs::create_directory(localizationFolderName.str());\n }\n\n if (!bfs::exists(identificationFolderName.str())) {\n bfs::create_directory(identificationFolderName.str());\n }\n \n _pathRoot = resultFolderName.str();\n CCTAG_COUT_VAR(_pathRoot);\n#endif\n}\n\nvoid CCTagVisualDebug::setPyramidLevel(int level) {\n#ifdef CCTAG_SERIALIZE\n _pyramidLevel = level;\n#endif\n}\n\nint CCTagVisualDebug::getPyramidLevel() {\n return _pyramidLevel;\n}\n\nstd::string CCTagVisualDebug::getPath() const {\n return _path;\n}\n\nvoid CCTagVisualDebug::setImageFileName(const std::string& imageFileName) {\n#ifdef CCTAG_SERIALIZE\n _imageFileName = imageFileName;\n CCTAG_COUT_VAR(_imageFileName);\n _path = _pathRoot + \"\/\" + imageFileName;\n CCTAG_COUT_VAR(_path);\n if (!bfs::exists(_path)) {\n bfs::create_directory(_path);\n CCTAG_COUT(\"creation done\");\n }\n CCTAG_COUT(\"exit\");\n#endif \n}\n\nvoid CCTagVisualDebug::initBackgroundImage(const cv::Mat & back)\n{\n#ifdef CCTAG_SERIALIZE\n cv::Mat temp; \/\/ todo@Lilian: why do I need to use temp ?\n cvtColor(back, temp, cv::COLOR_GRAY2RGB);\n _backImage = temp.clone();\n#endif\n}\n\nvoid CCTagVisualDebug::newSession(const std::string & sessionName) {\n#ifdef CCTAG_SERIALIZE\n \/\/ Don't erase old sessions\n if (_sessions.find(sessionName) == _sessions.end()) {\n _sessions[sessionName] = _backImage;\n }\n#endif\n}\n\nvoid CCTagVisualDebug::drawText(const cctag::Point2dN & p, const std::string & text, const cctag::Color & color) {\n#ifdef CCTAG_SERIALIZE\n CvFont font1;\n cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);\n\n IplImage iplBack = _backImage;\n cvPutText( &iplBack, text.c_str(),\n cvPoint((int) p.x(), (int) p.y()),\n &font1, CV_RGB(color[0] * 255, color[1] * 255, color[2] * 255));\n#endif\n}\n\nvoid CCTagVisualDebug::drawPoint(const cctag::Point2dN & point, const cctag::Color & color) {\n#ifdef CCTAG_SERIALIZE\n if (point.x() >= 1 && point.x() < _backImage.cols-1 &&\n point.y() >= 1 && point.y() < _backImage.rows-1)\n {\n cv::Vec3b cvColor;\n cvColor.val[0] = 255*color[0];\n cvColor.val[1] = 255*color[1]; \n cvColor.val[2] = 255*color[2]; \n _backImage.at(point.y(),point.x()) = cvColor;\n \/\/cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);\n }\n#endif \/\/ CCTAG_SERIALIZE\n}\n\nvoid CCTagVisualDebug::drawPoint(const cctag::DirectedPoint2d & point, const cctag::Color & color) {\n#ifdef CCTAG_SERIALIZE\n if (point.x() >= 1 && point.x() < _backImage.cols-1 &&\n point.y() >= 1 && point.y() < _backImage.rows-1)\n {\n \/\/cv::Vec3b cvColor;\n \/\/cvColor.val[0] = 255*color[0];\n \/\/cvColor.val[1] = 255*color[1]; \n \/\/cvColor.val[2] = 255*color[2]; \n \/\/_backImage.at(point.y(),point.x()) = cvColor;\n cv::Point p1(point.x(),point.y());\n cv::Point p2(point.x() + point.dX(),point.y() + point.dY());\n cv::arrowedLine( _backImage, p1, p2, cv::Scalar(255*color[0], 255*color[1], 255*color[2]) );\n \n \/\/cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);\n }\n#endif \/\/ CCTAG_SERIALIZE\n}\n\nvoid CCTagVisualDebug::drawPoints(const std::vector > & points, const cctag::Color & color)\n{\n#ifdef CCTAG_SERIALIZE\n BOOST_FOREACH(const cctag::Point2dN & point, points) {\n CCTagVisualDebug::instance().drawPoint(point, cctag::color_red);\n }\n#endif\n}\n\n\/\/ todo templater la function ci-dessus avec celle ci-dessous\nvoid CCTagVisualDebug::drawPoints(const std::vector > & points, const cctag::Color & color)\n{\n#ifdef CCTAG_SERIALIZE\n BOOST_FOREACH(const cctag::Point2dN & point, points) {\n CCTagVisualDebug::instance().drawPoint(cctag::Point2dN(point.x(),point.y()), cctag::color_red);\n }\n#endif\n}\n\nvoid CCTagVisualDebug::drawMarker(const cctag::CCTag& marker, bool drawScaledMarker)\n{\n#ifdef CCTAG_SERIALIZE\n numerical::geometry::Ellipse rescaledOuterEllipse;\n if (drawScaledMarker) {\n rescaledOuterEllipse = marker.rescaledOuterEllipse();\n } else {\n rescaledOuterEllipse = marker.outerEllipse();\n }\n Point2dN & center = rescaledOuterEllipse.center();\n \n \/\/ Display ellipses\n if (drawScaledMarker) {\n rescaledOuterEllipse = marker.rescaledOuterEllipse();\n } else {\n rescaledOuterEllipse = marker.outerEllipse();\n }\n\n cv::Scalar color;\n \/\/ Set the color\n if (marker.getStatus() == status::no_collected_cuts) {\n \/\/ Magenta\n color = cv::Scalar(255,0,255);\n }else if (marker.getStatus() == status::no_selected_cuts) {\n \/\/ Cyan\n color = cv::Scalar(0,255,255);\n }else if(marker.getStatus() == status::opti_has_diverged){\n \/\/ Red\n color = cv::Scalar(255,0,0);\n }else if(marker.getStatus() == status::id_not_reliable){\n \/\/ Cyan\n color = cv::Scalar(0,255,255);\n }else if(marker.getStatus() == status::id_reliable){\n \/\/ Green\n color = cv::Scalar(0,255,0);\n }else if(marker.getStatus() == status::degenerate){\n \/\/ Yellow 1\n color = cv::Scalar(255,255,0);\n }else if(marker.getStatus() == 0 ){\n \/\/ Green\n color = cv::Scalar(0,255,0);\n }\n\n \/\/CCTAT_COUT_VAR(color);\n \n cv::ellipse(_backImage , cv::Point(center.x(),center.y()),\n cv::Size(rescaledOuterEllipse.a(), rescaledOuterEllipse.b()),\n rescaledOuterEllipse.angle()*180\/M_PI, 0, 360, color);\n#endif\n}\n\nvoid CCTagVisualDebug::drawInfos(const cctag::CCTag& marker, bool drawScaledMarker)\n{\n#ifdef CCTAG_SERIALIZE\n CvFont font1;\n cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);\n\n std::string sId = boost::lexical_cast(marker.id() + 1);\n\n int x, y;\n if (drawScaledMarker) {\n x = int (marker.rescaledOuterEllipse().center().x());\n y = int (marker.rescaledOuterEllipse().center().y());\n } else {\n x = int (marker.outerEllipse().center().x());\n y = int (marker.outerEllipse().center().y());\n }\n\n IplImage iplImg = _backImage;\n cvPutText( &iplImg, sId.c_str(),\n cvPoint(x-10, y+10),\n &font1, CV_RGB(255, 140, 0));\n#endif\n}\n\nstd::string CCTagVisualDebug::getImageFileName() const {\n return _imageFileName;\n}\n\nvoid CCTagVisualDebug::out(const std::string & filename) const {\n#if defined(CCTAG_SERIALIZE) && defined(VISUAL_DEBUG)\n cv::imwrite(filename, _backImage);\n#endif\n}\n\nvoid CCTagVisualDebug::outPutAllSessions() const {\n#if defined(CCTAG_SERIALIZE) && defined(VISUAL_DEBUG)\n BOOST_FOREACH(const Sessions::const_iterator::value_type & v, _sessions) {\n const std::string filename = _path + \"\/\" + v.first + \".png\";\n cv::imwrite(filename, v.second);\n }\n#endif\n}\n\nvoid CCTagVisualDebug::writeLocalizationView(cctag::CCTag::List& markers) const {\n#ifdef CCTAG_SERIALIZE\n std::stringstream localizationResultFileName;\n localizationResultFileName << \"..\/localization\/\" << _imageFileName;\n CCTagVisualDebug::instance().newSession(localizationResultFileName.str());\n\n BOOST_FOREACH(const cctag::CCTag & marker, markers) {\n CCTagVisualDebug::instance().drawMarker(marker);\n CCTagVisualDebug::instance().drawInfos(marker);\n }\n#endif\n}\n\nvoid CCTagVisualDebug::writeIdentificationView(cctag::CCTag::List& markers) const {\n#ifdef CCTAG_SERIALIZE\n\n std::stringstream identificationResultFileName;\n identificationResultFileName << \"..\/identification\/\" << _imageFileName;\n CCTagVisualDebug::instance().newSession(identificationResultFileName.str());\n\n BOOST_FOREACH(const cctag::CCTag & marker, markers) {\n CCTagVisualDebug::instance().drawMarker(marker);\n CCTagVisualDebug::instance().drawPoints(marker.rescaledOuterEllipsePoints(), cctag::color_red);\n CCTagVisualDebug::instance().drawInfos(marker);\n }\n\n#endif\n}\n\nvoid CCTagVisualDebug::clearSessions() {\n#ifdef CCTAG_SERIALIZE\n _sessions.erase(_sessions.begin(), _sessions.end());\n#endif\n}\n\n} \/\/ namespace cctag\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n \n#define MAX_BUF 1024\n\n#include \n#include \n#include \n\nint main()\n{\n int fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );\n\t\n\tstruct sockaddr_un addr;\n\tbzero( &addr, sizeof(addr) );\n\taddr.sun_family = AF_LOCAL;\n\tstrcpy( addr.sun_path, \"\/tmp\/mpu.6050.unix.domain\" );\n\t\n char buf[MAX_BUF];\n if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0) {\n perror(\"setsockopt(SO_REUSEADDR) failed\");\n }\n if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)\n {\n\n printf(\" cannot bind socket: %d. Passed in address is invalid or port is in use\",errno);\n\n return 0;\n\n }\n\n int degree = 90;\n while(degree >0) {\n \tsocklen_t len = sizeof(addr);\n int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);\n if(ret>0){\n \/\/printf(\"Received: %s\\n\", buf);\n std::stringstream ss;\n ss << buf;\n boost::property_tree::ptree pt;\n boost::property_tree::read_json(ss, pt);\n std::cout << pt.get(\"yaw\") << std::endl;\n } else if (ret==0){\n } else {\n printf(\"ret=<%d>\\n\",ret);\n }\n }\n close(fd);\n\n return 0;\n}\nUpdate turn.cpp#include \n#include \n#include \n#include \n#include \n#include \n#include \n \n#define MAX_BUF 1024\n\n#include \n#include \n#include \n\nint main()\n{\n int fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );\n\t\n\tstruct sockaddr_un addr;\n\tbzero( &addr, sizeof(addr) );\n\taddr.sun_family = AF_LOCAL;\n\tstrcpy( addr.sun_path, \"\/tmp\/mpu.6050.unix.domain\" );\n\t\n int use = 1; \n if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) {\n perror(\"setsockopt(SO_REUSEADDR) failed\");\n }\n if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)\n {\n\n printf(\" cannot bind socket: %d. Passed in address is invalid or port is in use\",errno);\n\n return 0;\n\n }\n\n char buf[MAX_BUF];\n int degree = 90;\n while(degree >0) {\n \tsocklen_t len = sizeof(addr);\n int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);\n if(ret>0){\n \/\/printf(\"Received: %s\\n\", buf);\n std::stringstream ss;\n ss << buf;\n boost::property_tree::ptree pt;\n boost::property_tree::read_json(ss, pt);\n std::cout << pt.get(\"yaw\") << std::endl;\n } else if (ret==0){\n } else {\n printf(\"ret=<%d>\\n\",ret);\n }\n }\n close(fd);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Math\/DualComplex.h\"\n#include \"Math\/DualQuaternion.h\"\n\nnamespace Corrade { namespace Utility {\n\n#ifndef DOXYGEN_GENERATING_OUTPUT\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef MAGNUM_TARGET_GLES\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#endif\n\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef MAGNUM_TARGET_GLES\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#endif\n\n\/* For some reason mingw's GCC instantiates ConfigurationValue>\n (which depends on ConfigurationValue) before\n these and then loudly complains about multiple definitions. WTF. *\/\n\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef _WIN32\ntemplate struct ConfigurationValue>;\n#endif\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef _WIN32\ntemplate struct ConfigurationValue>;\n#endif\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef _WIN32\ntemplate struct ConfigurationValue>;\n#endif\n#ifndef MAGNUM_TARGET_GLES\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef _WIN32\ntemplate struct ConfigurationValue>;\n#endif\n#endif\n#endif\n\n}}\n\nnamespace Magnum { namespace Math {\n\n#ifndef DOXYGEN_GENERATING_OUTPUT\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion&);\n#endif\n\n\/* Check proper size of GL types *\/\nstatic_assert(sizeof(Vector<2, Float>) == 8, \"Improper size of 2-element Float vector\");\nstatic_assert(sizeof(Vector<3, Float>) == 12, \"Improper size of 3-element Float vector\");\nstatic_assert(sizeof(Vector<4, Float>) == 16, \"Improper size of 4-element Float vector\");\nstatic_assert(sizeof(Vector<2, Int>) == 8, \"Improper size of 2-element Int vector\");\nstatic_assert(sizeof(Vector<3, Int>) == 12, \"Improper size of 3-element Int vector\");\nstatic_assert(sizeof(Vector<4, Int>) == 16, \"Improper size of 4-element Int vector\");\nstatic_assert(sizeof(Vector<2, UnsignedInt>) == 8, \"Improper size of 2-element UnsignedInt vector\");\nstatic_assert(sizeof(Vector<3, UnsignedInt>) == 12, \"Improper size of 3-element UnsignedInt vector\");\nstatic_assert(sizeof(Vector<4, UnsignedInt>) == 16, \"Improper size of 4-element UnsignedInt vector\");\n#ifndef MAGNUM_TARGET_GLES\nstatic_assert(sizeof(Vector<2, Double>) == 16, \"Improper size of 2-element Double vector\");\nstatic_assert(sizeof(Vector<3, Double>) == 24, \"Improper size of 3-element Double vector\");\nstatic_assert(sizeof(Vector<4, Double>) == 32, \"Improper size of 4-element Double vector\");\n#endif\n\nstatic_assert(sizeof(RectangularMatrix<2, 2, Float>) == 16, \"Improper size of 2x2 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 3, Float>) == 36, \"Improper size of 3x3 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 4, Float>) == 64, \"Improper size of 4x4 Float matrix\");\n#ifndef MAGNUM_TARGET_GLES\nstatic_assert(sizeof(RectangularMatrix<2, 2, Double>) == 32, \"Improper size of 2x2 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 3, Double>) == 72, \"Improper size of 3x3 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 4, Double>) == 128, \"Improper size of 4x4 Double matrix\");\n#endif\n\nstatic_assert(sizeof(RectangularMatrix<2, 3, Float>) == 24, \"Improper size of 2x3 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 2, Float>) == 24, \"Improper size of 3x2 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<2, 4, Float>) == 32, \"Improper size of 2x4 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 2, Float>) == 32, \"Improper size of 4x2 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 4, Float>) == 48, \"Improper size of 3x4 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 3, Float>) == 48, \"Improper size of 4x3 Float matrix\");\n#ifndef MAGNUM_TARGET_GLES\nstatic_assert(sizeof(RectangularMatrix<2, 3, Double>) == 48, \"Improper size of 2x3 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 2, Double>) == 48, \"Improper size of 3x2 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<2, 4, Double>) == 64, \"Improper size of 2x4 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 2, Double>) == 64, \"Improper size of 4x2 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 4, Double>) == 96, \"Improper size of 3x4 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 3, Double>) == 96, \"Improper size of 4x3 Double matrix\");\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Float>&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Double>&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Float>&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Double>&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Int>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Int>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Int>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, UnsignedInt>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, UnsignedInt>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, UnsignedInt>&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Double>&);\n#endif\n#endif\n\n}}\n\nMinGW32's linker issues _are only_ MinGW32's fault.\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Math\/DualComplex.h\"\n#include \"Math\/DualQuaternion.h\"\n\nnamespace Corrade { namespace Utility {\n\n#ifndef DOXYGEN_GENERATING_OUTPUT\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef MAGNUM_TARGET_GLES\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#endif\n\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef MAGNUM_TARGET_GLES\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#endif\n\n\/* For some reason mingw's GCC instantiates ConfigurationValue>\n (which depends on ConfigurationValue) before\n these and then loudly complains about multiple definitions. WTF. *\/\n\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef __MINGW32__\ntemplate struct ConfigurationValue>;\n#endif\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef __MINGW32__\ntemplate struct ConfigurationValue>;\n#endif\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef __MINGW32__\ntemplate struct ConfigurationValue>;\n#endif\n#ifndef MAGNUM_TARGET_GLES\ntemplate struct ConfigurationValue>;\ntemplate struct ConfigurationValue>;\n#ifndef __MINGW32__\ntemplate struct ConfigurationValue>;\n#endif\n#endif\n#endif\n\n}}\n\nnamespace Magnum { namespace Math {\n\n#ifndef DOXYGEN_GENERATING_OUTPUT\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion&);\n#endif\n\n\/* Check proper size of GL types *\/\nstatic_assert(sizeof(Vector<2, Float>) == 8, \"Improper size of 2-element Float vector\");\nstatic_assert(sizeof(Vector<3, Float>) == 12, \"Improper size of 3-element Float vector\");\nstatic_assert(sizeof(Vector<4, Float>) == 16, \"Improper size of 4-element Float vector\");\nstatic_assert(sizeof(Vector<2, Int>) == 8, \"Improper size of 2-element Int vector\");\nstatic_assert(sizeof(Vector<3, Int>) == 12, \"Improper size of 3-element Int vector\");\nstatic_assert(sizeof(Vector<4, Int>) == 16, \"Improper size of 4-element Int vector\");\nstatic_assert(sizeof(Vector<2, UnsignedInt>) == 8, \"Improper size of 2-element UnsignedInt vector\");\nstatic_assert(sizeof(Vector<3, UnsignedInt>) == 12, \"Improper size of 3-element UnsignedInt vector\");\nstatic_assert(sizeof(Vector<4, UnsignedInt>) == 16, \"Improper size of 4-element UnsignedInt vector\");\n#ifndef MAGNUM_TARGET_GLES\nstatic_assert(sizeof(Vector<2, Double>) == 16, \"Improper size of 2-element Double vector\");\nstatic_assert(sizeof(Vector<3, Double>) == 24, \"Improper size of 3-element Double vector\");\nstatic_assert(sizeof(Vector<4, Double>) == 32, \"Improper size of 4-element Double vector\");\n#endif\n\nstatic_assert(sizeof(RectangularMatrix<2, 2, Float>) == 16, \"Improper size of 2x2 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 3, Float>) == 36, \"Improper size of 3x3 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 4, Float>) == 64, \"Improper size of 4x4 Float matrix\");\n#ifndef MAGNUM_TARGET_GLES\nstatic_assert(sizeof(RectangularMatrix<2, 2, Double>) == 32, \"Improper size of 2x2 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 3, Double>) == 72, \"Improper size of 3x3 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 4, Double>) == 128, \"Improper size of 4x4 Double matrix\");\n#endif\n\nstatic_assert(sizeof(RectangularMatrix<2, 3, Float>) == 24, \"Improper size of 2x3 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 2, Float>) == 24, \"Improper size of 3x2 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<2, 4, Float>) == 32, \"Improper size of 2x4 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 2, Float>) == 32, \"Improper size of 4x2 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 4, Float>) == 48, \"Improper size of 3x4 Float matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 3, Float>) == 48, \"Improper size of 4x3 Float matrix\");\n#ifndef MAGNUM_TARGET_GLES\nstatic_assert(sizeof(RectangularMatrix<2, 3, Double>) == 48, \"Improper size of 2x3 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 2, Double>) == 48, \"Improper size of 3x2 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<2, 4, Double>) == 64, \"Improper size of 2x4 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 2, Double>) == 64, \"Improper size of 4x2 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<3, 4, Double>) == 96, \"Improper size of 3x4 Double matrix\");\nstatic_assert(sizeof(RectangularMatrix<4, 3, Double>) == 96, \"Improper size of 4x3 Double matrix\");\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Float>&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Double>&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Float>&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Double>&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit&);\n#endif\n\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Float>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Int>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Int>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Int>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, UnsignedInt>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, UnsignedInt>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, UnsignedInt>&);\n#ifndef MAGNUM_TARGET_GLES\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Double>&);\ntemplate Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Double>&);\n#endif\n#endif\n\n}}\n\n<|endoftext|>"} {"text":"\/\/===- llvm\/ADT\/SmallVector.cpp - 'Normally small' vectors ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License.\n\/\/ ==============================================================================\n\/\/ LLVM Release License\n\/\/ ==============================================================================\n\/\/ University of Illinois\/NCSA\n\/\/ Open Source License\n\/\/\n\/\/ Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.\n\/\/ All rights reserved.\n\/\/\n\/\/ Developed by:\n\/\/\n\/\/ LLVM Team\n\/\/\n\/\/ University of Illinois at Urbana-Champaign\n\/\/\n\/\/ http:\/\/llvm.org\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal with\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n\/\/ of the Software, and to permit persons to whom the Software is furnished to do\n\/\/ so, subject to the following conditions:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimers.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimers in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the names of the LLVM Team, University of Illinois at\n\/\/ Urbana-Champaign, nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this Software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE\n\/\/ SOFTWARE.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the SmallVector class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"OgreSmallVector.h\"\n\nnamespace Ogre {\n\n\/\/\/ grow_pod - This is an implementation of the grow() method which only works\n\/\/\/ on POD-like datatypes and is out of line to reduce code duplication.\nvoid SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) {\n\tsize_t CurSizeBytes = size_in_bytes();\n size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; \/\/ Always grow.\n\tif (NewCapacityInBytes < MinSizeInBytes)\n\t\tNewCapacityInBytes = MinSizeInBytes;\n\n void *NewElts;\n if (this->isSmall()) {\n NewElts = malloc(NewCapacityInBytes);\n\t\n\t\/\/ Copy the elements over. No need to run dtors on PODs.\n\tmemcpy(NewElts, this->BeginX, CurSizeBytes);\n } else {\n \/\/ If this wasn't grown from the inline copy, grow the allocated space.\n NewElts = realloc(this->BeginX, NewCapacityInBytes);\n }\n\t\n\tthis->EndX = (char*)NewElts+CurSizeBytes;\n\tthis->BeginX = NewElts;\n\tthis->CapacityX = (char*)this->BeginX + NewCapacityInBytes;\n}\n\n}Added missing #include \"OgreStableHeaders.h\" to OgreSmallVector.cpp.\/\/===- llvm\/ADT\/SmallVector.cpp - 'Normally small' vectors ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License.\n\/\/ ==============================================================================\n\/\/ LLVM Release License\n\/\/ ==============================================================================\n\/\/ University of Illinois\/NCSA\n\/\/ Open Source License\n\/\/\n\/\/ Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.\n\/\/ All rights reserved.\n\/\/\n\/\/ Developed by:\n\/\/\n\/\/ LLVM Team\n\/\/\n\/\/ University of Illinois at Urbana-Champaign\n\/\/\n\/\/ http:\/\/llvm.org\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal with\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n\/\/ of the Software, and to permit persons to whom the Software is furnished to do\n\/\/ so, subject to the following conditions:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimers.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimers in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the names of the LLVM Team, University of Illinois at\n\/\/ Urbana-Champaign, nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this Software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE\n\/\/ SOFTWARE.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the SmallVector class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreSmallVector.h\"\n\nnamespace Ogre {\n\n\/\/\/ grow_pod - This is an implementation of the grow() method which only works\n\/\/\/ on POD-like datatypes and is out of line to reduce code duplication.\nvoid SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) {\n\tsize_t CurSizeBytes = size_in_bytes();\n size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; \/\/ Always grow.\n\tif (NewCapacityInBytes < MinSizeInBytes)\n\t\tNewCapacityInBytes = MinSizeInBytes;\n\n void *NewElts;\n if (this->isSmall()) {\n NewElts = malloc(NewCapacityInBytes);\n\t\n\t\/\/ Copy the elements over. No need to run dtors on PODs.\n\tmemcpy(NewElts, this->BeginX, CurSizeBytes);\n } else {\n \/\/ If this wasn't grown from the inline copy, grow the allocated space.\n NewElts = realloc(this->BeginX, NewCapacityInBytes);\n }\n\t\n\tthis->EndX = (char*)NewElts+CurSizeBytes;\n\tthis->BeginX = NewElts;\n\tthis->CapacityX = (char*)this->BeginX + NewCapacityInBytes;\n}\n\n}<|endoftext|>"} {"text":"\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/core\/data\/service\/data_transfer.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_shape.h\"\n#include \"tensorflow\/core\/framework\/tensor_testutil.h\"\n#include \"tensorflow\/core\/framework\/types.pb.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/platform\/status.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace {\n\nclass TestDataTransferServer : public DataTransferServer {\n public:\n explicit TestDataTransferServer(bool* called) : called_(called) {}\n Status Start() override {\n *called_ = true;\n return Status::OK();\n }\n int get_port() override { return 0; }\n\n private:\n bool* called_;\n};\n\ntemplate \nGetElementResult MakeElementResult(T value) {\n GetElementResult result;\n result.components.push_back(Tensor(std::move(value)));\n result.element_index = 0;\n result.end_of_sequence = false;\n return result;\n}\n\nTEST(DataTransferTest, RegisterDataTransferServerBuilder) {\n bool called = false;\n DataTransferServer::Register(\"test\", [&called](auto _) {\n return std::make_shared(&called);\n });\n\n std::shared_ptr server;\n TF_ASSERT_OK(DataTransferServer::Build(\"test\", {}, &server));\n EXPECT_FALSE(called);\n\n TF_ASSERT_OK(server->Start());\n EXPECT_TRUE(called);\n}\n\nTEST(DataTransferTest, EstimateMemoryUsageBytes) {\n GetElementResult empty;\n EXPECT_GT(empty.EstimatedMemoryUsageBytes(), 0);\n\n Tensor tensor(DT_INT64, TensorShape({10, 10}));\n GetElementResult int64_result = MakeElementResult(tensor);\n EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(), 100 * sizeof(int64_t));\n EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(),\n int64_result.components[0].AllocatedBytes());\n EXPECT_GE(int64_result.EstimatedMemoryUsageBytes(), sizeof(int64_result));\n}\n\nTEST(DataTransferTest, EstimateVarintMemoryUsageBytes) {\n const size_t data_size = 1000;\n CompressedElement compressed;\n compressed.set_data(std::string(data_size, 'a'));\n\n Tensor tensor(DT_VARIANT, TensorShape({}));\n tensor.scalar()() = std::move(compressed);\n\n GetElementResult variant_result = MakeElementResult(tensor);\n EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(), data_size);\n}\n\nTEST(DataTransferTest, CopyGetElementResult) {\n std::string hello_world = \"hello, world!\";\n GetElementResult result = MakeElementResult(hello_world);\n ASSERT_EQ(result.components.size(), 1);\n EXPECT_GT(result.EstimatedMemoryUsageBytes(), hello_world.size());\n\n GetElementResult copy = result.Copy();\n ASSERT_EQ(copy.components.size(), 1);\n test::ExpectEqual(result.components[0], copy.components[0]);\n EXPECT_EQ(copy.EstimatedMemoryUsageBytes(),\n result.EstimatedMemoryUsageBytes());\n}\n} \/\/ namespace\n} \/\/ namespace data\n} \/\/ namespace tensorflow\n#tf-data-service Add a test to verify estimated Tensor size.\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/core\/data\/service\/data_transfer.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_shape.h\"\n#include \"tensorflow\/core\/framework\/tensor_testutil.h\"\n#include \"tensorflow\/core\/framework\/types.pb.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/platform\/status.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace {\n\nclass TestDataTransferServer : public DataTransferServer {\n public:\n explicit TestDataTransferServer(bool* called) : called_(called) {}\n Status Start() override {\n *called_ = true;\n return Status::OK();\n }\n int get_port() override { return 0; }\n\n private:\n bool* called_;\n};\n\ntemplate \nGetElementResult MakeElementResult(T value) {\n GetElementResult result;\n result.components.push_back(Tensor(std::move(value)));\n result.element_index = 0;\n result.end_of_sequence = false;\n return result;\n}\n\nTEST(DataTransferTest, RegisterDataTransferServerBuilder) {\n bool called = false;\n DataTransferServer::Register(\"test\", [&called](auto _) {\n return std::make_shared(&called);\n });\n\n std::shared_ptr server;\n TF_ASSERT_OK(DataTransferServer::Build(\"test\", {}, &server));\n EXPECT_FALSE(called);\n\n TF_ASSERT_OK(server->Start());\n EXPECT_TRUE(called);\n}\n\nTEST(DataTransferTest, EstimateMemoryUsageBytes) {\n GetElementResult empty;\n EXPECT_GT(empty.EstimatedMemoryUsageBytes(), 0);\n\n Tensor tensor(DT_INT64, TensorShape({10, 100}));\n GetElementResult int64_result = MakeElementResult(tensor);\n EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(), 1000 * sizeof(int64_t));\n EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(),\n int64_result.components[0].AllocatedBytes());\n EXPECT_GE(int64_result.EstimatedMemoryUsageBytes(), sizeof(int64_result));\n}\n\nTEST(DataTransferTest, EstimateVariantMemoryUsageBytes) {\n const size_t data_size = 1000;\n CompressedElement compressed;\n compressed.set_data(std::string(data_size, 'a'));\n\n Tensor tensor(DT_VARIANT, TensorShape({}));\n tensor.scalar()() = compressed;\n\n GetElementResult variant_result = MakeElementResult(tensor);\n EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(), data_size);\n EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(),\n compressed.ByteSizeLong());\n EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(),\n compressed.SpaceUsedLong());\n}\n\nTEST(DataTransferTest, CopyGetElementResult) {\n std::string hello_world = \"hello, world!\";\n GetElementResult result = MakeElementResult(hello_world);\n ASSERT_EQ(result.components.size(), 1);\n EXPECT_GT(result.EstimatedMemoryUsageBytes(), hello_world.size());\n\n GetElementResult copy = result.Copy();\n ASSERT_EQ(copy.components.size(), 1);\n test::ExpectEqual(result.components[0], copy.components[0]);\n EXPECT_EQ(copy.EstimatedMemoryUsageBytes(),\n result.EstimatedMemoryUsageBytes());\n}\n} \/\/ namespace\n} \/\/ namespace data\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/\/---------------------------------------------------------------------------\/\/\n\/\/ \\file Chimera_MCSA.cpp\n\/\/ \\author Stuart R. Slattery\n\/\/ \\brief Monte Carlo Synthetic Acceleration solver definition.\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \"Chimera_MCSA.hpp\"\n#include \"Chimera_AdjointMC.hpp\"\n\n#include \n#include \n\nnamespace Chimera\n{\nnamespace Solvers\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/*! \n * \\brief Constructor.\n *\/\nMCSA::MCSA( Teuchos::RCP &linear_problem )\n : d_linear_problem( linear_problem )\n , d_num_iters( 0 )\n{ \/* ... *\/ }\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Destructor.\n *\/\nMCSA::~MCSA()\n{ \/* ... *\/ }\n \n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Solve.\n *\/\nvoid MCSA::iterate( const int max_iters, const double tolerance,\n\t\t const int num_histories, const double weight_cutoff )\n{\n \/\/ Extract the linear problem.\n Epetra_CrsMatrix *A = \n\tdynamic_cast( d_linear_problem->GetMatrix() );\n Epetra_Vector *x = \n\tdynamic_cast( d_linear_problem->GetLHS() );\n const Epetra_Vector *b = \n\tdynamic_cast( d_linear_problem->GetRHS() );\n\n \/\/ Setup the residual Adjoint MC solver.\n Epetra_Map row_map = A->RowMap();\n Epetra_Vector delta_x( row_map );\n Epetra_Vector residual( row_map );\n Teuchos::RCP residual_problem = Teuchos::rcp(\n\tnew Epetra_LinearProblem( A, &delta_x, &residual ) );\n AdjointMC mc_solver = AdjointMC( residual_problem );\n\n \/\/ Iterate.\n Epetra_CrsMatrix H = mc_solver.getH();\n Epetra_Vector temp_vec( row_map );\n d_num_iters = 0;\n double residual_norm = 1.0;\n double b_norm;\n b->NormInf( &b_norm );\n double conv_crit = b_norm*tolerance;\n while ( residual_norm > conv_crit && d_num_iters < max_iters )\n {\n\t\/\/ Richardson iteration.\n\tH.Apply( *x, temp_vec );\n\tx->Update( 1.0, temp_vec, 1.0, *b, 0.0 );\n\n\t\/\/ Compute the residual.\n\tA->Apply( *x, temp_vec );\n\tresidual.Update( 1.0, *b, -1.0, temp_vec, 0.0 );\n\n\t\/\/ Solve for delta_x.\n\tmc_solver.walk( num_histories, weight_cutoff );\n\n\t\/\/ Apply delta_x.\n\tx->Update( 1.0, delta_x, 1.0 );\n\n\t\/\/ Update convergence check.\n\tresidual.NormInf( &residual_norm );\n\t++d_num_iters;\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\n} \/\/ end namespace Solvers\n} \/\/ end namespace Chimera\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end Chimera_MCSA.cpp\n\/\/---------------------------------------------------------------------------\/\/\n\nadded output to mcsa\/\/---------------------------------------------------------------------------\/\/\n\/\/ \\file Chimera_MCSA.cpp\n\/\/ \\author Stuart R. Slattery\n\/\/ \\brief Monte Carlo Synthetic Acceleration solver definition.\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \"Chimera_MCSA.hpp\"\n#include \"Chimera_AdjointMC.hpp\"\n\n#include \n#include \n\nnamespace Chimera\n{\nnamespace Solvers\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/*! \n * \\brief Constructor.\n *\/\nMCSA::MCSA( Teuchos::RCP &linear_problem )\n : d_linear_problem( linear_problem )\n , d_num_iters( 0 )\n{ \/* ... *\/ }\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Destructor.\n *\/\nMCSA::~MCSA()\n{ \/* ... *\/ }\n \n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Solve.\n *\/\nvoid MCSA::iterate( const int max_iters, const double tolerance,\n\t\t const int num_histories, const double weight_cutoff )\n{\n \/\/ Extract the linear problem.\n Epetra_CrsMatrix *A = \n\tdynamic_cast( d_linear_problem->GetMatrix() );\n Epetra_Vector *x = \n\tdynamic_cast( d_linear_problem->GetLHS() );\n const Epetra_Vector *b = \n\tdynamic_cast( d_linear_problem->GetRHS() );\n\n \/\/ Setup the residual Adjoint MC solver.\n Epetra_Map row_map = A->RowMap();\n Epetra_Vector delta_x( row_map );\n Epetra_Vector residual( row_map );\n Teuchos::RCP residual_problem = Teuchos::rcp(\n\tnew Epetra_LinearProblem( A, &delta_x, &residual ) );\n AdjointMC mc_solver = AdjointMC( residual_problem );\n\n \/\/ Iterate.\n Epetra_CrsMatrix H = mc_solver.getH();\n Epetra_Vector temp_vec( row_map );\n d_num_iters = 0;\n double residual_norm = 1.0;\n double b_norm;\n b->NormInf( &b_norm );\n double conv_crit = b_norm*tolerance;\n while ( residual_norm > conv_crit && d_num_iters < max_iters )\n {\n\t\/\/ Richardson iteration.\n\tH.Apply( *x, temp_vec );\n\tx->Update( 1.0, temp_vec, 1.0, *b, 0.0 );\n\n\t\/\/ Compute the residual.\n\tA->Apply( *x, temp_vec );\n\tresidual.Update( 1.0, *b, -1.0, temp_vec, 0.0 );\n\n\t\/\/ Solve for delta_x.\n\tmc_solver.walk( num_histories, weight_cutoff );\n\n\t\/\/ Apply delta_x.\n\tx->Update( 1.0, delta_x, 1.0 );\n\n\t\/\/ Update convergence check.\n\tresidual.NormInf( &residual_norm );\n\t++d_num_iters;\n }\n\n std::cout << \"MCSA Iterations: \" << d_num_iters << std::endl;\n std::cout << \"Residual: \" << residual_norm << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\n} \/\/ end namespace Solvers\n} \/\/ end namespace Chimera\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end Chimera_MCSA.cpp\n\/\/---------------------------------------------------------------------------\/\/\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tchar* ReadFile::getToken_(Position& pos, char delimiter) const\n\t{\n\t\tint len = 0;\n\t\tchar* p = new char[200];\n\n\t\tif(pos >= strlen(line_)) \n\t\t{\n\t\t\tLog.error() << \"in getToken_ : pos too large\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\twhile (line_[pos] && line_[pos] != delimiter)\n\t\t{\n\t\t\t++pos;\n\t\t}\n\n\t\t++pos;\n\n\t\twhile (line_[pos] != delimiter)\n\t\t{\n\t\t\tif (!line_[pos])\n\t\t\t{\n\t\t\t\tLog.error() << \"open token\" << endl;\n\t\t\t\tthrow ReadFileError();\n\t\t\t}\n\n\t\t\tp[len] = line_[pos];\n\t\t\t++len;\n\t\t\t++pos;\n\t\t}\n\n\t\t++pos;\n\n\t\tif(len == 0) \n\t\t{\n\t\t\tLog.error() << \"token could not be read\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\tp[len] = '\\0';\n\t\treturn p;\n\t}\n\n\tchar* ReadFile::getToken_(Position& pos) const\n\t{\n\t\tint len = 0;\n\t\tchar* p = new char[200];\n\n\t\tif(pos >= strlen(line_)) \n\t\t{\n\t\t\tLog.error() << \"in getToken_ : pos too large\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\twhile (line_[pos] && isspace(line_[pos]))\n\t\t{\n\t\t\t++pos;\n\t\t}\n\n\t\twhile (line_[pos] && !isspace(line_[pos]))\n\t\t{\n\t\t\tp[len] = line_[pos];\n\t\t\t++len;\n\t\t\t++pos;\n\t\t}\n\t\t\n\t\tif(len == 0) \n\t\t{\n\t\t\tLog.error() << \"token could not be read\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\tp[len] = '\\0';\n\t\treturn p;\n\t}\n\n\tchar* ReadFile::getToken_() const\n\t{\n\t\tif (strlen(line_) > 199)\n\t\t{\n\t\t\tLog.error() << \"line too long\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\t\tint len = 0;\n\t\tint pos = 0;\n\n\t\tchar* p = new char[200];\n\n\t\tif(p == 0) \n\t\t{\n\t\t\tLog.error() << \"memory could not be assigned\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\twhile (line_[pos] && isspace(line_[pos]))\n\t\t{\n\t\t\t++pos;\n\t\t}\n\n\t\twhile (line_[pos] && !isspace(line_[pos]))\n\t\t{\n\t\t\tp[len] = line_[pos];\n\t\t\t++len;\n\t\t\t++pos;\n\t\t}\n\t\t\n\t\tif(len == 0) \n\t\t{\n\t\t\tLog.error() << \"token could not be read\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\tp[len] = '\\0';\n\t\treturn p;\n\t}\n\n\tstring ReadFile::copyString_(Position start, Position end) const\n\t{\n\t\tif (end >= strlen(line_))\n\t\t{\n\t\t\tLog.error() << \"error in copyString_\";\n\t\t\tthrow ReadFileError();\n\t\t}\n\t\tstring dest;\n\t\tfor (; start <= end ; ++start)\n\t\t{\n\t\t\tdest += line_[start];\n\t\t}\n\t\treturn dest;\n\t}\n\n\tint ReadFile::switch_(const vector& data) const\n\t{\n\t\tPosition i = 0;\n\t\twhile (i < data.size())\n\t\t{\n\t\t\tif (strcmp(line_, data[i].c_str()) == 0)\n\t\t\t{\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t\treturn (-1);\n\t}\n\n\tbool ReadFile::startsWith_(const char* text) const\n\t{\n\t\treturn (memcmp(line_, text, strlen(text)) == 0);\n\t}\n\n\tbool ReadFile::search_(const char* text)\n\t{\n\t\twhile (!in.eof())\n\t\t{\n\t\t\treadLine_();\n\n\t\t\tif (startsWith_(text))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool ReadFile::search_(const char* text, const char* stop)\n\t{\n\t\twhile (!in.eof())\n\t\t{\n\t\t\treadLine_();\n\t\t\tif (has_(stop))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (startsWith_(text))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid ReadFile::test_(bool condition, char* msg) const\n\t{\n\t\tif (condition == false)\n\t\t{\n\t\t\tLog.error() << msg;\n\t\t\tthrow ReadFileError();\n\t\t}\n\t}\n\n\tvoid ReadFile::readLine_()\n\t{\n\t\tin.getline(line_,200);\n\t}\n\n\tvoid ReadFile::skipLines_(int number)\n\t{\n\t\tfor (int i = 0; i <= number ; i++)\n\t\t{\n\t\t\tin.getline(line_,200);\n\t\t}\n\t}\n\n\tbool ReadFile::has_(const char* text) const\n\t{\n\t\tPosition pos_line = 0;\n\t\tPosition pos_line2;\n\t\tPosition pos_text;\n\t\tif(strlen(line_) == 0 || strlen(text) == 0 ||\n\t\t\t strlen(line_) < strlen(text) ) \n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\twhile (line_[pos_line])\n\t\t{\n\t\t\tpos_text = 0;\n\t\t\tpos_line2 = pos_line;\n\t\t\twhile (text[pos_text])\n\t\t\t{\n\t\t\t\tif (line_[pos_line2] != text[pos_text])\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++pos_text;\n\t\t\t\t++pos_line2;\n\t\t\t}\n\n\t\t\tif (!text[pos_text])\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t++pos_line;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\n} \/\/namespacechanged: in test now a warning is given#include \n#include \n#include \n#include \n#include\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tchar* ReadFile::getToken_(Position& pos, char delimiter) const\n\t{\n\t\tint len = 0;\n\t\tchar* p = new char[200];\n\n\t\tif(pos >= strlen(line_)) \n\t\t{\n\t\t\tLog.error() << \"in getToken_ : pos too large\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\twhile (line_[pos] && line_[pos] != delimiter)\n\t\t{\n\t\t\t++pos;\n\t\t}\n\n\t\t++pos;\n\n\t\twhile (line_[pos] != delimiter)\n\t\t{\n\t\t\tif (!line_[pos])\n\t\t\t{\n\t\t\t\tLog.error() << \"open token\" << endl;\n\t\t\t\tthrow ReadFileError();\n\t\t\t}\n\n\t\t\tp[len] = line_[pos];\n\t\t\t++len;\n\t\t\t++pos;\n\t\t}\n\n\t\t++pos;\n\n\t\tif(len == 0) \n\t\t{\n\t\t\tLog.error() << \"token could not be read\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\tp[len] = '\\0';\n\t\treturn p;\n\t}\n\n\tchar* ReadFile::getToken_(Position& pos) const\n\t{\n\t\tint len = 0;\n\t\tchar* p = new char[200];\n\n\t\tif(pos >= strlen(line_)) \n\t\t{\n\t\t\tLog.error() << \"in getToken_ : pos too large\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\twhile (line_[pos] && isspace(line_[pos]))\n\t\t{\n\t\t\t++pos;\n\t\t}\n\n\t\twhile (line_[pos] && !isspace(line_[pos]))\n\t\t{\n\t\t\tp[len] = line_[pos];\n\t\t\t++len;\n\t\t\t++pos;\n\t\t}\n\t\t\n\t\tif(len == 0) \n\t\t{\n\t\t\tLog.error() << \"token could not be read\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\tp[len] = '\\0';\n\t\treturn p;\n\t}\n\n\tchar* ReadFile::getToken_() const\n\t{\n\t\tif (strlen(line_) > 199)\n\t\t{\n\t\t\tLog.error() << \"line too long\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\t\tint len = 0;\n\t\tint pos = 0;\n\n\t\tchar* p = new char[200];\n\n\t\tif(p == 0) \n\t\t{\n\t\t\tLog.error() << \"memory could not be assigned\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\twhile (line_[pos] && isspace(line_[pos]))\n\t\t{\n\t\t\t++pos;\n\t\t}\n\n\t\twhile (line_[pos] && !isspace(line_[pos]))\n\t\t{\n\t\t\tp[len] = line_[pos];\n\t\t\t++len;\n\t\t\t++pos;\n\t\t}\n\t\t\n\t\tif(len == 0) \n\t\t{\n\t\t\tLog.error() << \"token could not be read\" << endl;\n\t\t\tthrow ReadFileError();\n\t\t}\n\n\t\tp[len] = '\\0';\n\t\treturn p;\n\t}\n\n\tstring ReadFile::copyString_(Position start, Position end) const\n\t{\n\t\tif (end >= strlen(line_))\n\t\t{\n\t\t\tLog.error() << \"error in copyString_\";\n\t\t\tthrow ReadFileError();\n\t\t}\n\t\tstring dest;\n\t\tfor (; start <= end ; ++start)\n\t\t{\n\t\t\tdest += line_[start];\n\t\t}\n\t\treturn dest;\n\t}\n\n\tint ReadFile::switch_(const vector& data) const\n\t{\n\t\tPosition i = 0;\n\t\twhile (i < data.size())\n\t\t{\n\t\t\tif (strcmp(line_, data[i].c_str()) == 0)\n\t\t\t{\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t\treturn (-1);\n\t}\n\n\tbool ReadFile::startsWith_(const char* text) const\n\t{\n\t\treturn (memcmp(line_, text, strlen(text)) == 0);\n\t}\n\n\tbool ReadFile::search_(const char* text)\n\t{\n\t\twhile (!in.eof())\n\t\t{\n\t\t\treadLine_();\n\n\t\t\tif (startsWith_(text))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool ReadFile::search_(const char* text, const char* stop)\n\t{\n\t\twhile (!in.eof())\n\t\t{\n\t\t\treadLine_();\n\t\t\tif (has_(stop))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (startsWith_(text))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid ReadFile::test_(bool condition, char* msg) const\n\t{\n\t\tif (condition == false)\n\t\t{\n\t\t\tLog.warn() << msg;\n\t\t\tthrow ReadFileError();\n\t\t}\n\t}\n\n\tvoid ReadFile::readLine_()\n\t{\n\t\tin.getline(line_,200);\n\t}\n\n\tvoid ReadFile::skipLines_(int number)\n\t{\n\t\tfor (int i = 0; i <= number ; i++)\n\t\t{\n\t\t\tin.getline(line_,200);\n\t\t}\n\t}\n\n\tbool ReadFile::has_(const char* text) const\n\t{\n\t\tPosition pos_line = 0;\n\t\tPosition pos_line2;\n\t\tPosition pos_text;\n\t\tif(strlen(line_) == 0 || strlen(text) == 0 ||\n\t\t\t strlen(line_) < strlen(text) ) \n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\twhile (line_[pos_line])\n\t\t{\n\t\t\tpos_text = 0;\n\t\t\tpos_line2 = pos_line;\n\t\t\twhile (text[pos_text])\n\t\t\t{\n\t\t\t\tif (line_[pos_line2] != text[pos_text])\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++pos_text;\n\t\t\t\t++pos_line2;\n\t\t\t}\n\n\t\t\tif (!text[pos_text])\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t++pos_line;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\n} \/\/namespace<|endoftext|>"} {"text":"\/** mock_exchange.cc -*- C++ -*-\n Rémi Attab, 18 Feb 2013\n Copyright (c) 2013 Datacratic. All rights reserved.\n\n Implementation of the mock exchange.\n\n*\/\n\n#include \"mock_exchange.h\"\n\n#include \"rtbkit\/core\/post_auction\/post_auction_loop.h\"\n#include \"soa\/service\/http_header.h\"\n#include \"jml\/utils\/smart_ptr_utils.h\"\n\n#include \n\nusing namespace std;\nusing namespace ML;\n\nnamespace RTBKIT {\n\n\/******************************************************************************\/\n\/* MOCK EXCHANGE *\/\n\/******************************************************************************\/\n\nMockExchange::\nMockExchange(Datacratic::ServiceProxyArguments & args, const std::string& name) :\n ServiceBase(name, args.makeServiceProxies()),\n running(0) {\n}\n\n\nMockExchange::\nMockExchange(const shared_ptr proxies, const string& name) :\n ServiceBase(name, proxies),\n running(0) {\n}\n\n\nMockExchange::\n~MockExchange() {\n threads.join_all();\n}\n\n\nvoid\nMockExchange::\nstart(Json::Value const & configuration) {\n auto workers = configuration[\"workers\"];\n\n for(auto i = workers.begin(), end = workers.end(); i != end; ++i) {\n auto json = *i;\n auto count = json.get(\"threads\", 1).asInt();\n\n\n for(auto j = 0; j != count; ++j) {\n std::cerr << \"starting worker \" << running << std::endl;\n ML::atomic_inc(running);\n\n threads.create_thread([=]() {\n Worker worker(this, json[\"bids\"], json[\"wins\"], json[\"events\"]);\n worker.run();\n\n ML::atomic_dec(running);\n });\n }\n }\n}\n\n\nvoid\nMockExchange::\nadd(BidSource * bid, WinSource * win, EventSource * event) {\n std::cerr << \"starting worker \" << running << std::endl;\n ML::atomic_inc(running);\n\n threads.create_thread([=]() {\n Worker worker(this, bid, win, event);\n worker.run();\n\n ML::atomic_dec(running);\n });\n}\n\n\nMockExchange::Worker::\nWorker(MockExchange * exchange, BidSource *bid, WinSource *win, EventSource *event) :\n exchange(exchange),\n bids(bid),\n wins(win),\n events(event),\n rng(random()) {\n}\n\n\nMockExchange::Worker::\nWorker(MockExchange * exchange, Json::Value bid, Json::Value win, Json::Value event) :\n exchange(exchange),\n bids(BidSource::createBidSource(std::move(bid))),\n wins(WinSource::createWinSource(std::move(win))),\n events(EventSource::createEventSource(std::move(event))),\n rng(random()) {\n}\n\n\nvoid\nMockExchange::Worker::\nrun() {\n while(bid());\n}\n\nbool\nMockExchange::Worker::bid() {\n for (;;) {\n auto br = bids->sendBidRequest();\n exchange->recordHit(\"requests\");\n\n auto response = bids->receiveBid();\n exchange->recordHit(\"responses\");\n\n if (!response.first) continue;\n vector items = response.second;\n\n for (auto & bid : items) {\n if(bid.maxPrice == 0) continue;\n exchange->recordHit(\"responses\");\n\n if (!wins) break;\n\n auto ret = isWin(br, bid);\n if (!ret.first) continue;\n\t\t\tML::sleep(0.5);\n\n\t\t\tbid.bidTimestamp = Date::now();\n\n wins->sendWin(br, bid, ret.second);\n exchange->recordHit(\"wins\");\n\n events->sendImpression(br, bid);\n exchange->recordHit(\"impressions\");\n\n if (!isClick(br, bid)) continue;\n events->sendClick(br, bid);\n exchange->recordHit(\"clicks\");\n }\n\n break;\n }\n\n return !bids->isDone();\n}\n\n\npair\nMockExchange::Worker::isWin(const BidRequest&, const ExchangeSource::Bid& bid) {\n if (rng.random01() >= 0.1)\n return make_pair(false, Amount());\n\n return make_pair(true, MicroUSD_CPM(bid.maxPrice * 0.6 + bid.maxPrice * rng.random01() * 0.4));\n}\n\n\nbool\nMockExchange::Worker::isClick(const BidRequest&, const ExchangeSource::Bid&) {\n return rng.random01() <= 0.1;\n}\n\n\n} \/\/ namepsace RTBKIT\nFixed some of the graphite logging for the mock exchange.\/** mock_exchange.cc -*- C++ -*-\n Rémi Attab, 18 Feb 2013\n Copyright (c) 2013 Datacratic. All rights reserved.\n\n Implementation of the mock exchange.\n\n*\/\n\n#include \"mock_exchange.h\"\n\n#include \"rtbkit\/core\/post_auction\/post_auction_loop.h\"\n#include \"soa\/service\/http_header.h\"\n#include \"jml\/utils\/smart_ptr_utils.h\"\n\n#include \n\nusing namespace std;\nusing namespace ML;\n\nnamespace RTBKIT {\n\n\/******************************************************************************\/\n\/* MOCK EXCHANGE *\/\n\/******************************************************************************\/\n\nMockExchange::\nMockExchange(Datacratic::ServiceProxyArguments & args, const std::string& name) :\n ServiceBase(name, args.makeServiceProxies()),\n running(0) {\n}\n\n\nMockExchange::\nMockExchange(const shared_ptr proxies, const string& name) :\n ServiceBase(name, proxies),\n running(0) {\n}\n\n\nMockExchange::\n~MockExchange() {\n threads.join_all();\n}\n\n\nvoid\nMockExchange::\nstart(Json::Value const & configuration) {\n auto workers = configuration[\"workers\"];\n\n for(auto i = workers.begin(), end = workers.end(); i != end; ++i) {\n auto json = *i;\n auto count = json.get(\"threads\", 1).asInt();\n\n\n for(auto j = 0; j != count; ++j) {\n std::cerr << \"starting worker \" << running << std::endl;\n ML::atomic_inc(running);\n\n threads.create_thread([=]() {\n Worker worker(this, json[\"bids\"], json[\"wins\"], json[\"events\"]);\n worker.run();\n\n ML::atomic_dec(running);\n });\n }\n }\n}\n\n\nvoid\nMockExchange::\nadd(BidSource * bid, WinSource * win, EventSource * event) {\n std::cerr << \"starting worker \" << running << std::endl;\n ML::atomic_inc(running);\n\n threads.create_thread([=]() {\n Worker worker(this, bid, win, event);\n worker.run();\n\n ML::atomic_dec(running);\n });\n}\n\n\nMockExchange::Worker::\nWorker(MockExchange * exchange, BidSource *bid, WinSource *win, EventSource *event) :\n exchange(exchange),\n bids(bid),\n wins(win),\n events(event),\n rng(random()) {\n}\n\n\nMockExchange::Worker::\nWorker(MockExchange * exchange, Json::Value bid, Json::Value win, Json::Value event) :\n exchange(exchange),\n bids(BidSource::createBidSource(std::move(bid))),\n wins(WinSource::createWinSource(std::move(win))),\n events(EventSource::createEventSource(std::move(event))),\n rng(random()) {\n}\n\n\nvoid\nMockExchange::Worker::\nrun() {\n while(bid());\n}\n\nbool\nMockExchange::Worker::bid() {\n for (;;) {\n auto br = bids->sendBidRequest();\n exchange->recordHit(\"requests\");\n\n auto response = bids->receiveBid();\n exchange->recordHit(\"responses\");\n\n vector items = response.second;\n\n if (!response.first || items.empty()) {\n exchange->recordHit(\"noBids\");\n continue;\n }\n\n for (auto & bid : items) {\n if(bid.maxPrice == 0) continue;\n exchange->recordHit(\"bids\");\n\n if (!wins) break;\n\n auto ret = isWin(br, bid);\n if (!ret.first) continue;\n ML::sleep(0.5);\n\n bid.bidTimestamp = Date::now();\n\n wins->sendWin(br, bid, ret.second);\n exchange->recordHit(\"wins\");\n\n events->sendImpression(br, bid);\n exchange->recordHit(\"impressions\");\n\n if (!isClick(br, bid)) continue;\n events->sendClick(br, bid);\n exchange->recordHit(\"clicks\");\n }\n\n break;\n }\n\n return !bids->isDone();\n}\n\n\npair\nMockExchange::Worker::isWin(const BidRequest&, const ExchangeSource::Bid& bid) {\n if (rng.random01() >= 0.1)\n return make_pair(false, Amount());\n\n return make_pair(true, MicroUSD_CPM(bid.maxPrice * 0.6 + bid.maxPrice * rng.random01() * 0.4));\n}\n\n\nbool\nMockExchange::Worker::isClick(const BidRequest&, const ExchangeSource::Bid&) {\n return rng.random01() <= 0.1;\n}\n\n\n} \/\/ namepsace RTBKIT\n<|endoftext|>"} {"text":"\/\/ ------------------------------------------------------------------------------------------------\n#include \"Core.hpp\"\n#include \"Base\/Shared.hpp\"\n#include \"Base\/Color3.hpp\"\n#include \"Base\/Vector2.hpp\"\n#include \"Base\/Vector3.hpp\"\n#include \"Entity\/Player.hpp\"\n#include \"Library\/Numeric\/LongInt.hpp\"\n\n\/\/ ------------------------------------------------------------------------------------------------\n#include \"Misc\/Functions.hpp\"\n#include \"Misc\/Model.hpp\"\n#include \"Misc\/Player.hpp\"\n#include \"Misc\/Vehicle.hpp\"\n#include \"Misc\/Weapon.hpp\"\n\n\/\/ ------------------------------------------------------------------------------------------------\nnamespace SqMod {\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic const Object & FindPlayer(Object & by)\n{\n switch (by.GetType())\n {\n case OT_INTEGER:\n {\n return Core::Get().GetPlayer(by.Cast< Int32 >()).mObj;\n } break;\n case OT_FLOAT:\n {\n return Core::Get().GetPlayer(std::round(by.Cast< Float32 >())).mObj;\n } break;\n case OT_STRING:\n {\n \/\/ Obtain the argument as a string\n String str(by.Cast< String >());\n \/\/ Attempt to locate the player with this name\n Int32 id = _Func->GetPlayerIdFromName(&str[0]);\n \/\/ Was there a player with this name?\n if (VALID_ENTITYEX(id, SQMOD_PLAYER_POOL))\n {\n Core::Get().GetPlayer(id).mObj;\n }\n } break;\n default: STHROWF(\"Unsupported search identifier\");\n }\n \/\/ Default to a null object\n return NullObject();\n}\n\n\/\/ ================================================================================================\nvoid Register_Misc(HSQUIRRELVM vm)\n{\n Table srvns(vm);\n\n srvns.SquirrelFunc(_SC(\"SendLogMessage\"), &SendLogMessage)\n .Func(_SC(\"GetVersion\"), &GetServerVersion)\n .Func(_SC(\"GetSettings\"), &GetServerSettings)\n .Func(_SC(\"GetNumberOfPlugins\"), &GetNumberOfPlugins)\n .Func(_SC(\"GetPluginInfo\"), &GetPluginInfo)\n .Func(_SC(\"FindPlugin\"), &FindPlugin)\n .Func(_SC(\"SendPluginCommand\"), &SendPluginCommand)\n .Func(_SC(\"GetTime\"), &GetTime)\n .Func(_SC(\"GetLastError\"), &GetLastError)\n .Func(_SC(\"GetPluginVersion\"), &GetPluginVersion)\n .Func(_SC(\"GetPluginVersionStr\"), &GetPluginVersionStr)\n .Func(_SC(\"GetPluginName\"), &GetPluginName)\n .Func(_SC(\"GetPluginAuthor\"), &GetPluginAuthor)\n .Func(_SC(\"GetPluginID\"), &GetPluginID)\n .Func(_SC(\"GetServerPort\"), &GetServerPort)\n .Func(_SC(\"GetServerFlags\"), &GetServerFlags)\n .Func(_SC(\"GetMaxPlayers\"), &GetMaxPlayers)\n .Func(_SC(\"SetMaxPlayers\"), &SetMaxPlayers)\n .Func(_SC(\"GetServerName\"), &GetServerName)\n .Func(_SC(\"SetServerName\"), &SetServerName)\n .Func(_SC(\"GetPassword\"), &GetServerPassword)\n .Func(_SC(\"SetPassword\"), &SetServerPassword)\n .Func(_SC(\"GetGameModeText\"), &GetGameModeText)\n .Func(_SC(\"SetGameModeText\"), &SetGameModeText)\n .Func(_SC(\"CreateRadioStream\"), &CreateRadioStream)\n .Func(_SC(\"CreateRadioStreamEx\"), &CreateRadioStreamEx)\n .Func(_SC(\"RemoveRadioStream\"), &RemoveRadioStream)\n .Func(_SC(\"Shutdown\"), &ShutdownServer)\n .Func(_SC(\"GetOption\"), &GetServerOption)\n .Func(_SC(\"SetOption\"), &SetServerOption)\n .Func(_SC(\"SetOptionEx\"), &SetServerOptionEx)\n .Func(_SC(\"GetWorldBounds\"), &GetWorldBounds)\n .Func(_SC(\"SetWorldBounds\"), &SetWorldBounds)\n .Func(_SC(\"SetWorldBoundsEx\"), &SetWorldBoundsEx)\n .Func(_SC(\"GetWastedSettings\"), &GetWastedSettings)\n .Func(_SC(\"SetWastedSettings\"), &SetWastedSettings)\n .Func(_SC(\"GetTimeRate\"), &GetTimeRate)\n .Func(_SC(\"SetTimeRate\"), &SetTimeRate)\n .Func(_SC(\"GetHour\"), &GetHour)\n .Func(_SC(\"SetHour\"), &SetHour)\n .Func(_SC(\"GetMinute\"), &GetMinute)\n .Func(_SC(\"SetMinute\"), &SetMinute)\n .Func(_SC(\"GetWeather\"), &GetWeather)\n .Func(_SC(\"SetWeather\"), &SetWeather)\n .Func(_SC(\"GetGravity\"), &GetGravity)\n .Func(_SC(\"SetGravity\"), &SetGravity)\n .Func(_SC(\"GetGameSpeed\"), &GetGameSpeed)\n .Func(_SC(\"SetGameSpeed\"), &SetGameSpeed)\n .Func(_SC(\"GetWaterLevel\"), &GetWaterLevel)\n .Func(_SC(\"SetWaterLevel\"), &SetWaterLevel)\n .Func(_SC(\"GetMaximumFlightAltitude\"), &GetMaximumFlightAltitude)\n .Func(_SC(\"SetMaximumFlightAltitude\"), &SetMaximumFlightAltitude)\n .Func(_SC(\"GetKillCommandDelay\"), &GetKillCommandDelay)\n .Func(_SC(\"SetKillCommandDelay\"), &SetKillCommandDelay)\n .Func(_SC(\"GetVehiclesForcedRespawnHeight\"), &GetVehiclesForcedRespawnHeight)\n .Func(_SC(\"SetVehiclesForcedRespawnHeight\"), &SetVehiclesForcedRespawnHeight)\n .Func(_SC(\"CreateExplosion\"), &CreateExplosion)\n .Func(_SC(\"CreateExplosionEx\"), &CreateExplosionEx)\n .Func(_SC(\"PlaySound\"), &PlaySound)\n .Func(_SC(\"PlaySoundEx\"), &PlaySoundEx)\n .Func(_SC(\"HideMapObject\"), &HideMapObject)\n .Func(_SC(\"HideMapObjectEx\"), &SetKeyCodeName)\n .Func(_SC(\"HideMapObjectRaw\"), &HideMapObjectRaw)\n .Func(_SC(\"ShowMapObject\"), &ShowMapObject)\n .Func(_SC(\"ShowMapObjectEx\"), &ShowMapObjectEx)\n .Func(_SC(\"ShowMapObjectRaw\"), &ShowMapObjectRaw)\n .Func(_SC(\"ShowAllMapObjects\"), &ShowAllMapObjects)\n .Func(_SC(\"GetWeaponDataValue\"), &GetWeaponDataValue)\n .Func(_SC(\"SetWeaponDataValue\"), &SetWeaponDataValue)\n .Func(_SC(\"ResetWeaponDataValue\"), &ResetWeaponDataValue)\n .Func(_SC(\"IsWeaponDataValueModified\"), &IsWeaponDataValueModified)\n .Func(_SC(\"ResetWeaponData\"), &ResetWeaponData)\n .Func(_SC(\"ResetAllWeaponData\"), &ResetAllWeaponData)\n .Func(_SC(\"AddPlayerClass\"), &AddPlayerClass)\n .Func(_SC(\"SetSpawnPlayerPosition\"), &SetSpawnPlayerPosition)\n .Func(_SC(\"SetSpawnCameraPosition\"), &SetSpawnCameraPosition)\n .Func(_SC(\"SetSpawnCameraLookAt\"), &SetSpawnCameraLookAt)\n .Func(_SC(\"SetSpawnPlayerPositionEx\"), &SetSpawnPlayerPositionEx)\n .Func(_SC(\"SetSpawnCameraPositionEx\"), &SetSpawnCameraPositionEx)\n .Func(_SC(\"SetSpawnCameraLookAtEx\"), &SetSpawnCameraLookAtEx)\n .Func(_SC(\"BanIP\"), &BanIP)\n .Func(_SC(\"UnbanIP\"), &UnbanIP)\n .Func(_SC(\"IsIPBanned\"), &IsIPBanned)\n .Func(_SC(\"GetPlayerIdFromName\"), &GetPlayerIdFromName)\n .Func(_SC(\"IsPlayerConnected\"), &IsPlayerConnected)\n .Func(_SC(\"ForceAllSelect\"), &ForceAllSelect)\n .Func(_SC(\"CheckEntityExists\"), &SetKeyCodeName);\n\n RootTable(vm).Bind(_SC(\"SqServer\"), srvns);\n\n RootTable(vm)\n .Func(_SC(\"FindPlayer\"), &FindPlayer)\n .Func(_SC(\"GetKeyCodeName\"), &GetKeyCodeName)\n .Func(_SC(\"SetKeyCodeName\"), &SetKeyCodeName)\n .Func(_SC(\"GetModelName\"), &GetModelName)\n .Func(_SC(\"SetModelName\"), &SetModelName)\n .Func(_SC(\"IsModelWeapon\"), &IsModelWeapon)\n .Func(_SC(\"IsModelActuallyWeapon\"), &IsModelActuallyWeapon)\n .Func(_SC(\"GetSkinName\"), &GetSkinName)\n .Func(_SC(\"SetSkinName\"), &SetSkinName)\n .Func(_SC(\"GetSkinID\"), &GetSkinID)\n .Func(_SC(\"IsSkinValid\"), &IsSkinValid)\n .Func(_SC(\"GetAutomobileName\"), &GetAutomobileName)\n .Func(_SC(\"SetAutomobileName\"), &SetAutomobileName)\n .Func(_SC(\"GetAutomobileID\"), &GetAutomobileID)\n .Func(_SC(\"IsAutomobileValid\"), &IsAutomobileValid)\n .Func(_SC(\"GetWeaponName\"), &GetWeaponName)\n .Func(_SC(\"SetWeaponName\"), &SetWeaponName)\n .Func(_SC(\"GetWeaponID\"), &GetWeaponID)\n .Func(_SC(\"IsWeaponValid\"), &IsWeaponValid)\n .Func(_SC(\"WeaponToModel\"), &WeaponToModel)\n .Func(_SC(\"IsWeaponNatural\"), &IsWeaponNatural)\n .Func(_SC(\"PlaySound\"), &PlaySound)\n .Func(_SC(\"PlaySoundEx\"), &PlaySoundEx)\n .Func(_SC(\"CreateExplosion\"), &CreateExplosion)\n .Func(_SC(\"CreateExplosionEx\"), &CreateExplosionEx);\n}\n\n} \/\/ Namespace:: SqMod\nImplement functions to broadcast messages to all players.\/\/ ------------------------------------------------------------------------------------------------\n#include \"Core.hpp\"\n#include \"Base\/Shared.hpp\"\n#include \"Base\/Color3.hpp\"\n#include \"Base\/Color4.hpp\"\n#include \"Base\/Vector2.hpp\"\n#include \"Base\/Vector3.hpp\"\n#include \"Entity\/Player.hpp\"\n#include \"Library\/Numeric\/LongInt.hpp\"\n\n\/\/ ------------------------------------------------------------------------------------------------\n#include \"Misc\/Functions.hpp\"\n#include \"Misc\/Model.hpp\"\n#include \"Misc\/Player.hpp\"\n#include \"Misc\/Vehicle.hpp\"\n#include \"Misc\/Weapon.hpp\"\n\n\/\/ ------------------------------------------------------------------------------------------------\nnamespace SqMod {\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic const Object & FindPlayer(Object & by)\n{\n switch (by.GetType())\n {\n case OT_INTEGER:\n {\n return Core::Get().GetPlayer(by.Cast< Int32 >()).mObj;\n } break;\n case OT_FLOAT:\n {\n return Core::Get().GetPlayer(std::round(by.Cast< Float32 >())).mObj;\n } break;\n case OT_STRING:\n {\n \/\/ Obtain the argument as a string\n String str(by.Cast< String >());\n \/\/ Attempt to locate the player with this name\n Int32 id = _Func->GetPlayerIdFromName(&str[0]);\n \/\/ Was there a player with this name?\n if (VALID_ENTITYEX(id, SQMOD_PLAYER_POOL))\n {\n Core::Get().GetPlayer(id).mObj;\n }\n } break;\n default: STHROWF(\"Unsupported search identifier\");\n }\n \/\/ Default to a null object\n return NullObject();\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic SQInteger SqBroadcastMsg(HSQUIRRELVM vm)\n{\n const Int32 top = sq_gettop(vm);\n \/\/ Was the message color specified?\n if (top <= 1)\n {\n return sq_throwerror(vm, \"Missing message color\");\n }\n \/\/ Was the message value specified?\n else if (top <= 2)\n {\n return sq_throwerror(vm, \"Missing message value\");\n }\n \/\/ Failed to retrieve a Color4 value\n bool failed = false;\n \/\/ The message color\n Color4 color;\n \/\/ Attempt to extract the argument values\n try\n {\n color = Var< Color4 >(vm, 2).value;\n }\n catch (...)\n {\n failed = true;\n }\n \/\/ Did we failed to retrieve a Color4 instance?\n if (failed)\n {\n \/\/ Attempt to extract the argument values\n try\n {\n color = Var< Color3 >(vm, 2).value;\n }\n catch (const Sqrat::Exception & e)\n {\n \/\/ Propagate the error\n return sq_throwerror(vm, e.Message().c_str());\n }\n }\n \/\/ Attempt to generate the string value\n StackStrF val(vm, 3);\n \/\/ Have we failed to retrieve the string?\n if (SQ_FAILED(val.mRes))\n {\n return val.mRes; \/\/ Propagate the error!\n }\n \/\/ Obtain the ends of the entity pool\n Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();\n Core::Players::const_iterator end = Core::Get().GetPlayers().cend();\n \/\/ The number of players that the message was sent to\n Uint32 count = 0;\n \/\/ Process each entity in the pool\n for (; itr != end; ++itr)\n {\n \/\/ Is this player instance valid?\n if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)\n {\n \/\/ Grab the player instance\n CPlayer * player = itr->mInst;\n \/\/ Send the resulted message string\n const vcmpError result = _Func->SendClientMessage(itr->mID, color.GetRGBA(),\n \"%s%s%s\",\n player->mMessagePrefix.c_str(),\n val.mPtr,\n player->mMessagePostfix.c_str());\n \/\/ Check the result\n if (result == vcmpErrorTooLargeInput)\n {\n return sq_throwerror(vm, ToStrF(\"Client message too big [%s]\", player->GetTag().c_str()));\n }\n \/\/ Add this player to the count\n ++count;\n }\n }\n \/\/ Push the count count on the stack\n sq_pushinteger(vm, count);\n \/\/ Specify that this function returned a value\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)\n{\n const Int32 top = sq_gettop(vm);\n \/\/ Was the index of the message prefix specified?\n if (top <= 1)\n {\n return sq_throwerror(vm, \"Missing prefix index\");\n }\n \/\/ Was the message value specified?\n else if (top <= 2)\n {\n return sq_throwerror(vm, \"Missing message value\");\n }\n \/\/ The prefix index\n Uint32 index;\n \/\/ Attempt to extract the argument values\n try\n {\n index = Var< Uint32 >(vm, 2).value;\n }\n catch (const Sqrat::Exception & e)\n {\n \/\/ Propagate the error\n return sq_throwerror(vm, e.Message().c_str());\n }\n \/\/ Perform a range check on the specified prefix index\n if (index > SQMOD_PLAYER_MSG_PREFIXES)\n {\n return sq_throwerror(vm, ToStrF(\"Prefix index is out of range: %u > %u\",\n index, SQMOD_PLAYER_MSG_PREFIXES));\n }\n \/\/ Attempt to generate the string value\n StackStrF val(vm, 3);\n \/\/ Have we failed to retrieve the string?\n if (SQ_FAILED(val.mRes))\n {\n return val.mRes; \/\/ Propagate the error!\n }\n vcmpError result = vcmpErrorNone;\n \/\/ Send the resulted message string\n \/\/ Obtain the ends of the entity pool\n Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();\n Core::Players::const_iterator end = Core::Get().GetPlayers().cend();\n \/\/ The number of players that the message was sent to\n Uint32 count = 0;\n \/\/ Process each entity in the pool\n for (; itr != end; ++itr)\n {\n \/\/ Is this player instance valid?\n if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)\n {\n \/\/ Grab the player instance\n CPlayer * player = itr->mInst;\n \/\/ Send the resulted message string\n if (player->mLimitPrefixPostfixMessage)\n {\n result = _Func->SendClientMessage(itr->mID, player->mMessageColor, \"%s%s\",\n player->mMessagePrefixes[index].c_str(), val.mPtr);\n }\n else\n {\n result = _Func->SendClientMessage(itr->mID, player->mMessageColor, \"%s%s%s%s\",\n player->mMessagePrefix.c_str(),\n player->mMessagePrefixes[index].c_str(), val.mPtr,\n player->mMessagePostfix.c_str());\n }\n \/\/ Check the result\n if (result == vcmpErrorTooLargeInput)\n {\n return sq_throwerror(vm, ToStrF(\"Client message too big [%s]\", player->GetTag().c_str()));\n }\n \/\/ Add this player to the count\n ++count;\n }\n }\n \/\/ Push the count count on the stack\n sq_pushinteger(vm, count);\n \/\/ Specify that this function returned a value\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)\n{\n const Int32 top = sq_gettop(vm);\n \/\/ Was the message color specified?\n if (top <= 4)\n {\n return sq_throwerror(vm, \"Missing message color\");\n }\n \/\/ Was the message value specified?\n else if (top <= 5)\n {\n return sq_throwerror(vm, \"Missing message value\");\n }\n \/\/ The message color\n Uint32 color;\n \/\/ Attempt to extract the argument values\n try\n {\n color = SQMOD_PACK_RGBA(Var< Uint8 >(vm, 2).value,\n Var< Uint8 >(vm, 3).value,\n Var< Uint8 >(vm, 4).value,\n Var< Uint8 >(vm, 5).value);\n }\n catch (const Sqrat::Exception & e)\n {\n \/\/ Propagate the error\n return sq_throwerror(vm, e.Message().c_str());\n }\n \/\/ Attempt to generate the string value\n StackStrF val(vm, 6);\n \/\/ Have we failed to retrieve the string?\n if (SQ_FAILED(val.mRes))\n {\n return val.mRes; \/\/ Propagate the error!\n }\n \/\/ Obtain the ends of the entity pool\n Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();\n Core::Players::const_iterator end = Core::Get().GetPlayers().cend();\n \/\/ The number of players that the message was sent to\n Uint32 count = 0;\n \/\/ Process each entity in the pool\n for (; itr != end; ++itr)\n {\n \/\/ Is this player instance valid?\n if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)\n {\n \/\/ Grab the player instance\n CPlayer * player = itr->mInst;\n \/\/ Send the resulted message string\n const vcmpError result = _Func->SendClientMessage(itr->mID, color,\n \"%s%s%s\",\n player->mMessagePrefix.c_str(),\n val.mPtr,\n player->mMessagePostfix.c_str());\n \/\/ Check the result\n if (result == vcmpErrorTooLargeInput)\n {\n return sq_throwerror(vm, ToStrF(\"Client message too big [%s]\", player->GetTag().c_str()));\n }\n \/\/ Add this player to the count\n ++count;\n }\n }\n \/\/ Push the count count on the stack\n sq_pushinteger(vm, count);\n \/\/ Specify that this function returned a value\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic SQInteger SqBroadcastMessage(HSQUIRRELVM vm)\n{\n const Int32 top = sq_gettop(vm);\n \/\/ Was the message value specified?\n if (top <= 1)\n {\n return sq_throwerror(vm, \"Missing message value\");\n }\n \/\/ Attempt to generate the string value\n StackStrF val(vm, 2);\n \/\/ Have we failed to retrieve the string?\n if (SQ_FAILED(val.mRes))\n {\n return val.mRes; \/\/ Propagate the error!\n }\n \/\/ Obtain the ends of the entity pool\n Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();\n Core::Players::const_iterator end = Core::Get().GetPlayers().cend();\n \/\/ The number of players that the message was sent to\n Uint32 count = 0;\n \/\/ Process each entity in the pool\n for (; itr != end; ++itr)\n {\n \/\/ Is this player instance valid?\n if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)\n {\n \/\/ Grab the player instance\n CPlayer * player = itr->mInst;\n \/\/ Send the resulted message string\n const vcmpError result = _Func->SendClientMessage(itr->mID, player->mMessageColor,\n \"%s%s%s\",\n player->mMessagePrefix.c_str(),\n val.mPtr,\n player->mMessagePostfix.c_str());\n \/\/ Check the result\n if (result == vcmpErrorTooLargeInput)\n {\n return sq_throwerror(vm, ToStrF(\"Client message too big [%s]\", player->GetTag().c_str()));\n }\n \/\/ Add this player to the count\n ++count;\n }\n }\n \/\/ Push the count count on the stack\n sq_pushinteger(vm, count);\n \/\/ Specify that this function returned a value\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic SQInteger SqBroadcastAnnounce(HSQUIRRELVM vm)\n{\n const Int32 top = sq_gettop(vm);\n \/\/ Was the announcement value specified?\n if (top <= 1)\n {\n return sq_throwerror(vm, \"Missing announcement value\");\n }\n \/\/ Attempt to generate the string value\n StackStrF val(vm, 2);\n \/\/ Have we failed to retrieve the string?\n if (SQ_FAILED(val.mRes))\n {\n return val.mRes; \/\/ Propagate the error!\n }\n \/\/ Obtain the ends of the entity pool\n Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();\n Core::Players::const_iterator end = Core::Get().GetPlayers().cend();\n \/\/ The number of players that the message was sent to\n Uint32 count = 0;\n \/\/ Process each entity in the pool\n for (; itr != end; ++itr)\n {\n \/\/ Is this player instance valid?\n if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)\n {\n \/\/ Grab the player instance\n CPlayer * player = itr->mInst;\n \/\/ Send the resulted announcement string\n const vcmpError result = _Func->SendGameMessage(itr->mID, player->mAnnounceStyle,\n \"%s%s%s\",\n player->mAnnouncePrefix.c_str(),\n val.mPtr,\n player->mAnnouncePostfix.c_str());\n \/\/ Validate the result\n if (result == vcmpErrorArgumentOutOfBounds)\n {\n return sq_throwerror(vm, ToStrF(\"Invalid announcement style [%s]\", player->GetTag().c_str()));\n }\n else if (result == vcmpErrorTooLargeInput)\n {\n return sq_throwerror(vm, ToStrF(\"Game message too big [%s]\", player->GetTag().c_str()));\n }\n \/\/ Add this player to the count\n ++count;\n }\n }\n \/\/ Push the count count on the stack\n sq_pushinteger(vm, count);\n \/\/ Specify that this function returned a value\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic SQInteger SqBroadcastAnnounceEx(HSQUIRRELVM vm)\n{\n const Int32 top = sq_gettop(vm);\n \/\/ Was the announcement style specified?\n if (top <= 1)\n {\n return sq_throwerror(vm, \"Missing announcement style\");\n }\n \/\/ Was the announcement value specified?\n else if (top <= 2)\n {\n return sq_throwerror(vm, \"Missing announcement value\");\n }\n \/\/ The announcement style\n Int32 style;\n \/\/ style to extract the argument values\n try\n {\n style = Var< Int32 >(vm, 2).value;\n }\n catch (const Sqrat::Exception & e)\n {\n \/\/ Propagate the error\n return sq_throwerror(vm, e.Message().c_str());\n }\n \/\/ Attempt to generate the string value\n StackStrF val(vm, 3);\n \/\/ Have we failed to retrieve the string?\n if (SQ_FAILED(val.mRes))\n {\n return val.mRes; \/\/ Propagate the error!\n }\n \/\/ Obtain the ends of the entity pool\n Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();\n Core::Players::const_iterator end = Core::Get().GetPlayers().cend();\n \/\/ The number of players that the message was sent to\n Uint32 count = 0;\n \/\/ Process each entity in the pool\n for (; itr != end; ++itr)\n {\n \/\/ Is this player instance valid?\n if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)\n {\n \/\/ Grab the player instance\n CPlayer * player = itr->mInst;\n \/\/ Send the resulted announcement string\n const vcmpError result = _Func->SendGameMessage(itr->mID, style,\n \"%s%s%s\",\n player->mAnnouncePrefix.c_str(),\n val.mPtr,\n player->mAnnouncePostfix.c_str());\n \/\/ Validate the result\n if (result == vcmpErrorArgumentOutOfBounds)\n {\n return sq_throwerror(vm, ToStrF(\"Invalid announcement style [%s]\", player->GetTag().c_str()));\n }\n else if (result == vcmpErrorTooLargeInput)\n {\n return sq_throwerror(vm, ToStrF(\"Game message too big [%s]\", player->GetTag().c_str()));\n }\n \/\/ Add this player to the count\n ++count;\n }\n }\n \/\/ Push the count count on the stack\n sq_pushinteger(vm, count);\n \/\/ Specify that this function returned a value\n return 1;\n}\n\n\/\/ ================================================================================================\nvoid Register_Misc(HSQUIRRELVM vm)\n{\n Table srvns(vm);\n\n srvns.SquirrelFunc(_SC(\"SendLogMessage\"), &SendLogMessage)\n .Func(_SC(\"GetVersion\"), &GetServerVersion)\n .Func(_SC(\"GetSettings\"), &GetServerSettings)\n .Func(_SC(\"GetNumberOfPlugins\"), &GetNumberOfPlugins)\n .Func(_SC(\"GetPluginInfo\"), &GetPluginInfo)\n .Func(_SC(\"FindPlugin\"), &FindPlugin)\n .Func(_SC(\"SendPluginCommand\"), &SendPluginCommand)\n .Func(_SC(\"GetTime\"), &GetTime)\n .Func(_SC(\"GetLastError\"), &GetLastError)\n .Func(_SC(\"GetPluginVersion\"), &GetPluginVersion)\n .Func(_SC(\"GetPluginVersionStr\"), &GetPluginVersionStr)\n .Func(_SC(\"GetPluginName\"), &GetPluginName)\n .Func(_SC(\"GetPluginAuthor\"), &GetPluginAuthor)\n .Func(_SC(\"GetPluginID\"), &GetPluginID)\n .Func(_SC(\"GetServerPort\"), &GetServerPort)\n .Func(_SC(\"GetServerFlags\"), &GetServerFlags)\n .Func(_SC(\"GetMaxPlayers\"), &GetMaxPlayers)\n .Func(_SC(\"SetMaxPlayers\"), &SetMaxPlayers)\n .Func(_SC(\"GetServerName\"), &GetServerName)\n .Func(_SC(\"SetServerName\"), &SetServerName)\n .Func(_SC(\"GetPassword\"), &GetServerPassword)\n .Func(_SC(\"SetPassword\"), &SetServerPassword)\n .Func(_SC(\"GetGameModeText\"), &GetGameModeText)\n .Func(_SC(\"SetGameModeText\"), &SetGameModeText)\n .Func(_SC(\"CreateRadioStream\"), &CreateRadioStream)\n .Func(_SC(\"CreateRadioStreamEx\"), &CreateRadioStreamEx)\n .Func(_SC(\"RemoveRadioStream\"), &RemoveRadioStream)\n .Func(_SC(\"Shutdown\"), &ShutdownServer)\n .Func(_SC(\"GetOption\"), &GetServerOption)\n .Func(_SC(\"SetOption\"), &SetServerOption)\n .Func(_SC(\"SetOptionEx\"), &SetServerOptionEx)\n .Func(_SC(\"GetWorldBounds\"), &GetWorldBounds)\n .Func(_SC(\"SetWorldBounds\"), &SetWorldBounds)\n .Func(_SC(\"SetWorldBoundsEx\"), &SetWorldBoundsEx)\n .Func(_SC(\"GetWastedSettings\"), &GetWastedSettings)\n .Func(_SC(\"SetWastedSettings\"), &SetWastedSettings)\n .Func(_SC(\"GetTimeRate\"), &GetTimeRate)\n .Func(_SC(\"SetTimeRate\"), &SetTimeRate)\n .Func(_SC(\"GetHour\"), &GetHour)\n .Func(_SC(\"SetHour\"), &SetHour)\n .Func(_SC(\"GetMinute\"), &GetMinute)\n .Func(_SC(\"SetMinute\"), &SetMinute)\n .Func(_SC(\"GetWeather\"), &GetWeather)\n .Func(_SC(\"SetWeather\"), &SetWeather)\n .Func(_SC(\"GetGravity\"), &GetGravity)\n .Func(_SC(\"SetGravity\"), &SetGravity)\n .Func(_SC(\"GetGameSpeed\"), &GetGameSpeed)\n .Func(_SC(\"SetGameSpeed\"), &SetGameSpeed)\n .Func(_SC(\"GetWaterLevel\"), &GetWaterLevel)\n .Func(_SC(\"SetWaterLevel\"), &SetWaterLevel)\n .Func(_SC(\"GetMaximumFlightAltitude\"), &GetMaximumFlightAltitude)\n .Func(_SC(\"SetMaximumFlightAltitude\"), &SetMaximumFlightAltitude)\n .Func(_SC(\"GetKillCommandDelay\"), &GetKillCommandDelay)\n .Func(_SC(\"SetKillCommandDelay\"), &SetKillCommandDelay)\n .Func(_SC(\"GetVehiclesForcedRespawnHeight\"), &GetVehiclesForcedRespawnHeight)\n .Func(_SC(\"SetVehiclesForcedRespawnHeight\"), &SetVehiclesForcedRespawnHeight)\n .Func(_SC(\"CreateExplosion\"), &CreateExplosion)\n .Func(_SC(\"CreateExplosionEx\"), &CreateExplosionEx)\n .Func(_SC(\"PlaySound\"), &PlaySound)\n .Func(_SC(\"PlaySoundEx\"), &PlaySoundEx)\n .Func(_SC(\"HideMapObject\"), &HideMapObject)\n .Func(_SC(\"HideMapObjectEx\"), &SetKeyCodeName)\n .Func(_SC(\"HideMapObjectRaw\"), &HideMapObjectRaw)\n .Func(_SC(\"ShowMapObject\"), &ShowMapObject)\n .Func(_SC(\"ShowMapObjectEx\"), &ShowMapObjectEx)\n .Func(_SC(\"ShowMapObjectRaw\"), &ShowMapObjectRaw)\n .Func(_SC(\"ShowAllMapObjects\"), &ShowAllMapObjects)\n .Func(_SC(\"GetWeaponDataValue\"), &GetWeaponDataValue)\n .Func(_SC(\"SetWeaponDataValue\"), &SetWeaponDataValue)\n .Func(_SC(\"ResetWeaponDataValue\"), &ResetWeaponDataValue)\n .Func(_SC(\"IsWeaponDataValueModified\"), &IsWeaponDataValueModified)\n .Func(_SC(\"ResetWeaponData\"), &ResetWeaponData)\n .Func(_SC(\"ResetAllWeaponData\"), &ResetAllWeaponData)\n .Func(_SC(\"AddPlayerClass\"), &AddPlayerClass)\n .Func(_SC(\"SetSpawnPlayerPosition\"), &SetSpawnPlayerPosition)\n .Func(_SC(\"SetSpawnCameraPosition\"), &SetSpawnCameraPosition)\n .Func(_SC(\"SetSpawnCameraLookAt\"), &SetSpawnCameraLookAt)\n .Func(_SC(\"SetSpawnPlayerPositionEx\"), &SetSpawnPlayerPositionEx)\n .Func(_SC(\"SetSpawnCameraPositionEx\"), &SetSpawnCameraPositionEx)\n .Func(_SC(\"SetSpawnCameraLookAtEx\"), &SetSpawnCameraLookAtEx)\n .Func(_SC(\"BanIP\"), &BanIP)\n .Func(_SC(\"UnbanIP\"), &UnbanIP)\n .Func(_SC(\"IsIPBanned\"), &IsIPBanned)\n .Func(_SC(\"GetPlayerIdFromName\"), &GetPlayerIdFromName)\n .Func(_SC(\"IsPlayerConnected\"), &IsPlayerConnected)\n .Func(_SC(\"ForceAllSelect\"), &ForceAllSelect)\n .Func(_SC(\"CheckEntityExists\"), &SetKeyCodeName);\n\n RootTable(vm).Bind(_SC(\"SqServer\"), srvns);\n\n RootTable(vm)\n .Func(_SC(\"FindPlayer\"), &FindPlayer)\n .Func(_SC(\"GetKeyCodeName\"), &GetKeyCodeName)\n .Func(_SC(\"SetKeyCodeName\"), &SetKeyCodeName)\n .Func(_SC(\"GetModelName\"), &GetModelName)\n .Func(_SC(\"SetModelName\"), &SetModelName)\n .Func(_SC(\"IsModelWeapon\"), &IsModelWeapon)\n .Func(_SC(\"IsModelActuallyWeapon\"), &IsModelActuallyWeapon)\n .Func(_SC(\"GetSkinName\"), &GetSkinName)\n .Func(_SC(\"SetSkinName\"), &SetSkinName)\n .Func(_SC(\"GetSkinID\"), &GetSkinID)\n .Func(_SC(\"IsSkinValid\"), &IsSkinValid)\n .Func(_SC(\"GetAutomobileName\"), &GetAutomobileName)\n .Func(_SC(\"SetAutomobileName\"), &SetAutomobileName)\n .Func(_SC(\"GetAutomobileID\"), &GetAutomobileID)\n .Func(_SC(\"IsAutomobileValid\"), &IsAutomobileValid)\n .Func(_SC(\"GetWeaponName\"), &GetWeaponName)\n .Func(_SC(\"SetWeaponName\"), &SetWeaponName)\n .Func(_SC(\"GetWeaponID\"), &GetWeaponID)\n .Func(_SC(\"IsWeaponValid\"), &IsWeaponValid)\n .Func(_SC(\"WeaponToModel\"), &WeaponToModel)\n .Func(_SC(\"IsWeaponNatural\"), &IsWeaponNatural)\n .Func(_SC(\"PlaySound\"), &PlaySound)\n .Func(_SC(\"PlaySoundEx\"), &PlaySoundEx)\n .Func(_SC(\"CreateExplosion\"), &CreateExplosion)\n .Func(_SC(\"CreateExplosionEx\"), &CreateExplosionEx)\n .SquirrelFunc(_SC(\"SqBroadcastMsg\"), &SqBroadcastMsg)\n .SquirrelFunc(_SC(\"SqBroadcastMsgP\"), &SqBroadcastMsgP)\n .SquirrelFunc(_SC(\"SqBroadcastMsgEx\"), &SqBroadcastMsgEx)\n .SquirrelFunc(_SC(\"SqBroadcastMessage\"), &SqBroadcastMessage)\n .SquirrelFunc(_SC(\"SqBroadcastAnnounce\"), &SqBroadcastAnnounce)\n .SquirrelFunc(_SC(\"SqBroadcastAnnounceEx\"), &SqBroadcastAnnounceEx)\n .SquirrelFunc(_SC(\"SqBroadcastText\"), &SqBroadcastAnnounce)\n .SquirrelFunc(_SC(\"SqBroadcastTextEx\"), &SqBroadcastAnnounceEx);\n}\n\n} \/\/ Namespace:: SqMod\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewobjectcontactofsdrmediaobj.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 13:05:53 $\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#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX\n#define _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX\n\n#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n#include \n#endif\n\nnamespace avmedia { class MediaItem; }\nclass Window;\n\nnamespace sdr\n{\n namespace contact\n {\n class SdrMediaWindow;\n\n class ViewObjectContactOfSdrMediaObj : public ViewObjectContact\n {\n public:\n\n ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,\n ViewContact& rViewContact,\n const ::avmedia::MediaItem& rMediaItem );\n\n \/\/ The destructor. When PrepareDelete() was not called before (see there)\n \/\/ warnings will be generated in debug version if there are still contacts\n \/\/ existing.\n virtual ~ViewObjectContactOfSdrMediaObj();\n\n public:\n\n Window* getWindow() const;\n\n bool hasPreferredSize() const;\n Size getPreferredSize() const;\n\n void updateMediaItem( ::avmedia::MediaItem& rItem ) const;\n void executeMediaItem( const ::avmedia::MediaItem& rItem );\n\n protected:\n\n \/\/ Prepare deletion of this object. This needs to be called always\n \/\/ before really deleting this objects. This is necessary since in a c++\n \/\/ destructor no virtual function calls are allowed. To avoid this problem,\n \/\/ it is required to first call PrepareDelete().\n virtual void PrepareDelete();\n\n \/\/ Paint this object. This is before evtl. SubObjects get painted. This method\n \/\/ needs to set the flag mbIsPainted and mbIsInvalidated and to set the\n \/\/ maPaintedRectangle member. This information is later used for invalidates\n \/\/ and repaints.\n virtual void PaintObject(DisplayInfo& rDisplayInfo);\n\n private:\n\n ::sdr::contact::SdrMediaWindow* mpMediaWindow;\n };\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX\nINTEGRATION: CWS aw039 (1.5.58); FILE MERGED 2006\/12\/19 12:57:05 aw 1.5.58.1: #i72701# added ShouldPaintObject to media object VC and changed VOC paint accordingly\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewobjectcontactofsdrmediaobj.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2007-01-22 15:13:36 $\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#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX\n#define _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX\n\n#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n#include \n#endif\n\nnamespace avmedia { class MediaItem; }\nclass Window;\n\nnamespace sdr\n{\n namespace contact\n {\n class SdrMediaWindow;\n\n class ViewObjectContactOfSdrMediaObj : public ViewObjectContact\n {\n public:\n\n ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,\n ViewContact& rViewContact,\n const ::avmedia::MediaItem& rMediaItem );\n\n \/\/ The destructor. When PrepareDelete() was not called before (see there)\n \/\/ warnings will be generated in debug version if there are still contacts\n \/\/ existing.\n virtual ~ViewObjectContactOfSdrMediaObj();\n\n public:\n\n Window* getWindow() const;\n\n bool hasPreferredSize() const;\n Size getPreferredSize() const;\n\n void updateMediaItem( ::avmedia::MediaItem& rItem ) const;\n void executeMediaItem( const ::avmedia::MediaItem& rItem );\n\n \/\/ #i72701#\n void checkMediaWindowPosition(DisplayInfo& rDisplayInfo) const;\n\n protected:\n\n \/\/ Prepare deletion of this object. This needs to be called always\n \/\/ before really deleting this objects. This is necessary since in a c++\n \/\/ destructor no virtual function calls are allowed. To avoid this problem,\n \/\/ it is required to first call PrepareDelete().\n virtual void PrepareDelete();\n\n \/\/ Paint this object. This is before evtl. SubObjects get painted. This method\n \/\/ needs to set the flag mbIsPainted and mbIsInvalidated and to set the\n \/\/ maPaintedRectangle member. This information is later used for invalidates\n \/\/ and repaints.\n virtual void PaintObject(DisplayInfo& rDisplayInfo);\n\n private:\n\n ::sdr::contact::SdrMediaWindow* mpMediaWindow;\n };\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX\n<|endoftext|>"} {"text":"#include \"global.h\"\n#include \"txn_table.h\"\n#include \"tpcc_query.h\"\n#include \"tpcc.h\"\n#include \"ycsb_query.h\"\n#include \"ycsb.h\"\n#include \"query.h\"\n#include \"txn.h\"\n#include \"mem_alloc.h\"\n#include \"row.h\"\n#include \"plock.h\"\n#include \"txn_pool.h\"\n\n#define MODIFY_START(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n while(pool[i].modify || pool[i].access > 0)\\\n pthread_cond_wait(&pool[i].cond_m,&pool[i].mtx);\\\n pool[i].modify = true; \\\n pthread_mutex_unlock(&pool[i].mtx); }\n\n#define MODIFY_END(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n pool[i].modify = false;\\\n pthread_cond_signal(&pool[i].cond_m); \\\n pthread_cond_broadcast(&pool[i].cond_a); \\\n pthread_mutex_unlock(&pool[i].mtx); }\n\n#define ACCESS_START(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n while(pool[i].modify)\\\n pthread_cond_wait(&pool[i].cond_a,&pool[i].mtx);\\\n pool[i].access++;\\\n pthread_mutex_unlock(&pool[i].mtx); }\n\n#define ACCESS_END(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n pool[i].access--;\\\n pthread_cond_signal(&pool[i].cond_m);\\\n pthread_mutex_unlock(&pool[i].mtx); }\n\nvoid TxnTable::init() {\n pthread_mutex_init(&mtx,NULL);\n pthread_cond_init(&cond_m,NULL);\n pthread_cond_init(&cond_a,NULL);\n modify = false;\n access = 0;\n cnt = 0;\n table_min_ts = UINT64_MAX;\n pool_size = g_inflight_max * g_node_cnt * 2 + 1;\n pool = (pool_node_t) mem_allocator.alloc(sizeof(pool_node) * pool_size , g_thread_cnt);\n for(uint32_t i = 0; i < pool_size;i++) {\n pool[i].head = NULL;\n pool[i].tail = NULL;\n pool[i].cnt = 0;\n pthread_mutex_init(&pool[i].mtx,NULL);\n pthread_cond_init(&pool[i].cond_m,NULL);\n pthread_cond_init(&pool[i].cond_a,NULL);\n pool[i].modify = false;\n pool[i].access = 0;\n pool[i].min_ts = UINT64_MAX;\n }\n}\n\nbool TxnTable::empty(uint64_t node_id) {\n return ts_pool.empty();\n}\n\nvoid TxnTable::add_txn(uint64_t node_id, txn_man * txn, base_query * qry) {\n\n uint64_t thd_prof_start = get_sys_clock();\n txn->set_query(qry);\n uint64_t txn_id = txn->get_txn_id();\n assert(txn_id == qry->txn_id);\n\n txn_man * next_txn = NULL;\n assert(txn->get_txn_id() == qry->txn_id);\n\n MODIFY_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n next_txn = t_node->txn;\n break;\n }\n t_node = t_node->next;\n }\n\n if(next_txn == NULL) {\n \/\/t_node = (txn_node_t) mem_allocator.alloc(sizeof(struct txn_node), g_thread_cnt);\n pthread_mutex_lock(&mtx);\n ts_pool.insert(TsMapPair(txn->get_ts(),NULL));\n pthread_mutex_unlock(&mtx);\n txn_table_pool.get(t_node);\n t_node->txn = txn;\n t_node->qry = qry;\n LIST_PUT_TAIL(pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail,t_node);\n pool[txn_id % pool_size].cnt++;\n if(pool[txn_id % pool_size].cnt > 1) {\n INC_STATS(0,txn_table_cflt,1);\n INC_STATS(0,txn_table_cflt_size,pool[txn_id % pool_size].cnt-1);\n }\n cnt++;\n }\n else {\n if(txn->get_ts() != t_node->txn->get_ts()) {\n pthread_mutex_lock(&mtx);\n ts_pool.erase(t_node->txn->get_ts());\n ts_pool.insert(TsMapPair(txn->get_ts(),NULL));\n pthread_mutex_unlock(&mtx);\n }\n t_node->txn = txn;\n t_node->qry = qry;\n }\n\n MODIFY_END(txn_id % pool_size);\n INC_STATS(0,thd_prof_txn_table_add,get_sys_clock() - thd_prof_start);\n}\nvoid TxnTable::get_txn(uint64_t node_id, uint64_t txn_id,txn_man *& txn,base_query *& qry){\n\n uint64_t thd_prof_start = get_sys_clock();\n txn = NULL;\n qry = NULL;\n INC_STATS(0,thd_prof_get_txn_cnt,1);\n ACCESS_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n txn = t_node->txn;\n qry = t_node->qry;\n assert(txn->get_txn_id() == qry->txn_id);\n break;\n }\n t_node = t_node->next;\n }\n\n ACCESS_END(txn_id % pool_size);\n INC_STATS(0,thd_prof_txn_table_get,get_sys_clock() - thd_prof_start);\n\n}\n\nvoid TxnTable::restart_txn(uint64_t txn_id){\n MODIFY_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n if(txn_id % g_node_cnt == g_node_id)\n t_node->qry->rtype = RTXN;\n else\n t_node->qry->rtype = RQRY;\n work_queue.enqueue(0,t_node->qry);\n break;\n }\n t_node = t_node->next;\n }\n\n MODIFY_END(txn_id % pool_size);\n\n}\n\nvoid TxnTable::delete_txn(uint64_t node_id, uint64_t txn_id){\n uint64_t thd_prof_start = get_sys_clock();\n uint64_t starttime = thd_prof_start;\n\n MODIFY_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n LIST_REMOVE_HT(t_node,pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail);\n pool[txn_id % pool_size].cnt--;\n cnt--;\n break;\n }\n t_node = t_node->next;\n }\n pthread_mutex_lock(&mtx);\n TsMap::iterator it2 = ts_pool.find(t_node->txn->get_ts());\n if(it2 != ts_pool.end())\n ts_pool.erase(it2);\n pthread_mutex_unlock(&mtx);\n\n MODIFY_END(txn_id % pool_size)\n\n if(t_node != NULL) {\n INC_STATS(0,thd_prof_txn_table1a,get_sys_clock() - thd_prof_start);\n thd_prof_start = get_sys_clock();\n assert(!t_node->txn->spec || t_node->txn->state == DONE);\n#if WORKLOAD == TPCC\n \/*\n t_node->txn->release();\n mem_allocator.free(t_node->txn, sizeof(tpcc_txn_man));\n if(t_node->qry->txn_id % g_node_cnt != node_id) {\n mem_allocator.free(t_node->qry, sizeof(tpcc_query));\n }\n *\/\n if(t_node->txn) {\n t_node->txn->release();\n txn_pool.put(t_node->txn);\n }\n#elif WORKLOAD == YCSB\n if(t_node->txn) {\n \/\/t_node->txn->release();\n \/\/mem_allocator.free(t_node->txn, sizeof(ycsb_txn_man));\n t_node->txn->release();\n txn_pool.put(t_node->txn);\n }\n \n if(t_node->qry) {\n \/\/YCSB_QUERY_FREE(t_node->qry)\n qry_pool.put(t_node->qry);\n }\n#endif\n \/\/mem_allocator.free(t_node, sizeof(struct txn_node));\n txn_table_pool.put(t_node);\n INC_STATS(0,thd_prof_txn_table2a,get_sys_clock() - thd_prof_start);\n }\n else {\n\n INC_STATS(0,thd_prof_txn_table1b,get_sys_clock() - thd_prof_start);\n }\n INC_STATS(0,thd_prof_txn_table2,get_sys_clock() - starttime);\n}\n\nuint64_t TxnTable::get_min_ts() {\n\n uint64_t min = UINT64_MAX;\n pthread_mutex_lock(&mtx);\n TsMap::iterator it = ts_pool.lower_bound(0);\n if(it != ts_pool.end())\n min = it->first;\n pthread_mutex_unlock(&mtx);\n return min;\n\n}\n\nvoid TxnTable::snapshot() {\n}\n\nRemoved txn_table.cnt race condition#include \"global.h\"\n#include \"txn_table.h\"\n#include \"tpcc_query.h\"\n#include \"tpcc.h\"\n#include \"ycsb_query.h\"\n#include \"ycsb.h\"\n#include \"query.h\"\n#include \"txn.h\"\n#include \"mem_alloc.h\"\n#include \"row.h\"\n#include \"plock.h\"\n#include \"txn_pool.h\"\n\n#define MODIFY_START(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n while(pool[i].modify || pool[i].access > 0)\\\n pthread_cond_wait(&pool[i].cond_m,&pool[i].mtx);\\\n pool[i].modify = true; \\\n pthread_mutex_unlock(&pool[i].mtx); }\n\n#define MODIFY_END(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n pool[i].modify = false;\\\n pthread_cond_signal(&pool[i].cond_m); \\\n pthread_cond_broadcast(&pool[i].cond_a); \\\n pthread_mutex_unlock(&pool[i].mtx); }\n\n#define ACCESS_START(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n while(pool[i].modify)\\\n pthread_cond_wait(&pool[i].cond_a,&pool[i].mtx);\\\n pool[i].access++;\\\n pthread_mutex_unlock(&pool[i].mtx); }\n\n#define ACCESS_END(i) {\\\n pthread_mutex_lock(&pool[i].mtx);\\\n pool[i].access--;\\\n pthread_cond_signal(&pool[i].cond_m);\\\n pthread_mutex_unlock(&pool[i].mtx); }\n\nvoid TxnTable::init() {\n pthread_mutex_init(&mtx,NULL);\n pthread_cond_init(&cond_m,NULL);\n pthread_cond_init(&cond_a,NULL);\n modify = false;\n access = 0;\n cnt = 0;\n table_min_ts = UINT64_MAX;\n pool_size = g_inflight_max * g_node_cnt * 2 + 1;\n pool = (pool_node_t) mem_allocator.alloc(sizeof(pool_node) * pool_size , g_thread_cnt);\n for(uint32_t i = 0; i < pool_size;i++) {\n pool[i].head = NULL;\n pool[i].tail = NULL;\n pool[i].cnt = 0;\n pthread_mutex_init(&pool[i].mtx,NULL);\n pthread_cond_init(&pool[i].cond_m,NULL);\n pthread_cond_init(&pool[i].cond_a,NULL);\n pool[i].modify = false;\n pool[i].access = 0;\n pool[i].min_ts = UINT64_MAX;\n }\n}\n\nbool TxnTable::empty(uint64_t node_id) {\n return ts_pool.empty();\n}\n\nvoid TxnTable::add_txn(uint64_t node_id, txn_man * txn, base_query * qry) {\n\n uint64_t thd_prof_start = get_sys_clock();\n txn->set_query(qry);\n uint64_t txn_id = txn->get_txn_id();\n assert(txn_id == qry->txn_id);\n\n txn_man * next_txn = NULL;\n assert(txn->get_txn_id() == qry->txn_id);\n\n MODIFY_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n next_txn = t_node->txn;\n break;\n }\n t_node = t_node->next;\n }\n\n if(next_txn == NULL) {\n \/\/t_node = (txn_node_t) mem_allocator.alloc(sizeof(struct txn_node), g_thread_cnt);\n pthread_mutex_lock(&mtx);\n ts_pool.insert(TsMapPair(txn->get_ts(),NULL));\n pthread_mutex_unlock(&mtx);\n txn_table_pool.get(t_node);\n t_node->txn = txn;\n t_node->qry = qry;\n LIST_PUT_TAIL(pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail,t_node);\n pool[txn_id % pool_size].cnt++;\n if(pool[txn_id % pool_size].cnt > 1) {\n INC_STATS(0,txn_table_cflt,1);\n INC_STATS(0,txn_table_cflt_size,pool[txn_id % pool_size].cnt-1);\n }\n ATOM_ADD(cnt,1);\n }\n else {\n if(txn->get_ts() != t_node->txn->get_ts()) {\n pthread_mutex_lock(&mtx);\n ts_pool.erase(t_node->txn->get_ts());\n ts_pool.insert(TsMapPair(txn->get_ts(),NULL));\n pthread_mutex_unlock(&mtx);\n }\n t_node->txn = txn;\n t_node->qry = qry;\n }\n\n MODIFY_END(txn_id % pool_size);\n INC_STATS(0,thd_prof_txn_table_add,get_sys_clock() - thd_prof_start);\n}\nvoid TxnTable::get_txn(uint64_t node_id, uint64_t txn_id,txn_man *& txn,base_query *& qry){\n\n uint64_t thd_prof_start = get_sys_clock();\n txn = NULL;\n qry = NULL;\n INC_STATS(0,thd_prof_get_txn_cnt,1);\n ACCESS_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n txn = t_node->txn;\n qry = t_node->qry;\n assert(txn->get_txn_id() == qry->txn_id);\n break;\n }\n t_node = t_node->next;\n }\n\n ACCESS_END(txn_id % pool_size);\n INC_STATS(0,thd_prof_txn_table_get,get_sys_clock() - thd_prof_start);\n\n}\n\nvoid TxnTable::restart_txn(uint64_t txn_id){\n MODIFY_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n if(txn_id % g_node_cnt == g_node_id)\n t_node->qry->rtype = RTXN;\n else\n t_node->qry->rtype = RQRY;\n work_queue.enqueue(0,t_node->qry);\n break;\n }\n t_node = t_node->next;\n }\n\n MODIFY_END(txn_id % pool_size);\n\n}\n\nvoid TxnTable::delete_txn(uint64_t node_id, uint64_t txn_id){\n uint64_t thd_prof_start = get_sys_clock();\n uint64_t starttime = thd_prof_start;\n\n MODIFY_START(txn_id % pool_size);\n\n txn_node_t t_node = pool[txn_id % pool_size].head;\n\n while (t_node != NULL) {\n if (t_node->txn->get_txn_id() == txn_id) {\n LIST_REMOVE_HT(t_node,pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail);\n pool[txn_id % pool_size].cnt--;\n ATOM_SUB(cnt,1);\n break;\n }\n t_node = t_node->next;\n }\n pthread_mutex_lock(&mtx);\n TsMap::iterator it2 = ts_pool.find(t_node->txn->get_ts());\n if(it2 != ts_pool.end())\n ts_pool.erase(it2);\n pthread_mutex_unlock(&mtx);\n\n MODIFY_END(txn_id % pool_size)\n\n if(t_node != NULL) {\n INC_STATS(0,thd_prof_txn_table1a,get_sys_clock() - thd_prof_start);\n thd_prof_start = get_sys_clock();\n assert(!t_node->txn->spec || t_node->txn->state == DONE);\n#if WORKLOAD == TPCC\n \/*\n t_node->txn->release();\n mem_allocator.free(t_node->txn, sizeof(tpcc_txn_man));\n if(t_node->qry->txn_id % g_node_cnt != node_id) {\n mem_allocator.free(t_node->qry, sizeof(tpcc_query));\n }\n *\/\n if(t_node->txn) {\n t_node->txn->release();\n txn_pool.put(t_node->txn);\n }\n#elif WORKLOAD == YCSB\n if(t_node->txn) {\n \/\/t_node->txn->release();\n \/\/mem_allocator.free(t_node->txn, sizeof(ycsb_txn_man));\n t_node->txn->release();\n txn_pool.put(t_node->txn);\n }\n \n if(t_node->qry) {\n \/\/YCSB_QUERY_FREE(t_node->qry)\n qry_pool.put(t_node->qry);\n }\n#endif\n \/\/mem_allocator.free(t_node, sizeof(struct txn_node));\n txn_table_pool.put(t_node);\n INC_STATS(0,thd_prof_txn_table2a,get_sys_clock() - thd_prof_start);\n }\n else {\n\n INC_STATS(0,thd_prof_txn_table1b,get_sys_clock() - thd_prof_start);\n }\n INC_STATS(0,thd_prof_txn_table2,get_sys_clock() - starttime);\n}\n\nuint64_t TxnTable::get_min_ts() {\n\n uint64_t min = UINT64_MAX;\n pthread_mutex_lock(&mtx);\n TsMap::iterator it = ts_pool.lower_bound(0);\n if(it != ts_pool.end())\n min = it->first;\n pthread_mutex_unlock(&mtx);\n return min;\n\n}\n\nvoid TxnTable::snapshot() {\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace BABYLON {\nnamespace Samples {\n\n\/**\n * @brief Simple post process render pipeline scene. This example demonstrates how to use the post\n * process renders pipeline.\n * @see https:\/\/www.babylonjs-playground.com\/#QCGFI6\n *\/\nclass SimplePostProcessRenderPipelineScene : public IRenderableScene {\n\npublic:\n SimplePostProcessRenderPipelineScene(ICanvas* iCanvas)\n : IRenderableScene(iCanvas), _blackAndWhite{nullptr}, _horizontalBlur{nullptr}\n {\n }\n\n ~SimplePostProcessRenderPipelineScene() override = default;\n\n const char* getName() override\n {\n return \"Simple Post Process Render Pipeline Scene\";\n }\n\n void initializeScene(ICanvas* canvas, Scene* scene) override\n {\n \/\/ Create a basic scene\n auto camera = FreeCamera::New(\"camera1\", Vector3(0.f, 5.f, -10.f), scene);\n camera->setTarget(Vector3::Zero());\n camera->attachControl(canvas, true);\n auto light = HemisphericLight::New(\"light1\", Vector3(0, 1, 0), scene);\n light->intensity = 0.7f;\n auto sphere = Mesh::CreateSphere(\"sphere1\", 16, 2, scene);\n sphere->position().y = 1.f;\n auto ground = Mesh::CreateGround(\"ground1\", 6, 6, 2, scene);\n\n \/\/ Get the engine reference\n auto engine = scene->getEngine();\n\n \/\/ Create a standard pipeline\n auto standardPipeline = PostProcessRenderPipeline::New(engine, \"standardPipeline\");\n\n \/\/ Create post processes\n _blackAndWhite = BlackAndWhitePostProcess::New(\"bw\", 1.f, nullptr, 0, engine, false);\n _horizontalBlur = BlurPostProcess::New(\"hb\", Vector2(1.f, 0.f), 20.f, 1.f, nullptr,\n std::nullopt, engine, false);\n\n \/\/ Create effect with multiple post processes and add to pipeline\n auto blackAndWhiteThenBlur = PostProcessRenderEffect::New(\n engine, \"blackAndWhiteThenBlur\", [this]() -> std::vector {\n return {_blackAndWhite, _horizontalBlur};\n });\n standardPipeline->addEffect(blackAndWhiteThenBlur);\n\n \/\/ Add pipeline to the scene's manager and attach to the camera\n scene->postProcessRenderPipelineManager()->addPipeline(standardPipeline);\n scene->postProcessRenderPipelineManager()->attachCamerasToRenderPipeline(\"standardPipeline\",\n camera);\n }\n\nprivate:\n PostProcessPtr _blackAndWhite, _horizontalBlur;\n\n}; \/\/ end of class SimplePostProcessRenderPipelineScene\n\nBABYLON_REGISTER_SAMPLE(\"Special FX\", SimplePostProcessRenderPipelineScene)\n\n} \/\/ end of namespace Samples\n} \/\/ end of namespace BABYLON\nUsing default sample mode for BlackAndWhitePostProcess#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace BABYLON {\nnamespace Samples {\n\n\/**\n * @brief Simple post process render pipeline scene. This example demonstrates how to use the post\n * process renders pipeline.\n * @see https:\/\/www.babylonjs-playground.com\/#QCGFI6\n *\/\nclass SimplePostProcessRenderPipelineScene : public IRenderableScene {\n\npublic:\n SimplePostProcessRenderPipelineScene(ICanvas* iCanvas)\n : IRenderableScene(iCanvas), _blackAndWhite{nullptr}, _horizontalBlur{nullptr}\n {\n }\n\n ~SimplePostProcessRenderPipelineScene() override = default;\n\n const char* getName() override\n {\n return \"Simple Post Process Render Pipeline Scene\";\n }\n\n void initializeScene(ICanvas* canvas, Scene* scene) override\n {\n \/\/ Create a basic scene\n auto camera = FreeCamera::New(\"camera1\", Vector3(0.f, 5.f, -10.f), scene);\n camera->setTarget(Vector3::Zero());\n camera->attachControl(canvas, true);\n auto light = HemisphericLight::New(\"light1\", Vector3(0, 1, 0), scene);\n light->intensity = 0.7f;\n auto sphere = Mesh::CreateSphere(\"sphere1\", 16, 2, scene);\n sphere->position().y = 1.f;\n auto ground = Mesh::CreateGround(\"ground1\", 6, 6, 2, scene);\n\n \/\/ Get the engine reference\n auto engine = scene->getEngine();\n\n \/\/ Create a standard pipeline\n auto standardPipeline = PostProcessRenderPipeline::New(engine, \"standardPipeline\");\n\n \/\/ Create post processes\n _blackAndWhite = BlackAndWhitePostProcess::New(\"bw\", 1.f, nullptr, std::nullopt, engine, false);\n _horizontalBlur = BlurPostProcess::New(\"hb\", Vector2(1.f, 0.f), 20.f, 1.f, nullptr,\n std::nullopt, engine, false);\n\n \/\/ Create effect with multiple post processes and add to pipeline\n auto blackAndWhiteThenBlur = PostProcessRenderEffect::New(\n engine, \"blackAndWhiteThenBlur\", [this]() -> std::vector {\n return {_blackAndWhite, _horizontalBlur};\n });\n standardPipeline->addEffect(blackAndWhiteThenBlur);\n\n \/\/ Add pipeline to the scene's manager and attach to the camera\n scene->postProcessRenderPipelineManager()->addPipeline(standardPipeline);\n scene->postProcessRenderPipelineManager()->attachCamerasToRenderPipeline(\"standardPipeline\",\n camera);\n }\n\nprivate:\n PostProcessPtr _blackAndWhite, _horizontalBlur;\n\n}; \/\/ end of class SimplePostProcessRenderPipelineScene\n\nBABYLON_REGISTER_SAMPLE(\"Special FX\", SimplePostProcessRenderPipelineScene)\n\n} \/\/ end of namespace Samples\n} \/\/ end of namespace BABYLON\n<|endoftext|>"} {"text":"\/\/A ROOT macro that prepares Tree for TMVA training\n\/\/----------------------------------------------\n\/\/Author: Maxwell Cui\n\/\/Date: Aug 19, 2017\n\/\/----------------------------------------------\n\n#include\n#include\n#include\n#include\n\nvoid create(TFile* inputTree, TString outputName)\n{\n TTree *oldTree=new TTree;\n inputTree->GetObject(\"nominal_Loose\",oldTree);\n \n \/\/Deactive all branches\n oldTree->SetBranchStatus(\"*\",0);\n\n \/\/Active the interested branches \n oldTree->SetBranchStatus(\"ht\",1);\n oldTree->SetBranchStatus(\"met_met\",1);\n oldTree->SetBranchStatus(\"met_sumet\",1);\n oldTree->SetBranchStatus(\"mu_pt\",1);\n oldTree->SetBranchStatus(\"el_pt\",1);\n oldTree->SetBranchStatus(\"mu\",1);\n oldTree->SetBranchStatus(\"jet_pt\",1);\n oldTree->SetBranchStatus(\"met_phi\",1);\n oldTree->SetBranchStatus(\"SSee_2016\",1);\n oldTree->SetBranchStatus(\"SSmm_2016\",1);\n oldTree->SetBranchStatus(\"SSem_2016\",1);\n oldTree->SetBranchStatus(\"eee_2016\",1);\n oldTree->SetBranchStatus(\"eem_2016\",1);\n oldTree->SetBranchStatus(\"emm_2016\",1);\n oldTree->SetBranchStatus(\"mmm_2016\",1);\n oldTree->SetBranchStatus(\"lep_pt\",1);\n oldTree->SetBranchStatus(\"jet_mv2c10\",1); \/\/Using MV2c10 for b-tagging\n oldTree->SetBranchStatus(\"weight_mc\",1);\n\n \/\/====================Output file==========================\n \/\/\n TFile *outputFile=new TFile(outputName,\"recreate\");\n \/\/ \n \/\/=========================================================\n\n \/\/Copy to new tree\n TTree *newTree=oldTree->CloneTree();\n\n \/\/Working with b-jet\n \/\/\n \/\/ Declaration of leaf types\n Float_t mu;\n vector *el_pt;\n vector *mu_pt;\n vector *jet_pt;\n vector *jet_mv2c10;\n Float_t met_met;\n Float_t met_phi;\n Float_t met_sumet;\n Int_t SSee_2016;\n Int_t SSmm_2016;\n Int_t SSem_2016;\n Int_t eee_2016;\n Int_t eem_2016;\n Int_t emm_2016;\n Int_t mmm_2016;\n vector *lep_pt;\n Float_t ht;\n\n \n \/\/ List of branches\n TBranch *b_mu; \/\/!\n TBranch *b_el_pt; \/\/!\n TBranch *b_mu_pt; \/\/!\n TBranch *b_jet_pt; \/\/!\n TBranch *b_jet_mv2c10; \/\/!\n TBranch *b_met_met; \/\/!\n TBranch *b_met_sumet;\n TBranch *b_met_phi; \/\/!\n TBranch *b_SSee_2016; \/\/!\n TBranch *b_SSmm_2016; \/\/!\n TBranch *b_SSem_2016; \/\/!\n TBranch *b_eee_2016; \/\/!\n TBranch *b_eem_2016; \/\/!\n TBranch *b_emm_2016; \/\/!\n TBranch *b_mmm_2016; \/\/!\n TBranch *b_lep_pt; \/\/!\n TBranch *b_ht; \/\/!\n\n\n \/\/Set object pointer\n el_pt = 0;\n mu_pt = 0;\n jet_pt = 0;\n jet_mv2c10 = 0;\n lep_pt = 0;\n \n \/\/Set branch addresses and brunch pointers\n oldTree->SetBranchAddress(\"mu\", &mu, &b_mu);\n oldTree->SetBranchAddress(\"el_pt\", &el_pt, &b_el_pt);\n oldTree->SetBranchAddress(\"mu_pt\", &mu_pt, &b_mu_pt);\n oldTree->SetBranchAddress(\"jet_pt\", &jet_pt, &b_jet_pt);\n oldTree->SetBranchAddress(\"jet_mv2c10\", &jet_mv2c10, &b_jet_mv2c10);\n oldTree->SetBranchAddress(\"met_met\", &met_met, &b_met_met);\n oldTree->SetBranchAddress(\"met_phi\", &met_phi, &b_met_phi);\n oldTree->SetBranchAddress(\"met_sumet\", &met_sumet, &b_met_sumet);\n oldTree->SetBranchAddress(\"SSee_2016\", &SSee_2016, &b_SSee_2016);\n oldTree->SetBranchAddress(\"SSmm_2016\", &SSmm_2016, &b_SSmm_2016);\n oldTree->SetBranchAddress(\"SSem_2016\", &SSem_2016, &b_SSem_2016);\n oldTree->SetBranchAddress(\"eee_2016\", &eee_2016, &b_eee_2016);\n oldTree->SetBranchAddress(\"eem_2016\", &eem_2016, &b_eem_2016);\n oldTree->SetBranchAddress(\"emm_2016\", &emm_2016, &b_emm_2016);\n oldTree->SetBranchAddress(\"mmm_2016\", &mmm_2016, &b_mmm_2016);\n oldTree->SetBranchAddress(\"lep_pt\", &lep_pt, &b_lep_pt);\n oldTree->SetBranchAddress(\"ht\", &ht, &b_ht);\n\n\n \/\/Declare bjet variable\n Int_t bjet;\n\n \/\/Add new branch\n TBranch *bjetBranch=newTree->Branch(\"bjet\",&bjet,\"bjet\/I\");\n\n Int_t nentries=(Int_t)oldTree->GetEntries();\n\n \/\/Calculate bjet, algorithm is provided by Prof. Varnes\n for(Int_t i=0;iGetEntry(i);\n bjet=0;\n if(SSee_2016 || SSem_2016 || SSmm_2016 || eee_2016 || eem_2016 || emm_2016 || mmm_2016)\n \t{\n \t for(unsigned int ibjet=0;ibjetsize();ibjet++)\n \t {\n \t \/\/\/ if (jet_mv2c10->at(ibjet) > 0.1758475) { \/\/ 85% WP \n\t if (jet_mv2c10->at(ibjet) > 0.645925) \n\t\t{ \/\/ 77% WP\n\t\t \/\/if (jet_mv2c10->at(ibjet) > 0.8244273) { \/\/ 70% WP\n\t\tbjet++;\n\t\t} \n \t }\n \t}\n bjetBranch->Fill();\n }\n \n \/\/Working with normalization \n \/\/\n Float_t lumi=36.1; \n\n \/\/Declare leaf and branch\n Float_t weight_mc;\n Float_t weight_jvt;\n Float_t weight_leptonSF_tightLeps;\n Float_t weight_indiv_SF_MU_TTVA;\n Float_t weight_pileup;\n Float_t weight_bTagSF_77;\n\n TBranch *b_weight_mc;\n TBranch *b_weight_jvt;\n TBranch *b_weight_leptonSF_tightLeps;\n TBranch *b_weight_indiv_SF_MU_TTVA;\n TBranch *b_weight_pileup;\n TBranch *b_weight_bTagSF_77;\n\n \/\/Set branch addresses and brunch pointers\n oldTree->SetBranchAddress(\"weight_mc\", &weight_mc, &b_weight_mc);\n oldTree->SetBranchAddress(\"weight_jvt\", &weight_jvt, &b_weight_jvt);\n oldTree->SetBranchAddress(\"weight_leptonSF_tightLeps\", &weight_leptonSF_tightLeps, &b_weight_leptonSF_tightLeps);\n oldTree->SetBranchAddress(\"weight_indiv_SF_MU_TTVA\", &weight_indiv_SF_MU_TTVA, &b_weight_indiv_SF_MU_TTVA);\n oldTree->SetBranchAddress(\"weight_pileup\", &weight_pileup, &b_weight_pileup);\n oldTree->SetBranchAddress(\"weight_bTagSF_77\", &weight_bTagSF_77, &b_weight_bTagSF_77);\n\n \n\n \/\/Get the data...algrithm is from Prof. Varnes\n TH1F *lumInt=new TH1F;\n inputTree->GetObject(\"hIntLum\",lumInt);\n Float_t mcnorm=lumInt->GetBinContent(1);\n \n \/\/Declare variable for event weight\n Float_t evtWeight;\n TBranch *evtBranch=newTree->Branch(\"evtWeight\",&evtWeight,\"evtWeight\/D\");\n\n std::cout<<\"mcnorm is: \"<GetEntry(j);\n evtWeight=weight_mc*weight_jvt*(weight_leptonSF_tightLeps\/weight_indiv_SF_MU_TTVA)*weight_pileup*weight_bTagSF_77*lumi\/mcnorm;\n std::cout<<\"The weight_jvt is: \"<Fill();\n }\n\n newTree->Fill();\n newTree->Print();\n newTree->Write();\n\n outputFile->Close();\n \n delete oldTree;\n delete lumInt;\n}\n\nvoid prepTree()\n{\n\n \/\/Variable 'envName' can be the environmental variable on the system that\n \/\/includes the path to the directory of the data files.\n \/\/Please make sure that the variable is exported.\n \n const char* envName=\"MCDATA\";\n std::string dataPATH=std::getenv(envName);\n if(dataPATH.empty())\n {\n std::cout<<\"\\tData path not found! Please make sure you export MCDATA which contains the path of data.\\n\";\n }\n else\n {\n std::cout<<\"\\tData path is: \"<major update\/\/A ROOT macro that prepares Tree for TMVA training\n\/\/----------------------------------------------\n\/\/Author: Maxwell Cui\n\/\/Created date: Aug 19, 2017\n\/\/Latest modified: Sep 7, 2017\n\/\/----------------------------------------------\n\n#include\n#include\n#include\n#include\n\nvoid create(TFile* inputTree, TString outputName)\n{\n TTree *oldTree=new TTree;\n inputTree->GetObject(\"nominal_Loose\",oldTree);\n \n \/\/Deactive all branches\n oldTree->SetBranchStatus(\"*\",0);\n\n \/\/Active the interested branches \n oldTree->SetBranchStatus(\"ht\",1);\n oldTree->SetBranchStatus(\"met_met\",1);\n oldTree->SetBranchStatus(\"met_sumet\",1);\n oldTree->SetBranchStatus(\"mu_pt\",1);\n oldTree->SetBranchStatus(\"el_pt\",1);\n oldTree->SetBranchStatus(\"mu\",1);\n oldTree->SetBranchStatus(\"jet_pt\",1);\n oldTree->SetBranchStatus(\"met_phi\",1);\n oldTree->SetBranchStatus(\"SSee_2016\",1);\n oldTree->SetBranchStatus(\"SSmm_2016\",1);\n oldTree->SetBranchStatus(\"SSem_2016\",1);\n oldTree->SetBranchStatus(\"eee_2016\",1);\n oldTree->SetBranchStatus(\"eem_2016\",1);\n oldTree->SetBranchStatus(\"emm_2016\",1);\n oldTree->SetBranchStatus(\"mmm_2016\",1);\n oldTree->SetBranchStatus(\"lep_pt\",1);\n oldTree->SetBranchStatus(\"jet_mv2c10\",1); \/\/Using MV2c10 for b-tagging\n\n oldTree->SetBranchStatus(\"weight_mc\",1);\n oldTree->SetBranchStatus(\"weight_jvt\",1);\n oldTree->SetBranchStatus(\"weight_leptonSF_tightLeps\",1);\n oldTree->SetBranchStatus(\"weight_indiv_SF_MU_TTVA\",1);\n oldTree->SetBranchStatus(\"weight_pileup\",1);\n oldTree->SetBranchStatus(\"weight_bTagSF_77\",1);\n\n \/\/====================Output file==========================\n \/\/\n TFile *outputFile=new TFile(outputName,\"recreate\");\n \/\/ \n \/\/=========================================================\n\n \/\/Copy to new tree\n TTree *newTree=oldTree->CloneTree();\n\n \/\/Working with b-jet\n \/\/\n \/\/ Declaration of leaf types\n Float_t mu;\n vector *el_pt;\n vector *mu_pt;\n vector *jet_pt;\n vector *jet_mv2c10;\n Float_t met_met;\n Float_t met_phi;\n Float_t met_sumet;\n Int_t SSee_2016;\n Int_t SSmm_2016;\n Int_t SSem_2016;\n Int_t eee_2016;\n Int_t eem_2016;\n Int_t emm_2016;\n Int_t mmm_2016;\n vector *lep_pt;\n Float_t ht;\n\n \n \/\/ List of branches\n TBranch *b_mu; \/\/!\n TBranch *b_el_pt; \/\/!\n TBranch *b_mu_pt; \/\/!\n TBranch *b_jet_pt; \/\/!\n TBranch *b_jet_mv2c10; \/\/!\n TBranch *b_met_met; \/\/!\n TBranch *b_met_sumet;\n TBranch *b_met_phi; \/\/!\n TBranch *b_SSee_2016; \/\/!\n TBranch *b_SSmm_2016; \/\/!\n TBranch *b_SSem_2016; \/\/!\n TBranch *b_eee_2016; \/\/!\n TBranch *b_eem_2016; \/\/!\n TBranch *b_emm_2016; \/\/!\n TBranch *b_mmm_2016; \/\/!\n TBranch *b_lep_pt; \/\/!\n TBranch *b_ht; \/\/!\n\n\n \/\/Set object pointer\n el_pt = 0;\n mu_pt = 0;\n jet_pt = 0;\n jet_mv2c10 = 0;\n lep_pt = 0;\n \n \/\/Set branch addresses and brunch pointers\n oldTree->SetBranchAddress(\"mu\", &mu, &b_mu);\n oldTree->SetBranchAddress(\"el_pt\", &el_pt, &b_el_pt);\n oldTree->SetBranchAddress(\"mu_pt\", &mu_pt, &b_mu_pt);\n oldTree->SetBranchAddress(\"jet_pt\", &jet_pt, &b_jet_pt);\n oldTree->SetBranchAddress(\"jet_mv2c10\", &jet_mv2c10, &b_jet_mv2c10);\n oldTree->SetBranchAddress(\"met_met\", &met_met, &b_met_met);\n oldTree->SetBranchAddress(\"met_phi\", &met_phi, &b_met_phi);\n oldTree->SetBranchAddress(\"met_sumet\", &met_sumet, &b_met_sumet);\n oldTree->SetBranchAddress(\"SSee_2016\", &SSee_2016, &b_SSee_2016);\n oldTree->SetBranchAddress(\"SSmm_2016\", &SSmm_2016, &b_SSmm_2016);\n oldTree->SetBranchAddress(\"SSem_2016\", &SSem_2016, &b_SSem_2016);\n oldTree->SetBranchAddress(\"eee_2016\", &eee_2016, &b_eee_2016);\n oldTree->SetBranchAddress(\"eem_2016\", &eem_2016, &b_eem_2016);\n oldTree->SetBranchAddress(\"emm_2016\", &emm_2016, &b_emm_2016);\n oldTree->SetBranchAddress(\"mmm_2016\", &mmm_2016, &b_mmm_2016);\n oldTree->SetBranchAddress(\"lep_pt\", &lep_pt, &b_lep_pt);\n oldTree->SetBranchAddress(\"ht\", &ht, &b_ht);\n\n\n \/\/Declare bjet variable\n Int_t bjet;\n\n \/\/Add new branch\n TBranch *bjetBranch=newTree->Branch(\"bjet\",&bjet,\"bjet\/I\");\n\n \/\/Get the number of events\n Int_t nentries=(Int_t)oldTree->GetEntries();\n\n \/\/Calculate bjet, algorithm is provided by Prof. Varnes\n for(Int_t i=0;iGetEntry(i);\n bjet=0;\n if(SSee_2016 || SSem_2016 || SSmm_2016 || eee_2016 || eem_2016 || emm_2016 || mmm_2016)\n \t{\n \t for(unsigned int ibjet=0;ibjetsize();ibjet++)\n \t {\n \t \/\/\/ if (jet_mv2c10->at(ibjet) > 0.1758475) { \/\/ 85% WP \n\t if (jet_mv2c10->at(ibjet) > 0.645925) \n\t\t{ \/\/ 77% WP\n\t\t \/\/if (jet_mv2c10->at(ibjet) > 0.8244273) { \/\/ 70% WP\n\t\tbjet++;\n\t\t} \n \t }\n \t}\n bjetBranch->Fill();\n }\n \n \/\/Working with normalization \n \/\/\n Float_t lumi=36.1; \n\n \/\/Declare leaf and branch\n Float_t weight_mc;\n Float_t weight_jvt;\n Float_t weight_leptonSF_tightLeps;\n Float_t weight_indiv_SF_MU_TTVA;\n Float_t weight_pileup;\n Float_t weight_bTagSF_77;\n\n TBranch *b_weight_mc;\n TBranch *b_weight_jvt;\n TBranch *b_weight_leptonSF_tightLeps;\n TBranch *b_weight_indiv_SF_MU_TTVA;\n TBranch *b_weight_pileup;\n TBranch *b_weight_bTagSF_77;\n\n \/\/Set branch addresses and brunch pointers\n oldTree->SetBranchAddress(\"weight_mc\", &weight_mc, &b_weight_mc);\n oldTree->SetBranchAddress(\"weight_jvt\", &weight_jvt, &b_weight_jvt);\n oldTree->SetBranchAddress(\"weight_leptonSF_tightLeps\", &weight_leptonSF_tightLeps, &b_weight_leptonSF_tightLeps);\n oldTree->SetBranchAddress(\"weight_indiv_SF_MU_TTVA\", &weight_indiv_SF_MU_TTVA, &b_weight_indiv_SF_MU_TTVA);\n oldTree->SetBranchAddress(\"weight_pileup\", &weight_pileup, &b_weight_pileup);\n oldTree->SetBranchAddress(\"weight_bTagSF_77\", &weight_bTagSF_77, &b_weight_bTagSF_77);\n\n \n\n \/\/Get the data...algrithm is from Prof. Varnes\n TH1F *lumInt=new TH1F;\n inputTree->GetObject(\"hIntLum\",lumInt);\n Float_t mcnorm=lumInt->GetBinContent(1);\n \n \/\/Declare variable for event weight\n Float_t evtWeight;\n TBranch *evtBranch=newTree->Branch(\"evtWeight\",&evtWeight,\"evtWeight\/F\");\n\n std::cout<<\"mcnorm is: \"<GetEntry(j);\n\n \/\/Calculate event weight\n evtWeight=weight_mc*weight_jvt*(weight_leptonSF_tightLeps\/weight_indiv_SF_MU_TTVA)*weight_pileup*weight_bTagSF_77*lumi\/mcnorm;\n \n std::cout<Fill();\n }\n\n newTree->Fill();\n newTree->Print();\n newTree->Write();\n\n outputFile->Close();\n \n delete oldTree;\n delete lumInt;\n}\n\nvoid prepTree()\n{\n\n \/\/Variable 'envName' can be the environmental variable on the system that\n \/\/includes the path to the directory of the data files.\n \/\/Please make sure that the variable is exported.\n \n const char* envName=\"MCDATA\";\n std::string dataPATH=std::getenv(envName);\n if(dataPATH.empty())\n {\n std::cout<<\"\\tData path not found! Please make sure you export MCDATA which contains the path of data.\\n\";\n }\n else\n {\n std::cout<<\"\\tData path is: \"<"} {"text":"#ifndef __PreassembledMass_INL\n#define __PreassembledMass_INL\n\n#include \"PreassembledMass.h\"\n\n#include \n\n#include \n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mass\n{\n\n\/\/\/ removing no longer necessary mapped masses\nclass RemoveChildMassVisitor : public simulation::Visitor\n{\npublic:\n RemoveChildMassVisitor(const core::ExecParams* params)\n : simulation::Visitor(params)\n {\n }\n\n virtual Result processNodeTopDown(simulation::Node* node)\n {\n core::behavior::BaseMass* mass;\n node->get(mass);\n if( !dynamic_cast(mass) )\n node->removeObject(mass);\n return RESULT_CONTINUE;\n }\n\n};\n\n\n\nunsigned int BasePreassembledMass::s_instanciationCounter = 0;\n\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::init()\n{\n core::behavior::Mass::init();\n}\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::bwdInit()\n{\n\n MassMatrix& massMatrix = *d_massMatrix.beginEdit();\n\n \/\/ if the mass matrix is not given manually\n if( massMatrix.rows() != massMatrix.cols() || massMatrix.rows()!=this->mstate->getMatrixSize() )\n {\n \/\/ perform assembly\n core::MechanicalParams mparams = *core::MechanicalParams::defaultInstance();\n mparams.setKFactor(0);\n mparams.setBFactor(0);\n mparams.setMFactor(1);\n mparams.setDt( this->getContext()->getDt() ); \/\/ should not be used but to be sure\n\n simulation::AssemblyVisitor assemblyVisitor( &mparams );\n this->getContext()->executeVisitor( &assemblyVisitor );\n component::linearsolver::AssembledSystem sys;\n assemblyVisitor.assemble( sys );\n massMatrix.compressedMatrix = sys.H;\n\n if( massMatrix.rows()!=this->mstate->getMatrixSize() )\n {\n serr<<\"Are you sure that every independent dofs are in independent graph branches?\\n\";\n assert(false);\n }\n\n if( _instanciationNumber == 0 ) \/\/ only the first one (last bwdInit called) will call the mass removal\n {\n \/\/ std::cerr<getContext()->executeVisitor( &removeChildMassVisitor );\n\n typename LinkMassNodes::Container massNodes = l_massNodes.getValue();\n for ( unsigned int i = 0; i < massNodes.size() ; i++)\n {\n if( massNodes[i]->isActive() ) massNodes[i]->setActive( false );\n }\n }\n }\n\n\n \/\/ for human debug\n Real totalmass = 0;\n for(size_t r=0;rmstate->getMatrixBlockSize()<\nvoid PreassembledMass< DataTypes >::addMDx( const core::MechanicalParams*, DataVecDeriv& res, const DataVecDeriv& dx, double factor )\n{\n if( factor == 1.0 )\n {\n d_massMatrix.getValue().addMult( res, dx );\n }\n else\n {\n d_massMatrix.getValue().addMult( res, dx, factor );\n }\n}\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::accFromF( const core::MechanicalParams*, DataVecDeriv& \/*acc*\/, const DataVecDeriv& \/*f*\/ )\n{\n serr<<\"accFromF not yet implemented (the matrix inversion is needed)\"<\ndouble PreassembledMass< DataTypes >::getKineticEnergy( const core::MechanicalParams*, const DataVecDeriv& v ) const\n{\n const VecDeriv& _v = v.getValue();\n double e = 0;\n\n VecDeriv Mv;\n d_massMatrix.getValue().mult( Mv, _v );\n\n for( unsigned int i=0 ; i<_v.size() ; i++ )\n e += _v[i] * Mv[i];\n\n return e\/2;\n}\n\ntemplate < class DataTypes >\ndouble PreassembledMass< DataTypes >::getPotentialEnergy( const core::MechanicalParams* mparams, const DataVecCoord& x ) const\n{\n serr<::getPotentialEnergy( mparams, x );\n\n\/\/ const VecCoord& _x = x.getValue();\n\n\/\/ VecCoord Mx\/* = d_massMatrix * _x*\/;\n\/\/ d_massMatrix.mult( Mx, _x );\n\n\/\/ SReal e = 0;\n\/\/ \/\/ gravity\n\/\/ Vec3d g ( this->getContext()->getGravity() );\n\/\/ Deriv theGravity;\n\/\/ DataTypes::set ( theGravity, g[0], g[1], g[2] );\n\/\/ for( unsigned int i=0 ; i<_x.size() ; i++ )\n\/\/ {\n\/\/ e -= theGravity*Mx[i];\n\/\/ }\n\/\/ return e;\n}\n\n\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::addGravityToV(const core::MechanicalParams* mparams, DataVecDeriv& d_v)\n{\n if(mparams)\n {\n VecDeriv& v = *d_v.beginEdit();\n\n \/\/ gravity\n Vec3 g ( this->getContext()->getGravity() * (mparams->dt()) );\n Deriv theGravity;\n DataTypes::set ( theGravity, g[0], g[1], g[2]);\n Deriv hg = theGravity * (mparams->dt());\n\n \/\/ add weight force\n for (unsigned int i=0; i\nvoid PreassembledMass< DataTypes >::addForce(const core::MechanicalParams* \/*mparams*\/, DataVecDeriv& f, const DataVecCoord& \/*x*\/, const DataVecDeriv& \/*v*\/)\n{\n \/\/if gravity was added separately (in solver's \"solve\" method), then nothing to do here\n if(this->m_separateGravity.getValue()) return;\n\n VecDeriv& _f = *f.beginEdit();\n\n \/\/ gravity\n Vec3 g ( this->getContext()->getGravity() );\n\/\/ Deriv theGravity;\n\/\/ DataTypes::set( theGravity, g[0], g[1], g[2] );\n \/\/ add weight\n\/\/ d_massMatrix.template addMul_by_line( _f, theGravity );\n\n \/\/TODO optimize this!!!\n VecDeriv gravities(_f.size());\n for(size_t i=0 ; i<_f.size() ; ++i )\n DataTypes::set( gravities[i], g[0], g[1], g[2] );\n d_massMatrix.getValue().addMult( _f, gravities );\n\n f.endEdit();\n}\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::addMToMatrix(const core::MechanicalParams *mparams, const sofa::core::behavior::MultiMatrixAccessor* matrix)\n{\n sofa::core::behavior::MultiMatrixAccessor::MatrixRef r = matrix->getMatrix(this->mstate);\n Real mFactor = (Real)mparams->mFactorIncludingRayleighDamping(this->rayleighMass.getValue());\n d_massMatrix.getValue().addToBaseMatrix( r.matrix, mFactor, r.offset );\n}\n\n} \/\/ namespace mass\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif \/\/ __PreassembledMass_INL\n[PreassembledMass] fixing warnings#ifndef __PreassembledMass_INL\n#define __PreassembledMass_INL\n\n#include \"PreassembledMass.h\"\n\n#include \n\n#include \n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mass\n{\n\n\/\/\/ removing no longer necessary mapped masses\nclass RemoveChildMassVisitor : public simulation::Visitor\n{\npublic:\n RemoveChildMassVisitor(const core::ExecParams* params)\n : simulation::Visitor(params)\n {\n }\n\n virtual Result processNodeTopDown(simulation::Node* node)\n {\n core::behavior::BaseMass* mass;\n node->get(mass);\n if( !dynamic_cast(mass) )\n node->removeObject(mass);\n return RESULT_CONTINUE;\n }\n\n};\n\n\n\nunsigned int BasePreassembledMass::s_instanciationCounter = 0;\n\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::init()\n{\n core::behavior::Mass::init();\n}\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::bwdInit()\n{\n\n MassMatrix& massMatrix = *d_massMatrix.beginEdit();\n\n \/\/ if the mass matrix is not given manually\n if( massMatrix.rows() != massMatrix.cols() || massMatrix.rows()!=(typename MassMatrix::Index)this->mstate->getMatrixSize() )\n {\n \/\/ perform assembly\n core::MechanicalParams mparams = *core::MechanicalParams::defaultInstance();\n mparams.setKFactor(0);\n mparams.setBFactor(0);\n mparams.setMFactor(1);\n mparams.setDt( this->getContext()->getDt() ); \/\/ should not be used but to be sure\n\n simulation::AssemblyVisitor assemblyVisitor( &mparams );\n this->getContext()->executeVisitor( &assemblyVisitor );\n component::linearsolver::AssembledSystem sys;\n assemblyVisitor.assemble( sys );\n massMatrix.compressedMatrix = sys.H;\n\n if( massMatrix.rows()!=(typename MassMatrix::Index)this->mstate->getMatrixSize() )\n {\n serr<<\"Are you sure that every independent dofs are in independent graph branches?\\n\";\n assert(false);\n }\n\n if( _instanciationNumber == 0 ) \/\/ only the first one (last bwdInit called) will call the mass removal\n {\n \/\/ std::cerr<getContext()->executeVisitor( &removeChildMassVisitor );\n\n typename LinkMassNodes::Container massNodes = l_massNodes.getValue();\n for ( unsigned int i = 0; i < massNodes.size() ; i++)\n {\n if( massNodes[i]->isActive() ) massNodes[i]->setActive( false );\n }\n }\n }\n\n\n \/\/ for human debug\n Real totalmass = 0;\n for(typename MassMatrix::Index r=0;rmstate->getMatrixBlockSize()<\nvoid PreassembledMass< DataTypes >::addMDx( const core::MechanicalParams*, DataVecDeriv& res, const DataVecDeriv& dx, double factor )\n{\n if( factor == 1.0 )\n {\n d_massMatrix.getValue().addMult( res, dx );\n }\n else\n {\n d_massMatrix.getValue().addMult( res, dx, factor );\n }\n}\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::accFromF( const core::MechanicalParams*, DataVecDeriv& \/*acc*\/, const DataVecDeriv& \/*f*\/ )\n{\n serr<<\"accFromF not yet implemented (the matrix inversion is needed)\"<\ndouble PreassembledMass< DataTypes >::getKineticEnergy( const core::MechanicalParams*, const DataVecDeriv& v ) const\n{\n const VecDeriv& _v = v.getValue();\n double e = 0;\n\n VecDeriv Mv;\n d_massMatrix.getValue().mult( Mv, _v );\n\n for( unsigned int i=0 ; i<_v.size() ; i++ )\n e += _v[i] * Mv[i];\n\n return e\/2;\n}\n\ntemplate < class DataTypes >\ndouble PreassembledMass< DataTypes >::getPotentialEnergy( const core::MechanicalParams* mparams, const DataVecCoord& x ) const\n{\n serr<::getPotentialEnergy( mparams, x );\n\n\/\/ const VecCoord& _x = x.getValue();\n\n\/\/ VecCoord Mx\/* = d_massMatrix * _x*\/;\n\/\/ d_massMatrix.mult( Mx, _x );\n\n\/\/ SReal e = 0;\n\/\/ \/\/ gravity\n\/\/ Vec3d g ( this->getContext()->getGravity() );\n\/\/ Deriv theGravity;\n\/\/ DataTypes::set ( theGravity, g[0], g[1], g[2] );\n\/\/ for( unsigned int i=0 ; i<_x.size() ; i++ )\n\/\/ {\n\/\/ e -= theGravity*Mx[i];\n\/\/ }\n\/\/ return e;\n}\n\n\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::addGravityToV(const core::MechanicalParams* mparams, DataVecDeriv& d_v)\n{\n if(mparams)\n {\n VecDeriv& v = *d_v.beginEdit();\n\n \/\/ gravity\n Vec3 g ( this->getContext()->getGravity() * (mparams->dt()) );\n Deriv theGravity;\n DataTypes::set ( theGravity, g[0], g[1], g[2]);\n Deriv hg = theGravity * (mparams->dt());\n\n \/\/ add weight force\n for (unsigned int i=0; i\nvoid PreassembledMass< DataTypes >::addForce(const core::MechanicalParams* \/*mparams*\/, DataVecDeriv& f, const DataVecCoord& \/*x*\/, const DataVecDeriv& \/*v*\/)\n{\n \/\/if gravity was added separately (in solver's \"solve\" method), then nothing to do here\n if(this->m_separateGravity.getValue()) return;\n\n VecDeriv& _f = *f.beginEdit();\n\n \/\/ gravity\n Vec3 g ( this->getContext()->getGravity() );\n\/\/ Deriv theGravity;\n\/\/ DataTypes::set( theGravity, g[0], g[1], g[2] );\n \/\/ add weight\n\/\/ d_massMatrix.template addMul_by_line( _f, theGravity );\n\n \/\/TODO optimize this!!!\n VecDeriv gravities(_f.size());\n for(size_t i=0 ; i<_f.size() ; ++i )\n DataTypes::set( gravities[i], g[0], g[1], g[2] );\n d_massMatrix.getValue().addMult( _f, gravities );\n\n f.endEdit();\n}\n\ntemplate < class DataTypes >\nvoid PreassembledMass< DataTypes >::addMToMatrix(const core::MechanicalParams *mparams, const sofa::core::behavior::MultiMatrixAccessor* matrix)\n{\n sofa::core::behavior::MultiMatrixAccessor::MatrixRef r = matrix->getMatrix(this->mstate);\n Real mFactor = (Real)mparams->mFactorIncludingRayleighDamping(this->rayleighMass.getValue());\n d_massMatrix.getValue().addToBaseMatrix( r.matrix, mFactor, r.offset );\n}\n\n} \/\/ namespace mass\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif \/\/ __PreassembledMass_INL\n<|endoftext|>"} {"text":"#ifndef __AIRINV_AIRINV_TYPES_HPP\n#define __AIRINV_AIRINV_TYPES_HPP\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n\/\/ Boost\n#include \n\/\/ StdAir\n#include \n#include \n\nnamespace AIRINV {\n\n \/\/ Forward declarations\n class AIRINV_Service;\n\n \/\/ \/\/\/\/\/\/\/\/\/ Exceptions \/\/\/\/\/\/\/\/\/\/\/\n class SegmentDateNotFoundException : public stdair::ParserException {\n public:\n \/** Constructor. *\/\n SegmentDateNotFoundException (const std::string& iWhat)\n : stdair::ParserException (iWhat) {}\n };\n\n class BookingException : public stdair::RootException {\n };\n\n\n \/\/ \/\/\/\/\/\/\/\/ Type definitions \/\/\/\/\/\/\/\/\/\n \/** Pointer on the AIRINV Service handler. *\/\n typedef boost::shared_ptr AIRINV_ServicePtr_T;\n \n \/** Typedef which defines a map of airline codes and the corresponding\n airline inventories. *\/\n typedef std::map AIRINV_ServicePtr_Map_T;\n\n \/** Define the FRAT5 curve. *\/\n typedef std::map FRAT5Curve_T;\n}\n#endif \/\/ __AIRINV_AIRINV_TYPES_HPP\n\n[Dev] Implemented, for DSim and SimCRS, the option of building the BOM tree either from parsing input files or from built-in samples.#ifndef __AIRINV_AIRINV_TYPES_HPP\n#define __AIRINV_AIRINV_TYPES_HPP\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n\/\/ Boost\n#include \n\/\/ StdAir\n#include \n#include \n\nnamespace AIRINV {\n\n \/\/ Forward declarations\n class AIRINV_Service;\n class AIRINV_Master_Service;\n\n\n \/\/ \/\/\/\/\/\/\/\/\/ Exceptions \/\/\/\/\/\/\/\/\/\/\/\n \/**\n * Specific exception when some BOM objects can not be found within\n * the inventory.\n *\/\n class SegmentDateNotFoundException : public stdair::ParserException {\n public:\n \/**\n * Constructor.\n *\/\n SegmentDateNotFoundException (const std::string& iWhat)\n : stdair::ParserException (iWhat) {}\n };\n\n \/**\n * Specific exception related to bookings made against the inventory.\n *\/\n class BookingException : public stdair::RootException {\n };\n\n\n \/\/ \/\/\/\/\/\/\/\/ Type definitions \/\/\/\/\/\/\/\/\/\n \/**\n * (Smart) Pointer on the AirInv (slave) service handler.\n *\/\n typedef boost::shared_ptr AIRINV_ServicePtr_T;\n \n \/**\n * (Smart) Pointer on the AirInv master service handler.\n *\/\n typedef boost::shared_ptr AIRINV_Master_ServicePtr_T;\n \n \/**\n * Type defining a map of airline codes and the corresponding\n * airline inventories.\n *\/\n typedef std::map AIRINV_ServicePtr_Map_T;\n\n \/**\n * Define the FRAT5 curve.\n *\/\n typedef std::map FRAT5Curve_T;\n\n}\n#endif \/\/ __AIRINV_AIRINV_TYPES_HPP\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace other{\n\nusing std::cout;\nusing std::endl;\nusing std::exception;\nusing std::numeric_limits;\ntypedef real T;\ntypedef Vector TV2;\ntypedef Vector TV3;\ntypedef Vector TV4;\n\nPropBase::PropBase()\n : hidden(false)\n , required(false)\n , abbrev(0)\n{}\n\nPropBase::~PropBase() {}\n\nvoid PropBase::dump(int indent) const {\n printf(\"%*sProp('%s',%s)\\n\",2*indent,\"\",name_().c_str(),value_str().c_str());\n}\n\n\/\/ Since PropBase doesn't by itself inherit from Object due to multiple inheritance woes,\n\/\/ we need a special wrapper class to expose Prop to python.\n\n#ifdef OTHER_PYTHON\nRef make_prop_shape(const string& n, NdArray a, RawArray shape) {\n const int rank = a.rank();\n OTHER_ASSERT(rank==shape.size());\n const int fixed = shape.count_matches(-1);\n if (shape.slice(0,fixed).count_matches(-1)!=fixed)\n throw ValueError(format(\"Prop: -1's in shape must occur at the beginning, got %s\",str(shape)));\n for (int i=fixed;i>(n,vec(a[0],a[1]));\n if (shape[0]==3) return new_>(n,vec(a[0],a[1],a[2]));\n if (shape[0]==4) return new_>(n,vec(a[0],a[1],a[2],a[3]));\n } else if (rank==1 && fixed==1)\n return new_>>(n,a.flat);\n else if (rank==2 && fixed==1) {\n if (shape[1]==2) return new_>>(n,vector_view_own<2>(a.flat));\n if (shape[1]==3) return new_>>(n,vector_view_own<3>(a.flat));\n if (shape[1]==4) return new_>>(n,vector_view_own<4>(a.flat));\n }\n throw NotImplementedError(format(\"Prop: shape specification %s is not implemented\",str(shape)));\n}\n\nRef make_prop(const string& n, PyObject* value) {\n \/\/ If the value has known simple type, make the corresponding property\n if (PyBool_Check(value))\n return new_>(n,from_python(value));\n if (PyInt_Check(value))\n return new_>(n,from_python(value));\n if (PyFloat_Check(value))\n return new_>(n,from_python(value));\n if (PyString_Check(value))\n return new_>(n,from_python(value));\n if (PySequence_Check(value)) {\n if (PyArray_Check(value)) {\n if (rotations_check(value))\n return new_>>(n,from_python>(value));\n if (rotations_check(value))\n return new_>>(n,from_python>(value));\n if (frames_check(value))\n return new_>>(n,from_python>(value));\n if (frames_check(value))\n return new_>>(n,from_python>(value));\n }\n NdArray a;\n try {\n a = from_python>(value);\n } catch (const exception&) {\n \/\/ If the NdArray conversion fails, squelch the error and fall back to our default\n PyErr_Clear();\n }\n return make_prop_shape(n,a,a.shape);\n }\n\n \/\/ Default to a property containing an arbitrary python object\n return new_>>(n,ref(*value));\n}\n#endif\n\ntemplate PropClamp::PropClamp()\n : min(-numeric_limits::max())\n , max( numeric_limits::max())\n , step(max) {}\n\ntemplate PropClamp::~PropClamp() {}\n\ntemplate Prop& PropClamp::set_min(const PropRef p, real alpha) {\n Prop& self = this->self();\n OTHER_ASSERT(p->name != self.name && !(p->prop_min && p->prop_min->x->name == self.name));\n prop_min.reset(new Tuple,Ref,real>(p,listen(p,curry(&Self::minimize,this)),alpha));\n minimize();\n return self;\n}\n\ntemplate Prop& PropClamp::set_max(const PropRef p, real alpha) {\n auto& self = this->self();\n OTHER_ASSERT(p->name != self.name && !(p->prop_max && p->prop_max->x->name == self.name));\n prop_max.reset(new Tuple,Ref,real>(p,listen(p,curry(&Self::maximize,this)),alpha));\n maximize();\n return self;\n}\n\ntemplate void PropClamp::minimize() {\n const auto& self = this->self();\n min = T(prop_min->x()*prop_min->z);\n T v = self();\n self.set_value(v < min ? min : v); \/\/a bit dirty, but we want to trigger update to toolbar\n}\n\ntemplate void PropClamp::maximize() {\n const auto& self = this->self();\n max = T(prop_max->x()*prop_max->z);\n T v = self();\n self.set_value(v > max ? max : v); \/\/a bit dirty, but we want to trigger update to toolbar\n}\n\ntemplate struct PropClamp;\ntemplate struct PropClamp;\n\n#ifdef OTHER_PYTHON\n\nPyObject* to_python(const PropBase& prop) {\n return to_python(prop.base());\n}\n\nPyObject* ptr_to_python(const PropBase* prop) {\n return (PyObject*)&prop->base()-1;\n}\n\nPropBase& FromPython::convert(PyObject* object) {\n ValueBase& value = from_python(object);\n if (PropBase* prop = dynamic_cast(&value))\n return *prop;\n throw TypeError(\"expected Prop, got Value\");\n}\n\nPropBase& prop_from_python(PyObject* object, const type_info& goal) {\n PropBase& self = from_python(object);\n const type_info& type = self.type();\n if (type==goal || !strcmp(type.name(),goal.name()))\n return self;\n throw TypeError(format(\"expected Prop<%s>, got Prop<%s>\",goal.name(),self.type().name()));\n}\n\nnamespace {\nstruct Unusable {\n bool operator==(Unusable) const { return true; }\n friend ostream& operator<<(ostream& output, Unusable) { return output; }\n};\n}\n\n\/\/ A Prop with a non-python convertible type\nstatic Ref unusable_prop_test() {\n BOOST_MPL_ASSERT((has_to_python));\n return new_>(\"unusable\",Unusable());\n}\n\n#endif\n\n}\nusing namespace other;\n\nvoid wrap_prop() {\n#ifdef OTHER_PYTHON\n OTHER_FUNCTION(make_prop)\n OTHER_FUNCTION(make_prop_shape)\n OTHER_FUNCTION(unusable_prop_test)\n#endif\n}\nProp: Make make_prop fall back to default in more cases#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace other{\n\nusing std::cout;\nusing std::endl;\nusing std::exception;\nusing std::numeric_limits;\ntypedef real T;\ntypedef Vector TV2;\ntypedef Vector TV3;\ntypedef Vector TV4;\n\nPropBase::PropBase()\n : hidden(false)\n , required(false)\n , abbrev(0)\n{}\n\nPropBase::~PropBase() {}\n\nvoid PropBase::dump(int indent) const {\n printf(\"%*sProp('%s',%s)\\n\",2*indent,\"\",name_().c_str(),value_str().c_str());\n}\n\n\/\/ Since PropBase doesn't by itself inherit from Object due to multiple inheritance woes,\n\/\/ we need a special wrapper class to expose Prop to python.\n\n#ifdef OTHER_PYTHON\nRef make_prop_shape(const string& n, NdArray a, RawArray shape) {\n const int rank = a.rank();\n OTHER_ASSERT(rank==shape.size());\n const int fixed = shape.count_matches(-1);\n if (shape.slice(0,fixed).count_matches(-1)!=fixed)\n throw ValueError(format(\"Prop: -1's in shape must occur at the beginning, got %s\",str(shape)));\n for (int i=fixed;i>(n,vec(a[0],a[1]));\n if (shape[0]==3) return new_>(n,vec(a[0],a[1],a[2]));\n if (shape[0]==4) return new_>(n,vec(a[0],a[1],a[2],a[3]));\n } else if (rank==1 && fixed==1)\n return new_>>(n,a.flat);\n else if (rank==2 && fixed==1) {\n if (shape[1]==2) return new_>>(n,vector_view_own<2>(a.flat));\n if (shape[1]==3) return new_>>(n,vector_view_own<3>(a.flat));\n if (shape[1]==4) return new_>>(n,vector_view_own<4>(a.flat));\n }\n throw NotImplementedError(format(\"Prop: shape specification %s is not implemented\",str(shape)));\n}\n\nRef make_prop(const string& n, PyObject* value) {\n \/\/ If the value has known simple type, make the corresponding property\n if (PyBool_Check(value))\n return new_>(n,from_python(value));\n if (PyInt_Check(value))\n return new_>(n,from_python(value));\n if (PyFloat_Check(value))\n return new_>(n,from_python(value));\n if (PyString_Check(value))\n return new_>(n,from_python(value));\n if (PySequence_Check(value)) {\n if (PyArray_Check(value)) {\n if (rotations_check(value))\n return new_>>(n,from_python>(value));\n if (rotations_check(value))\n return new_>>(n,from_python>(value));\n if (frames_check(value))\n return new_>>(n,from_python>(value));\n if (frames_check(value))\n return new_>>(n,from_python>(value));\n }\n NdArray a;\n try {\n a = from_python>(value);\n return make_prop_shape(n,a,a.shape);\n } catch (const exception&) {\n \/\/ If the conversion fails, squelch the error and fall back to our default\n PyErr_Clear();\n }\n }\n\n \/\/ Default to a property containing an arbitrary python object\n return new_>>(n,ref(*value));\n}\n#endif\n\ntemplate PropClamp::PropClamp()\n : min(-numeric_limits::max())\n , max( numeric_limits::max())\n , step(max) {}\n\ntemplate PropClamp::~PropClamp() {}\n\ntemplate Prop& PropClamp::set_min(const PropRef p, real alpha) {\n Prop& self = this->self();\n OTHER_ASSERT(p->name != self.name && !(p->prop_min && p->prop_min->x->name == self.name));\n prop_min.reset(new Tuple,Ref,real>(p,listen(p,curry(&Self::minimize,this)),alpha));\n minimize();\n return self;\n}\n\ntemplate Prop& PropClamp::set_max(const PropRef p, real alpha) {\n auto& self = this->self();\n OTHER_ASSERT(p->name != self.name && !(p->prop_max && p->prop_max->x->name == self.name));\n prop_max.reset(new Tuple,Ref,real>(p,listen(p,curry(&Self::maximize,this)),alpha));\n maximize();\n return self;\n}\n\ntemplate void PropClamp::minimize() {\n const auto& self = this->self();\n min = T(prop_min->x()*prop_min->z);\n T v = self();\n self.set_value(v < min ? min : v); \/\/a bit dirty, but we want to trigger update to toolbar\n}\n\ntemplate void PropClamp::maximize() {\n const auto& self = this->self();\n max = T(prop_max->x()*prop_max->z);\n T v = self();\n self.set_value(v > max ? max : v); \/\/a bit dirty, but we want to trigger update to toolbar\n}\n\ntemplate struct PropClamp;\ntemplate struct PropClamp;\n\n#ifdef OTHER_PYTHON\n\nPyObject* to_python(const PropBase& prop) {\n return to_python(prop.base());\n}\n\nPyObject* ptr_to_python(const PropBase* prop) {\n return (PyObject*)&prop->base()-1;\n}\n\nPropBase& FromPython::convert(PyObject* object) {\n ValueBase& value = from_python(object);\n if (PropBase* prop = dynamic_cast(&value))\n return *prop;\n throw TypeError(\"expected Prop, got Value\");\n}\n\nPropBase& prop_from_python(PyObject* object, const type_info& goal) {\n PropBase& self = from_python(object);\n const type_info& type = self.type();\n if (type==goal || !strcmp(type.name(),goal.name()))\n return self;\n throw TypeError(format(\"expected Prop<%s>, got Prop<%s>\",goal.name(),self.type().name()));\n}\n\nnamespace {\nstruct Unusable {\n bool operator==(Unusable) const { return true; }\n friend ostream& operator<<(ostream& output, Unusable) { return output; }\n};\n}\n\n\/\/ A Prop with a non-python convertible type\nstatic Ref unusable_prop_test() {\n BOOST_MPL_ASSERT((has_to_python));\n return new_>(\"unusable\",Unusable());\n}\n\n#endif\n\n}\nusing namespace other;\n\nvoid wrap_prop() {\n#ifdef OTHER_PYTHON\n OTHER_FUNCTION(make_prop)\n OTHER_FUNCTION(make_prop_shape)\n OTHER_FUNCTION(unusable_prop_test)\n#endif\n}\n<|endoftext|>"} {"text":"\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#define _WINSOCK2API_\n#endif\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ class interface header\n#include \"URLManager.h\"\n\n\/\/ system headers\n#ifdef _WIN32\n#include \n#endif\n#ifdef HAVE_CURL\n#include \n#endif\n#include \n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n#include \"StateDatabase.h\"\n\n\ntemplate <>\nURLManager* Singleton::_instance = (URLManager*)0;\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);\n#endif \/\/ HAVE_CURL\n\nbool URLManager::getURL(const std::string URL, std::string &data)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n char* newData = (char*)malloc(theLen + 1);\n memcpy(newData, theData, theLen);\n newData[theLen] = 0;\n\n data = newData;\n free(newData);\n\n return true;\n}\n\nbool URLManager::getURL(const std::string URL, void **data, unsigned int& size)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n *data = malloc(theLen);\n memcpy(*data, theData, theLen);\n size = theLen;\n return true;\n}\n\nvoid URLManager::freeURLData(void *data)\n{\n free(data);\n}\n\nURLManager::URLManager()\n{\n easyHandle = NULL;\n theData = NULL;\n theLen = 0;\n\n#ifdef HAVE_CURL\n CURLcode curlResult;\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((curlResult = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", curlResult);\n#endif\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n CURLcode result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_WRITEFUNCTION, writeFunction);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_FILE, this);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n#endif\n}\n\nURLManager::~URLManager()\n{\n clearInternal();\n\n#ifdef HAVE_CURL\n if (easyHandle)\n curl_easy_cleanup((CURL*)easyHandle);\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n curl_global_cleanup();\n#endif\n\n#endif\n}\n\nvoid URLManager::collectData(char* ptr, int len)\n{\n unsigned char\t*newData = (unsigned char*)malloc(theLen + len);\n if (theData)\n memcpy(newData, theData, theLen);\n\n memcpy(&(newData[theLen]), ptr, len);\n theLen += len;\n\n free(theData);\n theData = newData;\n}\n\nvoid URLManager::clearInternal()\n{\n if (theData)\n free (theData);\n\n theData = NULL;\n theLen = 0;\n}\n\n#ifdef HAVE_CURL\nbool URLManager::beginGet(const std::string URL)\n#else\nbool URLManager::beginGet(const std::string)\n#endif\n{\n#ifdef HAVE_CURL\n CURLcode result = CURLE_OK;\n if (!easyHandle) {\n return false;\n }\n\n float timeout = 15;\n if (BZDB.isSet(\"httpTimeout\"))\n timeout = BZDB.eval(\"httpTimeout\");\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_NOSIGNAL, true);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, URL.c_str());\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n \/\/ FIXME: This could block for a _long_ time.\n result = curl_easy_perform((CURL*)easyHandle);\n if (result == (CURLcode)CURLOPT_ERRORBUFFER) {\n DEBUG1(\"Error: server reported: %d\\n\", result);\n return false;\n } else if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, NULL);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n if (!theData)\n return false;\n\n return true;\n#else\n return false;\n#endif \/\/ HAVE_CURL\n}\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n int len = size * nmemb;\n ((URLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n#endif \/\/ HAVE_CURL\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nbetter not declare if your not going to use it\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#define _WINSOCK2API_\n#endif\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ class interface header\n#include \"URLManager.h\"\n\n\/\/ system headers\n#ifdef _WIN32\n#include \n#endif\n#ifdef HAVE_CURL\n#include \n#endif\n#include \n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n#include \"StateDatabase.h\"\n\n\ntemplate <>\nURLManager* Singleton::_instance = (URLManager*)0;\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);\n#endif \/\/ HAVE_CURL\n\nbool URLManager::getURL(const std::string URL, std::string &data)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n char* newData = (char*)malloc(theLen + 1);\n memcpy(newData, theData, theLen);\n newData[theLen] = 0;\n\n data = newData;\n free(newData);\n\n return true;\n}\n\nbool URLManager::getURL(const std::string URL, void **data, unsigned int& size)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n *data = malloc(theLen);\n memcpy(*data, theData, theLen);\n size = theLen;\n return true;\n}\n\nvoid URLManager::freeURLData(void *data)\n{\n free(data);\n}\n\nURLManager::URLManager()\n{\n easyHandle = NULL;\n theData = NULL;\n theLen = 0;\n\n#ifdef HAVE_CURL\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n CURLcode curlResult;\n if ((curlResult = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", curlResult);\n#endif\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n CURLcode result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_WRITEFUNCTION, writeFunction);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_FILE, this);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n#endif\n}\n\nURLManager::~URLManager()\n{\n clearInternal();\n\n#ifdef HAVE_CURL\n if (easyHandle)\n curl_easy_cleanup((CURL*)easyHandle);\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n curl_global_cleanup();\n#endif\n\n#endif\n}\n\nvoid URLManager::collectData(char* ptr, int len)\n{\n unsigned char\t*newData = (unsigned char*)malloc(theLen + len);\n if (theData)\n memcpy(newData, theData, theLen);\n\n memcpy(&(newData[theLen]), ptr, len);\n theLen += len;\n\n free(theData);\n theData = newData;\n}\n\nvoid URLManager::clearInternal()\n{\n if (theData)\n free (theData);\n\n theData = NULL;\n theLen = 0;\n}\n\n#ifdef HAVE_CURL\nbool URLManager::beginGet(const std::string URL)\n#else\nbool URLManager::beginGet(const std::string)\n#endif\n{\n#ifdef HAVE_CURL\n CURLcode result = CURLE_OK;\n if (!easyHandle) {\n return false;\n }\n\n float timeout = 15;\n if (BZDB.isSet(\"httpTimeout\"))\n timeout = BZDB.eval(\"httpTimeout\");\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_NOSIGNAL, true);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, URL.c_str());\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n \/\/ FIXME: This could block for a _long_ time.\n result = curl_easy_perform((CURL*)easyHandle);\n if (result == (CURLcode)CURLOPT_ERRORBUFFER) {\n DEBUG1(\"Error: server reported: %d\\n\", result);\n return false;\n } else if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, NULL);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n if (!theData)\n return false;\n\n return true;\n#else\n return false;\n#endif \/\/ HAVE_CURL\n}\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n int len = size * nmemb;\n ((URLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n#endif \/\/ HAVE_CURL\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"#include \"HOTP.h\"\n\n\/**\n* Converts a 64bit int to char\n*\/\nconst unsigned char * HOTP::toChar(int64_t number) const\n{\n\tunsigned char *temp=new unsigned char[8];\/\/8bytes (64bit)\n\n\tfor(int i=8-1;i>=0;--i)\/\/loop through number and copy to char\n\t{\n\t\ttemp[i]=(number&0xff);\n\t\tnumber>>=8;\n\t}\n\treturn temp;\n}\n\n\n\/**\n* convert a 8byte char to int\n*\/\nint64_t HOTP::toInt(const char*& number)\n{\n\treturn\n\t\t(((int64_t)number[0]<<56) & 0xff00000000000000U) |\n\t\t(((int64_t)number[1]<<48) & 0x00ff000000000000U) |\n\t\t(((int64_t)number[2]<<40) & 0x0000ff0000000000U) |\n\t\t(((int64_t)number[3]<<32) & 0x000000ff00000000U) |\n\t\t(((int64_t)number[4]<<24) & 0x00000000ff000000U) |\n\t\t(((int64_t)number[5]<<16) & 0x0000000000ff0000U) |\n\t\t(((int64_t)number[6]<<8) & 0x000000000000ff00U) |\n\t\t(((int64_t)number[7])\t & 0x00000000000000ffU);\n}\n\n\nunsigned char * HOTP::generateHmac(const EVP_MD* algo)\n{\n\treturn HMAC(algo,\n\t\t\t\tthis->secret,\/\/shared secret\n\t\t\t\tthis->secretLength,\/\/length of secret\n\t\t\t\tthis->toChar(this->counter),\/\/counter to char\n\t\t\t\t8,\/\/length of counter (8bytes)\n\t\t\t\t0,0);\/\/don't copy to any vars\n}\n\n\/**\n* Set length of one time password, and generates a HMAC-SHA-1 \n* from input secret and counter\n*\/\nvoid HOTP::initOTP(int codeLength)\n{\n\tthis->setLength(codeLength);\n\tthis->setHmac(this->generateHmac());\n}\n\n\nHOTP::HOTP(unsigned char * secret,int secretLength,int codeLength,int64_t c) : OTP()\n{\n\tthis->counter=c;\n\tthis->secretLength=secretLength;\n\t\n\tthis->secret=new unsigned char[this->secretLength];\n\n\tfor(int i=0;isecretLength;++i)\n\t\tthis->secret[i]=secret[i];\n\tthis->secret[this->secretLength]='\\0';\n\tthis->initOTP(codeLength);\n}\n\nint64_t HOTP::getCounter()\n{\n\treturn this->counter;\n}\n\nvoid HOTP::setCounter(int64_t c)\n{\n\tthis->counter=c;\n}added length to setHmac#include \"HOTP.h\"\n#include \n#include \n\/**\n* Converts a 64bit int to char\n*\/\nconst unsigned char * HOTP::toChar(int64_t number) const\n{\n\tunsigned char *temp=new unsigned char[8];\/\/8bytes (64bit)\n\n\tfor(int i=8-1;i>=0;--i)\/\/loop through number and copy to char\n\t{\n\t\ttemp[i]=(number&0xff);\n\t\tnumber>>=8;\n\t}\n\treturn temp;\n}\n\n\n\/**\n* convert a 8byte char to int\n*\/\nint64_t HOTP::toInt(const char*& number)\n{\n\treturn\n\t\t(((int64_t)number[0]<<56) & 0xff00000000000000U) |\n\t\t(((int64_t)number[1]<<48) & 0x00ff000000000000U) |\n\t\t(((int64_t)number[2]<<40) & 0x0000ff0000000000U) |\n\t\t(((int64_t)number[3]<<32) & 0x000000ff00000000U) |\n\t\t(((int64_t)number[4]<<24) & 0x00000000ff000000U) |\n\t\t(((int64_t)number[5]<<16) & 0x0000000000ff0000U) |\n\t\t(((int64_t)number[6]<<8) & 0x000000000000ff00U) |\n\t\t(((int64_t)number[7])\t & 0x00000000000000ffU);\n}\n\n\nunsigned char * HOTP::generateHmac(const EVP_MD* algo)\n{\n\treturn HMAC(algo,\n\t\t\t\tthis->secret,\/\/shared secret\n\t\t\t\tthis->secretLength,\/\/length of secret\n\t\t\t\tthis->toChar(this->counter),\/\/counter to char\n\t\t\t\t8,\/\/length of counter (8bytes)\n\t\t\t\t0,0);\/\/don't copy to any vars\n}\n\n\/**\n* Set length of one time password, and generates a HMAC-SHA-1 \n* from input secret and counter\n*\/\nvoid HOTP::initOTP(int codeLength)\n{\n\tthis->setLength(codeLength);\n\tthis->setHmac(this->generateHmac(),20);\n}\n\n\nHOTP::HOTP(unsigned char * secret,int secretLength,int codeLength,int64_t c) : OTP()\n{\n\tthis->counter=c;\n\tthis->secretLength=secretLength;\n\t\n\tthis->secret=new unsigned char[this->secretLength];\n\n\tfor(int i=0;isecretLength;++i)\n\t\tthis->secret[i]=secret[i];\n\tthis->secret[this->secretLength]='\\0';\n\tthis->initOTP(codeLength);\n}\n\nint64_t HOTP::getCounter()\n{\n\treturn this->counter;\n}\n\nvoid HOTP::setCounter(int64_t c)\n{\n\tthis->counter=c;\n}<|endoftext|>"} {"text":"\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include \n#include \"GamepadDeviceIOKit.hpp\"\n#include \"InputSystemMacOS.hpp\"\n#include \"..\/GamepadConfig.hpp\"\n#include \"..\/..\/utils\/Utils.hpp\"\n\nnamespace ouzel::input::macos\n{\n namespace\n {\n constexpr float thumbDeadzone = 0.2F;\n\n void deviceInput(void* ctx, IOReturn, void*, IOHIDValueRef value)\n {\n auto gamepadDevice = static_cast(ctx);\n gamepadDevice->handleInput(value);\n }\n }\n\n GamepadDeviceIOKit::GamepadDeviceIOKit(InputSystem& initInputSystem,\n DeviceId initId,\n IOHIDDeviceRef initDevice):\n GamepadDevice(initInputSystem, initId),\n device(initDevice)\n {\n if (const auto result = IOHIDDeviceOpen(device, kIOHIDOptionsTypeNone); result != kIOReturnSuccess)\n throw std::system_error(result, getErrorCategory(), \"Failed to open HID device\");\n\n const auto productName = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey)));\n if (productName)\n {\n if (const char* deviceName = CFStringGetCStringPtr(productName, kCFStringEncodingUTF8))\n name = deviceName;\n else\n {\n const auto stringLength = CFStringGetLength(productName);\n std::vector temp(static_cast(CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8)) + 1);\n if (CFStringGetCString(productName, temp.data(), static_cast(temp.size()), kCFStringEncodingUTF8))\n name = temp.data();\n }\n }\n\n const auto vendor = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVendorIDKey)));\n if (!vendor)\n throw std::runtime_error(\"Failed to get vendor ID\");\n\n std::int32_t vendorId;\n if (!CFNumberGetValue(vendor, kCFNumberSInt32Type, &vendorId))\n throw std::runtime_error(\"Failed to get vendor ID\");\n\n const auto product = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductIDKey)));\n if (!product)\n throw std::runtime_error(\"Failed to get product ID\");\n\n std::int32_t productId;\n if (!CFNumberGetValue(product, kCFNumberSInt32Type, &productId))\n throw std::runtime_error(\"Failed to get product ID\");\n\n const auto& gamepadConfig = getGamepadConfig(vendorId, productId);\n\n static const std::unordered_map axisUsageMap = {\n {kHIDUsage_GD_X, 0},\n {kHIDUsage_GD_Y, 1},\n {kHIDUsage_GD_Z, 2},\n {kHIDUsage_GD_Rx, 3},\n {kHIDUsage_GD_Ry, 4},\n {kHIDUsage_GD_Rz, 5}\n };\n\n const auto elementArray = IOHIDDeviceCopyMatchingElements(device, nullptr, kIOHIDOptionsTypeNone);\n const auto count = CFArrayGetCount(elementArray);\n\n for (CFIndex i = 0; i < count; ++i)\n {\n auto getElement = [](CFArrayRef elementArray, CFIndex i) noexcept {\n auto arrayValue = CFArrayGetValueAtIndex(elementArray, i);\n return bitCast(arrayValue);\n };\n\n const auto element = getElement(elementArray, i);\n const auto type = IOHIDElementGetType(element);\n const auto usagePage = IOHIDElementGetUsagePage(element);\n const auto usage = IOHIDElementGetUsage(element);\n\n if (usage == kHIDUsage_GD_Hatswitch)\n hatElement = element;\n\n if (usage >= kHIDUsage_Button_1 && usage < kHIDUsage_Button_1 + 24)\n {\n Button button;\n button.button = gamepadConfig.buttonMap[usage - kHIDUsage_Button_1];\n buttons.insert(std::pair(element, button));\n }\n\n if ((type == kIOHIDElementTypeInput_Misc || type == kIOHIDElementTypeInput_Axis) &&\n usagePage == kHIDPage_GenericDesktop)\n {\n auto usageIterator = axisUsageMap.find(usage);\n\n if (usageIterator != axisUsageMap.end())\n {\n const std::size_t index = usageIterator->second;\n\n Axis axis;\n axis.axis = gamepadConfig.axisMap[index];\n axis.min = IOHIDElementGetLogicalMin(element);\n axis.max = IOHIDElementGetLogicalMax(element);\n axis.range = axis.max - axis.min;\n\n switch (gamepadConfig.axisMap[index])\n {\n case Gamepad::Axis::none:\n break;\n case Gamepad::Axis::leftThumbX:\n axis.negativeButton = Gamepad::Button::leftThumbLeft;\n axis.positiveButton = Gamepad::Button::leftThumbRight;\n break;\n case Gamepad::Axis::leftThumbY:\n axis.negativeButton = Gamepad::Button::leftThumbUp;\n axis.positiveButton = Gamepad::Button::leftThumbDown;\n break;\n case Gamepad::Axis::rightThumbX:\n axis.negativeButton = Gamepad::Button::rightThumbLeft;\n axis.positiveButton = Gamepad::Button::rightThumbRight;\n break;\n case Gamepad::Axis::rightThumbY:\n axis.negativeButton = Gamepad::Button::rightThumbUp;\n axis.positiveButton = Gamepad::Button::rightThumbDown;\n break;\n case Gamepad::Axis::leftTrigger:\n axis.negativeButton = Gamepad::Button::leftTrigger;\n axis.positiveButton = Gamepad::Button::leftTrigger;\n hasLeftTrigger = true;\n break;\n case Gamepad::Axis::rightTrigger:\n axis.negativeButton = Gamepad::Button::rightTrigger;\n axis.positiveButton = Gamepad::Button::rightTrigger;\n hasRightTrigger = true;\n break;\n }\n\n axes.insert(std::pair(element, axis));\n }\n }\n }\n\n CFRelease(elementArray);\n\n IOHIDDeviceRegisterInputValueCallback(device, deviceInput, this);\n }\n\n void GamepadDeviceIOKit::handleInput(IOHIDValueRef value)\n {\n const auto element = IOHIDValueGetElement(value);\n const auto newValue = IOHIDValueGetIntegerValue(value);\n\n if (element == hatElement)\n {\n const auto oldHatValue = static_cast(hatValue);\n const std::uint32_t oldBitmask = (oldHatValue >= 8) ? 0 : (1 << (oldHatValue \/ 2)) | \/\/ first bit\n (1 << (oldHatValue \/ 2 + oldHatValue % 2)) % 4; \/\/ second bit\n\n const std::uint32_t newBitmask = (newValue >= 8) ? 0 : (1 << (newValue \/ 2)) | \/\/ first bit\n (1 << (newValue \/ 2 + newValue % 2)) % 4; \/\/ second bit\n\n if ((oldBitmask & 0x01) != (newBitmask & 0x01))\n handleButtonValueChange(Gamepad::Button::dPadUp,\n (newBitmask & 0x01) > 0,\n (newBitmask & 0x01) > 0 ? 1.0F : 0.0F);\n if ((oldBitmask & 0x02) != (newBitmask & 0x02))\n handleButtonValueChange(Gamepad::Button::dPadRight,\n (newBitmask & 0x02) > 0,\n (newBitmask & 0x02) > 0 ? 1.0F : 0.0F);\n if ((oldBitmask & 0x04) != (newBitmask & 0x04))\n handleButtonValueChange(Gamepad::Button::dPadDown,\n (newBitmask & 0x04) > 0,\n (newBitmask & 0x04) > 0 ? 1.0F : 0.0F);\n if ((oldBitmask & 0x08) != (newBitmask & 0x08))\n handleButtonValueChange(Gamepad::Button::dPadLeft,\n (newBitmask & 0x08) > 0,\n (newBitmask & 0x08) > 0 ? 1.0F : 0.0F);\n\n hatValue = newValue;\n }\n\n auto buttonIterator = buttons.find(element);\n\n if (buttonIterator != buttons.end())\n {\n Button& button = buttonIterator->second;\n\n if ((button.button != Gamepad::Button::leftTrigger || !hasLeftTrigger) &&\n (button.button != Gamepad::Button::rightTrigger || !hasRightTrigger))\n handleButtonValueChange(button.button, newValue > 0, (newValue > 0) ? 1.0F : 0.0F);\n\n button.value = newValue;\n }\n\n auto axisIterator = axes.find(element);\n\n if (axisIterator != axes.end())\n {\n Axis& axis = axisIterator->second;\n\n handleAxisChange(axis.value,\n newValue,\n axis.min, axis.range,\n axis.negativeButton, axis.positiveButton);\n\n axis.value = newValue;\n }\n }\n\n void GamepadDeviceIOKit::handleAxisChange(CFIndex oldValue, CFIndex newValue,\n CFIndex min, CFIndex range,\n Gamepad::Button negativeButton,\n Gamepad::Button positiveButton)\n {\n if (negativeButton == positiveButton)\n {\n const auto floatValue = static_cast(newValue - min) \/ range;\n\n handleButtonValueChange(negativeButton,\n floatValue > 0.0F,\n floatValue);\n }\n else\n {\n const auto floatValue = 2.0F * static_cast(newValue - min) \/ range - 1.0F;\n\n if (floatValue > 0.0F)\n handleButtonValueChange(positiveButton,\n floatValue > thumbDeadzone,\n floatValue);\n else if (floatValue < 0.0F)\n handleButtonValueChange(negativeButton,\n -floatValue > thumbDeadzone,\n -floatValue);\n else \/\/ thumbstick is 0\n {\n if (oldValue > newValue)\n handleButtonValueChange(positiveButton, false, 0.0F);\n else\n handleButtonValueChange(negativeButton, false, 0.0F);\n }\n }\n }\n}\nUse const\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include \n#include \"GamepadDeviceIOKit.hpp\"\n#include \"InputSystemMacOS.hpp\"\n#include \"..\/GamepadConfig.hpp\"\n#include \"..\/..\/utils\/Utils.hpp\"\n\nnamespace ouzel::input::macos\n{\n namespace\n {\n constexpr float thumbDeadzone = 0.2F;\n\n void deviceInput(void* ctx, IOReturn, void*, IOHIDValueRef value)\n {\n auto gamepadDevice = static_cast(ctx);\n gamepadDevice->handleInput(value);\n }\n }\n\n GamepadDeviceIOKit::GamepadDeviceIOKit(InputSystem& initInputSystem,\n DeviceId initId,\n IOHIDDeviceRef initDevice):\n GamepadDevice(initInputSystem, initId),\n device(initDevice)\n {\n if (const auto result = IOHIDDeviceOpen(device, kIOHIDOptionsTypeNone); result != kIOReturnSuccess)\n throw std::system_error(result, getErrorCategory(), \"Failed to open HID device\");\n\n const auto productName = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey)));\n if (productName)\n {\n if (const char* deviceName = CFStringGetCStringPtr(productName, kCFStringEncodingUTF8))\n name = deviceName;\n else\n {\n const auto stringLength = CFStringGetLength(productName);\n std::vector temp(static_cast(CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8)) + 1);\n if (CFStringGetCString(productName, temp.data(), static_cast(temp.size()), kCFStringEncodingUTF8))\n name = temp.data();\n }\n }\n\n const auto vendor = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVendorIDKey)));\n if (!vendor)\n throw std::runtime_error(\"Failed to get vendor ID\");\n\n std::int32_t vendorId;\n if (!CFNumberGetValue(vendor, kCFNumberSInt32Type, &vendorId))\n throw std::runtime_error(\"Failed to get vendor ID\");\n\n const auto product = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductIDKey)));\n if (!product)\n throw std::runtime_error(\"Failed to get product ID\");\n\n std::int32_t productId;\n if (!CFNumberGetValue(product, kCFNumberSInt32Type, &productId))\n throw std::runtime_error(\"Failed to get product ID\");\n\n const auto& gamepadConfig = getGamepadConfig(vendorId, productId);\n\n static const std::unordered_map axisUsageMap = {\n {kHIDUsage_GD_X, 0},\n {kHIDUsage_GD_Y, 1},\n {kHIDUsage_GD_Z, 2},\n {kHIDUsage_GD_Rx, 3},\n {kHIDUsage_GD_Ry, 4},\n {kHIDUsage_GD_Rz, 5}\n };\n\n const auto elementArray = IOHIDDeviceCopyMatchingElements(device, nullptr, kIOHIDOptionsTypeNone);\n const auto count = CFArrayGetCount(elementArray);\n\n for (CFIndex i = 0; i < count; ++i)\n {\n auto getElement = [](CFArrayRef elementArray, CFIndex i) noexcept {\n auto arrayValue = CFArrayGetValueAtIndex(elementArray, i);\n return bitCast(arrayValue);\n };\n\n const auto element = getElement(elementArray, i);\n const auto type = IOHIDElementGetType(element);\n const auto usagePage = IOHIDElementGetUsagePage(element);\n const auto usage = IOHIDElementGetUsage(element);\n\n if (usage == kHIDUsage_GD_Hatswitch)\n hatElement = element;\n\n if (usage >= kHIDUsage_Button_1 && usage < kHIDUsage_Button_1 + 24)\n {\n Button button;\n button.button = gamepadConfig.buttonMap[usage - kHIDUsage_Button_1];\n buttons.insert(std::pair(element, button));\n }\n\n if ((type == kIOHIDElementTypeInput_Misc || type == kIOHIDElementTypeInput_Axis) &&\n usagePage == kHIDPage_GenericDesktop)\n {\n auto usageIterator = axisUsageMap.find(usage);\n\n if (usageIterator != axisUsageMap.end())\n {\n const std::size_t index = usageIterator->second;\n\n Axis axis;\n axis.axis = gamepadConfig.axisMap[index];\n axis.min = IOHIDElementGetLogicalMin(element);\n axis.max = IOHIDElementGetLogicalMax(element);\n axis.range = axis.max - axis.min;\n\n switch (gamepadConfig.axisMap[index])\n {\n case Gamepad::Axis::none:\n break;\n case Gamepad::Axis::leftThumbX:\n axis.negativeButton = Gamepad::Button::leftThumbLeft;\n axis.positiveButton = Gamepad::Button::leftThumbRight;\n break;\n case Gamepad::Axis::leftThumbY:\n axis.negativeButton = Gamepad::Button::leftThumbUp;\n axis.positiveButton = Gamepad::Button::leftThumbDown;\n break;\n case Gamepad::Axis::rightThumbX:\n axis.negativeButton = Gamepad::Button::rightThumbLeft;\n axis.positiveButton = Gamepad::Button::rightThumbRight;\n break;\n case Gamepad::Axis::rightThumbY:\n axis.negativeButton = Gamepad::Button::rightThumbUp;\n axis.positiveButton = Gamepad::Button::rightThumbDown;\n break;\n case Gamepad::Axis::leftTrigger:\n axis.negativeButton = Gamepad::Button::leftTrigger;\n axis.positiveButton = Gamepad::Button::leftTrigger;\n hasLeftTrigger = true;\n break;\n case Gamepad::Axis::rightTrigger:\n axis.negativeButton = Gamepad::Button::rightTrigger;\n axis.positiveButton = Gamepad::Button::rightTrigger;\n hasRightTrigger = true;\n break;\n }\n\n axes.insert(std::pair(element, axis));\n }\n }\n }\n\n CFRelease(elementArray);\n\n IOHIDDeviceRegisterInputValueCallback(device, deviceInput, this);\n }\n\n void GamepadDeviceIOKit::handleInput(IOHIDValueRef value)\n {\n const auto element = IOHIDValueGetElement(value);\n const auto newValue = IOHIDValueGetIntegerValue(value);\n\n if (element == hatElement)\n {\n const auto oldHatValue = static_cast(hatValue);\n const std::uint32_t oldBitmask = (oldHatValue >= 8) ? 0 : (1 << (oldHatValue \/ 2)) | \/\/ first bit\n (1 << (oldHatValue \/ 2 + oldHatValue % 2)) % 4; \/\/ second bit\n\n const std::uint32_t newBitmask = (newValue >= 8) ? 0 : (1 << (newValue \/ 2)) | \/\/ first bit\n (1 << (newValue \/ 2 + newValue % 2)) % 4; \/\/ second bit\n\n if ((oldBitmask & 0x01) != (newBitmask & 0x01))\n handleButtonValueChange(Gamepad::Button::dPadUp,\n (newBitmask & 0x01) > 0,\n (newBitmask & 0x01) > 0 ? 1.0F : 0.0F);\n if ((oldBitmask & 0x02) != (newBitmask & 0x02))\n handleButtonValueChange(Gamepad::Button::dPadRight,\n (newBitmask & 0x02) > 0,\n (newBitmask & 0x02) > 0 ? 1.0F : 0.0F);\n if ((oldBitmask & 0x04) != (newBitmask & 0x04))\n handleButtonValueChange(Gamepad::Button::dPadDown,\n (newBitmask & 0x04) > 0,\n (newBitmask & 0x04) > 0 ? 1.0F : 0.0F);\n if ((oldBitmask & 0x08) != (newBitmask & 0x08))\n handleButtonValueChange(Gamepad::Button::dPadLeft,\n (newBitmask & 0x08) > 0,\n (newBitmask & 0x08) > 0 ? 1.0F : 0.0F);\n\n hatValue = newValue;\n }\n\n const auto buttonIterator = buttons.find(element);\n\n if (buttonIterator != buttons.end())\n {\n Button& button = buttonIterator->second;\n\n if ((button.button != Gamepad::Button::leftTrigger || !hasLeftTrigger) &&\n (button.button != Gamepad::Button::rightTrigger || !hasRightTrigger))\n handleButtonValueChange(button.button, newValue > 0, (newValue > 0) ? 1.0F : 0.0F);\n\n button.value = newValue;\n }\n\n const auto axisIterator = axes.find(element);\n\n if (axisIterator != axes.end())\n {\n Axis& axis = axisIterator->second;\n\n handleAxisChange(axis.value,\n newValue,\n axis.min, axis.range,\n axis.negativeButton, axis.positiveButton);\n\n axis.value = newValue;\n }\n }\n\n void GamepadDeviceIOKit::handleAxisChange(CFIndex oldValue, CFIndex newValue,\n CFIndex min, CFIndex range,\n Gamepad::Button negativeButton,\n Gamepad::Button positiveButton)\n {\n if (negativeButton == positiveButton)\n {\n const auto floatValue = static_cast(newValue - min) \/ range;\n\n handleButtonValueChange(negativeButton,\n floatValue > 0.0F,\n floatValue);\n }\n else\n {\n const auto floatValue = 2.0F * static_cast(newValue - min) \/ range - 1.0F;\n\n if (floatValue > 0.0F)\n handleButtonValueChange(positiveButton,\n floatValue > thumbDeadzone,\n floatValue);\n else if (floatValue < 0.0F)\n handleButtonValueChange(negativeButton,\n -floatValue > thumbDeadzone,\n -floatValue);\n else \/\/ thumbstick is 0\n {\n if (oldValue > newValue)\n handleButtonValueChange(positiveButton, false, 0.0F);\n else\n handleButtonValueChange(negativeButton, false, 0.0F);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------------\r\n\/\/ Copyright (c) 2013 GarageGames, LLC\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to\r\n\/\/ deal in the Software without restriction, including without limitation the\r\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\r\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\r\n\/\/ IN THE SOFTWARE.\r\n\/\/-----------------------------------------------------------------------------\r\n\r\n#include \"console\/console.h\"\r\n#include \"graphics\/dgl.h\"\r\n#include \"gui\/guiCanvas.h\"\r\n#include \"gui\/buttons\/guiRadioCtrl.h\"\r\n#include \"console\/consoleTypes.h\"\r\n#include \"gui\/guiDefaultControlRender.h\"\r\n\r\n\/\/---------------------------------------------------------------------------\r\nIMPLEMENT_CONOBJECT(GuiRadioCtrl);\r\n\r\nGuiRadioCtrl::GuiRadioCtrl()\r\n{\r\n}\r\n\r\n\r\nvoid GuiRadioCtrl::initPersistFields()\r\n{\r\n\tParent::initPersistFields();\r\n\taddField(\"groupNum\", TypeS32, Offset(mRadioGroup, GuiRadioCtrl));\r\n}\r\n\r\nvoid GuiRadioCtrl::renderInnerControl(RectI &boxRect, const GuiControlState currentState)\r\n{\r\n\tU8 stateIndex = currentState;\r\n\r\n\tif ((mProfile->mImageAsset->isAssetValid() && mProfile->mImageAsset->getFrameCount() > stateIndex) \r\n\t\t|| (mProfile->mBitmapName != NULL && mProfile->constructBitmapArray() > stateIndex))\r\n\t{\r\n\t\trenderUniversalRect(boxRect, mProfile, currentState);\r\n\t}\r\n\telse \r\n\t{\r\n\t\tS32 radius = boxRect.extent.x;\r\n\t\tif (boxRect.extent.y < radius)\r\n\t\t{\r\n\t\t\tradius = boxRect.extent.y;\r\n\t\t}\r\n\t\tradius = (S32)round(radius \/ 2);\r\n\t\tPoint2I center = Point2I(boxRect.point.x + (boxRect.extent.x \/ 2), boxRect.point.y + (boxRect.extent.y \/ 2));\r\n\t\trenderBorderedCircle(center, radius, mProfile, currentState);\r\n\t}\r\n}\r\n\r\nvoid GuiRadioCtrl::onAction()\r\n{\r\n\tif (!mActive)\r\n\t\treturn;\r\n\r\n\tmStateOn = false;\r\n\r\n\tParent::onAction();\r\n\r\n\tmessageSiblings(mRadioGroup);\r\n}\r\n\r\nvoid GuiRadioCtrl::setStateOn(bool bStateOn)\r\n{\r\n\tif (!mActive)\r\n\t\treturn;\r\n\r\n\tmStateOn = true;\r\n\tmessageSiblings(mRadioGroup);\r\n\r\n\tsetUpdate();\r\n}\r\n\r\nvoid GuiRadioCtrl::onMessage(GuiControl *sender, S32 msg)\r\n{\r\n\tParent::onMessage(sender, msg);\r\n\tif (mRadioGroup == msg)\r\n\t{\r\n\t\tmStateOn = (sender == this);\r\n\t\tsetUpdate();\r\n\t}\r\n}Fixed a Crash with GuiRadioCtrl\/\/-----------------------------------------------------------------------------\r\n\/\/ Copyright (c) 2013 GarageGames, LLC\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to\r\n\/\/ deal in the Software without restriction, including without limitation the\r\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\r\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\r\n\/\/ IN THE SOFTWARE.\r\n\/\/-----------------------------------------------------------------------------\r\n\r\n#include \"console\/console.h\"\r\n#include \"graphics\/dgl.h\"\r\n#include \"gui\/guiCanvas.h\"\r\n#include \"gui\/buttons\/guiRadioCtrl.h\"\r\n#include \"console\/consoleTypes.h\"\r\n#include \"gui\/guiDefaultControlRender.h\"\r\n\r\n\/\/---------------------------------------------------------------------------\r\nIMPLEMENT_CONOBJECT(GuiRadioCtrl);\r\n\r\nGuiRadioCtrl::GuiRadioCtrl()\r\n{\r\n}\r\n\r\n\r\nvoid GuiRadioCtrl::initPersistFields()\r\n{\r\n\tParent::initPersistFields();\r\n\taddField(\"groupNum\", TypeS32, Offset(mRadioGroup, GuiRadioCtrl));\r\n}\r\n\r\nvoid GuiRadioCtrl::renderInnerControl(RectI &boxRect, const GuiControlState currentState)\r\n{\r\n\tU8 stateIndex = currentState;\r\n\r\n\tif ((mProfile->mImageAsset != NULL && mProfile->mImageAsset->isAssetValid() && mProfile->mImageAsset->getFrameCount() > stateIndex) \r\n\t\t|| (mProfile->mBitmapName != NULL && mProfile->constructBitmapArray() > stateIndex))\r\n\t{\r\n\t\trenderUniversalRect(boxRect, mProfile, currentState);\r\n\t}\r\n\telse \r\n\t{\r\n\t\tS32 radius = boxRect.extent.x;\r\n\t\tif (boxRect.extent.y < radius)\r\n\t\t{\r\n\t\t\tradius = boxRect.extent.y;\r\n\t\t}\r\n\t\tradius = (S32)round(radius \/ 2);\r\n\t\tPoint2I center = Point2I(boxRect.point.x + (boxRect.extent.x \/ 2), boxRect.point.y + (boxRect.extent.y \/ 2));\r\n\t\trenderBorderedCircle(center, radius, mProfile, currentState);\r\n\t}\r\n}\r\n\r\nvoid GuiRadioCtrl::onAction()\r\n{\r\n\tif (!mActive)\r\n\t\treturn;\r\n\r\n\tmStateOn = false;\r\n\r\n\tParent::onAction();\r\n\r\n\tmessageSiblings(mRadioGroup);\r\n}\r\n\r\nvoid GuiRadioCtrl::setStateOn(bool bStateOn)\r\n{\r\n\tif (!mActive)\r\n\t\treturn;\r\n\r\n\tmStateOn = true;\r\n\tmessageSiblings(mRadioGroup);\r\n\r\n\tsetUpdate();\r\n}\r\n\r\nvoid GuiRadioCtrl::onMessage(GuiControl *sender, S32 msg)\r\n{\r\n\tParent::onMessage(sender, msg);\r\n\tif (mRadioGroup == msg)\r\n\t{\r\n\t\tmStateOn = (sender == this);\r\n\t\tsetUpdate();\r\n\t}\r\n}<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ This transformation forms clusters from instructions in same island and\n\/\/ assigned to save devices. Clusters are represented as regions.\n\/\/ Note that side-effecting ops are not correctly handled yet.\n\n#include \"llvm\/ADT\/MapVector.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"mlir\/IR\/Attributes.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/Block.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/BlockAndValueMapping.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/Builders.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/Operation.h\" \/\/ TF:llvm-project\n#include \"mlir\/Pass\/Pass.h\" \/\/ TF:llvm-project\n#include \"mlir\/Pass\/PassRegistry.h\" \/\/ TF:llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_device.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_executor.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/transforms\/passes.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n\nnamespace mlir {\nnamespace TFDevice {\n\nnamespace {\n\nstruct ClusterFormationPass : public FunctionPass {\n void runOnFunction() override;\n};\n\n\/\/ Cluster structure captures all the operations that are assigned to same\n\/\/ device and can form a legal strict cluster.\n\/\/ Ops must follow same ordering in their parent block. We rely on this\n\/\/ assumption to perform analysis.\nstruct Cluster {\n llvm::SmallVector ops;\n StringRef device;\n};\n\nStringRef GetDevice(Operation* op) {\n auto device_attr = op->getAttrOfType(\"device\");\n return device_attr ? device_attr.getValue() : \"\";\n}\n\n\/\/ An op can be merged into cluster if all of its operands are one of the\n\/\/ following:\n\/\/ 1) A block argument\n\/\/ 2) A value produced by other islands\n\/\/ 1) Defined before the cluster\n\/\/ 2) Defined by an operation in the cluster\n\/\/ TODO(ycao): This is not optimal as it doesn't consider the situation of\n\/\/ defining_op's operands all meet the requirements above. In that case, the\n\/\/ defining_op can be moved and to_merge op would be legal to absorb.\n\/\/ TODO(ycao): Take op side-effects into consideration since they can not be\n\/\/ re-ordered but forming clusters of non-continuous ops is effectively\n\/\/ re-ordering them..\nbool CanMergeIntoCluster(const Cluster& c, Operation* to_merge) {\n return llvm::all_of(to_merge->getOperands(), [&](Value operand) {\n \/\/ Block arguments.\n if (operand.isa()) return true;\n\n Operation* defining_op = operand.getDefiningOp();\n\n \/\/ Operand produced by other islands.\n if (defining_op->getBlock() != c.ops.front()->getBlock()) return true;\n\n \/\/ Defining op is before the cluster.\n if (defining_op->isBeforeInBlock(c.ops.front())) return true;\n\n \/\/ Defining op is between first and last operation in cluster. Note that\n \/\/ cluster may contain operations that are non-continuous in their original\n \/\/ block, thus we also need to check defining_op is also assigned to\n \/\/ cluster's device to be sure. This is a faster check than linearly\n \/\/ searching through all ops in cluster.\n if (defining_op->isBeforeInBlock(c.ops.back()->getNextNode()) &&\n GetDevice(defining_op) == c.device)\n return true;\n\n \/\/ Other cases, operand is generated after or outside the cluster, this\n \/\/ means it is illegal to merge operation.\n return false;\n });\n}\n\nvoid ReplaceLiveOutExternalUses(llvm::ArrayRef live_outs,\n tf_device::LaunchOp launch_op) {\n Region* launch_op_region = &launch_op.body();\n for (const auto& p : llvm::zip(live_outs, launch_op.getResults())) {\n Value from = std::get<0>(p);\n for (auto& use : from.getUses()) {\n if (launch_op_region->isAncestor(use.getOwner()->getParentRegion()))\n continue;\n use.set(std::get<1>(p));\n }\n }\n}\n\n\/\/ Get all escaped live-out values of a region.\nvoid GetLiveOuts(Region* region, llvm::SmallVectorImpl* live_outs) {\n live_outs->clear();\n\n for (Operation& op : region->front()) {\n for (Value v : op.getResults()) {\n \/\/ A value is live-out if any of its users are not inside value producer's\n \/\/ region.\n bool is_live_out = llvm::any_of(v.getUsers(), [&](Operation* user) {\n return !region->isAncestor(user->getParentRegion());\n });\n\n if (is_live_out) live_outs->emplace_back(v);\n }\n }\n}\n\n\/\/ Build a `tf_device.launch` op with a region that contains all the operations\n\/\/ in given cluster. Then all ops in cluster are replaced by `tf_device.launch`.\nvoid BuildLaunchForCluster(const Cluster& c, OpBuilder* builder) {\n \/\/ Set insertion point to right after all operations in cluster.\n builder->setInsertionPoint(c.ops.back()->getNextNode());\n\n \/\/ Create a stand-alone region to hold all instructions in the cluster.\n Region region;\n region.push_back(new Block);\n\n \/\/ Move all operations in cluster to newly created region, stripping their\n \/\/ \"device\" attribute since launch op already carries device information.\n Block* block = ®ion.front();\n for (Operation* op : c.ops) {\n op->moveBefore(block, block->end());\n op->removeAttr(builder->getIdentifier(\"device\"));\n }\n\n \/\/ Get all escaped live-out values of region, they are used later to determine\n \/\/ return values and types of launch op.\n llvm::SmallVector live_outs;\n GetLiveOuts(®ion, &live_outs);\n\n \/\/ Build a `tf_device.return` op at end of region, with all live-out values\n \/\/ as operand.\n OpBuilder return_builder(builder->getContext());\n return_builder.setInsertionPointToEnd(block);\n return_builder.create(return_builder.getUnknownLoc(),\n live_outs);\n\n llvm::SmallVector live_out_types;\n live_out_types.reserve(live_outs.size());\n for (Value v : live_outs) {\n live_out_types.emplace_back(v.getType());\n }\n\n tf_device::LaunchOp launch_op = builder->create(\n builder->getUnknownLoc(), builder->getStringAttr(c.device),\n live_out_types);\n\n \/\/ Attach the region to launch_op.\n launch_op.body().takeBody(region);\n\n \/\/ Replace any external uses of live-out values with return values of launch\n \/\/ op. So live-out values no longer escape the region.\n ReplaceLiveOutExternalUses(live_outs, launch_op);\n}\n\nvoid BuildClusters(Block* block, OpBuilder builder) {\n \/\/ Iteratively find clusters of different devices within an island.\n \/\/ Whenever we see an operation that is assigned to an accelerator device\n \/\/ (ie. device != \"\"), we try to merge it into the last cluster of same\n \/\/ device. If that is infeasible (say because of violating def-before-use),\n \/\/ create a new cluster with that operation and move on.\n llvm::MapVector nearest_clusters;\n for (Operation& op : llvm::make_early_inc_range(*block)) {\n auto device = GetDevice(&op);\n if (device == \"\") continue;\n\n \/\/ If no cluster of same device has been formed yet, create a new cluster\n \/\/ with op alone.\n auto it = nearest_clusters.find(device);\n if (it == nearest_clusters.end()) {\n nearest_clusters[device] = Cluster{{&op}, device};\n continue;\n }\n\n \/\/ Check if it is legal to merge op into nearest cluster of same device.\n \/\/ If positive, update cluster and move on to next operation.\n Cluster& nearest_cluster = it->second;\n if (CanMergeIntoCluster(nearest_cluster, &op)) {\n nearest_cluster.ops.emplace_back(&op);\n continue;\n }\n\n \/\/ If nearest cluster of same device can not absorb `op`, then that\n \/\/ cluster needs to be finalized by building a `tf_device.launch` op with\n \/\/ a region that contains all operations in clusters.\n BuildLaunchForCluster(nearest_cluster, &builder);\n\n \/\/ Create a new cluster to hold op alone and update nearest_clusters.\n nearest_clusters[device] = Cluster{{&op}, device};\n }\n\n \/\/ At the end, there might be left-over found clusters that need to be\n \/\/ built.\n for (auto& device_cluster : nearest_clusters)\n BuildLaunchForCluster(device_cluster.second, &builder);\n}\n\nvoid ClusterFormationPass::runOnFunction() {\n OpBuilder builder(getFunction().getContext());\n\n \/\/ Operates on individual blocks independently of if they are directly in the\n \/\/ function body or if they are nested in individual `tf_executor.island`.\n for (Block& block : getFunction().getBody()) BuildClusters(&block, builder);\n getFunction().walk([&](tf_executor::IslandOp island) {\n BuildClusters(&island.GetBody(), builder);\n });\n}\n\n} \/\/ namespace\n\nstd::unique_ptr> CreateClusterFormationPass() {\n return std::make_unique();\n}\n\nstatic PassRegistration pass(\n \"tf-device-cluster-formation\",\n \"Form clusters from instructions assigned to same device\");\n\n} \/\/ namespace TFDevice\n} \/\/ namespace mlir\nFix a subtle bug where we unsafely modify the list while iterating it.\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ This transformation forms clusters from instructions in same island and\n\/\/ assigned to save devices. Clusters are represented as regions.\n\/\/ Note that side-effecting ops are not correctly handled yet.\n\n#include \"llvm\/ADT\/MapVector.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"mlir\/IR\/Attributes.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/Block.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/BlockAndValueMapping.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/Builders.h\" \/\/ TF:llvm-project\n#include \"mlir\/IR\/Operation.h\" \/\/ TF:llvm-project\n#include \"mlir\/Pass\/Pass.h\" \/\/ TF:llvm-project\n#include \"mlir\/Pass\/PassRegistry.h\" \/\/ TF:llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_device.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_executor.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/transforms\/passes.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n\nnamespace mlir {\nnamespace TFDevice {\n\nnamespace {\n\nstruct ClusterFormationPass : public FunctionPass {\n void runOnFunction() override;\n};\n\n\/\/ Cluster structure captures all the operations that are assigned to same\n\/\/ device and can form a legal strict cluster.\n\/\/ Ops must follow same ordering in their parent block. We rely on this\n\/\/ assumption to perform analysis.\nstruct Cluster {\n llvm::SmallVector ops;\n StringRef device;\n};\n\nStringRef GetDevice(Operation* op) {\n auto device_attr = op->getAttrOfType(\"device\");\n return device_attr ? device_attr.getValue() : \"\";\n}\n\n\/\/ An op can be merged into cluster if all of its operands are one of the\n\/\/ following:\n\/\/ 1) A block argument\n\/\/ 2) A value produced by other islands\n\/\/ 1) Defined before the cluster\n\/\/ 2) Defined by an operation in the cluster\n\/\/ TODO(ycao): This is not optimal as it doesn't consider the situation of\n\/\/ defining_op's operands all meet the requirements above. In that case, the\n\/\/ defining_op can be moved and to_merge op would be legal to absorb.\n\/\/ TODO(ycao): Take op side-effects into consideration since they can not be\n\/\/ re-ordered but forming clusters of non-continuous ops is effectively\n\/\/ re-ordering them..\nbool CanMergeIntoCluster(const Cluster& c, Operation* to_merge) {\n return llvm::all_of(to_merge->getOperands(), [&](Value operand) {\n \/\/ Block arguments.\n if (operand.isa()) return true;\n\n Operation* defining_op = operand.getDefiningOp();\n\n \/\/ Operand produced by other islands.\n if (defining_op->getBlock() != c.ops.front()->getBlock()) return true;\n\n \/\/ Defining op is before the cluster.\n if (defining_op->isBeforeInBlock(c.ops.front())) return true;\n\n \/\/ Defining op is between first and last operation in cluster. Note that\n \/\/ cluster may contain operations that are non-continuous in their original\n \/\/ block, thus we also need to check defining_op is also assigned to\n \/\/ cluster's device to be sure. This is a faster check than linearly\n \/\/ searching through all ops in cluster.\n if (defining_op->isBeforeInBlock(c.ops.back()->getNextNode()) &&\n GetDevice(defining_op) == c.device)\n return true;\n\n \/\/ Other cases, operand is generated after or outside the cluster, this\n \/\/ means it is illegal to merge operation.\n return false;\n });\n}\n\nvoid ReplaceLiveOutExternalUses(llvm::ArrayRef live_outs,\n tf_device::LaunchOp launch_op) {\n Region* launch_op_region = &launch_op.body();\n for (const auto& p : llvm::zip(live_outs, launch_op.getResults())) {\n Value from = std::get<0>(p);\n \/\/ TODO(jingpu): move this to RegionUtils.h in MLIR core.\n for (auto& use : llvm::make_early_inc_range(from.getUses())) {\n if (launch_op_region->isAncestor(use.getOwner()->getParentRegion()))\n continue;\n use.set(std::get<1>(p));\n }\n }\n}\n\n\/\/ Get all escaped live-out values of a region.\nvoid GetLiveOuts(Region* region, llvm::SmallVectorImpl* live_outs) {\n live_outs->clear();\n\n for (Operation& op : region->front()) {\n for (Value v : op.getResults()) {\n \/\/ A value is live-out if any of its users are not inside value producer's\n \/\/ region.\n bool is_live_out = llvm::any_of(v.getUsers(), [&](Operation* user) {\n return !region->isAncestor(user->getParentRegion());\n });\n\n if (is_live_out) live_outs->emplace_back(v);\n }\n }\n}\n\n\/\/ Build a `tf_device.launch` op with a region that contains all the operations\n\/\/ in given cluster. Then all ops in cluster are replaced by `tf_device.launch`.\nvoid BuildLaunchForCluster(const Cluster& c, OpBuilder* builder) {\n \/\/ Set insertion point to right after all operations in cluster.\n builder->setInsertionPoint(c.ops.back()->getNextNode());\n\n \/\/ Create a stand-alone region to hold all instructions in the cluster.\n Region region;\n region.push_back(new Block);\n\n \/\/ Move all operations in cluster to newly created region, stripping their\n \/\/ \"device\" attribute since launch op already carries device information.\n Block* block = ®ion.front();\n for (Operation* op : c.ops) {\n op->moveBefore(block, block->end());\n op->removeAttr(builder->getIdentifier(\"device\"));\n }\n\n \/\/ Get all escaped live-out values of region, they are used later to determine\n \/\/ return values and types of launch op.\n llvm::SmallVector live_outs;\n GetLiveOuts(®ion, &live_outs);\n\n \/\/ Build a `tf_device.return` op at end of region, with all live-out values\n \/\/ as operand.\n OpBuilder return_builder(builder->getContext());\n return_builder.setInsertionPointToEnd(block);\n return_builder.create(return_builder.getUnknownLoc(),\n live_outs);\n\n llvm::SmallVector live_out_types;\n live_out_types.reserve(live_outs.size());\n for (Value v : live_outs) {\n live_out_types.emplace_back(v.getType());\n }\n\n tf_device::LaunchOp launch_op = builder->create(\n builder->getUnknownLoc(), builder->getStringAttr(c.device),\n live_out_types);\n\n \/\/ Attach the region to launch_op.\n launch_op.body().takeBody(region);\n\n \/\/ Replace any external uses of live-out values with return values of launch\n \/\/ op. So live-out values no longer escape the region.\n ReplaceLiveOutExternalUses(live_outs, launch_op);\n}\n\nvoid BuildClusters(Block* block, OpBuilder builder) {\n \/\/ Iteratively find clusters of different devices within an island.\n \/\/ Whenever we see an operation that is assigned to an accelerator device\n \/\/ (ie. device != \"\"), we try to merge it into the last cluster of same\n \/\/ device. If that is infeasible (say because of violating def-before-use),\n \/\/ create a new cluster with that operation and move on.\n llvm::MapVector nearest_clusters;\n for (Operation& op : llvm::make_early_inc_range(*block)) {\n auto device = GetDevice(&op);\n if (device == \"\") continue;\n\n \/\/ If no cluster of same device has been formed yet, create a new cluster\n \/\/ with op alone.\n auto it = nearest_clusters.find(device);\n if (it == nearest_clusters.end()) {\n nearest_clusters[device] = Cluster{{&op}, device};\n continue;\n }\n\n \/\/ Check if it is legal to merge op into nearest cluster of same device.\n \/\/ If positive, update cluster and move on to next operation.\n Cluster& nearest_cluster = it->second;\n if (CanMergeIntoCluster(nearest_cluster, &op)) {\n nearest_cluster.ops.emplace_back(&op);\n continue;\n }\n\n \/\/ If nearest cluster of same device can not absorb `op`, then that\n \/\/ cluster needs to be finalized by building a `tf_device.launch` op with\n \/\/ a region that contains all operations in clusters.\n BuildLaunchForCluster(nearest_cluster, &builder);\n\n \/\/ Create a new cluster to hold op alone and update nearest_clusters.\n nearest_clusters[device] = Cluster{{&op}, device};\n }\n\n \/\/ At the end, there might be left-over found clusters that need to be\n \/\/ built.\n for (auto& device_cluster : nearest_clusters)\n BuildLaunchForCluster(device_cluster.second, &builder);\n}\n\nvoid ClusterFormationPass::runOnFunction() {\n OpBuilder builder(getFunction().getContext());\n\n \/\/ Operates on individual blocks independently of if they are directly in the\n \/\/ function body or if they are nested in individual `tf_executor.island`.\n for (Block& block : getFunction().getBody()) BuildClusters(&block, builder);\n getFunction().walk([&](tf_executor::IslandOp island) {\n BuildClusters(&island.GetBody(), builder);\n });\n}\n\n} \/\/ namespace\n\nstd::unique_ptr> CreateClusterFormationPass() {\n return std::make_unique();\n}\n\nstatic PassRegistration pass(\n \"tf-device-cluster-formation\",\n \"Form clusters from instructions assigned to same device\");\n\n} \/\/ namespace TFDevice\n} \/\/ namespace mlir\n<|endoftext|>"} {"text":"\/*****************************************************************************\n\nYASK: Yet Another Stencil Kernel\nCopyright (c) 2014-2018, Intel Corporation\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\n* The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\n*****************************************************************************\/\n\n\/\/ Base class for defining stencil equations.\n\n#ifndef SOLN_HPP\n#define SOLN_HPP\n\n#include \nusing namespace std;\n\nnamespace yask {\n\n typedef enum { STENCIL_CONTEXT } YASKSection;\n typedef vector CodeList;\n typedef map ExtensionsList;\n\n class StencilSolution;\n class StencilBase;\n typedef map StencilList;\n\n \/\/ A base class for whole stencil solutions. This is used by solutions\n \/\/ defined in C++ that are inherited from StencilBase as well as those\n \/\/ defined via the stencil-compiler API.\n class StencilSolution :\n public virtual yc_solution {\n protected:\n \n \/\/ Simple name for the stencil soln.\n string _name;\n\n \/\/ Debug output.\n yask_output_ptr _debug_output;\n ostream* _dos = &std::cout;\n \n \/\/ All vars accessible by the kernel.\n Grids _grids; \/\/ keep track of all registered grids.\n\n \/\/ All equations defined in this solution.\n Eqs _eqs;\n\n \/\/ Settings for the solution.\n CompilerSettings _settings;\n\n \/\/ Code extensions that overload default functions from YASK in the\n \/\/ generated code for this solution.\n ExtensionsList _extensions;\n\n private:\n\n \/\/ Intermediate data needed to format output.\n Dimensions _dims; \/\/ various dimensions.\n EqGroups _eqGroups; \/\/ eq-groups for scalar and vector.\n EqGroups _clusterEqGroups; \/\/ eq-groups for scalar and vector.\n\n \/\/ Create the intermediate data.\n void analyze_solution(int vlen,\n bool is_folding_efficient);\n\n public:\n StencilSolution(const string& name) :\n _name(name) {\n yask_output_factory ofac;\n set_debug_output(ofac.new_stdout_output());\n }\n virtual ~StencilSolution() {}\n\n \/\/ Identification.\n virtual const string& getName() const { return _name; }\n \n \/\/ Simple accessors.\n virtual Grids& getGrids() { return _grids; }\n virtual Eqs& getEqs() { return _eqs; }\n virtual CompilerSettings& getSettings() { return _settings; }\n\n \/\/ Get user-provided code for the given section.\n CodeList * getExtensionCode(YASKSection section)\n { \n auto elem = _extensions.find(section);\n if ( elem != _extensions.end() ) {\n return &elem->second;\n }\n return NULL;\n }\n\n \/\/ Define grid values relative to current domain indices in each dimension.\n \/\/ This must be implemented by each concrete stencil solution.\n virtual void define() = 0;\n\n \/\/ stencil_solution APIs.\n \/\/ See yask_stencil_api.hpp for documentation.\n virtual void set_debug_output(yask_output_ptr debug) {\n _debug_output = debug; \/\/ to share ownership of referent.\n _dos = &_debug_output->get_ostream();\n }\n virtual void set_name(std::string name) {\n _name = name;\n }\n virtual const std::string& get_name() const {\n return _name;\n }\n\n virtual yc_grid_ptr new_grid(const std::string& name,\n const std::vector& dims);\n virtual yc_grid_ptr new_grid(const std::string& name,\n const std::initializer_list& dims) {\n std::vector dim_vec(dims);\n return new_grid(name, dim_vec);\n }\n virtual int get_num_grids() const {\n return int(_grids.size());\n }\n virtual yc_grid_ptr get_grid(const std::string& name) {\n for (int i = 0; i < get_num_grids(); i++)\n if (_grids.at(i)->getName() == name)\n return _grids.at(i);\n return nullptr;\n }\n virtual std::vector get_grids() {\n std::vector gv;\n for (int i = 0; i < get_num_grids(); i++)\n gv.push_back(_grids.at(i));\n return gv;\n }\n\n virtual int get_num_equations() const {\n return _eqs.getNumEqs();\n }\n virtual yc_equation_node_ptr get_equation(int n) {\n assert(n >= 0 && n < get_num_equations());\n return _eqs.getEqs().at(n);\n }\n virtual void set_fold(const std::string& dim, int len) {\n auto& fold = _settings._foldOptions;\n auto* p = fold.lookup(dim);\n if (p)\n *p = len;\n else\n fold.addDimBack(dim, len);\n }\n virtual void set_fold_len(const yc_index_node_ptr, int len);\n virtual void clear_folding() { _settings._foldOptions.clear(); }\n virtual void set_cluster_mult(const yc_index_node_ptr, int mult);\n virtual void clear_clustering() { _settings._clusterOptions.clear(); }\n virtual void set_element_bytes(int nbytes) { _settings._elem_bytes = nbytes; }\n virtual int get_element_bytes() const { return _settings._elem_bytes; }\n virtual void format(const std::string& format_type,\n yask_output_ptr output) ;\n };\n\n \/\/ A stencil solution that does not define any grids.\n \/\/ This is used by a program via the compiler API to add grids\n \/\/ programmatically.\n class EmptyStencil : public StencilSolution {\n\n \/\/ Do not define any dims.\n \/\/ Do not define any grids.\n \n public:\n EmptyStencil(std::string name) :\n StencilSolution(name) { }\n\n \/\/ Do not define any equations.\n virtual void define() { }\n };\n \n \/\/ An interface for all objects that participate in stencil definitions.\n \/\/ This allows a programmer to use object composition in addition to\n \/\/ inheritance from StencilBase to define stencils.\n class StencilPart {\n\n public:\n StencilPart() {}\n virtual ~StencilPart() {}\n\n \/\/ Return a reference to the main stencil object.\n virtual StencilSolution& get_stencil_solution() =0;\n };\n \n \/\/ The class all C++ stencil solutions must implement.\n class StencilBase : public StencilSolution,\n public StencilPart {\n \n public:\n \/\/ Initialize name and register this new object in a list.\n StencilBase(const string name, StencilList& stencils) :\n StencilSolution(name)\n {\n stencils[name] = this;\n }\n virtual ~StencilBase() { }\n\n \/\/ Return a reference to the main stencil-solution object.\n \/\/ For StencilBase, simply this object.\n virtual StencilSolution& get_stencil_solution() {\n return *this;\n }\n \n \/\/ Radius stub methods.\n virtual bool usesRadius() const { return false; }\n virtual bool setRadius(int radius) { return false; }\n virtual int getRadius() const { return 0; }\n\n };\n\n \/\/ A base class for stencils that have a 'radius'.\n class StencilRadiusBase : public StencilBase {\n protected:\n int _radius; \/\/ stencil radius.\n\n public:\n StencilRadiusBase(const string name, StencilList& stencils, int radius) :\n StencilBase(name, stencils), _radius(radius) {}\n\n \/\/ Does use radius.\n virtual bool usesRadius() const { return true; }\n \n \/\/ Set radius.\n \/\/ Return true if successful.\n virtual bool setRadius(int radius) {\n _radius = radius;\n return radius >= 0; \/\/ support only non-neg. radius.\n }\n\n \/\/ Get radius.\n virtual int getRadius() { return _radius; }\n };\n\n} \/\/ namespace yask.\n\n\/\/ Convenience macro for registering a stencil in a list.\n#define REGISTER_STENCIL(Class) static Class registered_ ## Class(stencils)\n\n\/\/ Convenience macros for adding 'extension' code to a stencil.\n#define REGISTER_CODE_EXTENSION(section, code) _extensions[section].push_back(code);\n#define REGISTER_STENCIL_CONTEXT_EXTENSION(...) REGISTER_CODE_EXTENSION(STENCIL_CONTEXT, #__VA_ARGS__)\n\n\/\/ Convenience macro for declaring dims.\n#define MAKE_STEP_INDEX(d) IndexExprPtr d = make_shared(#d, STEP_INDEX);\n#define MAKE_DOMAIN_INDEX(d) IndexExprPtr d = make_shared(#d, DOMAIN_INDEX);\n#define MAKE_MISC_INDEX(d) IndexExprPtr d = make_shared(#d, MISC_INDEX);\n\n\/\/ Convenience macros for creating grids in a class implementing StencilPart.\n\/\/ The 'gvar' arg is the var name and the grid name.\n\/\/ The remaining args are the dimension names.\n#define MAKE_GRID(gvar, ...) \\\n Grid gvar = Grid(#gvar, &get_stencil_solution(), ##__VA_ARGS__)\n#define MAKE_SCALAR(gvar) MAKE_GRID(gvar)\n#define MAKE_ARRAY(gvar, d1) MAKE_GRID(gvar, d1)\n\n#endif\nRemove gratuitous added space.\/*****************************************************************************\n\nYASK: Yet Another Stencil Kernel\nCopyright (c) 2014-2018, Intel Corporation\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\n* The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\n*****************************************************************************\/\n\n\/\/ Base class for defining stencil equations.\n\n#ifndef SOLN_HPP\n#define SOLN_HPP\n\n#include \nusing namespace std;\n\nnamespace yask {\n\n typedef enum { STENCIL_CONTEXT } YASKSection;\n typedef vector CodeList;\n typedef map ExtensionsList;\n\n class StencilSolution;\n class StencilBase;\n typedef map StencilList;\n\n \/\/ A base class for whole stencil solutions. This is used by solutions\n \/\/ defined in C++ that are inherited from StencilBase as well as those\n \/\/ defined via the stencil-compiler API.\n class StencilSolution :\n public virtual yc_solution {\n protected:\n \n \/\/ Simple name for the stencil soln.\n string _name;\n\n \/\/ Debug output.\n yask_output_ptr _debug_output;\n ostream* _dos = &std::cout;\n \n \/\/ All vars accessible by the kernel.\n Grids _grids; \/\/ keep track of all registered grids.\n\n \/\/ All equations defined in this solution.\n Eqs _eqs;\n\n \/\/ Settings for the solution.\n CompilerSettings _settings;\n\n \/\/ Code extensions that overload default functions from YASK in the\n \/\/ generated code for this solution.\n ExtensionsList _extensions;\n\n private:\n\n \/\/ Intermediate data needed to format output.\n Dimensions _dims; \/\/ various dimensions.\n EqGroups _eqGroups; \/\/ eq-groups for scalar and vector.\n EqGroups _clusterEqGroups; \/\/ eq-groups for scalar and vector.\n\n \/\/ Create the intermediate data.\n void analyze_solution(int vlen,\n bool is_folding_efficient);\n\n public:\n StencilSolution(const string& name) :\n _name(name) {\n yask_output_factory ofac;\n set_debug_output(ofac.new_stdout_output());\n }\n virtual ~StencilSolution() {}\n\n \/\/ Identification.\n virtual const string& getName() const { return _name; }\n \n \/\/ Simple accessors.\n virtual Grids& getGrids() { return _grids; }\n virtual Eqs& getEqs() { return _eqs; }\n virtual CompilerSettings& getSettings() { return _settings; }\n\n \/\/ Get user-provided code for the given section.\n CodeList * getExtensionCode(YASKSection section)\n { \n auto elem = _extensions.find(section);\n if ( elem != _extensions.end() ) {\n return &elem->second;\n }\n return NULL;\n }\n\n \/\/ Define grid values relative to current domain indices in each dimension.\n \/\/ This must be implemented by each concrete stencil solution.\n virtual void define() = 0;\n\n \/\/ stencil_solution APIs.\n \/\/ See yask_stencil_api.hpp for documentation.\n virtual void set_debug_output(yask_output_ptr debug) {\n _debug_output = debug; \/\/ to share ownership of referent.\n _dos = &_debug_output->get_ostream();\n }\n virtual void set_name(std::string name) {\n _name = name;\n }\n virtual const std::string& get_name() const {\n return _name;\n }\n\n virtual yc_grid_ptr new_grid(const std::string& name,\n const std::vector& dims);\n virtual yc_grid_ptr new_grid(const std::string& name,\n const std::initializer_list& dims) {\n std::vector dim_vec(dims);\n return new_grid(name, dim_vec);\n }\n virtual int get_num_grids() const {\n return int(_grids.size());\n }\n virtual yc_grid_ptr get_grid(const std::string& name) {\n for (int i = 0; i < get_num_grids(); i++)\n if (_grids.at(i)->getName() == name)\n return _grids.at(i);\n return nullptr;\n }\n virtual std::vector get_grids() {\n std::vector gv;\n for (int i = 0; i < get_num_grids(); i++)\n gv.push_back(_grids.at(i));\n return gv;\n }\n\n virtual int get_num_equations() const {\n return _eqs.getNumEqs();\n }\n virtual yc_equation_node_ptr get_equation(int n) {\n assert(n >= 0 && n < get_num_equations());\n return _eqs.getEqs().at(n);\n }\n virtual void set_fold(const std::string& dim, int len) {\n auto& fold = _settings._foldOptions;\n auto* p = fold.lookup(dim);\n if (p)\n *p = len;\n else\n fold.addDimBack(dim, len);\n }\n virtual void set_fold_len(const yc_index_node_ptr, int len);\n virtual void clear_folding() { _settings._foldOptions.clear(); }\n virtual void set_cluster_mult(const yc_index_node_ptr, int mult);\n virtual void clear_clustering() { _settings._clusterOptions.clear(); }\n virtual void set_element_bytes(int nbytes) { _settings._elem_bytes = nbytes; }\n virtual int get_element_bytes() const { return _settings._elem_bytes; }\n virtual void format(const std::string& format_type,\n yask_output_ptr output);\n };\n\n \/\/ A stencil solution that does not define any grids.\n \/\/ This is used by a program via the compiler API to add grids\n \/\/ programmatically.\n class EmptyStencil : public StencilSolution {\n\n \/\/ Do not define any dims.\n \/\/ Do not define any grids.\n \n public:\n EmptyStencil(std::string name) :\n StencilSolution(name) { }\n\n \/\/ Do not define any equations.\n virtual void define() { }\n };\n \n \/\/ An interface for all objects that participate in stencil definitions.\n \/\/ This allows a programmer to use object composition in addition to\n \/\/ inheritance from StencilBase to define stencils.\n class StencilPart {\n\n public:\n StencilPart() {}\n virtual ~StencilPart() {}\n\n \/\/ Return a reference to the main stencil object.\n virtual StencilSolution& get_stencil_solution() =0;\n };\n \n \/\/ The class all C++ stencil solutions must implement.\n class StencilBase : public StencilSolution,\n public StencilPart {\n \n public:\n \/\/ Initialize name and register this new object in a list.\n StencilBase(const string name, StencilList& stencils) :\n StencilSolution(name)\n {\n stencils[name] = this;\n }\n virtual ~StencilBase() { }\n\n \/\/ Return a reference to the main stencil-solution object.\n \/\/ For StencilBase, simply this object.\n virtual StencilSolution& get_stencil_solution() {\n return *this;\n }\n \n \/\/ Radius stub methods.\n virtual bool usesRadius() const { return false; }\n virtual bool setRadius(int radius) { return false; }\n virtual int getRadius() const { return 0; }\n\n };\n\n \/\/ A base class for stencils that have a 'radius'.\n class StencilRadiusBase : public StencilBase {\n protected:\n int _radius; \/\/ stencil radius.\n\n public:\n StencilRadiusBase(const string name, StencilList& stencils, int radius) :\n StencilBase(name, stencils), _radius(radius) {}\n\n \/\/ Does use radius.\n virtual bool usesRadius() const { return true; }\n \n \/\/ Set radius.\n \/\/ Return true if successful.\n virtual bool setRadius(int radius) {\n _radius = radius;\n return radius >= 0; \/\/ support only non-neg. radius.\n }\n\n \/\/ Get radius.\n virtual int getRadius() { return _radius; }\n };\n\n} \/\/ namespace yask.\n\n\/\/ Convenience macro for registering a stencil in a list.\n#define REGISTER_STENCIL(Class) static Class registered_ ## Class(stencils)\n\n\/\/ Convenience macros for adding 'extension' code to a stencil.\n#define REGISTER_CODE_EXTENSION(section, code) _extensions[section].push_back(code);\n#define REGISTER_STENCIL_CONTEXT_EXTENSION(...) REGISTER_CODE_EXTENSION(STENCIL_CONTEXT, #__VA_ARGS__)\n\n\/\/ Convenience macro for declaring dims.\n#define MAKE_STEP_INDEX(d) IndexExprPtr d = make_shared(#d, STEP_INDEX);\n#define MAKE_DOMAIN_INDEX(d) IndexExprPtr d = make_shared(#d, DOMAIN_INDEX);\n#define MAKE_MISC_INDEX(d) IndexExprPtr d = make_shared(#d, MISC_INDEX);\n\n\/\/ Convenience macros for creating grids in a class implementing StencilPart.\n\/\/ The 'gvar' arg is the var name and the grid name.\n\/\/ The remaining args are the dimension names.\n#define MAKE_GRID(gvar, ...) \\\n Grid gvar = Grid(#gvar, &get_stencil_solution(), ##__VA_ARGS__)\n#define MAKE_SCALAR(gvar) MAKE_GRID(gvar)\n#define MAKE_ARRAY(gvar, d1) MAKE_GRID(gvar, d1)\n\n#endif\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nTEST(MeshBasicGeometriesSuite, testMeshBox)\n{\n \/\/ create a box, mixing integers and floats\n BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n my_box.Build();\n ASSERT_TRUE(my_box.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_box.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n ASSERT_GT(diagonal_size, 17.320508);\n ASSERT_LT(diagonal_size, 17.320509);\n \/\/ create and add hypothesis\n StdMeshers_AutomaticLength* hyp1d_0 = new StdMeshers_AutomaticLength(0,0,meshgen);\n StdMeshers_NumberOfSegments* hyp1d_1 = new StdMeshers_NumberOfSegments(1,0,meshgen);\n hyp1d_1->SetNumberOfSegments(1);\n StdMeshers_Regular_1D* hyp1d_2 = new StdMeshers_Regular_1D(2,0,meshgen);\n StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(3,0,meshgen);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 3);\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshBoxMEFISTO2)\n{\n \/\/ create a box, mixing integers and floats\n BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n my_box.Build();\n ASSERT_TRUE(my_box.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_box.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n ASSERT_GT(diagonal_size, 17.320508);\n ASSERT_LT(diagonal_size, 17.320509);\n \/\/ create and add hypothesis\n StdMeshers_AutomaticLength* hyp1d = new StdMeshers_AutomaticLength(0,0,meshgen);\n StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(1,0,meshgen);\n StdMeshers_MEFISTO_2D* mef2d = new StdMeshers_MEFISTO_2D(2,0,meshgen) ;\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshSphere)\n{\n \/\/ the same as the previous test, but with a sphere\n BRepPrimAPI_MakeSphere my_sphere(10.);\n my_sphere.Build();\n ASSERT_TRUE(my_sphere.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_sphere.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshTorus)\n{\n \/\/ the same as the previous test, but with a sphere\n BRepPrimAPI_MakeTorus my_torus(10., 20.);\n my_torus.Build();\n ASSERT_TRUE(my_torus.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_torus.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nint main(int argc, char **argv){\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nFixed MeshBasicGeometries example#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nTEST(MeshBasicGeometriesSuite, testMeshBox)\n{\n \/\/ create a box, mixing integers and floats\n BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n my_box.Build();\n ASSERT_TRUE(my_box.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_box.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n ASSERT_GT(diagonal_size, 17.320508);\n ASSERT_LT(diagonal_size, 17.320509);\n \/\/ create and add hypothesis\n StdMeshers_AutomaticLength* hyp1d_0 = new StdMeshers_AutomaticLength(0,0,meshgen);\n StdMeshers_NumberOfSegments* hyp1d_1 = new StdMeshers_NumberOfSegments(1,0,meshgen);\n hyp1d_1->SetNumberOfSegments(1);\n StdMeshers_Regular_1D* hyp1d_2 = new StdMeshers_Regular_1D(2,0,meshgen);\n StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(3,0,meshgen);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 3);\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshBoxMEFISTO2)\n{\n \/\/ create a box, mixing integers and floats\n BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n my_box.Build();\n ASSERT_TRUE(my_box.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_box.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n ASSERT_GT(diagonal_size, 17.320508);\n ASSERT_LT(diagonal_size, 17.320509);\n \/\/ create and add hypothesis\n StdMeshers_Arithmetic1D* hyp1d = new StdMeshers_Arithmetic1D(0,0,meshgen);\n hyp1d->SetLength(0.1, false); \/\/ the smallest distance between 2 points\n hyp1d->SetLength(0.5, true); \/\/ the longest distance between 2 points\n StdMeshers_Regular_1D* an1DAlgo = new StdMeshers_Regular_1D(1, 0, meshgen); \/\/ interpolation\n StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(2,0,meshgen);\n StdMeshers_MEFISTO_2D* mef2d = new StdMeshers_MEFISTO_2D(3,0,meshgen) ;\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 3);\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshSphere)\n{\n \/\/ the same as the previous test, but with a sphere\n BRepPrimAPI_MakeSphere my_sphere(10.);\n my_sphere.Build();\n ASSERT_TRUE(my_sphere.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_sphere.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshQuadrangleTorus)\n{\n \/\/ the same as the previous test, but with a sphere\n BRepPrimAPI_MakeTorus my_torus(10., 20.);\n my_torus.Build();\n ASSERT_TRUE(my_torus.IsDone());\n \/\/ create the Mesh\n SMESH_Gen* meshgen = new SMESH_Gen();\n SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n \/\/ 1D\n StdMeshers_Arithmetic1D* hyp1d = new StdMeshers_Arithmetic1D(0,0,meshgen);\n hyp1d->SetLength(0.1, false); \/\/ the smallest distance between 2 points\n hyp1d->SetLength(0.5, true); \/\/ the longest distance between 2 points\n StdMeshers_Regular_1D* an1DAlgo = new StdMeshers_Regular_1D(1, 0, meshgen); \/\/ interpolation\n StdMeshers_Quadrangle_2D *a2dAlgo = new StdMeshers_Quadrangle_2D(2, 0, meshgen);\n \/\/ add hypothesis\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n \/\/ set geometry to be meshed\n mesh->ShapeToMesh(my_torus.Shape());\n ASSERT_TRUE(mesh->HasShapeToMesh());\n \/\/ compute the mesh\n meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n \/\/ free memory\n delete meshgen;\n delete mesh;\n}\n\nint main(int argc, char **argv){\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \"components\/RatingComponent.h\"\n#include \"Renderer.h\"\n#include \"Window.h\"\n#include \"Util.h\"\n#include \"resources\/SVGResource.h\"\n\nRatingComponent::RatingComponent(Window* window) : GuiComponent(window)\n{\n\tmFilledTexture = TextureResource::get(\":\/star_filled.svg\", true);\n\tmUnfilledTexture = TextureResource::get(\":\/star_unfilled.svg\", true);\n\tmValue = 0.5f;\n\tmSize << 64 * NUM_RATING_STARS, 64;\n\tupdateVertices();\n}\n\nvoid RatingComponent::setValue(const std::string& value)\n{\n\tif(value.empty())\n\t{\n\t\tmValue = 0.0f;\n\t}else{\n\t\tmValue = stof(value);\n\t\tif(mValue > 1.0f)\n\t\t\tmValue = 1.0f;\n\t\telse if(mValue < 0.0f)\n\t\t\tmValue = 0.0f;\n\t}\n\n\tupdateVertices();\n}\n\nstd::string RatingComponent::getValue() const\n{\n\treturn std::to_string((long double)mValue);\n}\n\nvoid RatingComponent::onSizeChanged()\n{\n\tif(mSize.y() == 0)\n\t\tmSize[1] = mSize.x() \/ NUM_RATING_STARS;\n\telse if(mSize.x() == 0)\n\t\tmSize[0] = mSize.y() * NUM_RATING_STARS;\n\n\tauto filledSVG = dynamic_cast(mFilledTexture.get());\n\tauto unfilledSVG = dynamic_cast(mUnfilledTexture.get());\n\n\tif(mSize.y() > 0)\n\t{\n\t\tsize_t heightPx = (size_t)round(mSize.y());\n\t\tif(filledSVG)\n\t\t\tfilledSVG->rasterizeAt(heightPx, heightPx);\n\t\tif(unfilledSVG)\n\t\t\tunfilledSVG->rasterizeAt(heightPx, heightPx);\n\t}\n\n\tupdateVertices();\n}\n\nvoid RatingComponent::updateVertices()\n{\n\tconst float numStars = NUM_RATING_STARS;\n\n\tconst float h = round(getSize().y()); \/\/ is the same as a single star's width\n\tconst float w = round(h * mValue * numStars);\n\tconst float fw = round(h * numStars);\n\n\tmVertices[0].pos << 0.0f, 0.0f;\n\t\tmVertices[0].tex << 0.0f, 1.0f;\n\tmVertices[1].pos << w, h;\n\t\tmVertices[1].tex << mValue * numStars, 0.0f;\n\tmVertices[2].pos << 0.0f, h;\n\t\tmVertices[2].tex << 0.0f, 0.0f;\n\n\tmVertices[3] = mVertices[0];\n\tmVertices[4].pos << w, 0.0f;\n\t\tmVertices[4].tex << mValue * numStars, 1.0f;\n\tmVertices[5] = mVertices[1];\n\n\tmVertices[6] = mVertices[4];\n\tmVertices[7].pos << fw, h;\n\t\tmVertices[7].tex << numStars, 0.0f;\n\tmVertices[8] = mVertices[1];\n\n\tmVertices[9] = mVertices[6];\n\tmVertices[10].pos << fw, 0.0f;\n\t\tmVertices[10].tex << numStars, 1.0f;\n\tmVertices[11] = mVertices[7];\n}\n\nvoid RatingComponent::render(const Eigen::Affine3f& parentTrans)\n{\n\tEigen::Affine3f trans = roundMatrix(parentTrans * getTransform());\n\tRenderer::setMatrix(trans);\n\n\tglEnable(GL_TEXTURE_2D);\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tglColor4ub(255, 255, 255, getOpacity());\n\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\n\tglVertexPointer(2, GL_FLOAT, sizeof(Vertex), &mVertices[0].pos);\n\tglTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &mVertices[0].tex);\n\t\n\tmFilledTexture->bind();\n\tglDrawArrays(GL_TRIANGLES, 0, 6);\n\n\tmUnfilledTexture->bind();\n\tglDrawArrays(GL_TRIANGLES, 6, 6);\n\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\n\tglDisable(GL_TEXTURE_2D);\n\tglDisable(GL_BLEND);\n\n\tglColor4ub(255, 255, 255, 255);\n\n\trenderChildren(trans);\n}\n\nbool RatingComponent::input(InputConfig* config, Input input)\n{\n\tif(config->isMappedTo(\"a\", input) && input.value != 0)\n\t{\n\t\tmValue += 1.f \/ NUM_RATING_STARS;\n\t\tif(mValue > 1.0f)\n\t\t\tmValue = 0.0f;\n\n\t\tupdateVertices();\n\t}\n\n\treturn GuiComponent::input(config, input);\n}\n\nvoid RatingComponent::applyTheme(const std::shared_ptr& theme, const std::string& view, const std::string& element, unsigned int properties)\n{\n\tGuiComponent::applyTheme(theme, view, element, properties);\n\n\tusing namespace ThemeFlags;\n\n\tconst ThemeData::ThemeElement* elem = theme->getElement(view, element, \"rating\");\n\tif(!elem)\n\t\treturn;\n\n\tbool imgChanged = false;\n\tif(properties & PATH && elem->has(\"filledPath\"))\n\t{\n\t\tmFilledTexture = TextureResource::get(elem->get(\"filledPath\"), true);\n\t\timgChanged = true;\n\t}\n\tif(properties & PATH && elem->has(\"unfilledPath\"))\n\t{\n\t\tmUnfilledTexture = TextureResource::get(elem->get(\"unfilledPath\"), true);\n\t\timgChanged = true;\n\t}\n\n\tif(imgChanged)\n\t\tonSizeChanged();\n}\n\nstd::vector RatingComponent::getHelpPrompts()\n{\n\tstd::vector prompts;\n\tprompts.push_back(HelpPrompt(\"a\", \"add star\"));\n\treturn prompts;\n}\nFixed ratings mysteriously not working on certain locales (e.g. German).#include \"components\/RatingComponent.h\"\n#include \"Renderer.h\"\n#include \"Window.h\"\n#include \"Util.h\"\n#include \"resources\/SVGResource.h\"\n\nRatingComponent::RatingComponent(Window* window) : GuiComponent(window)\n{\n\tmFilledTexture = TextureResource::get(\":\/star_filled.svg\", true);\n\tmUnfilledTexture = TextureResource::get(\":\/star_unfilled.svg\", true);\n\tmValue = 0.5f;\n\tmSize << 64 * NUM_RATING_STARS, 64;\n\tupdateVertices();\n}\n\nvoid RatingComponent::setValue(const std::string& value)\n{\n\tif(value.empty())\n\t{\n\t\tmValue = 0.0f;\n\t}else{\n\t\tmValue = stof(value);\n\t\tif(mValue > 1.0f)\n\t\t\tmValue = 1.0f;\n\t\telse if(mValue < 0.0f)\n\t\t\tmValue = 0.0f;\n\t}\n\n\tupdateVertices();\n}\n\nstd::string RatingComponent::getValue() const\n{\n\t\/\/ do not use std::to_string here as it will use the current locale\n\t\/\/ and that sometimes encodes decimals as commas\n\tstd::stringstream ss;\n\tss << mValue;\n\treturn ss.str();\n}\n\nvoid RatingComponent::onSizeChanged()\n{\n\tif(mSize.y() == 0)\n\t\tmSize[1] = mSize.x() \/ NUM_RATING_STARS;\n\telse if(mSize.x() == 0)\n\t\tmSize[0] = mSize.y() * NUM_RATING_STARS;\n\n\tauto filledSVG = dynamic_cast(mFilledTexture.get());\n\tauto unfilledSVG = dynamic_cast(mUnfilledTexture.get());\n\n\tif(mSize.y() > 0)\n\t{\n\t\tsize_t heightPx = (size_t)round(mSize.y());\n\t\tif(filledSVG)\n\t\t\tfilledSVG->rasterizeAt(heightPx, heightPx);\n\t\tif(unfilledSVG)\n\t\t\tunfilledSVG->rasterizeAt(heightPx, heightPx);\n\t}\n\n\tupdateVertices();\n}\n\nvoid RatingComponent::updateVertices()\n{\n\tconst float numStars = NUM_RATING_STARS;\n\n\tconst float h = round(getSize().y()); \/\/ is the same as a single star's width\n\tconst float w = round(h * mValue * numStars);\n\tconst float fw = round(h * numStars);\n\n\tmVertices[0].pos << 0.0f, 0.0f;\n\t\tmVertices[0].tex << 0.0f, 1.0f;\n\tmVertices[1].pos << w, h;\n\t\tmVertices[1].tex << mValue * numStars, 0.0f;\n\tmVertices[2].pos << 0.0f, h;\n\t\tmVertices[2].tex << 0.0f, 0.0f;\n\n\tmVertices[3] = mVertices[0];\n\tmVertices[4].pos << w, 0.0f;\n\t\tmVertices[4].tex << mValue * numStars, 1.0f;\n\tmVertices[5] = mVertices[1];\n\n\tmVertices[6] = mVertices[4];\n\tmVertices[7].pos << fw, h;\n\t\tmVertices[7].tex << numStars, 0.0f;\n\tmVertices[8] = mVertices[1];\n\n\tmVertices[9] = mVertices[6];\n\tmVertices[10].pos << fw, 0.0f;\n\t\tmVertices[10].tex << numStars, 1.0f;\n\tmVertices[11] = mVertices[7];\n}\n\nvoid RatingComponent::render(const Eigen::Affine3f& parentTrans)\n{\n\tEigen::Affine3f trans = roundMatrix(parentTrans * getTransform());\n\tRenderer::setMatrix(trans);\n\n\tglEnable(GL_TEXTURE_2D);\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tglColor4ub(255, 255, 255, getOpacity());\n\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\n\tglVertexPointer(2, GL_FLOAT, sizeof(Vertex), &mVertices[0].pos);\n\tglTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &mVertices[0].tex);\n\t\n\tmFilledTexture->bind();\n\tglDrawArrays(GL_TRIANGLES, 0, 6);\n\n\tmUnfilledTexture->bind();\n\tglDrawArrays(GL_TRIANGLES, 6, 6);\n\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\n\tglDisable(GL_TEXTURE_2D);\n\tglDisable(GL_BLEND);\n\n\tglColor4ub(255, 255, 255, 255);\n\n\trenderChildren(trans);\n}\n\nbool RatingComponent::input(InputConfig* config, Input input)\n{\n\tif(config->isMappedTo(\"a\", input) && input.value != 0)\n\t{\n\t\tmValue += 1.f \/ NUM_RATING_STARS;\n\t\tif(mValue > 1.0f)\n\t\t\tmValue = 0.0f;\n\n\t\tupdateVertices();\n\t}\n\n\treturn GuiComponent::input(config, input);\n}\n\nvoid RatingComponent::applyTheme(const std::shared_ptr& theme, const std::string& view, const std::string& element, unsigned int properties)\n{\n\tGuiComponent::applyTheme(theme, view, element, properties);\n\n\tusing namespace ThemeFlags;\n\n\tconst ThemeData::ThemeElement* elem = theme->getElement(view, element, \"rating\");\n\tif(!elem)\n\t\treturn;\n\n\tbool imgChanged = false;\n\tif(properties & PATH && elem->has(\"filledPath\"))\n\t{\n\t\tmFilledTexture = TextureResource::get(elem->get(\"filledPath\"), true);\n\t\timgChanged = true;\n\t}\n\tif(properties & PATH && elem->has(\"unfilledPath\"))\n\t{\n\t\tmUnfilledTexture = TextureResource::get(elem->get(\"unfilledPath\"), true);\n\t\timgChanged = true;\n\t}\n\n\tif(imgChanged)\n\t\tonSizeChanged();\n}\n\nstd::vector RatingComponent::getHelpPrompts()\n{\n\tstd::vector prompts;\n\tprompts.push_back(HelpPrompt(\"a\", \"add star\"));\n\treturn prompts;\n}\n<|endoftext|>"} {"text":"#include \"MicroBit.h\"\n\nextern \"C\" {\n void mp_run(void);\n\n void microbit_display_event(void);\n}\n\nstatic void event_listener(MicroBitEvent evt) {\n if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) {\n microbit_display_event();\n }\n}\n\nvoid app_main() {\n uBit.MessageBus.listen(MICROBIT_ID_DISPLAY,\n MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener);\n while (1) {\n mp_run();\n }\n}\nAdd commented-out debugging printfs for examining memory layout.#include \"MicroBit.h\"\n\nextern \"C\" {\n void mp_run(void);\n\n void microbit_display_event(void);\n}\n\nstatic void event_listener(MicroBitEvent evt) {\n if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) {\n microbit_display_event();\n }\n}\n\nvoid app_main() {\n \/*\n \/\/ debugging: print memory layout\n extern uint32_t __data_start__, __data_end__;\n extern uint32_t __bss_start__, __bss_end__;\n extern uint32_t __HeapLimit, __StackLimit, __StackTop;\n printf(\"__data_start__ = %p\\r\\n\", &__data_start__);\n printf(\"__data_end__ = %p\\r\\n\", &__data_end__);\n printf(\"__bss_start_ _ = %p\\r\\n\", &__bss_start__);\n printf(\"__bss_end__ = %p\\r\\n\", &__bss_end__);\n printf(\"__HeapLimit = %p\\r\\n\", &__HeapLimit);\n printf(\"__StackLimit = %p\\r\\n\", &__StackLimit);\n printf(\"__StackTop = %p\\r\\n\", &__StackTop);\n *\/\n\n uBit.MessageBus.listen(MICROBIT_ID_DISPLAY,\n MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener);\n while (1) {\n mp_run();\n }\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \n#include \n\n#include \"qnfctestcommon.h\"\n#include \"qnfctestutil.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nQTM_USE_NAMESPACE\n\nQ_DECLARE_METATYPE(QNearFieldTarget*)\nQ_DECLARE_METATYPE(QNearFieldTarget::Type)\nQ_DECLARE_METATYPE(QNdefFilter)\n\nclass tst_QNearFieldManager : public QObject\n{\n Q_OBJECT\n\npublic:\n tst_QNearFieldManager();\n\nprivate Q_SLOTS:\n void initTestCase();\n void cleanupTestCase();\n void targetDetected();\n void targetDetected_data();\n void unregisterTargetDetectedHandler();\n void registerTargetDetectedHandler();\n void registerTargetDetectedHandler_filter_data();\n void registerTargetDetectedHandler_filter();\n void registerTargetDetectedHandler_filter_negtive();\n void registerTargetDetectedHandler_filter_negtive_data();\n};\n\ntst_QNearFieldManager::tst_QNearFieldManager()\n{\n qRegisterMetaType(\"QNdefMessage\");\n qRegisterMetaType(\"QNearFieldTarget*\");\n}\n\nvoid tst_QNearFieldManager::initTestCase()\n{\n qRegisterMetaType(\"QNearFieldTarget *\");\n}\n\nvoid tst_QNearFieldManager::cleanupTestCase()\n{\n}\n\n\/*!\n Description: Unit test for NFC target detected and lost\n\n TestScenario: 1. Touch and remove llcp device\/Type1\/Type2\/Type3\/Type4 tag one by one\n\n TestExpectedResults: 1. llcp device\/Type1\/Type2\/Type3\/Type4 tag detected\/lost signal can be received\n*\/\n\nvoid tst_QNearFieldManager::targetDetected()\n{\n QFETCH(QNearFieldTarget::Type, type);\n QFETCH(QString, hint);\n\n QNearFieldManager nfcManager;\n\n QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));\n QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*)));\n\n nfcManager.startTargetDetection(type);\n QNfcTestUtil::ShowMessage(hint);\n QTRY_VERIFY(!targetDetectedSpy.isEmpty());\n\n QNearFieldTarget *target = targetDetectedSpy.first().at(0).value();\n\n QSignalSpy disconnectedSpy(target, SIGNAL(disconnected()));\n QVERIFY(target);\n\n QVERIFY(!target->uid().isEmpty());\n\n if (type != QNearFieldTarget::AnyTarget)\n {\n QCOMPARE(target->type(), type);\n }\n\n QNfcTestUtil::ShowMessage(\"please remove the target\");\n\n QTRY_VERIFY(!targetLostSpy.isEmpty());\n\n QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value();\n\n QCOMPARE(target, lostTarget);\n\n QVERIFY(!disconnectedSpy.isEmpty());\n\n nfcManager.stopTargetDetection();\n}\n\nvoid tst_QNearFieldManager::targetDetected_data()\n{\n QTest::addColumn(\"type\");\n QTest::addColumn(\"hint\");\n QTest::newRow(\"llcp device\") << QNearFieldTarget::AnyTarget << \"Please touch llcp device\";\n QTest::newRow(\"NfcTagType1\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type1\";\n QTest::newRow(\"NfcTagType2\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type2\";\n QTest::newRow(\"NfcTagType3\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type3\";\n QTest::newRow(\"NfcTagType4\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type4\";\n}\n\n\/*!\n Description: Unit test for NFC unregisterTargetDetectedHandler function\n\n TestScenario: 1.\n\n TestExpectedResults: 1. return false\n*\/\n\nvoid tst_QNearFieldManager::unregisterTargetDetectedHandler()\n{\n QNearFieldManager manager;\n\n QVERIFY(!manager.unregisterTargetDetectedHandler(-1));\n QVERIFY(!manager.unregisterTargetDetectedHandler(0));\n}\n\nclass MessageListener : public QObject\n{\n Q_OBJECT\n\nsignals:\n void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target);\n};\n\n\/*!\n Description: Unit test for NFC registerTargetDetectedHandler function\n\n TestScenario: 1. Symbian backend does not support registerTargetDetectedHandler without a QNdefFilter\n\n TestExpectedResults: 1. return -1\n*\/\nvoid tst_QNearFieldManager::registerTargetDetectedHandler()\n{\n QNearFieldManager manager;\n\n MessageListener listener;\n QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n int id = manager.registerTargetDetectedHandler(&listener,\n SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n QVERIFY(id == -1);\/\/symbian backend does not support registerTargetDetectedHandler without QNdefFilter\n}\n\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter_data()\n{\n QTest::addColumn(\"filter\");\n QTest::addColumn(\"hint\");\n\n QNdefFilter filter;\n\n filter.appendRecord(QNdefRecord::NfcRtd, \"Sp\");\n QTest::newRow(\"SP\") << filter << \"Please touch a tag with 'SP' NDef message\";\n\n filter.clear();\n filter.setOrderMatch(true);\n filter.appendRecord(QNdefRecord::Mime, \"image\/png\");\n filter.appendRecord(2, 10);\n filter.appendRecord(1, 1);\n QTest::newRow(\"Image + Multiple Text + URI\") << filter << \"Please touch a tag with 'Image + Multiple Text + URI' NDef message\";\n\n filter.clear();\n filter.setOrderMatch(true);\n filter.appendRecord(1, 1);\n filter.appendRecord(1, 1);\n QTest::newRow(\"Text + URI\") << filter << \"Please touch a tag with 'Text + URI' NDef message\";\n\n \/\/negtive test\n filter.clear();\n filter.appendRecord(1, 1);\n QTest::newRow(\"URI\") << filter << \"Please touch a tag without 'URI' NDef message\";\n\n}\n\n\/*!\n Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter\n\n TestScenario: 1. Touch a tag with random NDef message\/with 'Image + Multiple Text + URI' NDef message\/with 'Text + URI' NDef message\n\n TestExpectedResults: 1. matchedNdefMessage signal will be emitted\n*\/\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter()\n{\n QFETCH(QNdefFilter, filter);\n QFETCH(QString, hint);\n\n QNearFieldManager manager;\n\n MessageListener listener;\n QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n int id = manager.registerTargetDetectedHandler(filter, &listener,\n SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n QVERIFY(id != -1);\n\n QNfcTestUtil::ShowMessage(hint);\n\n QTRY_VERIFY(!messageSpy.isEmpty());\n\n const QNdefMessage message = messageSpy.first().at(0).value();\n\n QNearFieldTarget *target = messageSpy.first().at(1).value();\n\n QVERIFY(target == NULL);\/\/symbain backend always return NULL target\n\n QVERIFY(manager.unregisterTargetDetectedHandler(id));\n}\n\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive_data()\n{\n QTest::addColumn(\"filter\");\n QTest::addColumn(\"hint\");\n \/\/negtive test\n QNdefFilter filter;\n\n\n QTest::newRow(\"Empty\") << filter << \"Please touch a tag without NDef message\";\n\n filter.clear();\n filter.appendRecord(1, 1);\n QTest::newRow(\"URI\") << filter << \"Please touch a tag without 'URI' NDef message\";\n\n}\n\n\/*!\n Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter\n\n TestScenario: 1. Touch a tag without filter expected NDef message\n\n TestExpectedResults: 1. matchedNdefMessage signal will NOT be emitted\n*\/\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive()\n{\n QFETCH(QNdefFilter, filter);\n QFETCH(QString, hint);\n\n QNearFieldManager manager;\n\n MessageListener listener;\n QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n int id = manager.registerTargetDetectedHandler(filter, &listener,\n SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n QVERIFY(id != -1);\n\n QNfcTestUtil::ShowMessage(hint);\n\n QTRY_VERIFY(messageSpy.isEmpty());\n QVERIFY(manager.unregisterTargetDetectedHandler(id));\n}\n\nQTEST_MAIN(tst_QNearFieldManager);\n\n#include \"tst_qnearfieldmanager.moc\"\nchange test image type to gif\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \n#include \n\n#include \"qnfctestcommon.h\"\n#include \"qnfctestutil.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nQTM_USE_NAMESPACE\n\nQ_DECLARE_METATYPE(QNearFieldTarget*)\nQ_DECLARE_METATYPE(QNearFieldTarget::Type)\nQ_DECLARE_METATYPE(QNdefFilter)\n\nclass tst_QNearFieldManager : public QObject\n{\n Q_OBJECT\n\npublic:\n tst_QNearFieldManager();\n\nprivate Q_SLOTS:\n void initTestCase();\n void cleanupTestCase();\n void targetDetected();\n void targetDetected_data();\n void unregisterTargetDetectedHandler();\n void registerTargetDetectedHandler();\n void registerTargetDetectedHandler_filter_data();\n void registerTargetDetectedHandler_filter();\n void registerTargetDetectedHandler_filter_negtive();\n void registerTargetDetectedHandler_filter_negtive_data();\n};\n\ntst_QNearFieldManager::tst_QNearFieldManager()\n{\n qRegisterMetaType(\"QNdefMessage\");\n qRegisterMetaType(\"QNearFieldTarget*\");\n}\n\nvoid tst_QNearFieldManager::initTestCase()\n{\n qRegisterMetaType(\"QNearFieldTarget *\");\n}\n\nvoid tst_QNearFieldManager::cleanupTestCase()\n{\n}\n\n\/*!\n Description: Unit test for NFC target detected and lost\n\n TestScenario: 1. Touch and remove llcp device\/Type1\/Type2\/Type3\/Type4 tag one by one\n\n TestExpectedResults: 1. llcp device\/Type1\/Type2\/Type3\/Type4 tag detected\/lost signal can be received\n*\/\n\nvoid tst_QNearFieldManager::targetDetected()\n{\n QFETCH(QNearFieldTarget::Type, type);\n QFETCH(QString, hint);\n\n QNearFieldManager nfcManager;\n\n QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));\n QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*)));\n\n nfcManager.startTargetDetection(type);\n QNfcTestUtil::ShowMessage(hint);\n QTRY_VERIFY(!targetDetectedSpy.isEmpty());\n\n QNearFieldTarget *target = targetDetectedSpy.first().at(0).value();\n\n QSignalSpy disconnectedSpy(target, SIGNAL(disconnected()));\n QVERIFY(target);\n\n QVERIFY(!target->uid().isEmpty());\n\n if (type != QNearFieldTarget::AnyTarget)\n {\n QCOMPARE(target->type(), type);\n }\n\n QNfcTestUtil::ShowMessage(\"please remove the target\");\n\n QTRY_VERIFY(!targetLostSpy.isEmpty());\n\n QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value();\n\n QCOMPARE(target, lostTarget);\n\n QVERIFY(!disconnectedSpy.isEmpty());\n\n nfcManager.stopTargetDetection();\n}\n\nvoid tst_QNearFieldManager::targetDetected_data()\n{\n QTest::addColumn(\"type\");\n QTest::addColumn(\"hint\");\n QTest::newRow(\"llcp device\") << QNearFieldTarget::AnyTarget << \"Please touch llcp device\";\n QTest::newRow(\"NfcTagType1\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type1\";\n QTest::newRow(\"NfcTagType2\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type2\";\n QTest::newRow(\"NfcTagType3\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type3\";\n QTest::newRow(\"NfcTagType4\") << QNearFieldTarget::NfcTagType1 << \"Please touch tag type4\";\n}\n\n\/*!\n Description: Unit test for NFC unregisterTargetDetectedHandler function\n\n TestScenario: 1.\n\n TestExpectedResults: 1. return false\n*\/\n\nvoid tst_QNearFieldManager::unregisterTargetDetectedHandler()\n{\n QNearFieldManager manager;\n\n QVERIFY(!manager.unregisterTargetDetectedHandler(-1));\n QVERIFY(!manager.unregisterTargetDetectedHandler(0));\n}\n\nclass MessageListener : public QObject\n{\n Q_OBJECT\n\nsignals:\n void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target);\n};\n\n\/*!\n Description: Unit test for NFC registerTargetDetectedHandler function\n\n TestScenario: 1. Symbian backend does not support registerTargetDetectedHandler without a QNdefFilter\n\n TestExpectedResults: 1. return -1\n*\/\nvoid tst_QNearFieldManager::registerTargetDetectedHandler()\n{\n QNearFieldManager manager;\n\n MessageListener listener;\n QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n int id = manager.registerTargetDetectedHandler(&listener,\n SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n QVERIFY(id == -1);\/\/symbian backend does not support registerTargetDetectedHandler without QNdefFilter\n}\n\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter_data()\n{\n QTest::addColumn(\"filter\");\n QTest::addColumn(\"hint\");\n\n QNdefFilter filter;\n\n filter.appendRecord(QNdefRecord::NfcRtd, \"Sp\");\n QTest::newRow(\"SP\") << filter << \"Please touch a tag with 'SP' NDef message\";\n\n filter.clear();\n filter.setOrderMatch(true);\n filter.appendRecord(QNdefRecord::Mime, \"image\/gif\");\n filter.appendRecord(2, 10);\n filter.appendRecord(1, 1);\n QTest::newRow(\"Image + Multiple Text + URI\") << filter << \"Please touch a tag with 'Image + Multiple Text + URI' NDef message\";\n\n filter.clear();\n filter.setOrderMatch(true);\n filter.appendRecord(1, 1);\n filter.appendRecord(1, 1);\n QTest::newRow(\"Text + URI\") << filter << \"Please touch a tag with 'Text + URI' NDef message\";\n\n \/\/negtive test\n filter.clear();\n filter.appendRecord(1, 1);\n QTest::newRow(\"URI\") << filter << \"Please touch a tag without 'URI' NDef message\";\n\n}\n\n\/*!\n Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter\n\n TestScenario: 1. Touch a tag with random NDef message\/with 'Image + Multiple Text + URI' NDef message\/with 'Text + URI' NDef message\n\n TestExpectedResults: 1. matchedNdefMessage signal will be emitted\n*\/\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter()\n{\n QFETCH(QNdefFilter, filter);\n QFETCH(QString, hint);\n\n QNearFieldManager manager;\n\n MessageListener listener;\n QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n int id = manager.registerTargetDetectedHandler(filter, &listener,\n SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n QVERIFY(id != -1);\n\n QNfcTestUtil::ShowMessage(hint);\n\n QTRY_VERIFY(!messageSpy.isEmpty());\n\n const QNdefMessage message = messageSpy.first().at(0).value();\n\n QNearFieldTarget *target = messageSpy.first().at(1).value();\n\n QVERIFY(target == NULL);\/\/symbain backend always return NULL target\n\n QVERIFY(manager.unregisterTargetDetectedHandler(id));\n}\n\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive_data()\n{\n QTest::addColumn(\"filter\");\n QTest::addColumn(\"hint\");\n \/\/negtive test\n QNdefFilter filter;\n\n\n QTest::newRow(\"Empty\") << filter << \"Please touch a tag without NDef message\";\n\n filter.clear();\n filter.appendRecord(1, 1);\n QTest::newRow(\"URI\") << filter << \"Please touch a tag without 'URI' NDef message\";\n\n}\n\n\/*!\n Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter\n\n TestScenario: 1. Touch a tag without filter expected NDef message\n\n TestExpectedResults: 1. matchedNdefMessage signal will NOT be emitted\n*\/\nvoid tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive()\n{\n QFETCH(QNdefFilter, filter);\n QFETCH(QString, hint);\n\n QNearFieldManager manager;\n\n MessageListener listener;\n QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n int id = manager.registerTargetDetectedHandler(filter, &listener,\n SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));\n\n QVERIFY(id != -1);\n\n QNfcTestUtil::ShowMessage(hint);\n\n QTRY_VERIFY(messageSpy.isEmpty());\n QVERIFY(manager.unregisterTargetDetectedHandler(id));\n}\n\nQTEST_MAIN(tst_QNearFieldManager);\n\n#include \"tst_qnearfieldmanager.moc\"\n<|endoftext|>"} {"text":"\/\/ Petter Strandmark 2012.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace spii {\n\nvoid Solver::solve_newton(const Function& function,\n SolverResults* results) const\n{\n\tdouble global_start_time = wall_time();\n\n\t\/\/ Random number engine for random pertubation.\n\tstd::mt19937 prng(unsigned(1));\n\tstd::uniform_real_distribution uniform11(-1.0, 1.0);\n\tauto rand11 = std::bind(uniform11, prng);\n\n\t\/\/ Dimension of problem.\n\tsize_t n = function.get_number_of_scalars();\n\n\t\/\/ Determine whether to use sparse representation\n\t\/\/ and matrix factorization.\n\tbool use_sparsity;\n\tif (this->sparsity_mode == DENSE) {\n\t\tuse_sparsity = false;\n\t}\n\telse if (this->sparsity_mode == SPARSE) {\n\t\tuse_sparsity = true;\n\t}\n\telse {\n\t\tif (n <= 50) {\n\t\t\tuse_sparsity = false;\n\t\t}\n\t\telse {\n\t\t\tuse_sparsity = true;\n\t\t}\n\t}\n\n\t\/\/ Current point, gradient and Hessian.\n\tdouble fval = std::numeric_limits::quiet_NaN();;\n\tdouble fprev = std::numeric_limits::quiet_NaN();\n\tdouble normg0 = std::numeric_limits::quiet_NaN();\n\tdouble normg = std::numeric_limits::quiet_NaN();\n\tdouble normdx = std::numeric_limits::quiet_NaN();\n\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\tEigen::SparseMatrix sparse_H;\n\tif (use_sparsity) {\n\t\t\/\/ Create sparsity pattern for H.\n\t\tfunction.create_sparse_hessian(&sparse_H);\n\t\tif (this->log_function) {\n\t\t\tdouble nnz = double(sparse_H.nonZeros()) \/ double(n * n);\n\t\t\tchar str[1024];\n\t\t\tstd::sprintf(str, \"H is %dx%d with %d (%.5f%%) non-zeroes.\",\n\t\t\t\tsparse_H.rows(), sparse_H.cols(), sparse_H.nonZeros(), 100.0 * nnz);\n\t\t\tthis->log_function(str);\n\t\t}\n\t}\n\n\t\/\/ Copy the user state to the current point.\n\tfunction.copy_user_to_global(&x);\n\tEigen::VectorXd x2(n);\n\n\t\/\/ p will store the search direction.\n\tEigen::VectorXd p(function.get_number_of_scalars());\n\n\t\/\/ Dense and sparse Cholesky factorizers.\n\ttypedef Eigen::LLT LLT;\n\ttypedef Eigen::SimplicialLLT > SparseLLT;\n\tstd::unique_ptr factorization;\n\tstd::unique_ptr sparse_factorization;\n\tif (!use_sparsity) {\n\t\tfactorization.reset(new LLT(n));\n\t}\n\telse {\n\t\tsparse_factorization.reset(new SparseLLT);\n\t\t\/\/ The sparsity pattern of H is always the same. Therefore, it is enough\n\t\t\/\/ to analyze it once.\n\t\tsparse_factorization->analyzePattern(sparse_H);\n\t}\n\n\tFactorizationCache factorization_cache(n);\n\n\t\/\/\n\t\/\/ START MAIN ITERATION\n\t\/\/\n\tresults->startup_time = wall_time() - global_start_time;\n\tresults->exit_condition = SolverResults::INTERNAL_ERROR;\n\tint iter = 0;\n\twhile (true) {\n\n\t\tint log_interval = 1;\n\t\tif (iter > 30) {\n\t\t\tlog_interval = 10;\n\t\t}\n\t\tif (iter > 200) {\n\t\t\tlog_interval = 100;\n\t\t}\n\t\tif (iter > 2000) {\n\t\t\tlog_interval = 1000;\n\t\t}\n\n\t\t\/\/\n\t\t\/\/ Evaluate function and derivatives.\n\t\t\/\/\n\t\tdouble start_time = wall_time();\n\t\tif (use_sparsity) {\n\t\t\tfval = function.evaluate(x, &g, &sparse_H);\n\t\t}\n\t\telse {\n\t\t\tfval = function.evaluate(x, &g, &H);\n\t\t}\n\n\t\tnormg = std::max(g.maxCoeff(), -g.minCoeff());\n\t\tif (iter == 0) {\n\t\t\tnormg0 = normg;\n\t\t}\n\n\t\t\/\/ Check for NaN.\n\t\tif (normg != normg) {\n\t\t\tresults->exit_condition = SolverResults::FUNCTION_NAN;\n\t\t\tbreak;\n\t\t}\n\n\t\tresults->function_evaluation_time += wall_time() - start_time;\n\n\t\t\/\/\n\t\t\/\/ Test stopping criteriea\n\t\t\/\/\n\t\tstart_time = wall_time();\n\t\tif (this->check_exit_conditions(fval, fprev, normg,\n\t\t\t normg0, x.norm(), normdx,\n\t\t\t true, results)) {\n\t\t\tbreak;\n\t\t}\n\t\tif (iter >= this->maximum_iterations) {\n\t\t\tresults->exit_condition = SolverResults::NO_CONVERGENCE;\n\t\t\tbreak;\n\t\t}\n\t\tresults->stopping_criteria_time += wall_time() - start_time;\n\n\n\t\tint factorizations = 0;\n\t\tdouble tau = 0;\n\t\tdouble mindiag = 0;\n\n\t\tif (use_sparsity || this->factorization_method == ITERATIVE) {\n\t\t\t\/\/\n\t\t\t\/\/ Attempt repeated Cholesky factorization until the Hessian\n\t\t\t\/\/ becomes positive semidefinite.\n\t\t\t\/\/\n\t\t\t\/\/start_time = wall_time();\n\t\t\tdouble beta = 1.0;\n\n\t\t\tEigen::VectorXd dH;\n\t\t\tif (use_sparsity) {\n\t\t\t\tdH = sparse_H.diagonal();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdH = H.diagonal();\n\t\t\t}\n\t\t\tmindiag = dH.minCoeff();\n\n\t\t\tif (mindiag > 0) {\n\t\t\t\ttau = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau = -mindiag + beta;\n\t\t\t}\n\t\t\twhile (true) {\n\t\t\t\t\/\/ Add tau*I to the Hessian.\n\t\t\t\tif (tau > 0) {\n\t\t\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\t\t\tif (use_sparsity) {\n\t\t\t\t\t\t\tint ii = static_cast(i);\n\t\t\t\t\t\t\tsparse_H.coeffRef(ii, ii) = dH(i) + tau;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tH(i, i) = dH(i) + tau;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Attempt Cholesky factorization.\n\t\t\t\tbool success;\n\t\t\t\tif (use_sparsity) {\n\t\t\t\t\tsparse_factorization->factorize(sparse_H);\n\t\t\t\t\tsuccess = sparse_factorization->info() == Eigen::Success;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfactorization->compute(H);\n\t\t\t\t\tsuccess = factorization->info() == Eigen::Success;\n\t\t\t\t}\n\t\t\t\tfactorizations++;\n\t\t\t\t\/\/ Check for success.\n\t\t\t\tif (success) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttau = std::max(2*tau, beta);\n\n\t\t\t\tif (factorizations > 100) {\n\t\t\t\t\tthrow std::runtime_error(\"Solver::solve: factorization failed.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\n\n\t\t\tresults->matrix_factorization_time += wall_time() - start_time;\n\n\t\t\t\/\/\n\t\t\t\/\/ Solve linear system to obtain search direction.\n\t\t\t\/\/\n\t\t\tstart_time = wall_time();\n\n\t\t\tif (use_sparsity) {\n\t\t\t\tp = sparse_factorization->solve(-g);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp = factorization->solve(-g);\n\t\t\t}\n\n\t\t\tresults->linear_solver_time += wall_time() - start_time;\n\t\t}\n\t\telse {\n\t\t\t\/\/ Performs a BKP block diagonal factorization, modifies it, and\n\t\t\t\/\/ solvers the linear system.\n\t\t\tthis->BKP_dense(H, g, factorization_cache, &p, results);\n\t\t\tfactorizations = 1;\n\t\t}\n\n\t\t\/\/\n\t\t\/\/ Perform line search.\n\t\t\/\/\n\t\tstart_time = wall_time();\n\t\tdouble start_alpha = 1.0;\n\t\tdouble alpha = this->perform_linesearch(function, x, fval, g, p, &x2,\n\t\t start_alpha);\n\n\t\tif (alpha <= 1e-15) {\n\n\t\t\t\/\/ Attempt a simple steepest descent instead.\n\t\t\tp = -g;\n\t\t\talpha = this->perform_linesearch(function, x, fval, g, p, &x2,\n\t\t\t 1.0);\n\t\t\tif (alpha <= 0) {\n\n\t\t\t\tif (this->log_function) {\n\t\t\t\t\tthis->log_function(\"Steepest descent step failed. Numerical problems?\");\n\t\t\t\t}\n\n\t\t\t\t\/\/ This happens in really rare cases with numerical problems or\n\t\t\t\t\/\/ incorrectly defined objective functions. In the latter case,\n\t\t\t\t\/\/ there is not much to do. In the former case, randomly perturbing\n\t\t\t\t\/\/ x has been effective.\n\t\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\t\tx[i] = x[i] + 1e-6 * rand11() * x[i];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\talpha = 0;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Record length of this step.\n\t\tnormdx = alpha * p.norm();\n\t\t\/\/ Update current point.\n\t\tx = x + alpha * p;\n\n\t\tresults->backtracking_time += wall_time() - start_time;\n\n\t\t\/\/\n\t\t\/\/ Log the results of this iteration.\n\t\t\/\/\n\t\tstart_time = wall_time();\n\n\t\tif (this->log_function && iter % log_interval == 0) {\n\t\t\tchar str[1024];\n\t\t\tif (use_sparsity) {\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr f max|g_i| alpha fac tau min(H_ii)\");\n\t\t\t\t}\n\t\t\t\tstd::sprintf(str, \"%4d %+10.3e %9.3e %9.3e %3d %.1e %+.2e\",\n\t\t\t\t\titer, fval, normg, alpha, factorizations, tau, mindiag);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdouble detH = H.determinant();\n\t\t\t\tdouble normH = H.norm();\n\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr f max|g_i| ||H|| det(H) alpha fac\");\n\t\t\t\t}\n\t\t\t\tstd::sprintf(str, \"%4d %+10.3e %9.3e %9.3e %+10.3e %9.3e %3d\",\n\t\t\t\t\titer, fval, normg, normH, detH, alpha, factorizations);\n\t\t\t}\n\t\t\tthis->log_function(str);\n\t\t}\n\t\tresults->log_time += wall_time() - start_time;\n\n\t\tfprev = fval;\n\t\titer++;\n\t}\n\n\tfunction.copy_global_to_user(x);\n\tresults->total_time = wall_time() - global_start_time;\n\n\tif (this->log_function) {\n\t\tchar str[1024];\n\t\tstd::sprintf(str, \" end %+.3e %.3e\", fval, normg);\n\t\tthis->log_function(str);\n\t}\n}\n\n} \/\/ namespace spii\nLog formatting\/\/ Petter Strandmark 2012.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace spii {\n\nvoid Solver::solve_newton(const Function& function,\n SolverResults* results) const\n{\n\tdouble global_start_time = wall_time();\n\n\t\/\/ Random number engine for random pertubation.\n\tstd::mt19937 prng(unsigned(1));\n\tstd::uniform_real_distribution uniform11(-1.0, 1.0);\n\tauto rand11 = std::bind(uniform11, prng);\n\n\t\/\/ Dimension of problem.\n\tsize_t n = function.get_number_of_scalars();\n\n\t\/\/ Determine whether to use sparse representation\n\t\/\/ and matrix factorization.\n\tbool use_sparsity;\n\tif (this->sparsity_mode == DENSE) {\n\t\tuse_sparsity = false;\n\t}\n\telse if (this->sparsity_mode == SPARSE) {\n\t\tuse_sparsity = true;\n\t}\n\telse {\n\t\tif (n <= 50) {\n\t\t\tuse_sparsity = false;\n\t\t}\n\t\telse {\n\t\t\tuse_sparsity = true;\n\t\t}\n\t}\n\n\t\/\/ Current point, gradient and Hessian.\n\tdouble fval = std::numeric_limits::quiet_NaN();;\n\tdouble fprev = std::numeric_limits::quiet_NaN();\n\tdouble normg0 = std::numeric_limits::quiet_NaN();\n\tdouble normg = std::numeric_limits::quiet_NaN();\n\tdouble normdx = std::numeric_limits::quiet_NaN();\n\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\tEigen::SparseMatrix sparse_H;\n\tif (use_sparsity) {\n\t\t\/\/ Create sparsity pattern for H.\n\t\tfunction.create_sparse_hessian(&sparse_H);\n\t\tif (this->log_function) {\n\t\t\tdouble nnz = double(sparse_H.nonZeros()) \/ double(n * n);\n\t\t\tchar str[1024];\n\t\t\tstd::sprintf(str, \"H is %dx%d with %d (%.5f%%) non-zeroes.\",\n\t\t\t\tsparse_H.rows(), sparse_H.cols(), sparse_H.nonZeros(), 100.0 * nnz);\n\t\t\tthis->log_function(str);\n\t\t}\n\t}\n\n\t\/\/ Copy the user state to the current point.\n\tfunction.copy_user_to_global(&x);\n\tEigen::VectorXd x2(n);\n\n\t\/\/ p will store the search direction.\n\tEigen::VectorXd p(function.get_number_of_scalars());\n\n\t\/\/ Dense and sparse Cholesky factorizers.\n\ttypedef Eigen::LLT LLT;\n\ttypedef Eigen::SimplicialLLT > SparseLLT;\n\tstd::unique_ptr factorization;\n\tstd::unique_ptr sparse_factorization;\n\tif (!use_sparsity) {\n\t\tfactorization.reset(new LLT(n));\n\t}\n\telse {\n\t\tsparse_factorization.reset(new SparseLLT);\n\t\t\/\/ The sparsity pattern of H is always the same. Therefore, it is enough\n\t\t\/\/ to analyze it once.\n\t\tsparse_factorization->analyzePattern(sparse_H);\n\t}\n\n\tFactorizationCache factorization_cache(n);\n\n\t\/\/\n\t\/\/ START MAIN ITERATION\n\t\/\/\n\tresults->startup_time = wall_time() - global_start_time;\n\tresults->exit_condition = SolverResults::INTERNAL_ERROR;\n\tint iter = 0;\n\twhile (true) {\n\n\t\tint log_interval = 1;\n\t\tif (iter > 30) {\n\t\t\tlog_interval = 10;\n\t\t}\n\t\tif (iter > 200) {\n\t\t\tlog_interval = 100;\n\t\t}\n\t\tif (iter > 2000) {\n\t\t\tlog_interval = 1000;\n\t\t}\n\n\t\t\/\/\n\t\t\/\/ Evaluate function and derivatives.\n\t\t\/\/\n\t\tdouble start_time = wall_time();\n\t\tif (use_sparsity) {\n\t\t\tfval = function.evaluate(x, &g, &sparse_H);\n\t\t}\n\t\telse {\n\t\t\tfval = function.evaluate(x, &g, &H);\n\t\t}\n\n\t\tnormg = std::max(g.maxCoeff(), -g.minCoeff());\n\t\tif (iter == 0) {\n\t\t\tnormg0 = normg;\n\t\t}\n\n\t\t\/\/ Check for NaN.\n\t\tif (normg != normg) {\n\t\t\tresults->exit_condition = SolverResults::FUNCTION_NAN;\n\t\t\tbreak;\n\t\t}\n\n\t\tresults->function_evaluation_time += wall_time() - start_time;\n\n\t\t\/\/\n\t\t\/\/ Test stopping criteriea\n\t\t\/\/\n\t\tstart_time = wall_time();\n\t\tif (this->check_exit_conditions(fval, fprev, normg,\n\t\t\t normg0, x.norm(), normdx,\n\t\t\t true, results)) {\n\t\t\tbreak;\n\t\t}\n\t\tif (iter >= this->maximum_iterations) {\n\t\t\tresults->exit_condition = SolverResults::NO_CONVERGENCE;\n\t\t\tbreak;\n\t\t}\n\t\tresults->stopping_criteria_time += wall_time() - start_time;\n\n\n\t\tint factorizations = 0;\n\t\tdouble tau = 0;\n\t\tdouble mindiag = 0;\n\n\t\tif (use_sparsity || this->factorization_method == ITERATIVE) {\n\t\t\t\/\/\n\t\t\t\/\/ Attempt repeated Cholesky factorization until the Hessian\n\t\t\t\/\/ becomes positive semidefinite.\n\t\t\t\/\/\n\t\t\t\/\/start_time = wall_time();\n\t\t\tdouble beta = 1.0;\n\n\t\t\tEigen::VectorXd dH;\n\t\t\tif (use_sparsity) {\n\t\t\t\tdH = sparse_H.diagonal();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdH = H.diagonal();\n\t\t\t}\n\t\t\tmindiag = dH.minCoeff();\n\n\t\t\tif (mindiag > 0) {\n\t\t\t\ttau = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau = -mindiag + beta;\n\t\t\t}\n\t\t\twhile (true) {\n\t\t\t\t\/\/ Add tau*I to the Hessian.\n\t\t\t\tif (tau > 0) {\n\t\t\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\t\t\tif (use_sparsity) {\n\t\t\t\t\t\t\tint ii = static_cast(i);\n\t\t\t\t\t\t\tsparse_H.coeffRef(ii, ii) = dH(i) + tau;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tH(i, i) = dH(i) + tau;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Attempt Cholesky factorization.\n\t\t\t\tbool success;\n\t\t\t\tif (use_sparsity) {\n\t\t\t\t\tsparse_factorization->factorize(sparse_H);\n\t\t\t\t\tsuccess = sparse_factorization->info() == Eigen::Success;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfactorization->compute(H);\n\t\t\t\t\tsuccess = factorization->info() == Eigen::Success;\n\t\t\t\t}\n\t\t\t\tfactorizations++;\n\t\t\t\t\/\/ Check for success.\n\t\t\t\tif (success) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttau = std::max(2*tau, beta);\n\n\t\t\t\tif (factorizations > 100) {\n\t\t\t\t\tthrow std::runtime_error(\"Solver::solve: factorization failed.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\n\n\t\t\tresults->matrix_factorization_time += wall_time() - start_time;\n\n\t\t\t\/\/\n\t\t\t\/\/ Solve linear system to obtain search direction.\n\t\t\t\/\/\n\t\t\tstart_time = wall_time();\n\n\t\t\tif (use_sparsity) {\n\t\t\t\tp = sparse_factorization->solve(-g);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp = factorization->solve(-g);\n\t\t\t}\n\n\t\t\tresults->linear_solver_time += wall_time() - start_time;\n\t\t}\n\t\telse {\n\t\t\t\/\/ Performs a BKP block diagonal factorization, modifies it, and\n\t\t\t\/\/ solvers the linear system.\n\t\t\tthis->BKP_dense(H, g, factorization_cache, &p, results);\n\t\t\tfactorizations = 1;\n\t\t}\n\n\t\t\/\/\n\t\t\/\/ Perform line search.\n\t\t\/\/\n\t\tstart_time = wall_time();\n\t\tdouble start_alpha = 1.0;\n\t\tdouble alpha = this->perform_linesearch(function, x, fval, g, p, &x2,\n\t\t start_alpha);\n\n\t\tif (alpha <= 1e-15) {\n\n\t\t\t\/\/ Attempt a simple steepest descent instead.\n\t\t\tp = -g;\n\t\t\talpha = this->perform_linesearch(function, x, fval, g, p, &x2,\n\t\t\t 1.0);\n\t\t\tif (alpha <= 0) {\n\n\t\t\t\tif (this->log_function) {\n\t\t\t\t\tthis->log_function(\"Steepest descent step failed. Numerical problems?\");\n\t\t\t\t}\n\n\t\t\t\t\/\/ This happens in really rare cases with numerical problems or\n\t\t\t\t\/\/ incorrectly defined objective functions. In the latter case,\n\t\t\t\t\/\/ there is not much to do. In the former case, randomly perturbing\n\t\t\t\t\/\/ x has been effective.\n\t\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\t\tx[i] = x[i] + 1e-6 * rand11() * x[i];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\talpha = 0;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Record length of this step.\n\t\tnormdx = alpha * p.norm();\n\t\t\/\/ Update current point.\n\t\tx = x + alpha * p;\n\n\t\tresults->backtracking_time += wall_time() - start_time;\n\n\t\t\/\/\n\t\t\/\/ Log the results of this iteration.\n\t\t\/\/\n\t\tstart_time = wall_time();\n\n\t\tif (this->log_function && iter % log_interval == 0) {\n\t\t\tchar str[1024];\n\t\t\tif (use_sparsity) {\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr f max|g_i| alpha fac tau min(H_ii)\");\n\t\t\t\t}\n\t\t\t\tstd::sprintf(str, \"%4d %+10.6e %9.3e %9.3e %3d %.1e %+.2e\",\n\t\t\t\t\titer, fval, normg, alpha, factorizations, tau, mindiag);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdouble detH = H.determinant();\n\t\t\t\tdouble normH = H.norm();\n\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr f max|g_i| ||H|| det(H) alpha fac\");\n\t\t\t\t}\n\t\t\t\tstd::sprintf(str, \"%4d %+10.6e %9.3e %9.3e %+10.3e %9.3e %3d\",\n\t\t\t\t\titer, fval, normg, normH, detH, alpha, factorizations);\n\t\t\t}\n\t\t\tthis->log_function(str);\n\t\t}\n\t\tresults->log_time += wall_time() - start_time;\n\n\t\tfprev = fval;\n\t\titer++;\n\t}\n\n\tfunction.copy_global_to_user(x);\n\tresults->total_time = wall_time() - global_start_time;\n\n\tif (this->log_function) {\n\t\tchar str[1024];\n\t\tstd::sprintf(str, \" end %+10.6e %.3e\", fval, normg);\n\t\tthis->log_function(str);\n\t}\n}\n\n} \/\/ namespace spii\n<|endoftext|>"} {"text":"\/*\n * D-Bus AT-SPI, Qt Adaptor\n *\n * Copyright 2008-2011 Nokia Corporation and\/or its subsidiary(-ies).\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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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, see .\n *\/\n\n#include \"constant_mappings.h\"\n\n#include \n\n\/\/ FIXME the assignment of roles is quite arbitrary, at some point go through this list and sort and check that it makes sense\n\/\/ \"calendar\" \"check menu item\" \"color chooser\" \"column header\" \"dateeditor\" \"desktop icon\" \"desktop frame\"\n\/\/ \"directory pane\" \"drawing area\" \"file chooser\" \"fontchooser\" \"frame\" \"glass pane\" \"html container\" \"icon\"\n\/\/ \"internal frame\" \"option pane\" \"password text\" \"radio menu item\" \"root pane\" \"row header\" \"scroll pane\"\n\/\/ \"tear off menu item\" \"terminal\" \"toggle button\" \"tree table\" \"unknown\" \"viewport\" \"header\" \"footer\" \"paragraph\"\n\/\/ \"ruler\" \"autocomplete\" \"edit bar\" \"embedded component\" \"entry\" \"caption\"\n\/\/ \"heading\" \"page\" \"section\" \"redundant object\" \"form\" \"input method window\" \"menu\"\n\nQHash qSpiRoleMapping;\n\nstatic void initializeRoleMapping ()\n{\n qSpiRoleMapping.insert(QAccessible::NoRole, RoleNames(ATSPI_ROLE_INVALID, \"invalid\", QObject::tr(\"invalid role\")));\n qSpiRoleMapping.insert(QAccessible::TitleBar, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"title bar\")));\n qSpiRoleMapping.insert(QAccessible::MenuBar, RoleNames(ATSPI_ROLE_MENU_BAR, \"menu bar\", QObject::tr(\"menu bar\")));\n qSpiRoleMapping.insert(QAccessible::ScrollBar, RoleNames(ATSPI_ROLE_SCROLL_BAR, \"scroll bar\", QObject::tr(\"scroll bar\")));\n qSpiRoleMapping.insert(QAccessible::Grip, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"grip\")));\n qSpiRoleMapping.insert(QAccessible::Sound, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"sound\")));\n qSpiRoleMapping.insert(QAccessible::Cursor, RoleNames(ATSPI_ROLE_ARROW, \"arrow\", QObject::tr(\"cursor\")));\n qSpiRoleMapping.insert(QAccessible::Caret, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"caret\")));\n qSpiRoleMapping.insert(QAccessible::AlertMessage, RoleNames(ATSPI_ROLE_ALERT, \"alert\", QObject::tr(\"alert message\")));\n qSpiRoleMapping.insert(QAccessible::Window, RoleNames(ATSPI_ROLE_WINDOW, \"window\", QObject::tr(\"window\")));\n qSpiRoleMapping.insert(QAccessible::Client, RoleNames(ATSPI_ROLE_FILLER, \"filler\", QObject::tr(\"filler\")));\n qSpiRoleMapping.insert(QAccessible::PopupMenu, RoleNames(ATSPI_ROLE_POPUP_MENU, \"popup menu\", QObject::tr(\"popup menu\")));\n qSpiRoleMapping.insert(QAccessible::MenuItem, RoleNames(ATSPI_ROLE_MENU_ITEM, \"menu item\", QObject::tr(\"menu item\")));\n qSpiRoleMapping.insert(QAccessible::ToolTip, RoleNames(ATSPI_ROLE_TOOL_TIP, \"tool tip\", QObject::tr(\"tool tip\")));\n qSpiRoleMapping.insert(QAccessible::Application, RoleNames(ATSPI_ROLE_APPLICATION, \"application\", QObject::tr(\"application\")));\n qSpiRoleMapping.insert(QAccessible::Document, RoleNames(ATSPI_ROLE_DOCUMENT_FRAME, \"document frame\", QObject::tr(\"document\")));\n qSpiRoleMapping.insert(QAccessible::Pane, RoleNames(ATSPI_ROLE_PANEL, \"panel\", QObject::tr(\"pane\")));\n qSpiRoleMapping.insert(QAccessible::Chart, RoleNames(ATSPI_ROLE_CHART, \"chart\", QObject::tr(\"chart\")));\n qSpiRoleMapping.insert(QAccessible::Dialog, RoleNames(ATSPI_ROLE_DIALOG, \"dialog\", QObject::tr(\"dialog\")));\n qSpiRoleMapping.insert(QAccessible::Border, RoleNames(ATSPI_ROLE_FRAME, \"frame\", QObject::tr(\"border\")));\n qSpiRoleMapping.insert(QAccessible::Grouping, RoleNames(ATSPI_ROLE_PANEL, \"panel\", QObject::tr(\"grouping\")));\n qSpiRoleMapping.insert(QAccessible::Separator, RoleNames(ATSPI_ROLE_SEPARATOR, \"separator\", QObject::tr(\"separator\")));\n qSpiRoleMapping.insert(QAccessible::ToolBar, RoleNames(ATSPI_ROLE_TOOL_BAR, \"tool bar\", QObject::tr(\"tool bar\")));\n qSpiRoleMapping.insert(QAccessible::StatusBar, RoleNames(ATSPI_ROLE_STATUS_BAR, \"statusbar\", QObject::tr(\"status bar\")));\n qSpiRoleMapping.insert(QAccessible::Table, RoleNames(ATSPI_ROLE_TABLE, \"table\", QObject::tr(\"table\")));\n qSpiRoleMapping.insert(QAccessible::ColumnHeader, RoleNames(ATSPI_ROLE_TABLE_COLUMN_HEADER, \"column header\", QObject::tr(\"column header\")));\n qSpiRoleMapping.insert(QAccessible::RowHeader, RoleNames(ATSPI_ROLE_TABLE_ROW_HEADER, \"row header\", QObject::tr(\"row header\")));\n qSpiRoleMapping.insert(QAccessible::Column, RoleNames(ATSPI_ROLE_TABLE_CELL, \"table cell\", QObject::tr(\"column\")));\n qSpiRoleMapping.insert(QAccessible::Row, RoleNames(ATSPI_ROLE_TABLE_CELL, \"table cell\", QObject::tr(\"row\")));\n qSpiRoleMapping.insert(QAccessible::Cell, RoleNames(ATSPI_ROLE_TABLE_CELL, \"table cell\", QObject::tr(\"cell\")));\n qSpiRoleMapping.insert(QAccessible::Link, RoleNames(ATSPI_ROLE_LINK, \"link\" , QObject::tr(\"link\")));\n qSpiRoleMapping.insert(QAccessible::HelpBalloon, RoleNames(ATSPI_ROLE_DIALOG, \"dialog\", QObject::tr(\"help balloon\")));\n qSpiRoleMapping.insert(QAccessible::Assistant, RoleNames(ATSPI_ROLE_DIALOG, \"dialog\", QObject::tr(\"assistant\")));\n qSpiRoleMapping.insert(QAccessible::List, RoleNames(ATSPI_ROLE_LIST, \"list\", QObject::tr(\"list\")));\n qSpiRoleMapping.insert(QAccessible::ListItem, RoleNames(ATSPI_ROLE_LIST_ITEM, \"list item\", QObject::tr(\"list item\")));\n qSpiRoleMapping.insert(QAccessible::Tree, RoleNames(ATSPI_ROLE_TREE, \"tree\", QObject::tr(\"tree\")));\n qSpiRoleMapping.insert(QAccessible::TreeItem, RoleNames(ATSPI_ROLE_TABLE_CELL, \"tree item\", QObject::tr(\"tree item\")));\n qSpiRoleMapping.insert(QAccessible::PageTab, RoleNames(ATSPI_ROLE_PAGE_TAB, \"page tab\", QObject::tr(\"page tab\")));\n qSpiRoleMapping.insert(QAccessible::PropertyPage, RoleNames(ATSPI_ROLE_PAGE_TAB, \"page tab\", QObject::tr(\"property page\")));\n qSpiRoleMapping.insert(QAccessible::Indicator, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"indicator\")));\n qSpiRoleMapping.insert(QAccessible::Graphic, RoleNames(ATSPI_ROLE_IMAGE, \"image\", QObject::tr(\"graphic\")));\n qSpiRoleMapping.insert(QAccessible::StaticText, RoleNames(ATSPI_ROLE_LABEL, \"label\", QObject::tr(\"label\")));\n qSpiRoleMapping.insert(QAccessible::EditableText, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"text\")));\n qSpiRoleMapping.insert(QAccessible::PushButton, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"push button\")));\n qSpiRoleMapping.insert(QAccessible::CheckBox, RoleNames(ATSPI_ROLE_CHECK_BOX, \"check box\", QObject::tr(\"check box\")));\n qSpiRoleMapping.insert(QAccessible::RadioButton, RoleNames(ATSPI_ROLE_RADIO_BUTTON, \"radio button\", QObject::tr(\"radio box\")));\n qSpiRoleMapping.insert(QAccessible::ComboBox, RoleNames(ATSPI_ROLE_COMBO_BOX, \"combo box\", QObject::tr(\"combo box\")));\n qSpiRoleMapping.insert(QAccessible::ProgressBar, RoleNames(ATSPI_ROLE_PROGRESS_BAR, \"progress bar\", QObject::tr(\"progress bar\")));\n qSpiRoleMapping.insert(QAccessible::Dial, RoleNames(ATSPI_ROLE_DIAL, \"accelerator label\", QObject::tr(\"dial\")));\n qSpiRoleMapping.insert(QAccessible::HotkeyField, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"hotkey field\"))); \/\/FIXME text?\n qSpiRoleMapping.insert(QAccessible::Slider, RoleNames(ATSPI_ROLE_SLIDER, \"slider\", QObject::tr(\"slider\")));\n qSpiRoleMapping.insert(QAccessible::SpinBox, RoleNames(ATSPI_ROLE_SPIN_BUTTON, \"spin button\", QObject::tr(\"spin box\")));\n qSpiRoleMapping.insert(QAccessible::Canvas, RoleNames(ATSPI_ROLE_CANVAS, \"canvas\", QObject::tr(\"canvas\")));\n qSpiRoleMapping.insert(QAccessible::Animation, RoleNames(ATSPI_ROLE_ANIMATION, \"animation\", QObject::tr(\"animation\")));\n qSpiRoleMapping.insert(QAccessible::Equation, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"equation\")));\n qSpiRoleMapping.insert(QAccessible::ButtonDropDown, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"button drop down\")));\n qSpiRoleMapping.insert(QAccessible::ButtonMenu, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"button menu\")));\n qSpiRoleMapping.insert(QAccessible::ButtonDropGrid, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"button drop grid\")));\n qSpiRoleMapping.insert(QAccessible::Whitespace, RoleNames(ATSPI_ROLE_FILLER, \"filler\", QObject::tr(\"whitespace\")));\n qSpiRoleMapping.insert(QAccessible::PageTabList, RoleNames(ATSPI_ROLE_PAGE_TAB_LIST, \"page tab list\", QObject::tr(\"page tab list\")));\n qSpiRoleMapping.insert(QAccessible::Clock, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"clock\")));\n qSpiRoleMapping.insert(QAccessible::Splitter, RoleNames(ATSPI_ROLE_SPLIT_PANE, \"split pane\", QObject::tr(\"splitter\")));\n qSpiRoleMapping.insert(QAccessible::LayeredPane, RoleNames(ATSPI_ROLE_LAYERED_PANE, \"layered pane\", QObject::tr(\"layered pane\")));\n qSpiRoleMapping.insert(QAccessible::UserRole, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"user role\")));\n}\n\nquint64 spiStatesFromQState(QAccessible::State state)\n{\n quint64 spiState = 0;\n\n setSpiStateBit(&spiState, ATSPI_STATE_EDITABLE);\n setSpiStateBit(&spiState, ATSPI_STATE_ENABLED);\n setSpiStateBit(&spiState, ATSPI_STATE_SHOWING);\n setSpiStateBit(&spiState, ATSPI_STATE_VISIBLE);\n setSpiStateBit(&spiState, ATSPI_STATE_SENSITIVE);\n\n if (state & QAccessible::Unavailable) {\n unsetSpiStateBit(&spiState, ATSPI_STATE_ENABLED);\n unsetSpiStateBit(&spiState, ATSPI_STATE_SHOWING);\n unsetSpiStateBit(&spiState, ATSPI_STATE_VISIBLE);\n unsetSpiStateBit(&spiState, ATSPI_STATE_SENSITIVE);\n }\n\n if (state & QAccessible::Selected)\n setSpiStateBit(&spiState, ATSPI_STATE_SELECTED);\n if (state & QAccessible::Focused)\n setSpiStateBit(&spiState, ATSPI_STATE_FOCUSED);\n if (state & QAccessible::Pressed)\n setSpiStateBit(&spiState, ATSPI_STATE_PRESSED);\n if (state & QAccessible::Checked)\n setSpiStateBit(&spiState, ATSPI_STATE_CHECKED);\n if (state & QAccessible::Mixed)\n setSpiStateBit(&spiState, ATSPI_STATE_INDETERMINATE);\n if (state & QAccessible::ReadOnly)\n unsetSpiStateBit(&spiState, ATSPI_STATE_EDITABLE);\n \/\/ if (state & QAccessible::HotTracked)\n if (state & QAccessible::DefaultButton)\n setSpiStateBit(&spiState, ATSPI_STATE_IS_DEFAULT);\n if (state & QAccessible::Expanded)\n setSpiStateBit(&spiState, ATSPI_STATE_EXPANDED);\n if (state & QAccessible::Collapsed)\n setSpiStateBit(&spiState, ATSPI_STATE_COLLAPSED);\n if (state & QAccessible::Busy)\n setSpiStateBit(&spiState, ATSPI_STATE_BUSY);\n if ((state & QAccessible::Marqueed)\n || (state & QAccessible::Animated))\n setSpiStateBit(&spiState, ATSPI_STATE_ANIMATED);\n if ((state & QAccessible::Invisible)\n || (state & QAccessible::Offscreen))\n unsetSpiStateBit(&spiState, ATSPI_STATE_SHOWING);\n if (state & QAccessible::Sizeable)\n setSpiStateBit(&spiState, ATSPI_STATE_RESIZABLE);\n \/\/ if (state & QAccessible::Movable)\n \/\/ if (state & QAccessible::SelfVoicing)\n if (state & QAccessible::Focusable)\n setSpiStateBit(&spiState, ATSPI_STATE_FOCUSABLE);\n if (state & QAccessible::Selectable)\n setSpiStateBit(&spiState, ATSPI_STATE_SELECTABLE);\n \/\/ if (state & QAccessible::Linked)\n if (state & QAccessible::Traversed)\n setSpiStateBit(&spiState, ATSPI_STATE_VISITED);\n if (state & QAccessible::MultiSelectable)\n setSpiStateBit(&spiState, ATSPI_STATE_MULTISELECTABLE);\n if (state & QAccessible::ExtSelectable)\n setSpiStateBit(&spiState, ATSPI_STATE_SELECTABLE);\n \/\/ if (state & QAccessible::Protected)\n \/\/ if (state & QAccessible::HasPopup)\n if (state & QAccessible::Modal)\n setSpiStateBit(&spiState, ATSPI_STATE_MODAL);\n\n \/\/ Not implemented in Qt\n \/\/ if (state & QAccessible::SingleLine)\n \/\/ setSpiStateBit(&spiState, ATSPI_STATE_SINGLE_LINE);\n\n return spiState;\n}\n\nQSpiUIntList spiStateSetFromSpiStates(quint64 states)\n{\n uint low = states & 0xFFFFFFFF;\n uint high = (states >> 32) & 0xFFFFFFFF;\n\n QSpiUIntList stateList;\n stateList.append(low);\n stateList.append(high);\n return stateList;\n}\n\nvoid qSpiInitializeConstantMappings()\n{\n initializeRoleMapping();\n}\nWhen invisible we can also say not showing.\/*\n * D-Bus AT-SPI, Qt Adaptor\n *\n * Copyright 2008-2011 Nokia Corporation and\/or its subsidiary(-ies).\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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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, see .\n *\/\n\n#include \"constant_mappings.h\"\n\n#include \n\n\/\/ FIXME the assignment of roles is quite arbitrary, at some point go through this list and sort and check that it makes sense\n\/\/ \"calendar\" \"check menu item\" \"color chooser\" \"column header\" \"dateeditor\" \"desktop icon\" \"desktop frame\"\n\/\/ \"directory pane\" \"drawing area\" \"file chooser\" \"fontchooser\" \"frame\" \"glass pane\" \"html container\" \"icon\"\n\/\/ \"internal frame\" \"option pane\" \"password text\" \"radio menu item\" \"root pane\" \"row header\" \"scroll pane\"\n\/\/ \"tear off menu item\" \"terminal\" \"toggle button\" \"tree table\" \"unknown\" \"viewport\" \"header\" \"footer\" \"paragraph\"\n\/\/ \"ruler\" \"autocomplete\" \"edit bar\" \"embedded component\" \"entry\" \"caption\"\n\/\/ \"heading\" \"page\" \"section\" \"redundant object\" \"form\" \"input method window\" \"menu\"\n\nQHash qSpiRoleMapping;\n\nstatic void initializeRoleMapping ()\n{\n qSpiRoleMapping.insert(QAccessible::NoRole, RoleNames(ATSPI_ROLE_INVALID, \"invalid\", QObject::tr(\"invalid role\")));\n qSpiRoleMapping.insert(QAccessible::TitleBar, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"title bar\")));\n qSpiRoleMapping.insert(QAccessible::MenuBar, RoleNames(ATSPI_ROLE_MENU_BAR, \"menu bar\", QObject::tr(\"menu bar\")));\n qSpiRoleMapping.insert(QAccessible::ScrollBar, RoleNames(ATSPI_ROLE_SCROLL_BAR, \"scroll bar\", QObject::tr(\"scroll bar\")));\n qSpiRoleMapping.insert(QAccessible::Grip, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"grip\")));\n qSpiRoleMapping.insert(QAccessible::Sound, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"sound\")));\n qSpiRoleMapping.insert(QAccessible::Cursor, RoleNames(ATSPI_ROLE_ARROW, \"arrow\", QObject::tr(\"cursor\")));\n qSpiRoleMapping.insert(QAccessible::Caret, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"caret\")));\n qSpiRoleMapping.insert(QAccessible::AlertMessage, RoleNames(ATSPI_ROLE_ALERT, \"alert\", QObject::tr(\"alert message\")));\n qSpiRoleMapping.insert(QAccessible::Window, RoleNames(ATSPI_ROLE_WINDOW, \"window\", QObject::tr(\"window\")));\n qSpiRoleMapping.insert(QAccessible::Client, RoleNames(ATSPI_ROLE_FILLER, \"filler\", QObject::tr(\"filler\")));\n qSpiRoleMapping.insert(QAccessible::PopupMenu, RoleNames(ATSPI_ROLE_POPUP_MENU, \"popup menu\", QObject::tr(\"popup menu\")));\n qSpiRoleMapping.insert(QAccessible::MenuItem, RoleNames(ATSPI_ROLE_MENU_ITEM, \"menu item\", QObject::tr(\"menu item\")));\n qSpiRoleMapping.insert(QAccessible::ToolTip, RoleNames(ATSPI_ROLE_TOOL_TIP, \"tool tip\", QObject::tr(\"tool tip\")));\n qSpiRoleMapping.insert(QAccessible::Application, RoleNames(ATSPI_ROLE_APPLICATION, \"application\", QObject::tr(\"application\")));\n qSpiRoleMapping.insert(QAccessible::Document, RoleNames(ATSPI_ROLE_DOCUMENT_FRAME, \"document frame\", QObject::tr(\"document\")));\n qSpiRoleMapping.insert(QAccessible::Pane, RoleNames(ATSPI_ROLE_PANEL, \"panel\", QObject::tr(\"pane\")));\n qSpiRoleMapping.insert(QAccessible::Chart, RoleNames(ATSPI_ROLE_CHART, \"chart\", QObject::tr(\"chart\")));\n qSpiRoleMapping.insert(QAccessible::Dialog, RoleNames(ATSPI_ROLE_DIALOG, \"dialog\", QObject::tr(\"dialog\")));\n qSpiRoleMapping.insert(QAccessible::Border, RoleNames(ATSPI_ROLE_FRAME, \"frame\", QObject::tr(\"border\")));\n qSpiRoleMapping.insert(QAccessible::Grouping, RoleNames(ATSPI_ROLE_PANEL, \"panel\", QObject::tr(\"grouping\")));\n qSpiRoleMapping.insert(QAccessible::Separator, RoleNames(ATSPI_ROLE_SEPARATOR, \"separator\", QObject::tr(\"separator\")));\n qSpiRoleMapping.insert(QAccessible::ToolBar, RoleNames(ATSPI_ROLE_TOOL_BAR, \"tool bar\", QObject::tr(\"tool bar\")));\n qSpiRoleMapping.insert(QAccessible::StatusBar, RoleNames(ATSPI_ROLE_STATUS_BAR, \"statusbar\", QObject::tr(\"status bar\")));\n qSpiRoleMapping.insert(QAccessible::Table, RoleNames(ATSPI_ROLE_TABLE, \"table\", QObject::tr(\"table\")));\n qSpiRoleMapping.insert(QAccessible::ColumnHeader, RoleNames(ATSPI_ROLE_TABLE_COLUMN_HEADER, \"column header\", QObject::tr(\"column header\")));\n qSpiRoleMapping.insert(QAccessible::RowHeader, RoleNames(ATSPI_ROLE_TABLE_ROW_HEADER, \"row header\", QObject::tr(\"row header\")));\n qSpiRoleMapping.insert(QAccessible::Column, RoleNames(ATSPI_ROLE_TABLE_CELL, \"table cell\", QObject::tr(\"column\")));\n qSpiRoleMapping.insert(QAccessible::Row, RoleNames(ATSPI_ROLE_TABLE_CELL, \"table cell\", QObject::tr(\"row\")));\n qSpiRoleMapping.insert(QAccessible::Cell, RoleNames(ATSPI_ROLE_TABLE_CELL, \"table cell\", QObject::tr(\"cell\")));\n qSpiRoleMapping.insert(QAccessible::Link, RoleNames(ATSPI_ROLE_LINK, \"link\" , QObject::tr(\"link\")));\n qSpiRoleMapping.insert(QAccessible::HelpBalloon, RoleNames(ATSPI_ROLE_DIALOG, \"dialog\", QObject::tr(\"help balloon\")));\n qSpiRoleMapping.insert(QAccessible::Assistant, RoleNames(ATSPI_ROLE_DIALOG, \"dialog\", QObject::tr(\"assistant\")));\n qSpiRoleMapping.insert(QAccessible::List, RoleNames(ATSPI_ROLE_LIST, \"list\", QObject::tr(\"list\")));\n qSpiRoleMapping.insert(QAccessible::ListItem, RoleNames(ATSPI_ROLE_LIST_ITEM, \"list item\", QObject::tr(\"list item\")));\n qSpiRoleMapping.insert(QAccessible::Tree, RoleNames(ATSPI_ROLE_TREE, \"tree\", QObject::tr(\"tree\")));\n qSpiRoleMapping.insert(QAccessible::TreeItem, RoleNames(ATSPI_ROLE_TABLE_CELL, \"tree item\", QObject::tr(\"tree item\")));\n qSpiRoleMapping.insert(QAccessible::PageTab, RoleNames(ATSPI_ROLE_PAGE_TAB, \"page tab\", QObject::tr(\"page tab\")));\n qSpiRoleMapping.insert(QAccessible::PropertyPage, RoleNames(ATSPI_ROLE_PAGE_TAB, \"page tab\", QObject::tr(\"property page\")));\n qSpiRoleMapping.insert(QAccessible::Indicator, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"indicator\")));\n qSpiRoleMapping.insert(QAccessible::Graphic, RoleNames(ATSPI_ROLE_IMAGE, \"image\", QObject::tr(\"graphic\")));\n qSpiRoleMapping.insert(QAccessible::StaticText, RoleNames(ATSPI_ROLE_LABEL, \"label\", QObject::tr(\"label\")));\n qSpiRoleMapping.insert(QAccessible::EditableText, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"text\")));\n qSpiRoleMapping.insert(QAccessible::PushButton, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"push button\")));\n qSpiRoleMapping.insert(QAccessible::CheckBox, RoleNames(ATSPI_ROLE_CHECK_BOX, \"check box\", QObject::tr(\"check box\")));\n qSpiRoleMapping.insert(QAccessible::RadioButton, RoleNames(ATSPI_ROLE_RADIO_BUTTON, \"radio button\", QObject::tr(\"radio box\")));\n qSpiRoleMapping.insert(QAccessible::ComboBox, RoleNames(ATSPI_ROLE_COMBO_BOX, \"combo box\", QObject::tr(\"combo box\")));\n qSpiRoleMapping.insert(QAccessible::ProgressBar, RoleNames(ATSPI_ROLE_PROGRESS_BAR, \"progress bar\", QObject::tr(\"progress bar\")));\n qSpiRoleMapping.insert(QAccessible::Dial, RoleNames(ATSPI_ROLE_DIAL, \"accelerator label\", QObject::tr(\"dial\")));\n qSpiRoleMapping.insert(QAccessible::HotkeyField, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"hotkey field\"))); \/\/FIXME text?\n qSpiRoleMapping.insert(QAccessible::Slider, RoleNames(ATSPI_ROLE_SLIDER, \"slider\", QObject::tr(\"slider\")));\n qSpiRoleMapping.insert(QAccessible::SpinBox, RoleNames(ATSPI_ROLE_SPIN_BUTTON, \"spin button\", QObject::tr(\"spin box\")));\n qSpiRoleMapping.insert(QAccessible::Canvas, RoleNames(ATSPI_ROLE_CANVAS, \"canvas\", QObject::tr(\"canvas\")));\n qSpiRoleMapping.insert(QAccessible::Animation, RoleNames(ATSPI_ROLE_ANIMATION, \"animation\", QObject::tr(\"animation\")));\n qSpiRoleMapping.insert(QAccessible::Equation, RoleNames(ATSPI_ROLE_TEXT, \"text\", QObject::tr(\"equation\")));\n qSpiRoleMapping.insert(QAccessible::ButtonDropDown, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"button drop down\")));\n qSpiRoleMapping.insert(QAccessible::ButtonMenu, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"button menu\")));\n qSpiRoleMapping.insert(QAccessible::ButtonDropGrid, RoleNames(ATSPI_ROLE_PUSH_BUTTON, \"push button\", QObject::tr(\"button drop grid\")));\n qSpiRoleMapping.insert(QAccessible::Whitespace, RoleNames(ATSPI_ROLE_FILLER, \"filler\", QObject::tr(\"whitespace\")));\n qSpiRoleMapping.insert(QAccessible::PageTabList, RoleNames(ATSPI_ROLE_PAGE_TAB_LIST, \"page tab list\", QObject::tr(\"page tab list\")));\n qSpiRoleMapping.insert(QAccessible::Clock, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"clock\")));\n qSpiRoleMapping.insert(QAccessible::Splitter, RoleNames(ATSPI_ROLE_SPLIT_PANE, \"split pane\", QObject::tr(\"splitter\")));\n qSpiRoleMapping.insert(QAccessible::LayeredPane, RoleNames(ATSPI_ROLE_LAYERED_PANE, \"layered pane\", QObject::tr(\"layered pane\")));\n qSpiRoleMapping.insert(QAccessible::UserRole, RoleNames(ATSPI_ROLE_UNKNOWN, \"unknown\", QObject::tr(\"user role\")));\n}\n\nquint64 spiStatesFromQState(QAccessible::State state)\n{\n quint64 spiState = 0;\n\n setSpiStateBit(&spiState, ATSPI_STATE_EDITABLE);\n setSpiStateBit(&spiState, ATSPI_STATE_ENABLED);\n setSpiStateBit(&spiState, ATSPI_STATE_SHOWING);\n setSpiStateBit(&spiState, ATSPI_STATE_VISIBLE);\n setSpiStateBit(&spiState, ATSPI_STATE_SENSITIVE);\n\n if (state & QAccessible::Unavailable) {\n unsetSpiStateBit(&spiState, ATSPI_STATE_ENABLED);\n unsetSpiStateBit(&spiState, ATSPI_STATE_SHOWING);\n unsetSpiStateBit(&spiState, ATSPI_STATE_VISIBLE);\n unsetSpiStateBit(&spiState, ATSPI_STATE_SENSITIVE);\n }\n\n if (state & QAccessible::Selected)\n setSpiStateBit(&spiState, ATSPI_STATE_SELECTED);\n if (state & QAccessible::Focused)\n setSpiStateBit(&spiState, ATSPI_STATE_FOCUSED);\n if (state & QAccessible::Pressed)\n setSpiStateBit(&spiState, ATSPI_STATE_PRESSED);\n if (state & QAccessible::Checked)\n setSpiStateBit(&spiState, ATSPI_STATE_CHECKED);\n if (state & QAccessible::Mixed)\n setSpiStateBit(&spiState, ATSPI_STATE_INDETERMINATE);\n if (state & QAccessible::ReadOnly)\n unsetSpiStateBit(&spiState, ATSPI_STATE_EDITABLE);\n \/\/ if (state & QAccessible::HotTracked)\n if (state & QAccessible::DefaultButton)\n setSpiStateBit(&spiState, ATSPI_STATE_IS_DEFAULT);\n if (state & QAccessible::Expanded)\n setSpiStateBit(&spiState, ATSPI_STATE_EXPANDED);\n if (state & QAccessible::Collapsed)\n setSpiStateBit(&spiState, ATSPI_STATE_COLLAPSED);\n if (state & QAccessible::Busy)\n setSpiStateBit(&spiState, ATSPI_STATE_BUSY);\n if ((state & QAccessible::Marqueed)\n || (state & QAccessible::Animated))\n setSpiStateBit(&spiState, ATSPI_STATE_ANIMATED);\n if ((state & QAccessible::Invisible)\n || (state & QAccessible::Offscreen)) {\n unsetSpiStateBit(&spiState, ATSPI_STATE_SHOWING);\n unsetSpiStateBit(&spiState, ATSPI_STATE_VISIBLE);\n }\n if (state & QAccessible::Sizeable)\n setSpiStateBit(&spiState, ATSPI_STATE_RESIZABLE);\n \/\/ if (state & QAccessible::Movable)\n \/\/ if (state & QAccessible::SelfVoicing)\n if (state & QAccessible::Focusable)\n setSpiStateBit(&spiState, ATSPI_STATE_FOCUSABLE);\n if (state & QAccessible::Selectable)\n setSpiStateBit(&spiState, ATSPI_STATE_SELECTABLE);\n \/\/ if (state & QAccessible::Linked)\n if (state & QAccessible::Traversed)\n setSpiStateBit(&spiState, ATSPI_STATE_VISITED);\n if (state & QAccessible::MultiSelectable)\n setSpiStateBit(&spiState, ATSPI_STATE_MULTISELECTABLE);\n if (state & QAccessible::ExtSelectable)\n setSpiStateBit(&spiState, ATSPI_STATE_SELECTABLE);\n \/\/ if (state & QAccessible::Protected)\n \/\/ if (state & QAccessible::HasPopup)\n if (state & QAccessible::Modal)\n setSpiStateBit(&spiState, ATSPI_STATE_MODAL);\n\n \/\/ Not implemented in Qt\n \/\/ if (state & QAccessible::SingleLine)\n \/\/ setSpiStateBit(&spiState, ATSPI_STATE_SINGLE_LINE);\n\n return spiState;\n}\n\nQSpiUIntList spiStateSetFromSpiStates(quint64 states)\n{\n uint low = states & 0xFFFFFFFF;\n uint high = (states >> 32) & 0xFFFFFFFF;\n\n QSpiUIntList stateList;\n stateList.append(low);\n stateList.append(high);\n return stateList;\n}\n\nvoid qSpiInitializeConstantMappings()\n{\n initializeRoleMapping();\n}\n<|endoftext|>"} {"text":"\/\/ GeometricAlgebraEnv.cpp\n\n\/*\n * Copyright (C) 2012 Spencer T. Parkin\n *\n * This software has been released under the MIT License.\n * See the \"License.txt\" file in the project root directory\n * for more information about this license.\n *\n *\/\n\n#include \"..\/..\/CalcLib.h\"\n\nusing namespace CalcLib;\n\n\/\/=========================================================================================\nIMPLEMENT_CALCLIB_CLASS1( GeometricAlgebraEnvironment, Environment );\n\n\/\/=========================================================================================\nGeometricAlgebraEnvironment::GeometricAlgebraEnvironment( void )\n{\n\tdisplayMode = DISPLAY_AS_SUM_OF_BLADES;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ GeometricAlgebraEnvironment::~GeometricAlgebraEnvironment( void )\n{\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ void GeometricAlgebraEnvironment::PrintEnvironmentInfo( void )\n{\n\tPrint(\n\t\t\"\\n\"\n\t\t\"You are in the geometric algebra environment.\\n\"\n\t\t\"\\n\"\n\t);\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Number* GeometricAlgebraEnvironment::CreateNumber( void )\n{\n\tMultivectorNumber* multivectorNumber = new MultivectorNumber();\n\tNumber* number = multivectorNumber;\n\treturn number;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ FunctionEvaluator* GeometricAlgebraEnvironment::CreateFunction( const char* functionName )\n{\n\tFunctionEvaluator* functionEvaluator = 0;\n\n\tif( 0 == strcmp( functionName, \"reverse\" ) )\n\t\tfunctionEvaluator = new ReverseFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"scalar_part\" ) )\n\t\tfunctionEvaluator = new ScalarPartFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"grade_part\" ) )\n\t\tfunctionEvaluator = new GradePartFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"inverse\" ) )\n\t\tfunctionEvaluator = new InverseFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"exp\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_EXP );\n\telse if( 0 == strcmp( functionName, \"log\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_LOG );\n\telse if( 0 == strcmp( functionName, \"pow\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_POW );\n\telse if( 0 == strcmp( functionName, \"sqrt\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_SQRT );\n\telse if( 0 == strcmp( functionName, \"cos\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_COS );\n\telse if( 0 == strcmp( functionName, \"sin\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_SIN );\n\telse if( 0 == strcmp( functionName, \"tan\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_TAN );\n\telse if( 0 == strcmp( functionName, \"abs\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_ABS );\n\telse if( 0 == strcmp( functionName, \"acos\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_ACOS );\n\telse if( 0 == strcmp( functionName, \"asin\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_ASIN );\n\/\/\telse if( 0 == strcmp( functionName, \"conjugate\" ) )\n\/\/\t\tfunctionEvaluator = new ConjugateFunctionEvaluator();\n\telse\n\t\tfunctionEvaluator = Environment::CreateFunction( functionName );\n\t\n\treturn functionEvaluator;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Evaluator* GeometricAlgebraEnvironment::CreateVariable( const char* variableName )\n{\n\tConstantEvaluator* evaluator = 0;\n\tMultivectorNumber* multivectorNumber = 0;\n\tGeometricAlgebra::Vector* vector = 0;\n\tGeometricAlgebra::Blade* blade = 0;\n\tGeometricAlgebra::SumOfBlades* sumOfBlades = 0;\n\n\tif( 0 == strcmp( variableName, \"e0\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e0();\n\telse if( 0 == strcmp( variableName, \"e1\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e1();\n\telse if( 0 == strcmp( variableName, \"e2\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e2();\n\telse if( 0 == strcmp( variableName, \"e3\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e3();\n\telse if( 0 == strcmp( variableName, \"e0b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e0_bar();\n\telse if( 0 == strcmp( variableName, \"e1b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e1_bar();\n\telse if( 0 == strcmp( variableName, \"e2b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e2_bar();\n\telse if( 0 == strcmp( variableName, \"e3b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e3_bar();\n\telse if( 0 == strcmp( variableName, \"no\" ) )\n\t\tvector = new GeometricAlgebra::Vector_no();\n\telse if( 0 == strcmp( variableName, \"ni\" ) )\n\t\tvector = new GeometricAlgebra::Vector_ni();\n\telse if( 0 == strcmp( variableName, \"nob\" ) )\n\t\tvector = new GeometricAlgebra::Vector_no_bar();\n\telse if( 0 == strcmp( variableName, \"nib\" ) )\n\t\tvector = new GeometricAlgebra::Vector_ni_bar();\n\telse if( 0 == strcmp( variableName, \"i\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"I\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_ni() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_no() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"E0\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"E1\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"E2\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"Omega\" ) )\n\t{\n\t\tsumOfBlades = new GeometricAlgebra::SumOfBlades();\n\n\t\tUtilities::List vectorProduct;\n\n\t\tGeometricAlgebra::Blade blade_e1e5;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1_bar() );\n\t\tblade_e1e5.AssignBlade( vectorProduct, 1.0 );\n\n\t\tGeometricAlgebra::Blade blade_e2e6;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2_bar() );\n\t\tblade_e2e6.AssignBlade( vectorProduct, 1.0 );\n\n\t\tGeometricAlgebra::Blade blade_e3e7;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3_bar() );\n\t\tblade_e3e7.AssignBlade( vectorProduct, 1.0 );\n\n\t\tsumOfBlades->Accumulate( blade_e1e5 );\n\t\tsumOfBlades->Accumulate( blade_e2e6 );\n\t\tsumOfBlades->Accumulate( blade_e3e7 );\n\t}\n\telse if( 0 == strcmp( variableName, \"Alpha\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0_bar() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\n\tif( vector )\n\t\tmultivectorNumber = new MultivectorNumber( *vector );\n\telse if( blade )\n\t\tmultivectorNumber = new MultivectorNumber( *blade );\n\telse if( sumOfBlades )\n\t\tmultivectorNumber = new MultivectorNumber( *sumOfBlades );\n\n\tdelete vector;\n\tdelete blade;\n\tdelete sumOfBlades;\n\n\tif( multivectorNumber )\n\t\tevaluator = new ConstantEvaluator( multivectorNumber );\n\t\n\treturn evaluator;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Evaluator* GeometricAlgebraEnvironment::CreateBinaryOperator( const char* operatorName, Evaluator* leftOperand, Evaluator* rightOperand, bool& isBinaryOperationEvaluator )\n{\n\tBinaryArithmeticOperationEvaluator* evaluator = 0;\n\n\t\/\/ The geometric product is handled through normal multiplication,\n\t\/\/ but the inner and outer products are a special case.\n\tif( 0 == strcmp( operatorName, \"^\" ) )\n\t{\n\t\tevaluator = new BinaryArithmeticOperationEvaluator( BinaryArithmeticOperationEvaluator::ARITHMETIC_OPERATION_OUTER_PRODUCT );\n\t\tisBinaryOperationEvaluator = true;\n\t}\n\telse if( 0 == strcmp( operatorName, \".\" ) )\n\t{\n\t\tevaluator = new BinaryArithmeticOperationEvaluator( BinaryArithmeticOperationEvaluator::ARITHMETIC_OPERATION_INNER_PRODUCT );\n\t\tisBinaryOperationEvaluator = true;\n\t}\n\n\treturn evaluator;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Evaluator* GeometricAlgebraEnvironment::CreateUnaryOperator( const char* operatorName, Evaluator* operand, bool& isUnaryOperationEvaluator )\n{\n\tEvaluator* evaluator = 0;\n\n\tif( 0 == strcmp( operatorName, \"~\" ) )\n\t{\n\t\tReverseFunctionEvaluator* reverseFunctionEvaluator = new ReverseFunctionEvaluator();\n\t\tFunctionArgumentEvaluator* argument = new FunctionArgumentEvaluator();\n\t\targument->Argument( operand );\n\t\treverseFunctionEvaluator->AddArgument( argument, FunctionEvaluator::APPEND_TO_LIST_OF_ARGS );\n\t\tevaluator = reverseFunctionEvaluator;\n\t\tisUnaryOperationEvaluator = false;\n\t}\n\n\treturn evaluator;\n}\n\n\/\/ GeometricAlgebraEnv.cppfix bug i recently introduced\/\/ GeometricAlgebraEnv.cpp\n\n\/*\n * Copyright (C) 2012 Spencer T. Parkin\n *\n * This software has been released under the MIT License.\n * See the \"License.txt\" file in the project root directory\n * for more information about this license.\n *\n *\/\n\n#include \"..\/..\/CalcLib.h\"\n\nusing namespace CalcLib;\n\n\/\/=========================================================================================\nIMPLEMENT_CALCLIB_CLASS1( GeometricAlgebraEnvironment, Environment );\n\n\/\/=========================================================================================\nGeometricAlgebraEnvironment::GeometricAlgebraEnvironment( void )\n{\n\tdisplayMode = DISPLAY_AS_SUM_OF_BLADES;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ GeometricAlgebraEnvironment::~GeometricAlgebraEnvironment( void )\n{\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ void GeometricAlgebraEnvironment::PrintEnvironmentInfo( void )\n{\n\tPrint(\n\t\t\"\\n\"\n\t\t\"You are in the geometric algebra environment.\\n\"\n\t\t\"\\n\"\n\t);\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Number* GeometricAlgebraEnvironment::CreateNumber( void )\n{\n\tMultivectorNumber* multivectorNumber = new MultivectorNumber();\n\tNumber* number = multivectorNumber;\n\treturn number;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ FunctionEvaluator* GeometricAlgebraEnvironment::CreateFunction( const char* functionName )\n{\n\tFunctionEvaluator* functionEvaluator = 0;\n\n\tif( 0 == strcmp( functionName, \"reverse\" ) )\n\t\tfunctionEvaluator = new ReverseFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"scalar_part\" ) )\n\t\tfunctionEvaluator = new ScalarPartFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"grade_part\" ) )\n\t\tfunctionEvaluator = new GradePartFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"inverse\" ) )\n\t\tfunctionEvaluator = new InverseFunctionEvaluator();\n\telse if( 0 == strcmp( functionName, \"exp\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_EXP );\n\telse if( 0 == strcmp( functionName, \"log\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_LOG );\n\telse if( 0 == strcmp( functionName, \"pow\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_POW );\n\telse if( 0 == strcmp( functionName, \"sqrt\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_SQRT );\n\telse if( 0 == strcmp( functionName, \"cos\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_COS );\n\telse if( 0 == strcmp( functionName, \"sin\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_SIN );\n\telse if( 0 == strcmp( functionName, \"tan\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_TAN );\n\telse if( 0 == strcmp( functionName, \"abs\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_ABS );\n\telse if( 0 == strcmp( functionName, \"acos\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_ACOS );\n\telse if( 0 == strcmp( functionName, \"asin\" ) )\n\t\tfunctionEvaluator = new MultivectorMathFunctionEvaluator( MultivectorMathFunctionEvaluator::FUNC_ASIN );\n\/\/\telse if( 0 == strcmp( functionName, \"conjugate\" ) )\n\/\/\t\tfunctionEvaluator = new ConjugateFunctionEvaluator();\n\telse\n\t\tfunctionEvaluator = Environment::CreateFunction( functionName );\n\t\n\treturn functionEvaluator;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Evaluator* GeometricAlgebraEnvironment::CreateVariable( const char* variableName )\n{\n\tConstantEvaluator* evaluator = 0;\n\tMultivectorNumber* multivectorNumber = 0;\n\tGeometricAlgebra::Vector* vector = 0;\n\tGeometricAlgebra::Blade* blade = 0;\n\tGeometricAlgebra::SumOfBlades* sumOfBlades = 0;\n\n\tif( 0 == strcmp( variableName, \"e0\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e0();\n\telse if( 0 == strcmp( variableName, \"e1\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e1();\n\telse if( 0 == strcmp( variableName, \"e2\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e2();\n\telse if( 0 == strcmp( variableName, \"e3\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e3();\n\telse if( 0 == strcmp( variableName, \"e0b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e0_bar();\n\telse if( 0 == strcmp( variableName, \"e1b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e1_bar();\n\telse if( 0 == strcmp( variableName, \"e2b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e2_bar();\n\telse if( 0 == strcmp( variableName, \"e3b\" ) )\n\t\tvector = new GeometricAlgebra::Vector_e3_bar();\n\telse if( 0 == strcmp( variableName, \"no\" ) )\n\t\tvector = new GeometricAlgebra::Vector_no();\n\telse if( 0 == strcmp( variableName, \"ni\" ) )\n\t\tvector = new GeometricAlgebra::Vector_ni();\n\telse if( 0 == strcmp( variableName, \"nob\" ) )\n\t\tvector = new GeometricAlgebra::Vector_no_bar();\n\telse if( 0 == strcmp( variableName, \"nib\" ) )\n\t\tvector = new GeometricAlgebra::Vector_ni_bar();\n\telse if( 0 == strcmp( variableName, \"i\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"I\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_ni() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_no() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"E2\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"E1\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"E3\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\telse if( 0 == strcmp( variableName, \"Omega\" ) )\n\t{\n\t\tsumOfBlades = new GeometricAlgebra::SumOfBlades();\n\n\t\tUtilities::List vectorProduct;\n\n\t\tGeometricAlgebra::Blade blade_e1e5;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e1_bar() );\n\t\tblade_e1e5.AssignBlade( vectorProduct, 1.0 );\n\n\t\tGeometricAlgebra::Blade blade_e2e6;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e2_bar() );\n\t\tblade_e2e6.AssignBlade( vectorProduct, 1.0 );\n\n\t\tGeometricAlgebra::Blade blade_e3e7;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e3_bar() );\n\t\tblade_e3e7.AssignBlade( vectorProduct, 1.0 );\n\n\t\tsumOfBlades->Accumulate( blade_e1e5 );\n\t\tsumOfBlades->Accumulate( blade_e2e6 );\n\t\tsumOfBlades->Accumulate( blade_e3e7 );\n\t}\n\telse if( 0 == strcmp( variableName, \"Alpha\" ) )\n\t{\n\t\tblade = new GeometricAlgebra::Blade();\n\t\tUtilities::List vectorProduct;\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0() );\n\t\tvectorProduct.InsertRightOf( vectorProduct.RightMost(), new GeometricAlgebra::Vector_e0_bar() );\n\t\tblade->AssignBlade( vectorProduct, 1.0 );\n\t}\n\n\tif( vector )\n\t\tmultivectorNumber = new MultivectorNumber( *vector );\n\telse if( blade )\n\t\tmultivectorNumber = new MultivectorNumber( *blade );\n\telse if( sumOfBlades )\n\t\tmultivectorNumber = new MultivectorNumber( *sumOfBlades );\n\n\tdelete vector;\n\tdelete blade;\n\tdelete sumOfBlades;\n\n\tif( multivectorNumber )\n\t\tevaluator = new ConstantEvaluator( multivectorNumber );\n\t\n\treturn evaluator;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Evaluator* GeometricAlgebraEnvironment::CreateBinaryOperator( const char* operatorName, Evaluator* leftOperand, Evaluator* rightOperand, bool& isBinaryOperationEvaluator )\n{\n\tBinaryArithmeticOperationEvaluator* evaluator = 0;\n\n\t\/\/ The geometric product is handled through normal multiplication,\n\t\/\/ but the inner and outer products are a special case.\n\tif( 0 == strcmp( operatorName, \"^\" ) )\n\t{\n\t\tevaluator = new BinaryArithmeticOperationEvaluator( BinaryArithmeticOperationEvaluator::ARITHMETIC_OPERATION_OUTER_PRODUCT );\n\t\tisBinaryOperationEvaluator = true;\n\t}\n\telse if( 0 == strcmp( operatorName, \".\" ) )\n\t{\n\t\tevaluator = new BinaryArithmeticOperationEvaluator( BinaryArithmeticOperationEvaluator::ARITHMETIC_OPERATION_INNER_PRODUCT );\n\t\tisBinaryOperationEvaluator = true;\n\t}\n\n\treturn evaluator;\n}\n\n\/\/=========================================================================================\n\/*virtual*\/ Evaluator* GeometricAlgebraEnvironment::CreateUnaryOperator( const char* operatorName, Evaluator* operand, bool& isUnaryOperationEvaluator )\n{\n\tEvaluator* evaluator = 0;\n\n\tif( 0 == strcmp( operatorName, \"~\" ) )\n\t{\n\t\tReverseFunctionEvaluator* reverseFunctionEvaluator = new ReverseFunctionEvaluator();\n\t\tFunctionArgumentEvaluator* argument = new FunctionArgumentEvaluator();\n\t\targument->Argument( operand );\n\t\treverseFunctionEvaluator->AddArgument( argument, FunctionEvaluator::APPEND_TO_LIST_OF_ARGS );\n\t\tevaluator = reverseFunctionEvaluator;\n\t\tisUnaryOperationEvaluator = false;\n\t}\n\n\treturn evaluator;\n}\n\n\/\/ GeometricAlgebraEnv.cpp<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRecordDraw.h\"\n#include \"SkTSort.h\"\n\nvoid SkRecordDraw(const SkRecord& record,\n SkCanvas* canvas,\n const SkBBoxHierarchy* bbh,\n SkDrawPictureCallback* callback) {\n SkAutoCanvasRestore saveRestore(canvas, true \/*save now, restore at exit*\/);\n\n if (NULL != bbh) {\n \/\/ Draw only ops that affect pixels in the canvas's current clip.\n SkIRect query;\n#if 1 \/\/ TODO: Why is this the right way to make the query? I'd think it'd be the else branch.\n SkRect clipBounds;\n canvas->getClipBounds(&clipBounds);\n clipBounds.roundOut(&query);\n#else\n canvas->getClipDeviceBounds(&query);\n#endif\n SkTDArray ops;\n bbh->search(query, &ops);\n\n SkRecords::Draw draw(canvas);\n for (int i = 0; i < ops.count(); i++) {\n if (NULL != callback && callback->abortDrawing()) {\n return;\n }\n record.visit((uintptr_t)ops[i], draw); \/\/ See FillBounds below.\n }\n } else {\n \/\/ Draw all ops.\n for (SkRecords::Draw draw(canvas); draw.index() < record.count(); draw.next()) {\n if (NULL != callback && callback->abortDrawing()) {\n return;\n }\n record.visit(draw.index(), draw);\n }\n }\n}\n\nnamespace SkRecords {\n\n\/\/ FIXME: SkBitmaps are stateful, so we need to copy them to play back in multiple threads.\nstatic SkBitmap shallow_copy(const SkBitmap& bitmap) {\n return bitmap;\n}\n\n\/\/ NoOps draw nothing.\ntemplate <> void Draw::draw(const NoOp&) {}\n\n#define DRAW(T, call) template <> void Draw::draw(const T& r) { fCanvas->call; }\nDRAW(Restore, restore());\nDRAW(Save, save());\nDRAW(SaveLayer, saveLayer(r.bounds, r.paint, r.flags));\nDRAW(PopCull, popCull());\nDRAW(PushCull, pushCull(r.rect));\nDRAW(Clear, clear(r.color));\nDRAW(Concat, concat(r.matrix));\nDRAW(SetMatrix, setMatrix(SkMatrix::Concat(fInitialCTM, r.matrix)));\n\nDRAW(ClipPath, clipPath(r.path, r.op, r.doAA));\nDRAW(ClipRRect, clipRRect(r.rrect, r.op, r.doAA));\nDRAW(ClipRect, clipRect(r.rect, r.op, r.doAA));\nDRAW(ClipRegion, clipRegion(r.region, r.op));\n\nDRAW(DrawBitmap, drawBitmap(shallow_copy(r.bitmap), r.left, r.top, r.paint));\nDRAW(DrawBitmapMatrix, drawBitmapMatrix(shallow_copy(r.bitmap), r.matrix, r.paint));\nDRAW(DrawBitmapNine, drawBitmapNine(shallow_copy(r.bitmap), r.center, r.dst, r.paint));\nDRAW(DrawBitmapRectToRect,\n drawBitmapRectToRect(shallow_copy(r.bitmap), r.src, r.dst, r.paint, r.flags));\nDRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));\nDRAW(DrawOval, drawOval(r.oval, r.paint));\nDRAW(DrawPaint, drawPaint(r.paint));\nDRAW(DrawPath, drawPath(r.path, r.paint));\nDRAW(DrawPatch, drawPatch(r.cubics, r.colors, r.texCoords, r.xmode.get(), r.paint));\nDRAW(DrawPicture, drawPicture(r.picture, r.matrix, r.paint));\nDRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));\nDRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));\nDRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));\nDRAW(DrawRRect, drawRRect(r.rrect, r.paint));\nDRAW(DrawRect, drawRect(r.rect, r.paint));\nDRAW(DrawSprite, drawSprite(shallow_copy(r.bitmap), r.left, r.top, r.paint));\nDRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));\nDRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, r.matrix, r.paint));\nDRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,\n r.xmode.get(), r.indices, r.indexCount, r.paint));\n#undef DRAW\n\n\n\/\/ This is an SkRecord visitor that fills an SkBBoxHierarchy.\n\/\/\n\/\/ The interesting part here is how to calculate bounds for ops which don't\n\/\/ have intrinsic bounds. What is the bounds of a Save or a Translate?\n\/\/\n\/\/ We answer this by thinking about a particular definition of bounds: if I\n\/\/ don't execute this op, pixels in this rectangle might draw incorrectly. So\n\/\/ the bounds of a Save, a Translate, a Restore, etc. are the union of the\n\/\/ bounds of Draw* ops that they might have an effect on. For any given\n\/\/ Save\/Restore block, the bounds of the Save, the Restore, and any other\n\/\/ non-drawing (\"control\") ops inside are exactly the union of the bounds of\n\/\/ the drawing ops inside that block.\n\/\/\n\/\/ To implement this, we keep a stack of active Save blocks. As we consume ops\n\/\/ inside the Save\/Restore block, drawing ops are unioned with the bounds of\n\/\/ the block, and control ops are stashed away for later. When we finish the\n\/\/ block with a Restore, our bounds are complete, and we go back and fill them\n\/\/ in for all the control ops we stashed away.\nclass FillBounds : SkNoncopyable {\npublic:\n FillBounds(const SkRecord& record, SkBBoxHierarchy* bbh) : fBounds(record.count()) {\n \/\/ Calculate bounds for all ops. This won't go quite in order, so we'll need\n \/\/ to store the bounds separately then feed them in to the BBH later in order.\n const SkIRect largest = SkIRect::MakeLargest();\n fCTM.setIdentity();\n fCurrentClipBounds = largest;\n for (fCurrentOp = 0; fCurrentOp < record.count(); fCurrentOp++) {\n record.visit(fCurrentOp, *this);\n }\n\n \/\/ If we have any lingering unpaired Saves, simulate restores to make\n \/\/ sure all ops in those Save blocks have their bounds calculated.\n while (!fSaveStack.isEmpty()) {\n this->popSaveBlock();\n }\n\n \/\/ Any control ops not part of any Save\/Restore block draw everywhere.\n while (!fControlIndices.isEmpty()) {\n this->popControl(largest);\n }\n\n \/\/ Finally feed all stored bounds into the BBH. They'll be returned in this order.\n SkASSERT(NULL != bbh);\n for (uintptr_t i = 0; i < record.count(); i++) {\n if (!fBounds[i].isEmpty()) {\n bbh->insert((void*)i, fBounds[i], true\/*ok to defer*\/);\n }\n }\n bbh->flushDeferredInserts();\n }\n\n template void operator()(const T& op) {\n this->updateCTM(op);\n this->updateClipBounds(op);\n this->trackBounds(op);\n }\n\nprivate:\n struct SaveBounds {\n int controlOps; \/\/ Number of control ops in this Save block, including the Save.\n SkIRect bounds; \/\/ Bounds of everything in the block.\n const SkPaint* paint; \/\/ Unowned. If set, adjusts the bounds of all ops in this block.\n };\n\n template void updateCTM(const T&) { \/* most ops don't change the CTM *\/ }\n void updateCTM(const Restore& op) { fCTM = op.matrix; }\n void updateCTM(const SetMatrix& op) { fCTM = op.matrix; }\n void updateCTM(const Concat& op) { fCTM.preConcat(op.matrix); }\n\n template void updateClipBounds(const T&) { \/* most ops don't change the clip *\/ }\n \/\/ Each of these devBounds fields is the state of the device bounds after the op.\n \/\/ So Restore's devBounds are those bounds saved by its paired Save or SaveLayer.\n void updateClipBounds(const Restore& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipPath& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipRRect& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipRect& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipRegion& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const SaveLayer& op) {\n if (op.bounds) {\n fCurrentClipBounds.intersect(this->adjustAndMap(*op.bounds, op.paint));\n }\n }\n\n \/\/ The bounds of these ops must be calculated when we hit the Restore\n \/\/ from the bounds of the ops in the same Save block.\n void trackBounds(const Save&) { this->pushSaveBlock(NULL); }\n \/\/ TODO: bounds of SaveLayer may be more complicated?\n void trackBounds(const SaveLayer& op) { this->pushSaveBlock(op.paint); }\n void trackBounds(const Restore&) { fBounds[fCurrentOp] = this->popSaveBlock(); }\n\n void trackBounds(const Concat&) { this->pushControl(); }\n void trackBounds(const SetMatrix&) { this->pushControl(); }\n void trackBounds(const ClipRect&) { this->pushControl(); }\n void trackBounds(const ClipRRect&) { this->pushControl(); }\n void trackBounds(const ClipPath&) { this->pushControl(); }\n void trackBounds(const ClipRegion&) { this->pushControl(); }\n\n \/\/ For all other ops, we can calculate and store the bounds directly now.\n template void trackBounds(const T& op) {\n fBounds[fCurrentOp] = this->bounds(op);\n this->updateSaveBounds(fBounds[fCurrentOp]);\n }\n\n void pushSaveBlock(const SkPaint* paint) {\n \/\/ Starting a new Save block. Push a new entry to represent that.\n SaveBounds sb = { 0, SkIRect::MakeEmpty(), paint };\n fSaveStack.push(sb);\n this->pushControl();\n }\n\n SkIRect popSaveBlock() {\n \/\/ We're done the Save block. Apply the block's bounds to all control ops inside it.\n SaveBounds sb;\n fSaveStack.pop(&sb);\n while (sb.controlOps --> 0) {\n this->popControl(sb.bounds);\n }\n\n \/\/ This whole Save block may be part another Save block.\n this->updateSaveBounds(sb.bounds);\n\n \/\/ If called from a real Restore (not a phony one for balance), it'll need the bounds.\n return sb.bounds;\n }\n\n void pushControl() {\n fControlIndices.push(fCurrentOp);\n if (!fSaveStack.isEmpty()) {\n fSaveStack.top().controlOps++;\n }\n }\n\n void popControl(const SkIRect& bounds) {\n fBounds[fControlIndices.top()] = bounds;\n fControlIndices.pop();\n }\n\n void updateSaveBounds(const SkIRect& bounds) {\n \/\/ If we're in a Save block, expand its bounds to cover these bounds too.\n if (!fSaveStack.isEmpty()) {\n fSaveStack.top().bounds.join(bounds);\n }\n }\n\n \/\/ TODO: Remove this default when done bounding all ops.\n template SkIRect bounds(const T&) { return fCurrentClipBounds; }\n SkIRect bounds(const Clear&) { return SkIRect::MakeLargest(); } \/\/ Ignores the clip\n SkIRect bounds(const NoOp&) { return SkIRect::MakeEmpty(); } \/\/ NoOps don't draw anywhere.\n\n \/\/ Adjust rect for all paints that may affect its geometry, then map it to device space.\n SkIRect adjustAndMap(SkRect rect, const SkPaint* paint) {\n \/\/ Adjust rect for its own paint.\n if (paint) {\n if (paint->canComputeFastBounds()) {\n rect = paint->computeFastBounds(rect, &rect);\n } else {\n \/\/ The paint could do anything. The only safe answer is the current clip.\n return fCurrentClipBounds;\n }\n }\n\n \/\/ Adjust rect for all the paints from the SaveLayers we're inside.\n \/\/ For SaveLayers, only image filters will affect the bounds.\n for (int i = fSaveStack.count() - 1; i >= 0; i--) {\n if (fSaveStack[i].paint && fSaveStack[i].paint->getImageFilter()) {\n if (paint->canComputeFastBounds()) {\n rect = fSaveStack[i].paint->computeFastBounds(rect, &rect);\n } else {\n \/\/ Same deal as above.\n return fCurrentClipBounds;\n }\n }\n }\n\n \/\/ Map the rect back to device space.\n fCTM.mapRect(&rect);\n SkIRect devRect;\n rect.roundOut(&devRect);\n return devRect;\n }\n\n \/\/ Conservative device bounds for each op in the SkRecord.\n SkAutoTMalloc fBounds;\n\n \/\/ We walk fCurrentOp through the SkRecord, as we go using updateCTM()\n \/\/ and updateClipBounds() to maintain the exact CTM (fCTM) and conservative\n \/\/ device bounds of the current clip (fCurrentClipBounds).\n unsigned fCurrentOp;\n SkMatrix fCTM;\n SkIRect fCurrentClipBounds;\n\n \/\/ Used to track the bounds of Save\/Restore blocks and the control ops inside them.\n SkTDArray fSaveStack;\n SkTDArray fControlIndices;\n};\n\n} \/\/ namespace SkRecords\n\nvoid SkRecordFillBounds(const SkRecord& record, SkBBoxHierarchy* bbh) {\n SkRecords::FillBounds(record, bbh);\n}\nSmall tweaks and a bug fix.\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRecordDraw.h\"\n#include \"SkTSort.h\"\n\nvoid SkRecordDraw(const SkRecord& record,\n SkCanvas* canvas,\n const SkBBoxHierarchy* bbh,\n SkDrawPictureCallback* callback) {\n SkAutoCanvasRestore saveRestore(canvas, true \/*save now, restore at exit*\/);\n\n if (NULL != bbh) {\n \/\/ Draw only ops that affect pixels in the canvas's current clip.\n SkIRect query;\n#if 1 \/\/ TODO: Why is this the right way to make the query? I'd think it'd be the else branch.\n SkRect clipBounds;\n canvas->getClipBounds(&clipBounds);\n clipBounds.roundOut(&query);\n#else\n canvas->getClipDeviceBounds(&query);\n#endif\n SkTDArray ops;\n bbh->search(query, &ops);\n\n SkRecords::Draw draw(canvas);\n for (int i = 0; i < ops.count(); i++) {\n if (NULL != callback && callback->abortDrawing()) {\n return;\n }\n record.visit((uintptr_t)ops[i], draw); \/\/ See FillBounds below.\n }\n } else {\n \/\/ Draw all ops.\n for (SkRecords::Draw draw(canvas); draw.index() < record.count(); draw.next()) {\n if (NULL != callback && callback->abortDrawing()) {\n return;\n }\n record.visit(draw.index(), draw);\n }\n }\n}\n\nnamespace SkRecords {\n\n\/\/ FIXME: SkBitmaps are stateful, so we need to copy them to play back in multiple threads.\nstatic SkBitmap shallow_copy(const SkBitmap& bitmap) {\n return bitmap;\n}\n\n\/\/ NoOps draw nothing.\ntemplate <> void Draw::draw(const NoOp&) {}\n\n#define DRAW(T, call) template <> void Draw::draw(const T& r) { fCanvas->call; }\nDRAW(Restore, restore());\nDRAW(Save, save());\nDRAW(SaveLayer, saveLayer(r.bounds, r.paint, r.flags));\nDRAW(PopCull, popCull());\nDRAW(PushCull, pushCull(r.rect));\nDRAW(Clear, clear(r.color));\nDRAW(Concat, concat(r.matrix));\nDRAW(SetMatrix, setMatrix(SkMatrix::Concat(fInitialCTM, r.matrix)));\n\nDRAW(ClipPath, clipPath(r.path, r.op, r.doAA));\nDRAW(ClipRRect, clipRRect(r.rrect, r.op, r.doAA));\nDRAW(ClipRect, clipRect(r.rect, r.op, r.doAA));\nDRAW(ClipRegion, clipRegion(r.region, r.op));\n\nDRAW(DrawBitmap, drawBitmap(shallow_copy(r.bitmap), r.left, r.top, r.paint));\nDRAW(DrawBitmapMatrix, drawBitmapMatrix(shallow_copy(r.bitmap), r.matrix, r.paint));\nDRAW(DrawBitmapNine, drawBitmapNine(shallow_copy(r.bitmap), r.center, r.dst, r.paint));\nDRAW(DrawBitmapRectToRect,\n drawBitmapRectToRect(shallow_copy(r.bitmap), r.src, r.dst, r.paint, r.flags));\nDRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));\nDRAW(DrawOval, drawOval(r.oval, r.paint));\nDRAW(DrawPaint, drawPaint(r.paint));\nDRAW(DrawPath, drawPath(r.path, r.paint));\nDRAW(DrawPatch, drawPatch(r.cubics, r.colors, r.texCoords, r.xmode.get(), r.paint));\nDRAW(DrawPicture, drawPicture(r.picture, r.matrix, r.paint));\nDRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));\nDRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));\nDRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));\nDRAW(DrawRRect, drawRRect(r.rrect, r.paint));\nDRAW(DrawRect, drawRect(r.rect, r.paint));\nDRAW(DrawSprite, drawSprite(shallow_copy(r.bitmap), r.left, r.top, r.paint));\nDRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));\nDRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, r.matrix, r.paint));\nDRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,\n r.xmode.get(), r.indices, r.indexCount, r.paint));\n#undef DRAW\n\n\n\/\/ This is an SkRecord visitor that fills an SkBBoxHierarchy.\n\/\/\n\/\/ The interesting part here is how to calculate bounds for ops which don't\n\/\/ have intrinsic bounds. What is the bounds of a Save or a Translate?\n\/\/\n\/\/ We answer this by thinking about a particular definition of bounds: if I\n\/\/ don't execute this op, pixels in this rectangle might draw incorrectly. So\n\/\/ the bounds of a Save, a Translate, a Restore, etc. are the union of the\n\/\/ bounds of Draw* ops that they might have an effect on. For any given\n\/\/ Save\/Restore block, the bounds of the Save, the Restore, and any other\n\/\/ non-drawing (\"control\") ops inside are exactly the union of the bounds of\n\/\/ the drawing ops inside that block.\n\/\/\n\/\/ To implement this, we keep a stack of active Save blocks. As we consume ops\n\/\/ inside the Save\/Restore block, drawing ops are unioned with the bounds of\n\/\/ the block, and control ops are stashed away for later. When we finish the\n\/\/ block with a Restore, our bounds are complete, and we go back and fill them\n\/\/ in for all the control ops we stashed away.\nclass FillBounds : SkNoncopyable {\npublic:\n FillBounds(const SkRecord& record, SkBBoxHierarchy* bbh) : fBounds(record.count()) {\n \/\/ Calculate bounds for all ops. This won't go quite in order, so we'll need\n \/\/ to store the bounds separately then feed them in to the BBH later in order.\n const SkIRect largest = SkIRect::MakeLargest();\n fCTM.setIdentity();\n fCurrentClipBounds = largest;\n for (fCurrentOp = 0; fCurrentOp < record.count(); fCurrentOp++) {\n record.visit(fCurrentOp, *this);\n }\n\n \/\/ If we have any lingering unpaired Saves, simulate restores to make\n \/\/ sure all ops in those Save blocks have their bounds calculated.\n while (!fSaveStack.isEmpty()) {\n this->popSaveBlock();\n }\n\n \/\/ Any control ops not part of any Save\/Restore block draw everywhere.\n while (!fControlIndices.isEmpty()) {\n this->popControl(largest);\n }\n\n \/\/ Finally feed all stored bounds into the BBH. They'll be returned in this order.\n SkASSERT(NULL != bbh);\n for (uintptr_t i = 0; i < record.count(); i++) {\n if (!fBounds[i].isEmpty()) {\n bbh->insert((void*)i, fBounds[i], true\/*ok to defer*\/);\n }\n }\n bbh->flushDeferredInserts();\n }\n\n template void operator()(const T& op) {\n this->updateCTM(op);\n this->updateClipBounds(op);\n this->trackBounds(op);\n }\n\nprivate:\n struct SaveBounds {\n int controlOps; \/\/ Number of control ops in this Save block, including the Save.\n SkIRect bounds; \/\/ Bounds of everything in the block.\n const SkPaint* paint; \/\/ Unowned. If set, adjusts the bounds of all ops in this block.\n };\n\n template void updateCTM(const T&) { \/* most ops don't change the CTM *\/ }\n void updateCTM(const Restore& op) { fCTM = op.matrix; }\n void updateCTM(const SetMatrix& op) { fCTM = op.matrix; }\n void updateCTM(const Concat& op) { fCTM.preConcat(op.matrix); }\n\n template void updateClipBounds(const T&) { \/* most ops don't change the clip *\/ }\n \/\/ Each of these devBounds fields is the state of the device bounds after the op.\n \/\/ So Restore's devBounds are those bounds saved by its paired Save or SaveLayer.\n void updateClipBounds(const Restore& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipPath& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipRRect& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipRect& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const ClipRegion& op) { fCurrentClipBounds = op.devBounds; }\n void updateClipBounds(const SaveLayer& op) {\n if (op.bounds) {\n fCurrentClipBounds.intersect(this->adjustAndMap(*op.bounds, op.paint));\n }\n }\n\n \/\/ The bounds of these ops must be calculated when we hit the Restore\n \/\/ from the bounds of the ops in the same Save block.\n void trackBounds(const Save&) { this->pushSaveBlock(NULL); }\n \/\/ TODO: bounds of SaveLayer may be more complicated?\n void trackBounds(const SaveLayer& op) { this->pushSaveBlock(op.paint); }\n void trackBounds(const Restore&) { fBounds[fCurrentOp] = this->popSaveBlock(); }\n\n void trackBounds(const Concat&) { this->pushControl(); }\n void trackBounds(const SetMatrix&) { this->pushControl(); }\n void trackBounds(const ClipRect&) { this->pushControl(); }\n void trackBounds(const ClipRRect&) { this->pushControl(); }\n void trackBounds(const ClipPath&) { this->pushControl(); }\n void trackBounds(const ClipRegion&) { this->pushControl(); }\n\n \/\/ For all other ops, we can calculate and store the bounds directly now.\n template void trackBounds(const T& op) {\n fBounds[fCurrentOp] = this->bounds(op);\n this->updateSaveBounds(fBounds[fCurrentOp]);\n }\n\n void pushSaveBlock(const SkPaint* paint) {\n \/\/ Starting a new Save block. Push a new entry to represent that.\n SaveBounds sb = { 0, SkIRect::MakeEmpty(), paint };\n fSaveStack.push(sb);\n this->pushControl();\n }\n\n SkIRect popSaveBlock() {\n \/\/ We're done the Save block. Apply the block's bounds to all control ops inside it.\n SaveBounds sb;\n fSaveStack.pop(&sb);\n while (sb.controlOps --> 0) {\n this->popControl(sb.bounds);\n }\n\n \/\/ This whole Save block may be part another Save block.\n this->updateSaveBounds(sb.bounds);\n\n \/\/ If called from a real Restore (not a phony one for balance), it'll need the bounds.\n return sb.bounds;\n }\n\n void pushControl() {\n fControlIndices.push(fCurrentOp);\n if (!fSaveStack.isEmpty()) {\n fSaveStack.top().controlOps++;\n }\n }\n\n void popControl(const SkIRect& bounds) {\n fBounds[fControlIndices.top()] = bounds;\n fControlIndices.pop();\n }\n\n void updateSaveBounds(const SkIRect& bounds) {\n \/\/ If we're in a Save block, expand its bounds to cover these bounds too.\n if (!fSaveStack.isEmpty()) {\n fSaveStack.top().bounds.join(bounds);\n }\n }\n\n \/\/ TODO: Remove this default when done bounding all ops.\n template SkIRect bounds(const T&) const { return fCurrentClipBounds; }\n SkIRect bounds(const Clear&) const { return SkIRect::MakeLargest(); } \/\/ Ignores the clip\n SkIRect bounds(const NoOp&) const { return SkIRect::MakeEmpty(); } \/\/ NoOps don't draw.\n\n \/\/ Returns true if rect was meaningfully adjusted for the effects of paint,\n \/\/ false if the paint could affect the rect in unknown ways.\n static bool AdjustForPaint(const SkPaint* paint, SkRect* rect) {\n if (paint) {\n if (paint->canComputeFastBounds()) {\n *rect = paint->computeFastBounds(*rect, rect);\n return true;\n }\n return false;\n }\n return true;\n }\n\n \/\/ Adjust rect for all paints that may affect its geometry, then map it to device space.\n SkIRect adjustAndMap(SkRect rect, const SkPaint* paint) const {\n \/\/ Inverted rectangles really confuse our BBHs.\n rect.sort();\n\n \/\/ Adjust the rect for its own paint.\n if (!AdjustForPaint(paint, &rect)) {\n \/\/ The paint could do anything to our bounds. The only safe answer is the current clip.\n return fCurrentClipBounds;\n }\n\n \/\/ Adjust rect for all the paints from the SaveLayers we're inside.\n for (int i = fSaveStack.count() - 1; i >= 0; i--) {\n if (!AdjustForPaint(fSaveStack[i].paint, &rect)) {\n \/\/ Same deal as above.\n return fCurrentClipBounds;\n }\n }\n\n \/\/ Map the rect back to device space.\n fCTM.mapRect(&rect);\n SkIRect devRect;\n rect.roundOut(&devRect);\n\n \/\/ Nothing can draw outside the current clip.\n \/\/ (Only bounded ops call into this method, so oddballs like Clear don't matter here.)\n devRect.intersect(fCurrentClipBounds);\n return devRect;\n }\n\n \/\/ Conservative device bounds for each op in the SkRecord.\n SkAutoTMalloc fBounds;\n\n \/\/ We walk fCurrentOp through the SkRecord, as we go using updateCTM()\n \/\/ and updateClipBounds() to maintain the exact CTM (fCTM) and conservative\n \/\/ device bounds of the current clip (fCurrentClipBounds).\n unsigned fCurrentOp;\n SkMatrix fCTM;\n SkIRect fCurrentClipBounds;\n\n \/\/ Used to track the bounds of Save\/Restore blocks and the control ops inside them.\n SkTDArray fSaveStack;\n SkTDArray fControlIndices;\n};\n\n} \/\/ namespace SkRecords\n\nvoid SkRecordFillBounds(const SkRecord& record, SkBBoxHierarchy* bbh) {\n SkRecords::FillBounds(record, bbh);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2018, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file implements ECDSA signing.\n *\/\n\n#include \"ecdsa.hpp\"\n\n#include \n#include \n\n#include \"common\/code_utils.hpp\"\n#include \"common\/debug.hpp\"\n#include \"common\/random.hpp\"\n\nnamespace ot {\nnamespace Crypto {\n\n#if OPENTHREAD_ENABLE_ECDSA\n\notError Ecdsa::Sign(uint8_t * aOutput,\n uint16_t * aOutputLength,\n const uint8_t *aInputHash,\n uint16_t aInputHashLength,\n const uint8_t *aPrivateKey,\n uint16_t aPrivateKeyLength)\n{\n otError error = OT_ERROR_NONE;\n mbedtls_ecdsa_context ctx;\n mbedtls_pk_context pkCtx;\n mbedtls_ecp_keypair * keypair;\n mbedtls_mpi rMpi;\n mbedtls_mpi sMpi;\n\n mbedtls_pk_init(&pkCtx);\n mbedtls_ecdsa_init(&ctx);\n\n \/\/ Parse a private key in PEM format.\n VerifyOrExit(mbedtls_pk_parse_key(&pkCtx, aPrivateKey, aPrivateKeyLength, NULL, 0) == 0,\n error = OT_ERROR_INVALID_ARGS);\n VerifyOrExit(mbedtls_pk_get_type(&pkCtx) == MBEDTLS_PK_ECKEY, error = OT_ERROR_INVALID_ARGS);\n\n keypair = mbedtls_pk_ec(pkCtx);\n assert(keypair != NULL);\n\n VerifyOrExit(mbedtls_ecdsa_from_keypair(&ctx, keypair) == 0, error = OT_ERROR_FAILED);\n\n mbedtls_mpi_init(&rMpi);\n mbedtls_mpi_init(&sMpi);\n\n \/\/ Sign using ECDSA.\n VerifyOrExit(mbedtls_ecdsa_sign(&ctx.grp, &rMpi, &sMpi, &ctx.d, aInputHash, aInputHashLength, FillRandom, NULL) ==\n 0,\n error = OT_ERROR_FAILED);\n VerifyOrExit(mbedtls_mpi_size(&rMpi) + mbedtls_mpi_size(&sMpi) <= *aOutputLength, error = OT_ERROR_NO_BUFS);\n\n \/\/ Concatenate the two octet sequences in the order R and then S.\n VerifyOrExit(mbedtls_mpi_write_binary(&rMpi, aOutput, mbedtls_mpi_size(&rMpi)) == 0, error = OT_ERROR_FAILED);\n *aOutputLength = mbedtls_mpi_size(&rMpi);\n\n VerifyOrExit(mbedtls_mpi_write_binary(&sMpi, aOutput + *aOutputLength, mbedtls_mpi_size(&sMpi)) == 0,\n error = OT_ERROR_FAILED);\n *aOutputLength += mbedtls_mpi_size(&sMpi);\n\nexit:\n mbedtls_mpi_free(&rMpi);\n mbedtls_mpi_free(&sMpi);\n mbedtls_ecdsa_free(&ctx);\n mbedtls_pk_free(&pkCtx);\n\n return error;\n}\n\nint Ecdsa::FillRandom(void *, unsigned char *aBuffer, size_t aSize)\n{\n Random::FillBuffer(aBuffer, aSize);\n\n return 0;\n}\n\n#endif \/\/ OPENTHREAD_ENABLE_ECDSA\n\n} \/\/ namespace Crypto\n} \/\/ namespace ot\n[ecdsa] do not free mpi context before initializing it (#3366)\/*\n * Copyright (c) 2018, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file implements ECDSA signing.\n *\/\n\n#include \"ecdsa.hpp\"\n\n#include \n#include \n\n#include \"common\/code_utils.hpp\"\n#include \"common\/debug.hpp\"\n#include \"common\/random.hpp\"\n\nnamespace ot {\nnamespace Crypto {\n\n#if OPENTHREAD_ENABLE_ECDSA\n\notError Ecdsa::Sign(uint8_t * aOutput,\n uint16_t * aOutputLength,\n const uint8_t *aInputHash,\n uint16_t aInputHashLength,\n const uint8_t *aPrivateKey,\n uint16_t aPrivateKeyLength)\n{\n otError error = OT_ERROR_NONE;\n mbedtls_ecdsa_context ctx;\n mbedtls_pk_context pkCtx;\n mbedtls_ecp_keypair * keypair;\n mbedtls_mpi rMpi;\n mbedtls_mpi sMpi;\n\n mbedtls_pk_init(&pkCtx);\n mbedtls_ecdsa_init(&ctx);\n mbedtls_mpi_init(&rMpi);\n mbedtls_mpi_init(&sMpi);\n\n \/\/ Parse a private key in PEM format.\n VerifyOrExit(mbedtls_pk_parse_key(&pkCtx, aPrivateKey, aPrivateKeyLength, NULL, 0) == 0,\n error = OT_ERROR_INVALID_ARGS);\n VerifyOrExit(mbedtls_pk_get_type(&pkCtx) == MBEDTLS_PK_ECKEY, error = OT_ERROR_INVALID_ARGS);\n\n keypair = mbedtls_pk_ec(pkCtx);\n assert(keypair != NULL);\n\n VerifyOrExit(mbedtls_ecdsa_from_keypair(&ctx, keypair) == 0, error = OT_ERROR_FAILED);\n\n \/\/ Sign using ECDSA.\n VerifyOrExit(mbedtls_ecdsa_sign(&ctx.grp, &rMpi, &sMpi, &ctx.d, aInputHash, aInputHashLength, FillRandom, NULL) ==\n 0,\n error = OT_ERROR_FAILED);\n VerifyOrExit(mbedtls_mpi_size(&rMpi) + mbedtls_mpi_size(&sMpi) <= *aOutputLength, error = OT_ERROR_NO_BUFS);\n\n \/\/ Concatenate the two octet sequences in the order R and then S.\n VerifyOrExit(mbedtls_mpi_write_binary(&rMpi, aOutput, mbedtls_mpi_size(&rMpi)) == 0, error = OT_ERROR_FAILED);\n *aOutputLength = mbedtls_mpi_size(&rMpi);\n\n VerifyOrExit(mbedtls_mpi_write_binary(&sMpi, aOutput + *aOutputLength, mbedtls_mpi_size(&sMpi)) == 0,\n error = OT_ERROR_FAILED);\n *aOutputLength += mbedtls_mpi_size(&sMpi);\n\nexit:\n mbedtls_mpi_free(&rMpi);\n mbedtls_mpi_free(&sMpi);\n mbedtls_ecdsa_free(&ctx);\n mbedtls_pk_free(&pkCtx);\n\n return error;\n}\n\nint Ecdsa::FillRandom(void *, unsigned char *aBuffer, size_t aSize)\n{\n Random::FillBuffer(aBuffer, aSize);\n\n return 0;\n}\n\n#endif \/\/ OPENTHREAD_ENABLE_ECDSA\n\n} \/\/ namespace Crypto\n} \/\/ namespace ot\n<|endoftext|>"} {"text":"\/*\r\n ==============================================================================\r\n\r\n ADSR.cpp\r\n Created: 5 Dec 2014 4:16:24pm\r\n Author: Penguinum-tea\r\n\r\n ==============================================================================\r\n*\/\r\n\r\n#include \"ADSR.h\"\r\n#include \r\n\r\nnamespace homu {\r\n\r\nvoid ADSR::start() {\r\n state = attackState;\r\n current_sample = 0;\r\n}\r\n\r\nvoid ADSR::setAttack(float a) { attack = int(a * sample_rate); }\r\n\r\nvoid ADSR::setDecay(float d) { decay = int(d * sample_rate); }\r\n\r\nvoid ADSR::setSustain(float s) { sustain = s; }\r\n\r\nvoid ADSR::setRelease(float r) { release = int(r * sample_rate); }\r\n\r\nfloat ADSR::nextSample() {\r\n const int cur_state = state;\r\n switch (cur_state) {\r\n case attackState:\r\n if (attack == 0) {\r\n last_value = 1;\r\n state++;\r\n } else {\r\n last_value = float(current_sample) \/ float(attack);\r\n if (current_sample >= attack) {\r\n state++;\r\n current_sample = 0;\r\n }\r\n }\r\n break;\r\n case decayState:\r\n if (decay == 0) {\r\n last_value = sustain;\r\n state++;\r\n } else {\r\n last_value =\r\n 1 - (1 - sustain) * float(current_sample) \/ float(decay);\r\n if (current_sample >= decay) {\r\n state++;\r\n current_sample = 0;\r\n }\r\n }\r\n break;\r\n case sustainState:\r\n last_value = sustain;\r\n break;\r\n case releaseState:\r\n if (release == 0) {\r\n last_value = 0;\r\n state++;\r\n } else {\r\n last_value = release_max -\r\n release_max * float(current_sample) \/ float(release);\r\n if (current_sample >= release) {\r\n state = finalState;\r\n }\r\n }\r\n break;\r\n default:\r\n last_value = 0;\r\n break;\r\n }\r\n current_sample++;\r\n return last_value;\r\n}\r\n\r\nvoid ADSR::stopSustain() {\r\n if (state < releaseState) {\r\n state = releaseState;\r\n release_max = last_value;\r\n current_sample = 0;\r\n }\r\n}\r\n\r\nbool ADSR::finished() const {\r\n return (state == finalState);\r\n}\r\n\r\nint ADSR::getState() {\r\n return state;\r\n}\r\n\r\nvoid ADSR::setState(int s) {\r\n state = s;\r\n}\r\n\r\n}\r\nfix logic\/*\r\n ==============================================================================\r\n\r\n ADSR.cpp\r\n Created: 5 Dec 2014 4:16:24pm\r\n Author: Penguinum-tea\r\n\r\n ==============================================================================\r\n*\/\r\n\r\n#include \"ADSR.h\"\r\n\r\nnamespace homu {\r\n\r\nvoid ADSR::start() {\r\n state = attackState;\r\n current_sample = 0;\r\n}\r\n\r\nvoid ADSR::setAttack(float a) { attack = int(a * sample_rate); }\r\n\r\nvoid ADSR::setDecay(float d) { decay = int(d * sample_rate); }\r\n\r\nvoid ADSR::setSustain(float s) { sustain = s; }\r\n\r\nvoid ADSR::setRelease(float r) { release = int(r * sample_rate); }\r\n\r\nfloat ADSR::nextSample() {\r\n const int cur_state = state;\r\n switch (cur_state) {\r\n case attackState:\r\n if (attack == 0) {\r\n state++;\r\n } else {\r\n last_value = float(current_sample) \/ float(attack);\r\n if (current_sample >= attack) {\r\n state++;\r\n current_sample = 0;\r\n }\r\n break;\r\n }\r\n case decayState:\r\n if (decay == 0) {\r\n state++;\r\n } else {\r\n last_value =\r\n 1 - (1 - sustain) * float(current_sample) \/ float(decay);\r\n if (current_sample >= decay) {\r\n state++;\r\n current_sample = 0;\r\n }\r\n break;\r\n }\r\n case sustainState:\r\n last_value = sustain;\r\n break;\r\n case releaseState:\r\n if (release == 0) {\r\n last_value = 0;\r\n state++;\r\n } else {\r\n last_value = release_max -\r\n release_max * float(current_sample) \/ float(release);\r\n if (current_sample >= release) {\r\n state = finalState;\r\n }\r\n }\r\n break;\r\n default:\r\n last_value = 0;\r\n break;\r\n }\r\n current_sample++;\r\n return last_value;\r\n}\r\n\r\nvoid ADSR::stopSustain() {\r\n if (state < releaseState) {\r\n state = releaseState;\r\n release_max = last_value;\r\n current_sample = 0;\r\n }\r\n}\r\n\r\nbool ADSR::finished() const {\r\n return (state == finalState);\r\n}\r\n\r\nint ADSR::getState() {\r\n return state;\r\n}\r\n\r\nvoid ADSR::setState(int s) {\r\n state = s;\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"#include \"easypr\/core\/plate_detect.h\"\n#include \"easypr\/util\/util.h\"\n\nnamespace easypr {\n\n CPlateDetect::CPlateDetect() {\n m_plateLocate = new CPlateLocate();\n\n m_maxPlates = 3;\n m_type = 0;\n\n m_showDetect = false;\n }\n\n CPlateDetect::~CPlateDetect() { SAFE_RELEASE(m_plateLocate); }\n\n int CPlateDetect::plateDetect(Mat src, std::vector &resultVec, int type,\n bool showDetectArea, int img_index) {\n\n std::vector color_Plates;\n std::vector sobel_Plates;\n std::vector mser_Plates;\n\n std::vector all_result_Plates;\n if ( !type || type & PR_DETECT_SOBEL) {\n m_plateLocate->plateSobelLocate(src, sobel_Plates, img_index);\n std::vector& sobel_result_Plates = sobel_Plates;\n\n for (size_t i = 0; i < sobel_result_Plates.size(); i++) {\n CPlate plate = sobel_result_Plates[i];\n plate.setPlateLocateType(SOBEL);\n\n all_result_Plates.push_back(plate);\n }\n }\n\n if ( !type || type & PR_DETECT_COLOR) {\n m_plateLocate->plateColorLocate(src, color_Plates, img_index);\n std::vector& color_result_Plates = color_Plates;\n\n for (size_t i = 0; i < color_result_Plates.size(); i++) {\n CPlate plate = color_result_Plates[i];\n\n plate.setPlateLocateType(COLOR);\n all_result_Plates.push_back(plate);\n }\n }\n\n if ( !type || type & PR_DETECT_CMSER) {\n m_plateLocate->plateMserLocate(src, mser_Plates, img_index);\n std::vector& mser_result_Plates = mser_Plates;\n\n for (size_t i = 0; i < mser_result_Plates.size(); i++) {\n CPlate plate = mser_result_Plates[i];\n\n plate.setPlateLocateType(CMSER);\n all_result_Plates.push_back(plate);\n }\n }\n\n \/\/ ʹ÷Ǽֵжϳ\n PlateJudge::instance()->plateJudgeUsingNMS(all_result_Plates, resultVec, m_maxPlates);\n\n if (showDetectArea || getDetectShow()) {\n int index = 0;\n\n Mat result;\n src.copyTo(result);\n\n for (size_t j = 0; j < resultVec.size(); j++) {\n CPlate item = resultVec[j];\n Mat plate = item.getPlateMat();\n\n int height = 36;\n int width = 136;\n if (height * index + height < result.rows) {\n Mat imageRoi = result(Rect(0, 0 + height * index, width, height));\n addWeighted(imageRoi, 0, plate, 1, 0, imageRoi);\n }\n index++;\n\n RotatedRect minRect = item.getPlatePos();\n Point2f rect_points[4];\n minRect.points(rect_points);\n\n Scalar lineColor = Scalar(255, 255, 255);\n\n if (item.getPlateLocateType() == SOBEL) lineColor = Scalar(255, 0, 0);\n if (item.getPlateLocateType() == COLOR) lineColor = Scalar(0, 255, 0);\n if (item.getPlateLocateType() == CMSER) lineColor = Scalar(0, 0, 255);\n\n for (int j = 0; j < 4; j++)\n line(result, rect_points[j], rect_points[(j + 1) % 4], lineColor, 2, 8);\n }\n\n \/\/ʾλͼƬ\n showResult(result, img_index);\n }\n\n\n \/*if (0) {\n Mat result = src.clone();\n for (size_t i = 0; i < all_result_Plates.size(); i++) {\n CPlate plate = all_result_Plates.at(i);\n\n Rect_ outputRect;\n calcSafeRect(plate.getPlatePos(), src, outputRect);\n cv::rectangle(result, outputRect, Scalar(0, 0, 255));\n\n if (0){\n std::stringstream ss(std::stringstream::in | std::stringstream::out);\n ss << \"resources\/image\/tmp\/plate_\" << index << \"_\" << i << \".jpg\";\n imwrite(ss.str(), src(outputRect));\n }\n }\n\n if (0) {\n imshow(\"result\", result);\n waitKey(0);\n destroyWindow(\"result\");\n }\n }*\/\n\n return 0;\n }\n\n int CPlateDetect::plateDetect(Mat src, std::vector &resultVec, int img_index) {\n int result = plateDetect(src, resultVec, m_type, false, img_index);\n return result;\n }\n\n void CPlateDetect::LoadSVM(std::string path) {\n PlateJudge::instance()->LoadModel(path);\n }\n\n\n int CPlateDetect::showResult(const Mat &result, int img_index) {\n namedWindow(\"EasyPR\", CV_WINDOW_AUTOSIZE);\n\n const int RESULTWIDTH = 640; \/\/ 640 930\n const int RESULTHEIGHT = 540; \/\/ 540 710\n\n Mat img_window;\n img_window.create(RESULTHEIGHT, RESULTWIDTH, CV_8UC3);\n\n int nRows = result.rows;\n int nCols = result.cols;\n\n Mat result_resize;\n if (nCols <= img_window.cols && nRows <= img_window.rows) {\n result_resize = result;\n\n }\n else if (nCols > img_window.cols && nRows <= img_window.rows) {\n float scale = float(img_window.cols) \/ float(nCols);\n resize(result, result_resize, Size(), scale, scale, CV_INTER_AREA);\n\n }\n else if (nCols <= img_window.cols && nRows > img_window.rows) {\n float scale = float(img_window.rows) \/ float(nRows);\n resize(result, result_resize, Size(), scale, scale, CV_INTER_AREA);\n\n }\n else if (nCols > img_window.cols && nRows > img_window.rows) {\n Mat result_middle;\n float scale = float(img_window.cols) \/ float(nCols);\n resize(result, result_middle, Size(), scale, scale, CV_INTER_AREA);\n\n if (result_middle.rows > img_window.rows) {\n float scale = float(img_window.rows) \/ float(result_middle.rows);\n resize(result_middle, result_resize, Size(), scale, scale, CV_INTER_AREA);\n }\n else {\n result_resize = result_middle;\n }\n }\n else {\n result_resize = result;\n }\n\n Mat imageRoi = img_window(Rect((RESULTWIDTH - result_resize.cols) \/ 2,\n (RESULTHEIGHT - result_resize.rows) \/ 2,\n result_resize.cols, result_resize.rows));\n addWeighted(imageRoi, 0, result_resize, 1, 0, imageRoi);\n\n if (1) {\n imshow(\"EasyPR\", img_window);\n waitKey(0);\n destroyWindow(\"EasyPR\");\n }\n\n if (1) {\n std::stringstream ss(std::stringstream::in | std::stringstream::out);\n ss << \"resources\/image\/tmp\/Result\/plate_\" << img_index << \".jpg\";\n imwrite(ss.str(), img_window);\n }\n\n return 0;\n }\n}* fix #93.#include \"easypr\/core\/plate_detect.h\"\n#include \"easypr\/util\/util.h\"\n\nnamespace easypr {\n\n CPlateDetect::CPlateDetect() {\n m_plateLocate = new CPlateLocate();\n\n m_maxPlates = 3;\n m_type = 0;\n\n m_showDetect = false;\n }\n\n CPlateDetect::~CPlateDetect() { SAFE_RELEASE(m_plateLocate); }\n\n int CPlateDetect::plateDetect(Mat src, std::vector &resultVec, int type,\n bool showDetectArea, int img_index) {\n\n std::vector color_Plates;\n std::vector sobel_Plates;\n std::vector mser_Plates;\n\n std::vector all_result_Plates;\n if ( !type || type & PR_DETECT_SOBEL) {\n m_plateLocate->plateSobelLocate(src, sobel_Plates, img_index);\n std::vector& sobel_result_Plates = sobel_Plates;\n\n for (size_t i = 0; i < sobel_result_Plates.size(); i++) {\n CPlate plate = sobel_result_Plates[i];\n plate.setPlateLocateType(SOBEL);\n\n all_result_Plates.push_back(plate);\n }\n }\n\n if ( !type || type & PR_DETECT_COLOR) {\n m_plateLocate->plateColorLocate(src, color_Plates, img_index);\n std::vector& color_result_Plates = color_Plates;\n\n for (size_t i = 0; i < color_result_Plates.size(); i++) {\n CPlate plate = color_result_Plates[i];\n\n plate.setPlateLocateType(COLOR);\n all_result_Plates.push_back(plate);\n }\n }\n\n if ( !type || type & PR_DETECT_CMSER) {\n m_plateLocate->plateMserLocate(src, mser_Plates, img_index);\n std::vector& mser_result_Plates = mser_Plates;\n\n for (size_t i = 0; i < mser_result_Plates.size(); i++) {\n CPlate plate = mser_result_Plates[i];\n\n plate.setPlateLocateType(CMSER);\n all_result_Plates.push_back(plate);\n }\n }\n\n \/\/ ʹ÷Ǽֵжϳ\n PlateJudge::instance()->plateJudgeUsingNMS(all_result_Plates, resultVec, m_maxPlates);\n\n if (showDetectArea || getDetectShow()) {\n int index = 0;\n\n Mat result;\n src.copyTo(result);\n\n for (size_t j = 0; j < resultVec.size(); j++) {\n CPlate item = resultVec[j];\n Mat plate = item.getPlateMat();\n\n int height = 36;\n int width = 136;\n if (height * index + height < result.rows) {\n Mat imageRoi = result(Rect(0, 0 + height * index, width, height));\n addWeighted(imageRoi, 0, plate, 1, 0, imageRoi);\n }\n index++;\n\n RotatedRect minRect = item.getPlatePos();\n Point2f rect_points[4];\n minRect.points(rect_points);\n\n Scalar lineColor = Scalar(255, 255, 255);\n\n if (item.getPlateLocateType() == SOBEL) lineColor = Scalar(255, 0, 0);\n if (item.getPlateLocateType() == COLOR) lineColor = Scalar(0, 255, 0);\n if (item.getPlateLocateType() == CMSER) lineColor = Scalar(0, 0, 255);\n\n for (int j = 0; j < 4; j++)\n line(result, rect_points[j], rect_points[(j + 1) % 4], lineColor, 2, 8);\n }\n\n \/\/ʾλͼƬ\n showResult(result, img_index);\n }\n\n\n \/*if (0) {\n Mat result = src.clone();\n for (size_t i = 0; i < all_result_Plates.size(); i++) {\n CPlate plate = all_result_Plates.at(i);\n\n Rect_ outputRect;\n calcSafeRect(plate.getPlatePos(), src, outputRect);\n cv::rectangle(result, outputRect, Scalar(0, 0, 255));\n\n if (0){\n std::stringstream ss(std::stringstream::in | std::stringstream::out);\n ss << \"resources\/image\/tmp\/plate_\" << index << \"_\" << i << \".jpg\";\n imwrite(ss.str(), src(outputRect));\n }\n }\n\n if (0) {\n imshow(\"result\", result);\n waitKey(0);\n destroyWindow(\"result\");\n }\n }*\/\n\n return 0;\n }\n\n int CPlateDetect::plateDetect(Mat src, std::vector &resultVec, int img_index) {\n int result = plateDetect(src, resultVec, m_type, false, img_index);\n return result;\n }\n\n void CPlateDetect::LoadSVM(std::string path) {\n PlateJudge::instance()->LoadModel(path);\n }\n\n int CPlateDetect::showResult(const Mat &result, int img_index) {\n namedWindow(\"EasyPR\", CV_WINDOW_AUTOSIZE);\n\n const int RESULTWIDTH = 640; \/\/ 640 930\n const int RESULTHEIGHT = 540; \/\/ 540 710\n\n Mat img_window;\n img_window.create(RESULTHEIGHT, RESULTWIDTH, CV_8UC3);\n\n int nRows = result.rows;\n int nCols = result.cols;\n\n Mat result_resize;\n if (nCols <= img_window.cols && nRows <= img_window.rows) {\n result_resize = result;\n\n }\n else if (nCols > img_window.cols && nRows <= img_window.rows) {\n float scale = float(img_window.cols) \/ float(nCols);\n resize(result, result_resize, Size(), scale, scale, CV_INTER_AREA);\n\n }\n else if (nCols <= img_window.cols && nRows > img_window.rows) {\n float scale = float(img_window.rows) \/ float(nRows);\n resize(result, result_resize, Size(), scale, scale, CV_INTER_AREA);\n\n }\n else if (nCols > img_window.cols && nRows > img_window.rows) {\n Mat result_middle;\n float scale = float(img_window.cols) \/ float(nCols);\n resize(result, result_middle, Size(), scale, scale, CV_INTER_AREA);\n\n if (result_middle.rows > img_window.rows) {\n float scale = float(img_window.rows) \/ float(result_middle.rows);\n resize(result_middle, result_resize, Size(), scale, scale, CV_INTER_AREA);\n }\n else {\n result_resize = result_middle;\n }\n }\n else {\n result_resize = result;\n }\n\n Mat imageRoi = img_window(Rect((RESULTWIDTH - result_resize.cols) \/ 2,\n (RESULTHEIGHT - result_resize.rows) \/ 2,\n result_resize.cols, result_resize.rows));\n addWeighted(imageRoi, 0, result_resize, 1, 0, imageRoi);\n\n if (1) {\n imshow(\"EasyPR\", img_window);\n waitKey(0);\n destroyWindow(\"EasyPR\");\n }\n\n if (1) {\n std::stringstream ss(std::stringstream::in | std::stringstream::out);\n ss << \"resources\/image\/tmp\/Result\/plate_\" << img_index << \".jpg\";\n imwrite(ss.str(), img_window);\n }\n\n return 0;\n }\n}<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2012-2020 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth 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 VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"vscore.h\"\n#include \n#include \n#ifdef VS_TARGET_CPU_X86\n#include \"x86utils.h\"\n#endif\n\n#if defined(HAVE_SCHED_GETAFFINITY)\n#include \n#elif defined(HAVE_CPUSET_GETAFFINITY)\n#include \n#include \n#include \n#endif\n\nsize_t VSThreadPool::getNumAvailableThreads() {\n size_t nthreads = std::thread::hardware_concurrency();\n#ifdef _WIN32\n DWORD_PTR pAff = 0;\n DWORD_PTR sAff = 0;\n BOOL res = GetProcessAffinityMask(GetCurrentProcess(), &pAff, &sAff);\n if (res && pAff != 0) {\n std::bitset b(pAff);\n nthreads = b.count();\n }\n#elif defined(HAVE_SCHED_GETAFFINITY)\n \/\/ Linux only.\n cpu_set_t affinity;\n if (sched_getaffinity(0, sizeof(cpu_set_t), &affinity) == 0)\n nthreads = CPU_COUNT(&affinity);\n#elif defined(HAVE_CPUSET_GETAFFINITY)\n \/\/ BSD only (FreeBSD only?)\n cpuset_t affinity;\n if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(cpuset_t), &affinity) == 0)\n nthreads = CPU_COUNT(&affinity);\n#endif\n\n return nthreads;\n}\n\nbool VSThreadPool::taskCmp(const PVSFrameContext &a, const PVSFrameContext &b) {\n return (a->reqOrder < b->reqOrder) || (a->reqOrder == b->reqOrder && a->key.second < b->key.second);\n}\n\nvoid VSThreadPool::runTasksWrapper(VSThreadPool *owner, std::atomic &stop) {\n owner->runTasks(stop);\n}\n\nvoid VSThreadPool::runTasks(std::atomic &stop) {\n#ifdef VS_TARGET_OS_WINDOWS\n if (!vs_isSSEStateOk())\n core->logFatal(\"Bad SSE state detected after creating new thread\");\n#endif\n\n std::unique_lock lock(taskLock);\n\n while (true) {\n bool ranTask = false;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Go through all tasks from the top (oldest) and process the first one possible\n std::set seenNodes;\n\n for (auto iter = tasks.begin(); iter != tasks.end(); ++iter) {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Handle the output tasks\n VSFrameContext *frameContext = iter->get();\n VSNode *node = frameContext->key.first;\n\n \/\/ FIXME, somewhat ugly code duplication and is effectively a success only version of the notification at the end\n \/\/ Fast exit path for checking cache\n if (node->cacheEnabled) {\n PVSFrame f = node->getCachedFrameInternal(frameContext->key.second);\n\n if (f) { \n bool needsSort = false;\n\n for (size_t i = 0; i < frameContext->notifyCtxList.size(); i++) {\n PVSFrameContext ¬ify = frameContext->notifyCtxList[i];\n notify->availableFrames.push_back({frameContext->key, f});\n\n assert(notify->numFrameRequests > 0);\n if (--notify->numFrameRequests == 0) {\n queueTask(notify);\n needsSort = true;\n }\n }\n\n PVSFrameContext mainContextRef = std::move(*iter);\n\n if (frameContext->external)\n returnFrame(frameContext, f);\n\n allContexts.erase(frameContext->key);\n tasks.erase(iter);\n\n if (needsSort)\n tasks.sort(taskCmp);\n\n ranTask = true;\n break;\n }\n }\n\n int filterMode = node->filterMode;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n \/\/ Don't try to lock the same node twice since it's likely to fail and will produce more out of order requests as well\n if (filterMode != fmFrameState && !seenNodes.insert(node).second)\n continue;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This part handles the locking for the different filter modes\n\n\n \/\/ Does the filter need the per instance mutex? fmFrameState, fmUnordered and fmParallelRequests (when in the arAllFramesReady state) use this\n bool useSerialLock = (filterMode == fmFrameState || filterMode == fmUnordered || (filterMode == fmParallelRequests && !frameContext->first));\n\n if (useSerialLock) {\n if (!node->serialMutex.try_lock())\n continue;\n if (filterMode == fmFrameState) {\n if (node->serialFrame == -1) {\n node->serialFrame = frameContext->key.second;\n \/\/ another frame already in progress?\n } else if (node->serialFrame != frameContext->key.second) {\n node->serialMutex.unlock();\n continue;\n }\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Remove the context from the task list and keep references around until processing is done\n\n PVSFrameContext frameContextRef = std::move(*iter);\n tasks.erase(iter);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Figure out the activation reason\n\n assert(frameContext->numFrameRequests == 0);\n int ar = arInitial;\n if (frameContext->hasError()) {\n ar = arError;\n } else if (!frameContext->first) {\n ar = (node->apiMajor == 3) ? static_cast(vs3::arAllFramesReady) : static_cast(arAllFramesReady);\n } else if (frameContext->first) {\n frameContext->first = false;\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Do the actual processing\n\n lock.unlock();\n\n PVSFrame f = node->getFrameInternal(frameContext->key.second, ar, frameContext);\n ranTask = true;\n\n bool frameProcessingDone = f || frameContext->hasError();\n if (frameContext->hasError() && f)\n core->logFatal(\"A frame was returned by \" + node->name + \" but an error was also set, this is not allowed\");\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Unlock so the next job can run on the context\n if (useSerialLock) {\n if (filterMode == fmFrameState && frameProcessingDone)\n node->serialFrame = -1;\n node->serialMutex.unlock();\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Handle frames that were requested\n bool requestedFrames = frameContext->reqList.size() > 0 && !frameProcessingDone;\n bool needsSort = false;\n if (f && requestedFrames)\n core->logFatal(\"A frame was returned at the end of processing by \" + node->name + \" but there are still outstanding requests\");\n\n lock.lock();\n\n if (requestedFrames) {\n assert(frameContext->numFrameRequests == 0);\n\n for (size_t i = 0; i < frameContext->reqList.size(); i++)\n startInternalRequest(frameContextRef, frameContext->reqList[i]);\n\n frameContext->numFrameRequests = frameContext->reqList.size();\n frameContext->reqList.clear();\n }\n\n if (frameProcessingDone)\n allContexts.erase(frameContext->key);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Notify all dependent contexts\n\n if (frameContext->hasError()) {\n for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) {\n PVSFrameContext ¬ify = frameContextRef->notifyCtxList[i];\n notify->setError(frameContextRef->getErrorMessage());\n\n assert(notify->numFrameRequests > 0);\n if (--notify->numFrameRequests == 0) {\n queueTask(notify);\n needsSort = true;\n }\n }\n\n if (frameContext->external)\n returnFrame(frameContext, f);\n } else if (f) {\n for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) {\n PVSFrameContext ¬ify = frameContextRef->notifyCtxList[i];\n notify->availableFrames.push_back({frameContextRef->key, f});\n\n assert(notify->numFrameRequests > 0);\n if (--notify->numFrameRequests == 0) {\n queueTask(notify);\n needsSort = true;\n }\n }\n\n if (frameContext->external)\n returnFrame(frameContext, f);\n } else if (requestedFrames) {\n \/\/ already scheduled, do nothing\n } else {\n core->logFatal(\"No frame returned at the end of processing by \" + node->name);\n }\n\n if (needsSort)\n tasks.sort(taskCmp);\n break;\n }\n\n\n if (!ranTask || activeThreads > maxThreads) {\n --activeThreads;\n if (stop) {\n lock.unlock();\n break;\n }\n if (++idleThreads == allThreads.size())\n allIdle.notify_one();\n\n newWork.wait(lock);\n --idleThreads;\n ++activeThreads;\n }\n }\n}\n\nVSThreadPool::VSThreadPool(VSCore *core) : core(core), activeThreads(0), idleThreads(0), reqCounter(0), stopThreads(false), ticks(0) {\n setThreadCount(0);\n}\n\nsize_t VSThreadPool::threadCount() {\n std::lock_guard l(taskLock);\n return maxThreads;\n}\n\nvoid VSThreadPool::spawnThread() {\n std::thread *thread = new std::thread(runTasksWrapper, this, std::ref(stopThreads));\n allThreads.insert(std::make_pair(thread->get_id(), thread));\n ++activeThreads;\n}\n\nsize_t VSThreadPool::setThreadCount(size_t threads) {\n std::lock_guard l(taskLock);\n maxThreads = threads > 0 ? threads : getNumAvailableThreads();\n if (maxThreads == 0) {\n maxThreads = 1;\n core->logMessage(mtWarning, \"Couldn't detect optimal number of threads. Thread count set to 1.\");\n }\n return maxThreads;\n}\n\nvoid VSThreadPool::queueTask(const PVSFrameContext &ctx) {\n tasks.push_back(ctx);\n wakeThread();\n}\n\nvoid VSThreadPool::wakeThread() {\n if (activeThreads < maxThreads) {\n if (idleThreads == 0) \/\/ newly spawned threads are active so no need to notify an additional thread\n spawnThread();\n else\n newWork.notify_one();\n }\n}\n\nvoid VSThreadPool::releaseThread() {\n --activeThreads;\n}\n\nvoid VSThreadPool::reserveThread() {\n ++activeThreads;\n}\n\nvoid VSThreadPool::startExternal(const PVSFrameContext &context) {\n assert(context);\n std::lock_guard l(taskLock);\n context->reqOrder = ++reqCounter;\n tasks.push_back(context); \/\/ external requests can't be combined so just add to queue\n wakeThread();\n}\n\nvoid VSThreadPool::returnFrame(const VSFrameContext *rCtx, const PVSFrame &f) {\n assert(rCtx->frameDone);\n bool outputLock = rCtx->lockOnOutput;\n \/\/ we need to unlock here so the callback may request more frames without causing a deadlock\n \/\/ AND so that slow callbacks will only block operations in this thread, not all the others\n taskLock.unlock();\n if (rCtx->hasError()) {\n if (outputLock)\n callbackLock.lock();\n rCtx->frameDone(rCtx->userData, nullptr, rCtx->key.second, rCtx->key.first, rCtx->errorMessage.c_str());\n if (outputLock)\n callbackLock.unlock();\n } else {\n f->add_ref();\n if (outputLock)\n callbackLock.lock();\n rCtx->frameDone(rCtx->userData, f.get(), rCtx->key.second, rCtx->key.first, nullptr);\n if (outputLock)\n callbackLock.unlock();\n }\n taskLock.lock();\n}\n\nvoid VSThreadPool::startInternalRequest(const PVSFrameContext ¬ify, NodeOutputKey key) {\n \/\/technically this could be done by walking up the context chain and add a new notification to the correct one\n \/\/unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it\n\n if (key.second < 0)\n core->logFatal(\"Negative frame request by: \" + notify->key.first->getName());\n\n \/\/ check to see if it's time to reevaluate cache sizes\n if (core->memory->isOverLimit()) {\n ticks = 0;\n core->notifyCaches(true);\n } else if (\/*!context->upstreamContext && *\/++ticks == 500) { \/\/ a normal tick for caches to adjust their sizes based on recent history\n ticks = 0;\n core->notifyCaches(false);\n }\n\n \n auto it = allContexts.find(key);\n if (it != allContexts.end()) {\n PVSFrameContext &ctx = it->second;\n ctx->notifyCtxList.push_back(notify);\n ctx->reqOrder = std::min(ctx->reqOrder, notify->reqOrder);\n } else {\n PVSFrameContext ctx = new VSFrameContext(key, notify);\n \/\/ create a new context and append it to the tasks\n allContexts.insert(std::make_pair(key, ctx));\n tasks.push_back(ctx);\n }\n\n wakeThread();\n}\n\nbool VSThreadPool::isWorkerThread() {\n std::lock_guard m(taskLock);\n return allThreads.count(std::this_thread::get_id()) > 0;\n}\n\nvoid VSThreadPool::waitForDone() {\n std::unique_lock m(taskLock);\n if (idleThreads < allThreads.size())\n allIdle.wait(m);\n}\n\nVSThreadPool::~VSThreadPool() {\n std::unique_lock m(taskLock);\n stopThreads = true;\n\n while (!allThreads.empty()) {\n auto iter = allThreads.begin();\n auto thread = iter->second;\n newWork.notify_all();\n m.unlock();\n thread->join();\n m.lock();\n allThreads.erase(iter);\n delete thread;\n newWork.notify_all();\n }\n\n assert(activeThreads == 0);\n assert(idleThreads == 0);\n};\nFix comments\/*\n* Copyright (c) 2012-2021 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth 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 VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"vscore.h\"\n#include \n#include \n#ifdef VS_TARGET_CPU_X86\n#include \"x86utils.h\"\n#endif\n\n#if defined(HAVE_SCHED_GETAFFINITY)\n#include \n#elif defined(HAVE_CPUSET_GETAFFINITY)\n#include \n#include \n#include \n#endif\n\nsize_t VSThreadPool::getNumAvailableThreads() {\n size_t nthreads = std::thread::hardware_concurrency();\n#ifdef _WIN32\n DWORD_PTR pAff = 0;\n DWORD_PTR sAff = 0;\n BOOL res = GetProcessAffinityMask(GetCurrentProcess(), &pAff, &sAff);\n if (res && pAff != 0) {\n std::bitset b(pAff);\n nthreads = b.count();\n }\n#elif defined(HAVE_SCHED_GETAFFINITY)\n \/\/ Linux only.\n cpu_set_t affinity;\n if (sched_getaffinity(0, sizeof(cpu_set_t), &affinity) == 0)\n nthreads = CPU_COUNT(&affinity);\n#elif defined(HAVE_CPUSET_GETAFFINITY)\n \/\/ BSD only (FreeBSD only?)\n cpuset_t affinity;\n if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(cpuset_t), &affinity) == 0)\n nthreads = CPU_COUNT(&affinity);\n#endif\n\n return nthreads;\n}\n\nbool VSThreadPool::taskCmp(const PVSFrameContext &a, const PVSFrameContext &b) {\n return (a->reqOrder < b->reqOrder) || (a->reqOrder == b->reqOrder && a->key.second < b->key.second);\n}\n\nvoid VSThreadPool::runTasksWrapper(VSThreadPool *owner, std::atomic &stop) {\n owner->runTasks(stop);\n}\n\nvoid VSThreadPool::runTasks(std::atomic &stop) {\n#ifdef VS_TARGET_OS_WINDOWS\n if (!vs_isSSEStateOk())\n core->logFatal(\"Bad SSE state detected after creating new thread\");\n#endif\n\n std::unique_lock lock(taskLock);\n\n while (true) {\n bool ranTask = false;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Go through all tasks from the top (oldest) and process the first one possible\n\n std::set seenNodes;\n\n for (auto iter = tasks.begin(); iter != tasks.end(); ++iter) {\n\n\n\n VSFrameContext *frameContext = iter->get();\n VSNode *node = frameContext->key.first;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Fast path if a frame is cached\n\n if (node->cacheEnabled) {\n PVSFrame f = node->getCachedFrameInternal(frameContext->key.second);\n\n if (f) { \n bool needsSort = false;\n\n for (size_t i = 0; i < frameContext->notifyCtxList.size(); i++) {\n PVSFrameContext ¬ify = frameContext->notifyCtxList[i];\n notify->availableFrames.push_back({frameContext->key, f});\n\n assert(notify->numFrameRequests > 0);\n if (--notify->numFrameRequests == 0) {\n queueTask(notify);\n needsSort = true;\n }\n }\n\n PVSFrameContext mainContextRef = std::move(*iter);\n\n if (frameContext->external)\n returnFrame(frameContext, f);\n\n allContexts.erase(frameContext->key);\n tasks.erase(iter);\n\n if (needsSort)\n tasks.sort(taskCmp);\n\n ranTask = true;\n break;\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This part handles the locking for the different filter modes\n\n int filterMode = node->filterMode;\n\n \/\/ Don't try to lock the same node twice since it's likely to fail and will produce more out of order requests as well\n if (filterMode != fmFrameState && !seenNodes.insert(node).second)\n continue;\n\n \/\/ Does the filter need the per instance mutex? fmFrameState, fmUnordered and fmParallelRequests (when in the arAllFramesReady state) use this\n bool useSerialLock = (filterMode == fmFrameState || filterMode == fmUnordered || (filterMode == fmParallelRequests && !frameContext->first));\n\n if (useSerialLock) {\n if (!node->serialMutex.try_lock())\n continue;\n if (filterMode == fmFrameState) {\n if (node->serialFrame == -1) {\n node->serialFrame = frameContext->key.second;\n \/\/ another frame already in progress?\n } else if (node->serialFrame != frameContext->key.second) {\n node->serialMutex.unlock();\n continue;\n }\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Remove the context from the task list and keep references around until processing is done\n\n PVSFrameContext frameContextRef = std::move(*iter);\n tasks.erase(iter);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Figure out the activation reason\n\n assert(frameContext->numFrameRequests == 0);\n int ar = arInitial;\n if (frameContext->hasError()) {\n ar = arError;\n } else if (!frameContext->first) {\n ar = (node->apiMajor == 3) ? static_cast(vs3::arAllFramesReady) : static_cast(arAllFramesReady);\n } else if (frameContext->first) {\n frameContext->first = false;\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Do the actual processing\n\n lock.unlock();\n\n PVSFrame f = node->getFrameInternal(frameContext->key.second, ar, frameContext);\n ranTask = true;\n\n bool frameProcessingDone = f || frameContext->hasError();\n if (frameContext->hasError() && f)\n core->logFatal(\"A frame was returned by \" + node->name + \" but an error was also set, this is not allowed\");\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Unlock so the next job can run on the context\n if (useSerialLock) {\n if (filterMode == fmFrameState && frameProcessingDone)\n node->serialFrame = -1;\n node->serialMutex.unlock();\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Handle frames that were requested\n bool requestedFrames = frameContext->reqList.size() > 0 && !frameProcessingDone;\n bool needsSort = false;\n if (f && requestedFrames)\n core->logFatal(\"A frame was returned at the end of processing by \" + node->name + \" but there are still outstanding requests\");\n\n lock.lock();\n\n if (requestedFrames) {\n assert(frameContext->numFrameRequests == 0);\n\n for (size_t i = 0; i < frameContext->reqList.size(); i++)\n startInternalRequest(frameContextRef, frameContext->reqList[i]);\n\n frameContext->numFrameRequests = frameContext->reqList.size();\n frameContext->reqList.clear();\n }\n\n if (frameProcessingDone)\n allContexts.erase(frameContext->key);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Notify all dependent contexts\n\n if (frameContext->hasError()) {\n for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) {\n PVSFrameContext ¬ify = frameContextRef->notifyCtxList[i];\n notify->setError(frameContextRef->getErrorMessage());\n\n assert(notify->numFrameRequests > 0);\n if (--notify->numFrameRequests == 0) {\n queueTask(notify);\n needsSort = true;\n }\n }\n\n if (frameContext->external)\n returnFrame(frameContext, f);\n } else if (f) {\n for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) {\n PVSFrameContext ¬ify = frameContextRef->notifyCtxList[i];\n notify->availableFrames.push_back({frameContextRef->key, f});\n\n assert(notify->numFrameRequests > 0);\n if (--notify->numFrameRequests == 0) {\n queueTask(notify);\n needsSort = true;\n }\n }\n\n if (frameContext->external)\n returnFrame(frameContext, f);\n } else if (requestedFrames) {\n \/\/ already scheduled, do nothing\n } else {\n core->logFatal(\"No frame returned at the end of processing by \" + node->name);\n }\n\n if (needsSort)\n tasks.sort(taskCmp);\n break;\n }\n\n if (!ranTask || activeThreads > maxThreads) {\n --activeThreads;\n if (stop) {\n lock.unlock();\n break;\n }\n if (++idleThreads == allThreads.size())\n allIdle.notify_one();\n\n newWork.wait(lock);\n --idleThreads;\n ++activeThreads;\n }\n }\n}\n\nVSThreadPool::VSThreadPool(VSCore *core) : core(core), activeThreads(0), idleThreads(0), reqCounter(0), stopThreads(false), ticks(0) {\n setThreadCount(0);\n}\n\nsize_t VSThreadPool::threadCount() {\n std::lock_guard l(taskLock);\n return maxThreads;\n}\n\nvoid VSThreadPool::spawnThread() {\n std::thread *thread = new std::thread(runTasksWrapper, this, std::ref(stopThreads));\n allThreads.insert(std::make_pair(thread->get_id(), thread));\n ++activeThreads;\n}\n\nsize_t VSThreadPool::setThreadCount(size_t threads) {\n std::lock_guard l(taskLock);\n maxThreads = threads > 0 ? threads : getNumAvailableThreads();\n if (maxThreads == 0) {\n maxThreads = 1;\n core->logMessage(mtWarning, \"Couldn't detect optimal number of threads. Thread count set to 1.\");\n }\n return maxThreads;\n}\n\nvoid VSThreadPool::queueTask(const PVSFrameContext &ctx) {\n tasks.push_back(ctx);\n wakeThread();\n}\n\nvoid VSThreadPool::wakeThread() {\n if (activeThreads < maxThreads) {\n if (idleThreads == 0) \/\/ newly spawned threads are active so no need to notify an additional thread\n spawnThread();\n else\n newWork.notify_one();\n }\n}\n\nvoid VSThreadPool::releaseThread() {\n --activeThreads;\n}\n\nvoid VSThreadPool::reserveThread() {\n ++activeThreads;\n}\n\nvoid VSThreadPool::startExternal(const PVSFrameContext &context) {\n assert(context);\n std::lock_guard l(taskLock);\n context->reqOrder = ++reqCounter;\n tasks.push_back(context); \/\/ external requests can't be combined so just add to queue\n wakeThread();\n}\n\nvoid VSThreadPool::returnFrame(const VSFrameContext *rCtx, const PVSFrame &f) {\n assert(rCtx->frameDone);\n bool outputLock = rCtx->lockOnOutput;\n \/\/ we need to unlock here so the callback may request more frames without causing a deadlock\n \/\/ AND so that slow callbacks will only block operations in this thread, not all the others\n taskLock.unlock();\n if (rCtx->hasError()) {\n if (outputLock)\n callbackLock.lock();\n rCtx->frameDone(rCtx->userData, nullptr, rCtx->key.second, rCtx->key.first, rCtx->errorMessage.c_str());\n if (outputLock)\n callbackLock.unlock();\n } else {\n f->add_ref();\n if (outputLock)\n callbackLock.lock();\n rCtx->frameDone(rCtx->userData, f.get(), rCtx->key.second, rCtx->key.first, nullptr);\n if (outputLock)\n callbackLock.unlock();\n }\n taskLock.lock();\n}\n\nvoid VSThreadPool::startInternalRequest(const PVSFrameContext ¬ify, NodeOutputKey key) {\n \/\/technically this could be done by walking up the context chain and add a new notification to the correct one\n \/\/unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it\n\n if (key.second < 0)\n core->logFatal(\"Negative frame request by: \" + notify->key.first->getName());\n\n \/\/ check to see if it's time to reevaluate cache sizes\n if (core->memory->isOverLimit()) {\n ticks = 0;\n core->notifyCaches(true);\n } else if (\/*!context->upstreamContext && *\/++ticks == 500) { \/\/ a normal tick for caches to adjust their sizes based on recent history\n ticks = 0;\n core->notifyCaches(false);\n }\n\n \n auto it = allContexts.find(key);\n if (it != allContexts.end()) {\n PVSFrameContext &ctx = it->second;\n ctx->notifyCtxList.push_back(notify);\n ctx->reqOrder = std::min(ctx->reqOrder, notify->reqOrder);\n } else {\n PVSFrameContext ctx = new VSFrameContext(key, notify);\n \/\/ create a new context and append it to the tasks\n allContexts.insert(std::make_pair(key, ctx));\n tasks.push_back(ctx);\n }\n\n wakeThread();\n}\n\nbool VSThreadPool::isWorkerThread() {\n std::lock_guard m(taskLock);\n return allThreads.count(std::this_thread::get_id()) > 0;\n}\n\nvoid VSThreadPool::waitForDone() {\n std::unique_lock m(taskLock);\n if (idleThreads < allThreads.size())\n allIdle.wait(m);\n}\n\nVSThreadPool::~VSThreadPool() {\n std::unique_lock m(taskLock);\n stopThreads = true;\n\n while (!allThreads.empty()) {\n auto iter = allThreads.begin();\n auto thread = iter->second;\n newWork.notify_all();\n m.unlock();\n thread->join();\n m.lock();\n allThreads.erase(iter);\n delete thread;\n newWork.notify_all();\n }\n\n assert(activeThreads == 0);\n assert(idleThreads == 0);\n};\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2012 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth 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 VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"vscore.h\"\n\nVSThread::VSThread(VSThreadPool *owner) : owner(owner), stop(false) {\n\n}\n\nvoid VSThread::stopThread() {\n stop = true;\n}\n\nvoid VSThread::run() {\n owner->lock.lock();\n owner->activeThreads++;\n\n while (true) {\n bool ranTask = false;\n\n for (int i = 0; i < owner->tasks.count(); i++) {\n PFrameContext rCtx = owner->tasks[i];\n\n if (rCtx->frameDone && rCtx->returnedFrame) {\n owner->tasks.removeAt(i--);\n owner->returnFrame(rCtx, rCtx->returnedFrame);\n ranTask = true;\n break;\n } else {\n\n PFrameContext pCtx = rCtx;\n\n if (rCtx->returnedFrame || rCtx->hasError())\n rCtx = rCtx->upstreamContext;\n\n Q_ASSERT(rCtx);\n Q_ASSERT(pCtx);\n\n \/\/ if an error has already been flagged upstream simply drop this task so a filter won't get multiple arError calls for the same frame\n if (rCtx->hasError()) {\n owner->tasks.removeAt(i--);\n continue;\n }\n\n bool isSingleInstance = (rCtx->clip->filterMode == fmParallelRequests && pCtx->returnedFrame && rCtx->numFrameRequests == 1 && pCtx != rCtx) || rCtx->clip->filterMode == fmSerial;\n\n \/\/ this check is common for both filter modes, it makes sure that multiple calls won't be made in parallel to a single filter to produce the same frame\n \/\/ special casing so serial unordered doesn't need yet another list\n if (owner->runningTasks.contains(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n)))\n continue;\n\n if (isSingleInstance) {\n \/\/ this is the complicated case, a new frame may not be started until all calls are completed for the current one\n if (owner->framesInProgress.contains(rCtx->clip) && owner->framesInProgress[rCtx->clip] != rCtx->n)\n continue;\n }\n\n \/\/ mark task as active\n owner->tasks.removeAt(i--);\n owner->runningTasks.insert(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n), rCtx);\n\n if (isSingleInstance)\n owner->framesInProgress.insert(rCtx->clip, rCtx->n);\n\n ActivationReason ar = arInitial;\n\n if (pCtx->hasError()) {\n ar = arError;\n rCtx->setError(pCtx->getErrorMessage());\n } else if (pCtx != rCtx && pCtx->returnedFrame) {\n if (--rCtx->numFrameRequests)\n ar = arFrameReady;\n else\n ar = arAllFramesReady;\n\n Q_ASSERT(rCtx->numFrameRequests >= 0);\n rCtx->availableFrames.insert(NodeOutputKey(pCtx->clip, pCtx->n, pCtx->index), pCtx->returnedFrame);\n rCtx->lastCompletedN = pCtx->n;\n rCtx->lastCompletedNode = pCtx->node;\n }\n\n owner->lock.unlock();\n \/\/ run task\n\n PVideoFrame f = rCtx->clip->getFrameInternal(rCtx->n, ar, rCtx);\n ranTask = true;\n owner->lock.lock();\n\n if (f && rCtx->numFrameRequests > 0)\n qFatal(\"Frame returned but there are still pending frame requests, filter: \" + rCtx->clip->name);\n\n owner->runningTasks.remove(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n));\n\n\t\t\t\tif (f || ar == arError || rCtx->hasError()) {\n \/\/ free all input frames quickly since the frame processing is done\n rCtx->availableFrames.clear();\n\n if (isSingleInstance) {\n if (owner->framesInProgress[rCtx->clip] != rCtx->n && !rCtx->hasError())\n qWarning(\"Releasing unobtained frame lock\");\n\n owner->framesInProgress.remove(rCtx->clip);\n }\n\n owner->allContexts.remove(NodeOutputKey(rCtx->clip, rCtx->n, rCtx->index));\n }\n\n if (rCtx->hasError()) {\n PFrameContext n;\n\n do {\n n = rCtx->notificationChain;\n\n if (n) {\n rCtx->notificationChain.clear();\n n->setError(rCtx->getErrorMessage());\n }\n\n if (rCtx->upstreamContext) {\n owner->startInternal(rCtx);\n }\n\n if (rCtx->frameDone) {\n owner->lock.unlock();\n QMutexLocker callbackLock(&owner->callbackLock);\n rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, rCtx->getErrorMessage().constData());\n callbackLock.unlock();\n owner->lock.lock();\n }\n } while ((rCtx = n));\n } else if (f) {\n Q_ASSERT(rCtx->numFrameRequests == 0);\n PFrameContext n;\n\n do {\n n = rCtx->notificationChain;\n\n if (n)\n rCtx->notificationChain.clear();\n\n if (rCtx->upstreamContext) {\n rCtx->returnedFrame = f;\n owner->startInternal(rCtx);\n }\n\n if (rCtx->frameDone)\n owner->returnFrame(rCtx, f);\n } while ((rCtx = n));\n } else if (rCtx->numFrameRequests > 0 || rCtx->n < 0) {\n \/\/ already scheduled or in the case of negative n it is simply a cache notify message\n } else {\n qFatal(\"No frame returned at the end of processing by \" + rCtx->clip->name);\n }\n\n break;\n }\n }\n\n if (!ranTask && !stop) {\n owner->activeThreads--;\n owner->newWork.wait(&owner->lock);\n owner->activeThreads++;\n } else if (stop) {\n owner->activeThreads--;\n owner->lock.unlock();\n return;\n }\n }\n}\n\nVSThreadPool::VSThreadPool(VSCore *core, int threads) : core(core), activeThreads(0) {\n setThreadCount(threads > 0 ? threads : QThread::idealThreadCount());\n}\n\nint\tVSThreadPool::activeThreadCount() const {\n return activeThreads;\n}\n\nint\tVSThreadPool::threadCount() const {\n return allThreads.count();\n}\n\nvoid VSThreadPool::setThreadCount(int threadCount) {\n QMutexLocker m(&lock);\n\n while (threadCount > allThreads.count()) {\n VSThread *vst = new VSThread(this);\n allThreads.insert(vst);\n vst->start();\n }\n\n while (threadCount < allThreads.count()) {\n VSThread *t = *allThreads.begin();\n t->stopThread();\n newWork.wakeAll();\n m.unlock();\n t->wait();\n m.relock();\n allThreads.remove(t);\n delete t;\n newWork.wakeAll();\n }\n}\n\nvoid VSThreadPool::wakeThread() {\n if (activeThreads < threadCount())\n newWork.wakeOne();\n}\n\nvoid VSThreadPool::releaseThread() {\n setThreadCount(allThreads.count() + 1);\n}\n\nvoid VSThreadPool::reserveThread() {\n setThreadCount(allThreads.count() - 1);\n}\n\nvoid VSThreadPool::notifyCaches(CacheActivation reason) {\n for (int i = 0; i < core->caches.count(); i++)\n tasks.insert(0, PFrameContext(new FrameContext(reason, 0, core->caches[i], PFrameContext())));\n}\n\nvoid VSThreadPool::start(const PFrameContext &context) {\n Q_ASSERT(context);\n QMutexLocker m(&lock);\n startInternal(context);\n}\n\nvoid VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) {\n Q_ASSERT(rCtx->frameDone);\n \/\/ we need to unlock here so the callback may request more frames without causing a deadlock\n \/\/ AND so that slow callbacks will only block operations in this thread, not all the others\n lock.unlock();\n VSFrameRef *ref = new VSFrameRef(f);\n QMutexLocker m(&callbackLock);\n rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL);\n m.unlock();\n lock.lock();\n}\n\nvoid VSThreadPool::startInternal(const PFrameContext &context) {\n \/\/technically this could be done by walking up the context chain and add a new notification to the correct one\n \/\/unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it\n\n if (context->n < 0)\n qFatal(\"Negative frame request by: \" + context->clip->name);\n\n \/\/ check to see if it's time to reevaluate cache sizes\n if (core->memory->isOverLimit()) {\n \/\/if (core->memory->isOverLimit()) {\n ticks = 0;\n notifyCaches(cNeedMemory);\n }\n\n \/\/ a normal tick for caches to adjust their sizes based on recent history\n if (!context->upstreamContext && ticks.fetchAndAddAcquire(1) == 99) {\n ticks = 0;\n notifyCaches(cCacheTick);\n }\n\n \/\/ add it immediately if the task is to return a completed frame\n if (context->returnedFrame) {\n tasks.append(context);\n wakeThread();\n return;\n } else {\n if (context->upstreamContext)\n context->upstreamContext->numFrameRequests++;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ see if the task is a duplicate\n foreach(const PFrameContext &ctx, tasks) {\n if (context->clip == ctx->clip && context->n == ctx->n && context->index == ctx->index) {\n if (ctx->returnedFrame) {\n \/\/ special case where the requested frame is encountered \"by accident\"\n context->returnedFrame = ctx->returnedFrame;\n tasks.append(context);\n wakeThread();\n return;\n } else {\n PFrameContext rCtx = ctx;\n\n if (rCtx->returnedFrame)\n rCtx = rCtx->upstreamContext;\n\n if (context->clip == rCtx->clip && context->n == rCtx->n && context->index == ctx->index) {\n PFrameContext t = rCtx;\n\n while (t && t->notificationChain)\n t = t->notificationChain;\n\n t->notificationChain = context;\n return;\n }\n }\n }\n }\n\n NodeOutputKey p(context->clip, context->n, context->index);\n\n if (allContexts.contains(p)) {\n PFrameContext ctx = allContexts[p];\n Q_ASSERT(ctx);\n Q_ASSERT(context->clip == ctx->clip && context->n == ctx->n);\n\n if (ctx->returnedFrame) {\n \/\/ special case where the requested frame is encountered \"by accident\"\n context->returnedFrame = ctx->returnedFrame;\n tasks.append(context);\n wakeThread();\n return;\n } else {\n while (ctx->notificationChain)\n ctx = ctx->notificationChain;\n ctx->notificationChain = context;\n return;\n }\n } else {\n allContexts[p] = context;\n }\n\n tasks.append(context);\n wakeThread();\n return;\n }\n\n}\n\nvoid VSThreadPool::waitForDone() {\n\n}\n\nVSThreadPool::~VSThreadPool() {\n setThreadCount(0);\n};\nRemove duplicate commented line\/*\n* Copyright (c) 2012 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth 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 VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"vscore.h\"\n\nVSThread::VSThread(VSThreadPool *owner) : owner(owner), stop(false) {\n\n}\n\nvoid VSThread::stopThread() {\n stop = true;\n}\n\nvoid VSThread::run() {\n owner->lock.lock();\n owner->activeThreads++;\n\n while (true) {\n bool ranTask = false;\n\n for (int i = 0; i < owner->tasks.count(); i++) {\n PFrameContext rCtx = owner->tasks[i];\n\n if (rCtx->frameDone && rCtx->returnedFrame) {\n owner->tasks.removeAt(i--);\n owner->returnFrame(rCtx, rCtx->returnedFrame);\n ranTask = true;\n break;\n } else {\n\n PFrameContext pCtx = rCtx;\n\n if (rCtx->returnedFrame || rCtx->hasError())\n rCtx = rCtx->upstreamContext;\n\n Q_ASSERT(rCtx);\n Q_ASSERT(pCtx);\n\n \/\/ if an error has already been flagged upstream simply drop this task so a filter won't get multiple arError calls for the same frame\n if (rCtx->hasError()) {\n owner->tasks.removeAt(i--);\n continue;\n }\n\n bool isSingleInstance = (rCtx->clip->filterMode == fmParallelRequests && pCtx->returnedFrame && rCtx->numFrameRequests == 1 && pCtx != rCtx) || rCtx->clip->filterMode == fmSerial;\n\n \/\/ this check is common for both filter modes, it makes sure that multiple calls won't be made in parallel to a single filter to produce the same frame\n \/\/ special casing so serial unordered doesn't need yet another list\n if (owner->runningTasks.contains(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n)))\n continue;\n\n if (isSingleInstance) {\n \/\/ this is the complicated case, a new frame may not be started until all calls are completed for the current one\n if (owner->framesInProgress.contains(rCtx->clip) && owner->framesInProgress[rCtx->clip] != rCtx->n)\n continue;\n }\n\n \/\/ mark task as active\n owner->tasks.removeAt(i--);\n owner->runningTasks.insert(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n), rCtx);\n\n if (isSingleInstance)\n owner->framesInProgress.insert(rCtx->clip, rCtx->n);\n\n ActivationReason ar = arInitial;\n\n if (pCtx->hasError()) {\n ar = arError;\n rCtx->setError(pCtx->getErrorMessage());\n } else if (pCtx != rCtx && pCtx->returnedFrame) {\n if (--rCtx->numFrameRequests)\n ar = arFrameReady;\n else\n ar = arAllFramesReady;\n\n Q_ASSERT(rCtx->numFrameRequests >= 0);\n rCtx->availableFrames.insert(NodeOutputKey(pCtx->clip, pCtx->n, pCtx->index), pCtx->returnedFrame);\n rCtx->lastCompletedN = pCtx->n;\n rCtx->lastCompletedNode = pCtx->node;\n }\n\n owner->lock.unlock();\n \/\/ run task\n\n PVideoFrame f = rCtx->clip->getFrameInternal(rCtx->n, ar, rCtx);\n ranTask = true;\n owner->lock.lock();\n\n if (f && rCtx->numFrameRequests > 0)\n qFatal(\"Frame returned but there are still pending frame requests, filter: \" + rCtx->clip->name);\n\n owner->runningTasks.remove(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n));\n\n\t\t\t\tif (f || ar == arError || rCtx->hasError()) {\n \/\/ free all input frames quickly since the frame processing is done\n rCtx->availableFrames.clear();\n\n if (isSingleInstance) {\n if (owner->framesInProgress[rCtx->clip] != rCtx->n && !rCtx->hasError())\n qWarning(\"Releasing unobtained frame lock\");\n\n owner->framesInProgress.remove(rCtx->clip);\n }\n\n owner->allContexts.remove(NodeOutputKey(rCtx->clip, rCtx->n, rCtx->index));\n }\n\n if (rCtx->hasError()) {\n PFrameContext n;\n\n do {\n n = rCtx->notificationChain;\n\n if (n) {\n rCtx->notificationChain.clear();\n n->setError(rCtx->getErrorMessage());\n }\n\n if (rCtx->upstreamContext) {\n owner->startInternal(rCtx);\n }\n\n if (rCtx->frameDone) {\n owner->lock.unlock();\n QMutexLocker callbackLock(&owner->callbackLock);\n rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, rCtx->getErrorMessage().constData());\n callbackLock.unlock();\n owner->lock.lock();\n }\n } while ((rCtx = n));\n } else if (f) {\n Q_ASSERT(rCtx->numFrameRequests == 0);\n PFrameContext n;\n\n do {\n n = rCtx->notificationChain;\n\n if (n)\n rCtx->notificationChain.clear();\n\n if (rCtx->upstreamContext) {\n rCtx->returnedFrame = f;\n owner->startInternal(rCtx);\n }\n\n if (rCtx->frameDone)\n owner->returnFrame(rCtx, f);\n } while ((rCtx = n));\n } else if (rCtx->numFrameRequests > 0 || rCtx->n < 0) {\n \/\/ already scheduled or in the case of negative n it is simply a cache notify message\n } else {\n qFatal(\"No frame returned at the end of processing by \" + rCtx->clip->name);\n }\n\n break;\n }\n }\n\n if (!ranTask && !stop) {\n owner->activeThreads--;\n owner->newWork.wait(&owner->lock);\n owner->activeThreads++;\n } else if (stop) {\n owner->activeThreads--;\n owner->lock.unlock();\n return;\n }\n }\n}\n\nVSThreadPool::VSThreadPool(VSCore *core, int threads) : core(core), activeThreads(0) {\n setThreadCount(threads > 0 ? threads : QThread::idealThreadCount());\n}\n\nint\tVSThreadPool::activeThreadCount() const {\n return activeThreads;\n}\n\nint\tVSThreadPool::threadCount() const {\n return allThreads.count();\n}\n\nvoid VSThreadPool::setThreadCount(int threadCount) {\n QMutexLocker m(&lock);\n\n while (threadCount > allThreads.count()) {\n VSThread *vst = new VSThread(this);\n allThreads.insert(vst);\n vst->start();\n }\n\n while (threadCount < allThreads.count()) {\n VSThread *t = *allThreads.begin();\n t->stopThread();\n newWork.wakeAll();\n m.unlock();\n t->wait();\n m.relock();\n allThreads.remove(t);\n delete t;\n newWork.wakeAll();\n }\n}\n\nvoid VSThreadPool::wakeThread() {\n if (activeThreads < threadCount())\n newWork.wakeOne();\n}\n\nvoid VSThreadPool::releaseThread() {\n setThreadCount(allThreads.count() + 1);\n}\n\nvoid VSThreadPool::reserveThread() {\n setThreadCount(allThreads.count() - 1);\n}\n\nvoid VSThreadPool::notifyCaches(CacheActivation reason) {\n for (int i = 0; i < core->caches.count(); i++)\n tasks.insert(0, PFrameContext(new FrameContext(reason, 0, core->caches[i], PFrameContext())));\n}\n\nvoid VSThreadPool::start(const PFrameContext &context) {\n Q_ASSERT(context);\n QMutexLocker m(&lock);\n startInternal(context);\n}\n\nvoid VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) {\n Q_ASSERT(rCtx->frameDone);\n \/\/ we need to unlock here so the callback may request more frames without causing a deadlock\n \/\/ AND so that slow callbacks will only block operations in this thread, not all the others\n lock.unlock();\n VSFrameRef *ref = new VSFrameRef(f);\n QMutexLocker m(&callbackLock);\n rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL);\n m.unlock();\n lock.lock();\n}\n\nvoid VSThreadPool::startInternal(const PFrameContext &context) {\n \/\/technically this could be done by walking up the context chain and add a new notification to the correct one\n \/\/unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it\n\n if (context->n < 0)\n qFatal(\"Negative frame request by: \" + context->clip->name);\n\n \/\/ check to see if it's time to reevaluate cache sizes\n if (core->memory->isOverLimit()) {\n ticks = 0;\n notifyCaches(cNeedMemory);\n }\n\n \/\/ a normal tick for caches to adjust their sizes based on recent history\n if (!context->upstreamContext && ticks.fetchAndAddAcquire(1) == 99) {\n ticks = 0;\n notifyCaches(cCacheTick);\n }\n\n \/\/ add it immediately if the task is to return a completed frame\n if (context->returnedFrame) {\n tasks.append(context);\n wakeThread();\n return;\n } else {\n if (context->upstreamContext)\n context->upstreamContext->numFrameRequests++;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ see if the task is a duplicate\n foreach(const PFrameContext &ctx, tasks) {\n if (context->clip == ctx->clip && context->n == ctx->n && context->index == ctx->index) {\n if (ctx->returnedFrame) {\n \/\/ special case where the requested frame is encountered \"by accident\"\n context->returnedFrame = ctx->returnedFrame;\n tasks.append(context);\n wakeThread();\n return;\n } else {\n PFrameContext rCtx = ctx;\n\n if (rCtx->returnedFrame)\n rCtx = rCtx->upstreamContext;\n\n if (context->clip == rCtx->clip && context->n == rCtx->n && context->index == ctx->index) {\n PFrameContext t = rCtx;\n\n while (t && t->notificationChain)\n t = t->notificationChain;\n\n t->notificationChain = context;\n return;\n }\n }\n }\n }\n\n NodeOutputKey p(context->clip, context->n, context->index);\n\n if (allContexts.contains(p)) {\n PFrameContext ctx = allContexts[p];\n Q_ASSERT(ctx);\n Q_ASSERT(context->clip == ctx->clip && context->n == ctx->n);\n\n if (ctx->returnedFrame) {\n \/\/ special case where the requested frame is encountered \"by accident\"\n context->returnedFrame = ctx->returnedFrame;\n tasks.append(context);\n wakeThread();\n return;\n } else {\n while (ctx->notificationChain)\n ctx = ctx->notificationChain;\n ctx->notificationChain = context;\n return;\n }\n } else {\n allContexts[p] = context;\n }\n\n tasks.append(context);\n wakeThread();\n return;\n }\n\n}\n\nvoid VSThreadPool::waitForDone() {\n\n}\n\nVSThreadPool::~VSThreadPool() {\n setThreadCount(0);\n};\n<|endoftext|>"} {"text":"\/*!\n * @file cudapolisher.cpp\n *\n * @brief CUDA Polisher class source file\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"sequence.hpp\"\n#include \"cudapolisher.hpp\"\n#include \n\n#include \"bioparser\/bioparser.hpp\"\n\nnamespace racon {\n\n\/\/ The logger used by racon has a fixed size of 20 bins\n\/\/ which is used for the progress bar updates. Hence all\n\/\/ updates need to be broken into 20 bins.\nconst uint32_t RACON_LOGGER_BIN_SIZE = 20;\n\nCUDAPolisher::CUDAPolisher(std::unique_ptr> sparser,\n std::unique_ptr> oparser,\n std::unique_ptr> tparser,\n PolisherType type, uint32_t window_length, double quality_threshold,\n double error_threshold, int8_t match, int8_t mismatch, int8_t gap,\n uint32_t num_threads, uint32_t cuda_batches, bool cuda_banded_alignment)\n : Polisher(std::move(sparser), std::move(oparser), std::move(tparser),\n type, window_length, quality_threshold,\n error_threshold, match, mismatch, gap, num_threads)\n , cuda_batches_(cuda_batches)\n , gap_(gap)\n , mismatch_(mismatch)\n , match_(match)\n , cuda_banded_alignment_(cuda_banded_alignment)\n{\n#ifdef DEBUG\n window_length_ = 200;\n std::cerr << \"In DEBUG mode. Using window size of \" << window_length_ << std::endl;\n#endif\n\n genomeworks::cudapoa::Init();\n genomeworks::cudaaligner::Init();\n\n GW_CU_CHECK_ERR(cudaGetDeviceCount(&num_devices_));\n\n if (num_devices_ < 1)\n {\n throw std::runtime_error(\"No GPU devices found.\");\n }\n\n std::cerr << \"Using \" << num_devices_ << \" GPU(s) to perform polishing\" << std::endl;\n\n \/\/ Run dummy call on each device to initialize CUDA context.\n for(int32_t dev_id = 0; dev_id < num_devices_; dev_id++)\n {\n std::cerr << \"Initialize device \" << dev_id << std::endl;\n GW_CU_CHECK_ERR(cudaSetDevice(dev_id));\n GW_CU_CHECK_ERR(cudaFree(0));\n }\n\n std::cerr << \"[CUDAPolisher] Constructed.\" << std::endl;\n}\n\nCUDAPolisher::~CUDAPolisher()\n{\n cudaDeviceSynchronize();\n cudaProfilerStop();\n}\n\nvoid CUDAPolisher::find_overlap_breaking_points(std::vector>& overlaps)\n{\n std::mutex mutex_overlaps;\n uint32_t next_overlap_index = 0;\n\n \/\/ Lambda expression for filling up next batch of alignments.\n auto fill_next_batch = [&mutex_overlaps, &next_overlap_index, &overlaps, this](CUDABatchAligner* batch) -> void {\n batch->reset();\n\n \/\/ Use mutex to read the vector containing windows in a threadsafe manner.\n std::lock_guard guard(mutex_overlaps);\n\n uint32_t initial_count = next_overlap_index;\n uint32_t count = overlaps.size();\n while(next_overlap_index < count)\n {\n if (batch->addOverlap(overlaps.at(next_overlap_index).get(), sequences_))\n {\n next_overlap_index++;\n }\n else\n {\n break;\n }\n }\n if (next_overlap_index - initial_count > 0)\n {\n fprintf(stderr, \"Processing overlaps %d - %d (of %d) in batch %d\\n\",\n initial_count,\n next_overlap_index ,\n count,\n batch->getBatchID());\n }\n };\n\n \/\/ Lambda expression for processing a batch of alignments.\n auto process_batch = [&fill_next_batch, this](CUDABatchAligner* batch) -> void {\n while(true)\n {\n fill_next_batch(batch);\n if (batch->hasOverlaps())\n {\n \/\/ Launch workload.\n batch->alignAll();\n batch->find_breaking_points(window_length_);\n }\n else\n {\n break;\n }\n }\n };\n\n \/\/ Create batches based on arguments provided to program.\n for(uint32_t batch = 0; batch < cuda_batches_; batch++)\n {\n batch_aligners_.emplace_back(createCUDABatchAligner(20000, 20000, 1000, 0));\n }\n\n \/\/ Run batched alignment.\n std::vector> thread_futures;\n for(uint32_t i = 0; i < batch_aligners_.size(); i++)\n {\n thread_futures.emplace_back(std::async(std::launch::async,\n process_batch,\n batch_aligners_.at(i).get())\n );\n }\n\n \/\/ Wait for threads to finish, and collect their results.\n for (const auto& future : thread_futures) {\n future.wait();\n }\n\n batch_aligners_.clear();\n\n log(std::string(\"[racon::CUDAPolisher::initialize] aligned overlaps\"));\n\n \/\/ TODO: Kept CPU overlap alignment right now while GPU is a dummy implmentation.\n Polisher::find_overlap_breaking_points(overlaps);\n}\n\nvoid CUDAPolisher::polish(std::vector>& dst,\n bool drop_unpolished_sequences)\n{\n \/\/ Creation and use of batches.\n const uint32_t MAX_WINDOWS = 256;\n const uint32_t MAX_DEPTH_PER_WINDOW = 200;\n\n \/\/ Bin batches into each GPU.\n std::vector batches_per_gpu(num_devices_, 0);\n\n#ifdef DEBUG\n for(uint32_t i = 0; i < 1; i++)\n#else\n for(uint32_t i = 0; i < cuda_batches_; i++)\n#endif\n {\n uint32_t device = i % num_devices_;\n batches_per_gpu.at(device) = batches_per_gpu.at(device) + 1;\n }\n\n for(int32_t device = 0; device < num_devices_; device++)\n {\n for(uint32_t batch = 0; batch < batches_per_gpu.at(device); batch++)\n {\n batch_processors_.emplace_back(createCUDABatch(MAX_WINDOWS, MAX_DEPTH_PER_WINDOW, device, gap_, mismatch_, match_, cuda_banded_alignment_));\n }\n }\n\n log(std::string(\"[racon::CUDAPolisher::polish] allocated memory on GPUs\"));\n\n \/\/ Mutex for accessing the vector of windows.\n std::mutex mutex_windows;\n\n \/\/ Initialize window consensus statuses.\n window_consensus_status_.resize(windows_.size(), false);\n\n \/\/ Index of next window to be added to a batch.\n#ifdef DEBUG\n uint32_t next_window_index = 5000;\n#else\n uint32_t next_window_index = 0;\n#endif\n\n \/\/ Variables for keeping track of logger progress bar.\n uint32_t logger_step = windows_.size() \/ RACON_LOGGER_BIN_SIZE;\n uint32_t last_logger_count = 0;\n\n \/\/ Lambda function for adding windows to batches.\n auto fill_next_batch = [&mutex_windows, &next_window_index, &logger_step, &last_logger_count, this](CUDABatchProcessor* batch) -> std::pair {\n batch->reset();\n\n \/\/ Use mutex to read the vector containing windows in a threadsafe manner.\n std::lock_guard guard(mutex_windows);\n\n \/\/ TODO: Reducing window wize by 10 for debugging.\n uint32_t initial_count = next_window_index;\n#ifdef DEBUG\n uint32_t count = 5001;\/\/windows_.size();\n#else\n uint32_t count = windows_.size();\n#endif\n while(next_window_index < count)\n {\n if (batch->addWindow(windows_.at(next_window_index)))\n {\n next_window_index++;\n }\n else\n {\n break;\n }\n }\n\n uint32_t logger_count = initial_count \/ logger_step;\n if (next_window_index - initial_count > 0 && logger_count > last_logger_count)\n {\n bar(std::string(\"[racon::CUDAPolisher::polish] generating consensus\"));\n last_logger_count++;\n }\n\n\n return std::pair(initial_count, next_window_index);\n };\n\n \/\/ Lambda function for processing each batch.\n auto process_batch = [&fill_next_batch, this](CUDABatchProcessor* batch) -> void {\n while(true)\n {\n std::pair range = fill_next_batch(batch);\n if (batch->hasWindows())\n {\n \/\/ Launch workload.\n const std::vector& results = batch->generateConsensus();\n\n \/\/ Check if the number of batches processed is same as the range of\n \/\/ of windows that were added.\n if (results.size() != (range.second - range.first))\n {\n throw std::runtime_error(\"Windows processed doesn't match \\\n range of windows passed to batch\\n\");\n }\n\n \/\/ Copy over the results from the batch into the per window\n \/\/ result vector of the CUDAPolisher.\n for(uint32_t i = 0; i < results.size(); i++)\n {\n window_consensus_status_.at(range.first + i) = results.at(i);\n }\n }\n else\n {\n break;\n }\n }\n };\n\n \/\/ Process each of the batches in a separate thread.\n std::vector> thread_futures;\n for(uint32_t i = 0; i < batch_processors_.size(); i++)\n {\n thread_futures.emplace_back(std::async(std::launch::async,\n process_batch,\n batch_processors_.at(i).get())\n );\n }\n\n \/\/ Wait for threads to finish, and collect their results.\n for (const auto& future : thread_futures) {\n future.wait();\n }\n\n \/\/ Process each failed windows in parallel on CPU\n std::vector> thread_failed_windows;\n for (uint64_t i = 0; i < windows_.size(); ++i) {\n if (window_consensus_status_.at(i) == false){\n thread_failed_windows.emplace_back(thread_pool_->submit_task(\n [&](uint64_t j) -> bool {\n auto it = thread_to_id_.find(std::this_thread::get_id());\n if (it == thread_to_id_.end()) {\n fprintf(stderr, \"[racon::Polisher::polish] error: \"\n \"thread identifier not present!\\n\");\n exit(1);\n }\n return window_consensus_status_.at(j) = windows_[j]->generate_consensus(\n alignment_engines_[it->second]);\n }, i));\n }\n }\n \/\/ Wait for threads to finish, and collect their results.\n for (const auto& t : thread_failed_windows) {\n t.wait();\n }\n\n if (logger_step != 0) {\n bar(std::string(\"[racon::CUDAPolisher::polish] generating consensus\"));\n } else {\n log(std::string(\"[racon::CUDAPolisher::polish] generating consensus\"));\n }\n\n \/\/ Collect results from all windows into final output.\n std::string polished_data = \"\";\n uint32_t num_polished_windows = 0;\n\n for (uint64_t i = 0; i < windows_.size(); ++i) {\n\n num_polished_windows += window_consensus_status_.at(i) == true ? 1 : 0;\n polished_data += windows_[i]->consensus();\n\n if (i == windows_.size() - 1 || windows_[i + 1]->rank() == 0) {\n double polished_ratio = num_polished_windows \/\n static_cast(windows_[i]->rank() + 1);\n\n if (!drop_unpolished_sequences || polished_ratio > 0) {\n std::string tags = type_ == PolisherType::kF ? \"r\" : \"\";\n tags += \" LN:i:\" + std::to_string(polished_data.size());\n tags += \" RC:i:\" + std::to_string(targets_coverages_[windows_[i]->id()]);\n tags += \" XC:f:\" + std::to_string(polished_ratio);\n dst.emplace_back(createSequence(sequences_[windows_[i]->id()]->name() +\n tags, polished_data));\n }\n\n num_polished_windows = 0;\n polished_data.clear();\n }\n windows_[i].reset();\n }\n\n \/\/ Clear POA processors.\n batch_processors_.clear();\n}\n\n}\n[cudaposlisher] disable cuda aligner path\/*!\n * @file cudapolisher.cpp\n *\n * @brief CUDA Polisher class source file\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"sequence.hpp\"\n#include \"cudapolisher.hpp\"\n#include \n\n#include \"bioparser\/bioparser.hpp\"\n\nnamespace racon {\n\n\/\/ The logger used by racon has a fixed size of 20 bins\n\/\/ which is used for the progress bar updates. Hence all\n\/\/ updates need to be broken into 20 bins.\nconst uint32_t RACON_LOGGER_BIN_SIZE = 20;\n\nCUDAPolisher::CUDAPolisher(std::unique_ptr> sparser,\n std::unique_ptr> oparser,\n std::unique_ptr> tparser,\n PolisherType type, uint32_t window_length, double quality_threshold,\n double error_threshold, int8_t match, int8_t mismatch, int8_t gap,\n uint32_t num_threads, uint32_t cuda_batches, bool cuda_banded_alignment)\n : Polisher(std::move(sparser), std::move(oparser), std::move(tparser),\n type, window_length, quality_threshold,\n error_threshold, match, mismatch, gap, num_threads)\n , cuda_batches_(cuda_batches)\n , gap_(gap)\n , mismatch_(mismatch)\n , match_(match)\n , cuda_banded_alignment_(cuda_banded_alignment)\n{\n#ifdef DEBUG\n window_length_ = 200;\n std::cerr << \"In DEBUG mode. Using window size of \" << window_length_ << std::endl;\n#endif\n\n genomeworks::cudapoa::Init();\n genomeworks::cudaaligner::Init();\n\n GW_CU_CHECK_ERR(cudaGetDeviceCount(&num_devices_));\n\n if (num_devices_ < 1)\n {\n throw std::runtime_error(\"No GPU devices found.\");\n }\n\n std::cerr << \"Using \" << num_devices_ << \" GPU(s) to perform polishing\" << std::endl;\n\n \/\/ Run dummy call on each device to initialize CUDA context.\n for(int32_t dev_id = 0; dev_id < num_devices_; dev_id++)\n {\n std::cerr << \"Initialize device \" << dev_id << std::endl;\n GW_CU_CHECK_ERR(cudaSetDevice(dev_id));\n GW_CU_CHECK_ERR(cudaFree(0));\n }\n\n std::cerr << \"[CUDAPolisher] Constructed.\" << std::endl;\n}\n\nCUDAPolisher::~CUDAPolisher()\n{\n cudaDeviceSynchronize();\n cudaProfilerStop();\n}\n\nvoid CUDAPolisher::find_overlap_breaking_points(std::vector>& overlaps)\n{\n#if 0\n std::mutex mutex_overlaps;\n uint32_t next_overlap_index = 0;\n\n \/\/ Lambda expression for filling up next batch of alignments.\n auto fill_next_batch = [&mutex_overlaps, &next_overlap_index, &overlaps, this](CUDABatchAligner* batch) -> void {\n batch->reset();\n\n \/\/ Use mutex to read the vector containing windows in a threadsafe manner.\n std::lock_guard guard(mutex_overlaps);\n\n uint32_t initial_count = next_overlap_index;\n uint32_t count = overlaps.size();\n while(next_overlap_index < count)\n {\n if (batch->addOverlap(overlaps.at(next_overlap_index).get(), sequences_))\n {\n next_overlap_index++;\n }\n else\n {\n break;\n }\n }\n if (next_overlap_index - initial_count > 0)\n {\n fprintf(stderr, \"Processing overlaps %d - %d (of %d) in batch %d\\n\",\n initial_count,\n next_overlap_index ,\n count,\n batch->getBatchID());\n }\n };\n\n \/\/ Lambda expression for processing a batch of alignments.\n auto process_batch = [&fill_next_batch, this](CUDABatchAligner* batch) -> void {\n while(true)\n {\n fill_next_batch(batch);\n if (batch->hasOverlaps())\n {\n \/\/ Launch workload.\n batch->alignAll();\n batch->find_breaking_points(window_length_);\n }\n else\n {\n break;\n }\n }\n };\n\n \/\/ Create batches based on arguments provided to program.\n for(uint32_t batch = 0; batch < cuda_batches_; batch++)\n {\n batch_aligners_.emplace_back(createCUDABatchAligner(20000, 20000, 1000, 0));\n }\n\n \/\/ Run batched alignment.\n std::vector> thread_futures;\n for(uint32_t i = 0; i < batch_aligners_.size(); i++)\n {\n thread_futures.emplace_back(std::async(std::launch::async,\n process_batch,\n batch_aligners_.at(i).get())\n );\n }\n\n \/\/ Wait for threads to finish, and collect their results.\n for (const auto& future : thread_futures) {\n future.wait();\n }\n\n batch_aligners_.clear();\n\n log(std::string(\"[racon::CUDAPolisher::initialize] aligned overlaps\"));\n#endif\n\n \/\/ TODO: Kept CPU overlap alignment right now while GPU is a dummy implmentation.\n Polisher::find_overlap_breaking_points(overlaps);\n}\n\nvoid CUDAPolisher::polish(std::vector>& dst,\n bool drop_unpolished_sequences)\n{\n \/\/ Creation and use of batches.\n const uint32_t MAX_WINDOWS = 256;\n const uint32_t MAX_DEPTH_PER_WINDOW = 200;\n\n \/\/ Bin batches into each GPU.\n std::vector batches_per_gpu(num_devices_, 0);\n\n#ifdef DEBUG\n for(uint32_t i = 0; i < 1; i++)\n#else\n for(uint32_t i = 0; i < cuda_batches_; i++)\n#endif\n {\n uint32_t device = i % num_devices_;\n batches_per_gpu.at(device) = batches_per_gpu.at(device) + 1;\n }\n\n for(int32_t device = 0; device < num_devices_; device++)\n {\n for(uint32_t batch = 0; batch < batches_per_gpu.at(device); batch++)\n {\n batch_processors_.emplace_back(createCUDABatch(MAX_WINDOWS, MAX_DEPTH_PER_WINDOW, device, gap_, mismatch_, match_, cuda_banded_alignment_));\n }\n }\n\n log(std::string(\"[racon::CUDAPolisher::polish] allocated memory on GPUs\"));\n\n \/\/ Mutex for accessing the vector of windows.\n std::mutex mutex_windows;\n\n \/\/ Initialize window consensus statuses.\n window_consensus_status_.resize(windows_.size(), false);\n\n \/\/ Index of next window to be added to a batch.\n#ifdef DEBUG\n uint32_t next_window_index = 5000;\n#else\n uint32_t next_window_index = 0;\n#endif\n\n \/\/ Variables for keeping track of logger progress bar.\n uint32_t logger_step = windows_.size() \/ RACON_LOGGER_BIN_SIZE;\n uint32_t last_logger_count = 0;\n\n \/\/ Lambda function for adding windows to batches.\n auto fill_next_batch = [&mutex_windows, &next_window_index, &logger_step, &last_logger_count, this](CUDABatchProcessor* batch) -> std::pair {\n batch->reset();\n\n \/\/ Use mutex to read the vector containing windows in a threadsafe manner.\n std::lock_guard guard(mutex_windows);\n\n \/\/ TODO: Reducing window wize by 10 for debugging.\n uint32_t initial_count = next_window_index;\n#ifdef DEBUG\n uint32_t count = 5001;\/\/windows_.size();\n#else\n uint32_t count = windows_.size();\n#endif\n while(next_window_index < count)\n {\n if (batch->addWindow(windows_.at(next_window_index)))\n {\n next_window_index++;\n }\n else\n {\n break;\n }\n }\n\n uint32_t logger_count = initial_count \/ logger_step;\n if (next_window_index - initial_count > 0 && logger_count > last_logger_count)\n {\n bar(std::string(\"[racon::CUDAPolisher::polish] generating consensus\"));\n last_logger_count++;\n }\n\n\n return std::pair(initial_count, next_window_index);\n };\n\n \/\/ Lambda function for processing each batch.\n auto process_batch = [&fill_next_batch, this](CUDABatchProcessor* batch) -> void {\n while(true)\n {\n std::pair range = fill_next_batch(batch);\n if (batch->hasWindows())\n {\n \/\/ Launch workload.\n const std::vector& results = batch->generateConsensus();\n\n \/\/ Check if the number of batches processed is same as the range of\n \/\/ of windows that were added.\n if (results.size() != (range.second - range.first))\n {\n throw std::runtime_error(\"Windows processed doesn't match \\\n range of windows passed to batch\\n\");\n }\n\n \/\/ Copy over the results from the batch into the per window\n \/\/ result vector of the CUDAPolisher.\n for(uint32_t i = 0; i < results.size(); i++)\n {\n window_consensus_status_.at(range.first + i) = results.at(i);\n }\n }\n else\n {\n break;\n }\n }\n };\n\n \/\/ Process each of the batches in a separate thread.\n std::vector> thread_futures;\n for(uint32_t i = 0; i < batch_processors_.size(); i++)\n {\n thread_futures.emplace_back(std::async(std::launch::async,\n process_batch,\n batch_processors_.at(i).get())\n );\n }\n\n \/\/ Wait for threads to finish, and collect their results.\n for (const auto& future : thread_futures) {\n future.wait();\n }\n\n \/\/ Process each failed windows in parallel on CPU\n std::vector> thread_failed_windows;\n for (uint64_t i = 0; i < windows_.size(); ++i) {\n if (window_consensus_status_.at(i) == false){\n thread_failed_windows.emplace_back(thread_pool_->submit_task(\n [&](uint64_t j) -> bool {\n auto it = thread_to_id_.find(std::this_thread::get_id());\n if (it == thread_to_id_.end()) {\n fprintf(stderr, \"[racon::Polisher::polish] error: \"\n \"thread identifier not present!\\n\");\n exit(1);\n }\n return window_consensus_status_.at(j) = windows_[j]->generate_consensus(\n alignment_engines_[it->second]);\n }, i));\n }\n }\n \/\/ Wait for threads to finish, and collect their results.\n for (const auto& t : thread_failed_windows) {\n t.wait();\n }\n\n if (logger_step != 0) {\n bar(std::string(\"[racon::CUDAPolisher::polish] generating consensus\"));\n } else {\n log(std::string(\"[racon::CUDAPolisher::polish] generating consensus\"));\n }\n\n \/\/ Collect results from all windows into final output.\n std::string polished_data = \"\";\n uint32_t num_polished_windows = 0;\n\n for (uint64_t i = 0; i < windows_.size(); ++i) {\n\n num_polished_windows += window_consensus_status_.at(i) == true ? 1 : 0;\n polished_data += windows_[i]->consensus();\n\n if (i == windows_.size() - 1 || windows_[i + 1]->rank() == 0) {\n double polished_ratio = num_polished_windows \/\n static_cast(windows_[i]->rank() + 1);\n\n if (!drop_unpolished_sequences || polished_ratio > 0) {\n std::string tags = type_ == PolisherType::kF ? \"r\" : \"\";\n tags += \" LN:i:\" + std::to_string(polished_data.size());\n tags += \" RC:i:\" + std::to_string(targets_coverages_[windows_[i]->id()]);\n tags += \" XC:f:\" + std::to_string(polished_ratio);\n dst.emplace_back(createSequence(sequences_[windows_[i]->id()]->name() +\n tags, polished_data));\n }\n\n num_polished_windows = 0;\n polished_data.clear();\n }\n windows_[i].reset();\n }\n\n \/\/ Clear POA processors.\n batch_processors_.clear();\n}\n\n}\n<|endoftext|>"} {"text":"\n#include \"MenuItem.hpp\"\n#include \"Menu.hpp\"\n#include \"Message.hpp\"\n#include \"Window.hpp\"\n#include \"registory.hpp\"\n#include \"convert.hpp\"\n#include \"deleting.hpp\"\n#include \"ownership.hpp\"\n\nnamespace rbe\n{\n\tnamespace gc\n\t{\n\t\ttemplate<>\n\t\tvoid Deleting(BMenuItem *o, BMenu *t)\n\t\t{\n\t\t\tif (o->fSubmenu == t)\n\t\t\t\to->fSubmenu = NULL;\n\t\t}\n\t}\n\n\tnamespace B\n\t{\n\t\tvoid\n\t\tMenuItem::rbe__gc_mark(void *ptr)\n\t\t{\n\t\t\tBMenuItem *_this = static_cast(ptr);\n\t\t\tif (_this->fWindow != NULL) {\n\t\t\t\tVALUE vwindow = Convert::ToValue(_this->fWindow);\n\t\t\t\trb_gc_mark(vwindow);\n\t\t\t}\n\t\t\tObjectRegistory::Instance()->Mark(ptr);\n\t\t}\n\n\t\tvoid\n\t\tMenuItem::rbe__gc_free(void *ptr)\n\t\t{\n\t\t\tBMenuItem *_this = static_cast(ptr);\n\t\t\tObjectRegistory::Instance()->Delete(ptr);\n\t\t\t_this->fMessage = NULL;\n\t\t\t_this->fSubmenu = NULL;\n\t\t\tdelete _this;\n\t\t}\n\n\t\tVALUE MenuItem::rbe__initialize(int argc, VALUE *argv, VALUE self)\n\t\t{\n\t\t\tVALUE vargs[4];\n\t\t\tBMenuItem *_this = NULL;\n\n\t\t\trb_scan_args(argc, argv, \"13\", &vargs[0], &vargs[1], &vargs[2], &vargs[3]);\n\n\t\t\tif (2 <= argc && argc <= 4) {\n\t\t\t\tif (!Convert::IsConvertable(vargs[0])) goto break_0;\n\t\t\t\tif (!Convert::IsConvertable(vargs[1])) goto break_0;\n\t\t\t\tif (2 < argc && !Convert::IsConvertable(vargs[2])) goto break_0;\n\t\t\t\tif (3 < argc && !Convert::IsConvertable(vargs[3])) goto break_0;\n\t\t\t\tconst char * label = Convert::FromValue(vargs[0]);\n\t\t\t\tBMessage * message = Convert::FromValue(vargs[1]);\n\t\t\t\tchar shortcut = (2 < argc ? Convert::FromValue(vargs[2]) : 0);\n\t\t\t\tuint32 modifiers = (3 < argc ? Convert::FromValue(vargs[3]) : 0);\n\t\t\t\t_this = new BMenuItem(label, message, shortcut, modifiers);\n\t\t\t\tPointerOf::Class *ptr = static_cast::Class *>(_this);\n\t\t\t\tDATA_PTR(self) = static_cast(ptr);\n\t\t\t\tObjectRegistory::Instance()->Add(self);\n\t\t\t\tif (!NIL_P(argv[1])) {\n\t\t\t\t\tgc::Ownership0 *ownership = new gc::Ownership(argv[1]);\n\t\t\t\t\tObjectRegistory::Instance()->Own(self, ownership);\n\t\t\t\t}\n\t\t\t\tgoto fin;\n\t\t\t}\n\t\tbreak_0:\n\n\t\t\tif (1 <= argc && argc <= 2) {\n\t\t\t\tif (!Convert::IsConvertable(vargs[0])) goto break_1;\n\t\t\t\tif (1 < argc && !Convert::IsConvertable(vargs[1])) goto break_1;\n\t\t\t\tBMenu * menu = Convert::FromValue(vargs[0]);\n\t\t\t\tBMessage * message = (1 < argc ? Convert::FromValue(vargs[1]) : NULL);\n\t\t\t\t_this = new BMenuItem(menu, message);\n\t\t\t\tPointerOf::Class *ptr = static_cast::Class *>(_this);\n\t\t\t\tDATA_PTR(self) = static_cast(ptr);\n\t\t\t\tObjectRegistory::Instance()->Add(self);\n\t\t\t\tif (!NIL_P(argv[0])) {\n\t\t\t\t\tgc::Ownership0 *ownership = new gc::Ownership(argv[0]);\n\t\t\t\t\tObjectRegistory::Instance()->Own(self, ownership);\n\t\t\t\t}\n\t\t\t\tif (!NIL_P(argv[1])) {\n\t\t\t\t\tgc::Ownership0 *ownership = new gc::Ownership(argv[1]);\n\t\t\t\t\tObjectRegistory::Instance()->Own(self, ownership);\n\t\t\t\t}\n\t\t\t\tgoto fin;\n\t\t\t}\n\t\tbreak_1:\n\n\t\tfin:\n\t\t\tif (_this == NULL)\n\t\t\t\trb_raise(rb_eTypeError, \"wrong type of arguments\");\n\t\t\treturn self;\n\t\t}\n\t}\n}\nB::MenuItem marks it's menu (fSuper)\n#include \"MenuItem.hpp\"\n#include \"Menu.hpp\"\n#include \"Message.hpp\"\n#include \"Window.hpp\"\n#include \"registory.hpp\"\n#include \"convert.hpp\"\n#include \"deleting.hpp\"\n#include \"ownership.hpp\"\n\nnamespace rbe\n{\n\tnamespace gc\n\t{\n\t\ttemplate<>\n\t\tvoid Deleting(BMenuItem *o, BMenu *t)\n\t\t{\n\t\t\tif (o->fSubmenu == t)\n\t\t\t\to->fSubmenu = NULL;\n\t\t}\n\t}\n\n\tnamespace B\n\t{\n\t\tvoid\n\t\tMenuItem::rbe__gc_mark(void *ptr)\n\t\t{\n\t\t\tBMenuItem *_this = static_cast(ptr);\n\t\t\tif (_this->fWindow != NULL) {\n\t\t\t\tVALUE vwindow = Convert::ToValue(_this->fWindow);\n\t\t\t\trb_gc_mark(vwindow);\n\t\t\t}\n\t\t\tif (_this->fSuper != NULL) {\n\t\t\t\tVALUE vmenu = Convert::ToValue(_this->fSuper);\n\t\t\t\trb_gc_mark(vmenu);\n\t\t\t}\n\t\t\tObjectRegistory::Instance()->Mark(ptr);\n\t\t}\n\n\t\tvoid\n\t\tMenuItem::rbe__gc_free(void *ptr)\n\t\t{\n\t\t\tBMenuItem *_this = static_cast(ptr);\n\t\t\tObjectRegistory::Instance()->Delete(ptr);\n\t\t\t_this->fMessage = NULL;\n\t\t\t_this->fSubmenu = NULL;\n\t\t\tdelete _this;\n\t\t}\n\n\t\tVALUE MenuItem::rbe__initialize(int argc, VALUE *argv, VALUE self)\n\t\t{\n\t\t\tVALUE vargs[4];\n\t\t\tBMenuItem *_this = NULL;\n\n\t\t\trb_scan_args(argc, argv, \"13\", &vargs[0], &vargs[1], &vargs[2], &vargs[3]);\n\n\t\t\tif (2 <= argc && argc <= 4) {\n\t\t\t\tif (!Convert::IsConvertable(vargs[0])) goto break_0;\n\t\t\t\tif (!Convert::IsConvertable(vargs[1])) goto break_0;\n\t\t\t\tif (2 < argc && !Convert::IsConvertable(vargs[2])) goto break_0;\n\t\t\t\tif (3 < argc && !Convert::IsConvertable(vargs[3])) goto break_0;\n\t\t\t\tconst char * label = Convert::FromValue(vargs[0]);\n\t\t\t\tBMessage * message = Convert::FromValue(vargs[1]);\n\t\t\t\tchar shortcut = (2 < argc ? Convert::FromValue(vargs[2]) : 0);\n\t\t\t\tuint32 modifiers = (3 < argc ? Convert::FromValue(vargs[3]) : 0);\n\t\t\t\t_this = new BMenuItem(label, message, shortcut, modifiers);\n\t\t\t\tPointerOf::Class *ptr = static_cast::Class *>(_this);\n\t\t\t\tDATA_PTR(self) = static_cast(ptr);\n\t\t\t\tObjectRegistory::Instance()->Add(self);\n\t\t\t\tif (!NIL_P(argv[1])) {\n\t\t\t\t\tgc::Ownership0 *ownership = new gc::Ownership(argv[1]);\n\t\t\t\t\tObjectRegistory::Instance()->Own(self, ownership);\n\t\t\t\t}\n\t\t\t\tgoto fin;\n\t\t\t}\n\t\tbreak_0:\n\n\t\t\tif (1 <= argc && argc <= 2) {\n\t\t\t\tif (!Convert::IsConvertable(vargs[0])) goto break_1;\n\t\t\t\tif (1 < argc && !Convert::IsConvertable(vargs[1])) goto break_1;\n\t\t\t\tBMenu * menu = Convert::FromValue(vargs[0]);\n\t\t\t\tBMessage * message = (1 < argc ? Convert::FromValue(vargs[1]) : NULL);\n\t\t\t\t_this = new BMenuItem(menu, message);\n\t\t\t\tPointerOf::Class *ptr = static_cast::Class *>(_this);\n\t\t\t\tDATA_PTR(self) = static_cast(ptr);\n\t\t\t\tObjectRegistory::Instance()->Add(self);\n\t\t\t\tif (!NIL_P(argv[0])) {\n\t\t\t\t\tgc::Ownership0 *ownership = new gc::Ownership(argv[0]);\n\t\t\t\t\tObjectRegistory::Instance()->Own(self, ownership);\n\t\t\t\t}\n\t\t\t\tif (!NIL_P(argv[1])) {\n\t\t\t\t\tgc::Ownership0 *ownership = new gc::Ownership(argv[1]);\n\t\t\t\t\tObjectRegistory::Instance()->Own(self, ownership);\n\t\t\t\t}\n\t\t\t\tgoto fin;\n\t\t\t}\n\t\tbreak_1:\n\n\t\tfin:\n\t\t\tif (_this == NULL)\n\t\t\t\trb_raise(rb_eTypeError, \"wrong type of arguments\");\n\t\t\treturn self;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#ifndef __BH_VE_CPU_SPECIALIZER\n#define __BH_VE_CPU_SPECIALIZER\n\n#include \n\nvoid specializer_init()\n{\n ctemplate::mutable_default_template_cache()->SetTemplateRootDirectory(template_path);\n ctemplate::LoadTemplate(\"license.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"include.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"range.tpl\", ctemplate::STRIP_BLANK_LINES);\n \n ctemplate::LoadTemplate(\"reduction.1d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"reduction.2d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"reduction.3d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"reduction.nd.tpl\", ctemplate::STRIP_BLANK_LINES);\n\n ctemplate::LoadTemplate(\"traverse.1d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.2d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.3d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.nd.ddd.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.nd.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::mutable_default_template_cache()->Freeze();\n}\n\nvoid symbolize(bh_instruction *instr, bh_sij_t &sij) {\n\n char symbol_c[500]; \/\/ String representation buffers\n char dims_str[10];\n\n sij.instr = instr;\n switch (sij.instr->opcode) { \/\/ [OPCODE_SWITCH]\n\n case BH_NONE: \/\/ System opcodes\n case BH_DISCARD:\n case BH_SYNC:\n case BH_FREE:\n case BH_USERFUNC: \/\/ Extensions\n break;\n\n case BH_ADD_REDUCE: \/\/ Reductions\n case BH_MULTIPLY_REDUCE:\n case BH_MINIMUM_REDUCE:\n case BH_MAXIMUM_REDUCE:\n case BH_LOGICAL_AND_REDUCE:\n case BH_BITWISE_AND_REDUCE:\n case BH_LOGICAL_OR_REDUCE:\n case BH_LOGICAL_XOR_REDUCE:\n case BH_BITWISE_OR_REDUCE:\n case BH_BITWISE_XOR_REDUCE:\n sij.ndims = sij.instr->operand[1].ndim; \/\/ Dimensions\n sij.lmask = bh_layoutmask(sij.instr); \/\/ Layout mask\n sij.tsig = bh_typesig(sij.instr); \/\/ Type signature\n\n if (sij.ndims <= 3) { \/\/ String representation\n sprintf(dims_str, \"%ldD\", sij.ndims);\n } else {\n sprintf(dims_str, \"ND\");\n }\n sprintf(symbol_c, \"%s_%s_%s_%s\",\n bh_opcode_text(sij.instr->opcode),\n bh_typesig_to_shorthand(sij.tsig),\n dims_str,\n bh_layoutmask_to_shorthand(sij.lmask)\n );\n\n sij.symbol = string(symbol_c);\n break;\n\n case BH_RANGE:\n\n sij.ndims = sij.instr->operand[0].ndim; \/\/ Dimensions\n sij.lmask = bh_layoutmask(sij.instr); \/\/ Layout mask\n sij.tsig = bh_typesig(sij.instr); \/\/ Type signature\n\n sprintf(symbol_c, \"%s_%s_ND_%s\",\n bh_opcode_text(sij.instr->opcode),\n bh_typesig_to_shorthand(sij.tsig),\n bh_layoutmask_to_shorthand(sij.lmask)\n );\n\n sij.symbol = string(symbol_c);\n break;\n\n default: \/\/ Built-in\n \n sij.ndims = sij.instr->operand[0].ndim; \/\/ Dimensions\n sij.lmask = bh_layoutmask(sij.instr); \/\/ Layout mask\n sij.tsig = bh_typesig(sij.instr); \/\/ Type signature\n\n if (sij.ndims <= 3) { \/\/ String representation\n sprintf(dims_str, \"%ldD\", sij.ndims);\n } else {\n sprintf(dims_str, \"ND\");\n }\n sprintf(symbol_c, \"%s_%s_%s_%s\",\n bh_opcode_text(sij.instr->opcode),\n bh_typesig_to_shorthand(sij.tsig),\n dims_str,\n bh_layoutmask_to_shorthand(sij.lmask)\n );\n\n sij.symbol = string(symbol_c);\n break;\n }\n}\n\nstring specialize(bh_sij_t &sij) {\n\n char template_fn[500]; \/\/ NOTE: constants like these are often traumatizing!\n\n bool cres = false;\n\n ctemplate::TemplateDictionary dict(\"codegen\");\n ctemplate::TemplateDictionary include_dict(\"INCLUDE\");\n\n switch (sij.instr->opcode) { \/\/ OPCODE_SWITCH\n\n case BH_RANGE:\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n sprintf(template_fn, \"range.tpl\");\n\n cres = true;\n break;\n\n case BH_ADD_REDUCE:\n case BH_MULTIPLY_REDUCE:\n case BH_MINIMUM_REDUCE:\n case BH_MAXIMUM_REDUCE:\n case BH_LOGICAL_AND_REDUCE:\n case BH_BITWISE_AND_REDUCE:\n case BH_LOGICAL_OR_REDUCE:\n case BH_LOGICAL_XOR_REDUCE:\n case BH_BITWISE_OR_REDUCE:\n case BH_BITWISE_XOR_REDUCE:\n\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n\n if (sij.ndims <= 3) {\n sprintf(template_fn, \"reduction.%ldd.tpl\", sij.ndims);\n } else {\n sprintf(template_fn, \"reduction.nd.tpl\");\n }\n\n cres = true;\n break;\n\n case BH_ADD:\n case BH_SUBTRACT:\n case BH_MULTIPLY:\n case BH_DIVIDE:\n case BH_POWER:\n case BH_GREATER:\n case BH_GREATER_EQUAL:\n case BH_LESS:\n case BH_LESS_EQUAL:\n case BH_EQUAL:\n case BH_NOT_EQUAL:\n case BH_LOGICAL_AND:\n case BH_LOGICAL_OR:\n case BH_LOGICAL_XOR:\n case BH_MAXIMUM:\n case BH_MINIMUM:\n case BH_BITWISE_AND:\n case BH_BITWISE_OR:\n case BH_BITWISE_XOR:\n case BH_LEFT_SHIFT:\n case BH_RIGHT_SHIFT:\n case BH_ARCTAN2:\n case BH_MOD:\n case BH_RANDOM:\n\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n if ((sij.lmask & A2_CONSTANT) == A2_CONSTANT) {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n dict.SetValue(\"TYPE_A2\", enum_to_ctypestr(sij.instr->constant.type));\n dict.ShowSection(\"a1_dense\");\n dict.ShowSection(\"a2_scalar\");\n } else if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->constant.type));\n dict.SetValue(\"TYPE_A2\", enum_to_ctypestr(sij.instr->operand[2].base->type));\n dict.ShowSection(\"a1_scalar\");\n dict.ShowSection(\"a2_dense\");\n } else {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n dict.SetValue(\"TYPE_A2\", enum_to_ctypestr(sij.instr->operand[2].base->type));\n dict.ShowSection(\"a1_dense\");\n dict.ShowSection(\"a2_dense\");\n\n }\n if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS + A2_CONTIGUOUS)) || \\\n (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT + A2_CONTIGUOUS)) || \\\n (sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS + A2_CONSTANT))) {\n sprintf(template_fn, \"traverse.nd.ddd.tpl\");\n } else {\n if (sij.ndims<=3) {\n sprintf(template_fn, \"traverse.%ldd.tpl\", sij.ndims);\n } else {\n sprintf(template_fn, \"traverse.nd.tpl\");\n }\n }\n\n cres = true;\n break;\n\n case BH_ABSOLUTE:\n case BH_LOGICAL_NOT:\n case BH_INVERT:\n case BH_COS:\n case BH_SIN:\n case BH_TAN:\n case BH_COSH:\n case BH_SINH:\n case BH_TANH:\n case BH_ARCSIN:\n case BH_ARCCOS:\n case BH_ARCTAN:\n case BH_ARCSINH:\n case BH_ARCCOSH:\n case BH_ARCTANH:\n case BH_EXP:\n case BH_EXP2:\n case BH_EXPM1:\n case BH_LOG:\n case BH_LOG2:\n case BH_LOG10:\n case BH_LOG1P:\n case BH_SQRT:\n case BH_CEIL:\n case BH_TRUNC:\n case BH_FLOOR:\n case BH_RINT:\n case BH_ISNAN:\n case BH_ISINF:\n case BH_IDENTITY:\n\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->constant.type));\n dict.ShowSection(\"a1_scalar\");\n } else {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n dict.ShowSection(\"a1_dense\");\n }\n\n if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS)) || \\\n (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT))) {\n sprintf(template_fn, \"traverse.nd.ddd.tpl\");\n } else {\n\n if (sij.ndims<=3) {\n sprintf(template_fn, \"traverse.%ldd.tpl\", sij.ndims);\n } else {\n sprintf(template_fn, \"traverse.nd.tpl\");\n }\n\n }\n\n cres = true;\n break;\n\n default:\n printf(\"cpu-ve: Err=[Unsupported ufunc...]\\n\");\n }\n\n if (!cres) {\n throw runtime_error(\"cpu-ve: Failed specializing code.\");\n }\n\n string sourcecode = \"\";\n ctemplate::ExpandTemplate(\"include.tpl\", ctemplate::STRIP_BLANK_LINES, &include_dict, &sourcecode);\n ctemplate::ExpandTemplate(\n template_fn,\n ctemplate::STRIP_BLANK_LINES,\n &dict,\n &sourcecode\n );\n\n return sourcecode;\n}\n\n#endif\n\ncpu: Removed the deprecated BH_USERFUNC.#ifndef __BH_VE_CPU_SPECIALIZER\n#define __BH_VE_CPU_SPECIALIZER\n\n#include \n\nvoid specializer_init()\n{\n ctemplate::mutable_default_template_cache()->SetTemplateRootDirectory(template_path);\n ctemplate::LoadTemplate(\"license.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"include.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"range.tpl\", ctemplate::STRIP_BLANK_LINES);\n \n ctemplate::LoadTemplate(\"reduction.1d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"reduction.2d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"reduction.3d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"reduction.nd.tpl\", ctemplate::STRIP_BLANK_LINES);\n\n ctemplate::LoadTemplate(\"traverse.1d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.2d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.3d.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.nd.ddd.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::LoadTemplate(\"traverse.nd.tpl\", ctemplate::STRIP_BLANK_LINES);\n ctemplate::mutable_default_template_cache()->Freeze();\n}\n\nvoid symbolize(bh_instruction *instr, bh_sij_t &sij) {\n\n char symbol_c[500]; \/\/ String representation buffers\n char dims_str[10];\n\n sij.instr = instr;\n switch (sij.instr->opcode) { \/\/ [OPCODE_SWITCH]\n\n case BH_NONE: \/\/ System opcodes\n case BH_DISCARD:\n case BH_SYNC:\n case BH_FREE:\n break;\n\n case BH_ADD_REDUCE: \/\/ Reductions\n case BH_MULTIPLY_REDUCE:\n case BH_MINIMUM_REDUCE:\n case BH_MAXIMUM_REDUCE:\n case BH_LOGICAL_AND_REDUCE:\n case BH_BITWISE_AND_REDUCE:\n case BH_LOGICAL_OR_REDUCE:\n case BH_LOGICAL_XOR_REDUCE:\n case BH_BITWISE_OR_REDUCE:\n case BH_BITWISE_XOR_REDUCE:\n sij.ndims = sij.instr->operand[1].ndim; \/\/ Dimensions\n sij.lmask = bh_layoutmask(sij.instr); \/\/ Layout mask\n sij.tsig = bh_typesig(sij.instr); \/\/ Type signature\n\n if (sij.ndims <= 3) { \/\/ String representation\n sprintf(dims_str, \"%ldD\", sij.ndims);\n } else {\n sprintf(dims_str, \"ND\");\n }\n sprintf(symbol_c, \"%s_%s_%s_%s\",\n bh_opcode_text(sij.instr->opcode),\n bh_typesig_to_shorthand(sij.tsig),\n dims_str,\n bh_layoutmask_to_shorthand(sij.lmask)\n );\n\n sij.symbol = string(symbol_c);\n break;\n\n case BH_RANGE:\n\n sij.ndims = sij.instr->operand[0].ndim; \/\/ Dimensions\n sij.lmask = bh_layoutmask(sij.instr); \/\/ Layout mask\n sij.tsig = bh_typesig(sij.instr); \/\/ Type signature\n\n sprintf(symbol_c, \"%s_%s_ND_%s\",\n bh_opcode_text(sij.instr->opcode),\n bh_typesig_to_shorthand(sij.tsig),\n bh_layoutmask_to_shorthand(sij.lmask)\n );\n\n sij.symbol = string(symbol_c);\n break;\n\n default: \/\/ Built-in\n \n sij.ndims = sij.instr->operand[0].ndim; \/\/ Dimensions\n sij.lmask = bh_layoutmask(sij.instr); \/\/ Layout mask\n sij.tsig = bh_typesig(sij.instr); \/\/ Type signature\n\n if (sij.ndims <= 3) { \/\/ String representation\n sprintf(dims_str, \"%ldD\", sij.ndims);\n } else {\n sprintf(dims_str, \"ND\");\n }\n sprintf(symbol_c, \"%s_%s_%s_%s\",\n bh_opcode_text(sij.instr->opcode),\n bh_typesig_to_shorthand(sij.tsig),\n dims_str,\n bh_layoutmask_to_shorthand(sij.lmask)\n );\n\n sij.symbol = string(symbol_c);\n break;\n }\n}\n\nstring specialize(bh_sij_t &sij) {\n\n char template_fn[500]; \/\/ NOTE: constants like these are often traumatizing!\n\n bool cres = false;\n\n ctemplate::TemplateDictionary dict(\"codegen\");\n ctemplate::TemplateDictionary include_dict(\"INCLUDE\");\n\n switch (sij.instr->opcode) { \/\/ OPCODE_SWITCH\n\n case BH_RANGE:\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n sprintf(template_fn, \"range.tpl\");\n\n cres = true;\n break;\n\n case BH_ADD_REDUCE:\n case BH_MULTIPLY_REDUCE:\n case BH_MINIMUM_REDUCE:\n case BH_MAXIMUM_REDUCE:\n case BH_LOGICAL_AND_REDUCE:\n case BH_BITWISE_AND_REDUCE:\n case BH_LOGICAL_OR_REDUCE:\n case BH_LOGICAL_XOR_REDUCE:\n case BH_BITWISE_OR_REDUCE:\n case BH_BITWISE_XOR_REDUCE:\n\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n\n if (sij.ndims <= 3) {\n sprintf(template_fn, \"reduction.%ldd.tpl\", sij.ndims);\n } else {\n sprintf(template_fn, \"reduction.nd.tpl\");\n }\n\n cres = true;\n break;\n\n case BH_ADD:\n case BH_SUBTRACT:\n case BH_MULTIPLY:\n case BH_DIVIDE:\n case BH_POWER:\n case BH_GREATER:\n case BH_GREATER_EQUAL:\n case BH_LESS:\n case BH_LESS_EQUAL:\n case BH_EQUAL:\n case BH_NOT_EQUAL:\n case BH_LOGICAL_AND:\n case BH_LOGICAL_OR:\n case BH_LOGICAL_XOR:\n case BH_MAXIMUM:\n case BH_MINIMUM:\n case BH_BITWISE_AND:\n case BH_BITWISE_OR:\n case BH_BITWISE_XOR:\n case BH_LEFT_SHIFT:\n case BH_RIGHT_SHIFT:\n case BH_ARCTAN2:\n case BH_MOD:\n case BH_RANDOM:\n\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n if ((sij.lmask & A2_CONSTANT) == A2_CONSTANT) {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n dict.SetValue(\"TYPE_A2\", enum_to_ctypestr(sij.instr->constant.type));\n dict.ShowSection(\"a1_dense\");\n dict.ShowSection(\"a2_scalar\");\n } else if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->constant.type));\n dict.SetValue(\"TYPE_A2\", enum_to_ctypestr(sij.instr->operand[2].base->type));\n dict.ShowSection(\"a1_scalar\");\n dict.ShowSection(\"a2_dense\");\n } else {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n dict.SetValue(\"TYPE_A2\", enum_to_ctypestr(sij.instr->operand[2].base->type));\n dict.ShowSection(\"a1_dense\");\n dict.ShowSection(\"a2_dense\");\n\n }\n if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS + A2_CONTIGUOUS)) || \\\n (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT + A2_CONTIGUOUS)) || \\\n (sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS + A2_CONSTANT))) {\n sprintf(template_fn, \"traverse.nd.ddd.tpl\");\n } else {\n if (sij.ndims<=3) {\n sprintf(template_fn, \"traverse.%ldd.tpl\", sij.ndims);\n } else {\n sprintf(template_fn, \"traverse.nd.tpl\");\n }\n }\n\n cres = true;\n break;\n\n case BH_ABSOLUTE:\n case BH_LOGICAL_NOT:\n case BH_INVERT:\n case BH_COS:\n case BH_SIN:\n case BH_TAN:\n case BH_COSH:\n case BH_SINH:\n case BH_TANH:\n case BH_ARCSIN:\n case BH_ARCCOS:\n case BH_ARCTAN:\n case BH_ARCSINH:\n case BH_ARCCOSH:\n case BH_ARCTANH:\n case BH_EXP:\n case BH_EXP2:\n case BH_EXPM1:\n case BH_LOG:\n case BH_LOG2:\n case BH_LOG10:\n case BH_LOG1P:\n case BH_SQRT:\n case BH_CEIL:\n case BH_TRUNC:\n case BH_FLOOR:\n case BH_RINT:\n case BH_ISNAN:\n case BH_ISINF:\n case BH_IDENTITY:\n\n dict.SetValue(\"OPERATOR\", bhopcode_to_cexpr(sij.instr->opcode));\n if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->constant.type));\n dict.ShowSection(\"a1_scalar\");\n } else {\n dict.SetValue(\"SYMBOL\", sij.symbol);\n dict.SetValue(\"TYPE_A0\", enum_to_ctypestr(sij.instr->operand[0].base->type));\n dict.SetValue(\"TYPE_A1\", enum_to_ctypestr(sij.instr->operand[1].base->type));\n dict.ShowSection(\"a1_dense\");\n }\n\n if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS)) || \\\n (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT))) {\n sprintf(template_fn, \"traverse.nd.ddd.tpl\");\n } else {\n\n if (sij.ndims<=3) {\n sprintf(template_fn, \"traverse.%ldd.tpl\", sij.ndims);\n } else {\n sprintf(template_fn, \"traverse.nd.tpl\");\n }\n\n }\n\n cres = true;\n break;\n\n default:\n printf(\"cpu-ve: Err=[Unsupported ufunc...]\\n\");\n }\n\n if (!cres) {\n throw runtime_error(\"cpu-ve: Failed specializing code.\");\n }\n\n string sourcecode = \"\";\n ctemplate::ExpandTemplate(\"include.tpl\", ctemplate::STRIP_BLANK_LINES, &include_dict, &sourcecode);\n ctemplate::ExpandTemplate(\n template_fn,\n ctemplate::STRIP_BLANK_LINES,\n &dict,\n &sourcecode\n );\n\n return sourcecode;\n}\n\n#endif\n\n<|endoftext|>"} {"text":"#include \"Zero.hpp\"\n\n#include \"Funcs.hpp\"\n\n\/*\n * Implements gsetvar vnds function.\n * gsetvar var mod val\n * Modifier is '=' '+' or '-' in script, simplify to ('-':-1, '=':0, '+':1).\n * MAY need to be UTF8 friendly\n *\/\n\nvoid op_setvar(char* var, int* modifier, char* value) {\n\tif (GetData()->if_fail != 0)\n\t\treturn;\n\n\tint value_r = 0, ret;\n\tif(value == NULL)\n\t\tret = 0;\n\telse\n\t\tret = sscanf(value, \"%d\", &value_r);\n\n\tif(ret == 0) { \/\/ value is a variable not a number\n\t\tif(*modifier == 0) {\n\t\t\tGetData()->s_flags[0][std::string(var)] = GetData()->s_flags[0][std::string(value)];\n\t\t}\n\t\telse if (*modifier == -1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] -= GetData()->s_flags[0][std::string(value)];\n\t\t}\n\t\telse if (*modifier == 1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] += GetData()->s_flags[0][std::string(value)];\n\t\t}\n\t}\n\telse {\n\t\tif(*modifier == 0) {\n\t\t\tGetData()->s_flags[0][std::string(var)] = value_r;\n\t\t}\n\t\telse if (*modifier == -1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] -= value_r;\n\t\t}\n\t\telse if (*modifier == 1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] += value_r;\n\t\t}\n\t\telse if (*modifier == -2) {\n\t\t\t\/\/ There's a rare case on program start where a resetall\n\t\t\t\/\/ happens.\n\n\t\t\tif(!strcmp(var, \"~\")) {\n\t\t\t\t\/\/ We'll handle it by searching through and deleting all non-G values.\n\t\t\t\t\/\/ g values are global, so they by definition survive this.\n\t\n\t\t\t\tif(!GetData()->s_flags[0].empty()) {\n\t\t\t\t\tstd::map::iterator item = GetData()->s_flags[0].begin();\n\t\t\t\t\twhile(item != GetData()->s_flags[0].end()) {\n\t\t\t\t\t\tif(item->first.c_str()[0] != 'g')\n\t\t\t\t\t\t\tGetData()->s_flags[0].erase(item++);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\titem++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tGetData()->s_flags[0][std::string(var)] = 0;\n\t\t}\n\t}\n}\nAnd it's an extension technically, so added a vndc_enabled check#include \"Zero.hpp\"\n\n#include \"Funcs.hpp\"\n\n\/*\n * Implements gsetvar vnds function.\n * gsetvar var mod val\n * Modifier is '=' '+' or '-' in script, simplify to ('-':-1, '=':0, '+':1).\n * MAY need to be UTF8 friendly\n *\/\n\nvoid op_setvar(char* var, int* modifier, char* value) {\n\tif (GetData()->if_fail != 0)\n\t\treturn;\n\n\tint value_r = 0, ret;\n\tif(value == NULL)\n\t\tret = 0;\n\telse\n\t\tret = sscanf(value, \"%d\", &value_r);\n\n\tif(ret == 0 && GetData()->vndc_enabled) { \/\/ value is a variable not a number\n\t\tif(*modifier == 0) {\n\t\t\tGetData()->s_flags[0][std::string(var)] = GetData()->s_flags[0][std::string(value)];\n\t\t}\n\t\telse if (*modifier == -1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] -= GetData()->s_flags[0][std::string(value)];\n\t\t}\n\t\telse if (*modifier == 1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] += GetData()->s_flags[0][std::string(value)];\n\t\t}\n\t}\n\telse {\n\t\tif(*modifier == 0) {\n\t\t\tGetData()->s_flags[0][std::string(var)] = value_r;\n\t\t}\n\t\telse if (*modifier == -1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] -= value_r;\n\t\t}\n\t\telse if (*modifier == 1) {\n\t\t\tGetData()->s_flags[0][std::string(var)] += value_r;\n\t\t}\n\t\telse if (*modifier == -2) {\n\t\t\t\/\/ There's a rare case on program start where a resetall\n\t\t\t\/\/ happens.\n\n\t\t\tif(!strcmp(var, \"~\")) {\n\t\t\t\t\/\/ We'll handle it by searching through and deleting all non-G values.\n\t\t\t\t\/\/ g values are global, so they by definition survive this.\n\t\n\t\t\t\tif(!GetData()->s_flags[0].empty()) {\n\t\t\t\t\tstd::map::iterator item = GetData()->s_flags[0].begin();\n\t\t\t\t\twhile(item != GetData()->s_flags[0].end()) {\n\t\t\t\t\t\tif(item->first.c_str()[0] != 'g')\n\t\t\t\t\t\t\tGetData()->s_flags[0].erase(item++);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\titem++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tGetData()->s_flags[0][std::string(var)] = 0;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#include \"pocketcalculator.h\"\n#include \"calc.h\"\n#include \"sevensegment.h\"\n#include \n#include \n#include \n#include \n\nnamespace pocketcalculator {\n\tvoid calc(std::istream& input, std::ostream& output, unsigned const scale_factor)\n\ttry {\n\t\tauto const result = ::calc(input);\n\t\tsevensegment::printLargeNumber(result, output, scale_factor);\n\t} catch(std::exception const&) {\n\t\tsevensegment::printLargeError(output, scale_factor);\n\t}\n\n\tunsigned automatic_scale() {\n\t\t\/\/ NOTE: can't use std::unique_ptr because the memory pointed to by the\n\t\t\/\/ pointer is not ours\n\t\tchar const * const scale_ptr { std::getenv(\"POCKETCALCULATOR_SCALE\") };\n\n\t\tif (scale_ptr != nullptr)\n\t\t\treturn std::stoul(std::string { scale_ptr });\n\n\t\treturn default_scale_factor;\n\t}\n\n\tvoid start(std::istream& input, std::ostream& output, unsigned scale_factor) {\n\t\tif (scale_factor == 0)\n\t\t\tscale_factor = automatic_scale();\n\n\t\twhile (!input.eof()) calc(input, output, scale_factor);\n\t}\n}\nstyle#include \"pocketcalculator.h\"\n#include \"calc.h\"\n#include \"sevensegment.h\"\n#include \n#include \n#include \n#include \n\nnamespace pocketcalculator {\n\tvoid calc(std::istream& input, std::ostream& output, unsigned const scale_factor)\n\ttry {\n\t\tauto const result = ::calc(input);\n\t\tsevensegment::printLargeNumber(result, output, scale_factor);\n\t} catch(std::exception const&) {\n\t\tsevensegment::printLargeError(output, scale_factor);\n\t}\n\n\tunsigned automatic_scale() {\n\t\t\/\/ NOTE: can't use std::unique_ptr because the memory pointed to by the\n\t\t\/\/ pointer is not ours\n\t\tchar const * const scale_ptr { std::getenv(\"POCKETCALCULATOR_SCALE\") };\n\n\t\tif (scale_ptr != nullptr)\n\t\t\treturn std::stoul(std::string { scale_ptr });\n\n\t\treturn default_scale_factor;\n\t}\n\n\tvoid start(std::istream& input, std::ostream& output, unsigned scale_factor) {\n\t\tif (scale_factor == 0)\n\t\t\tscale_factor = automatic_scale();\n\n\t\twhile (!input.eof())\n\t\t\tcalc(input, output, scale_factor);\n\t}\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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\/**\n * @file\n **\/\n\n#include \"modules\/planning\/lattice\/behavior_decider\/signal_light_scenario.h\"\n\n#include \n#include \n#include \n\n#include \"gflags\/gflags.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/util\/map_util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/proto\/planning_internal.pb.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::adapter::AdapterManager;\nusing apollo::perception::TrafficLight;\nusing apollo::perception::TrafficLightDetection;\nusing apollo::common::util::WithinBound;\n\nvoid SignalLightScenario::Reset() {}\n\nbool SignalLightScenario::Init() {\n exist_ = true;\n return exist_;\n}\n\nint SignalLightScenario::ComputeScenarioDecision(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n PlanningTarget* planning_target) {\n CHECK(frame != nullptr);\n\n if (!FindValidSignalLight(reference_line_info)) {\n AINFO << \"No valid signal light along reference line\";\n return 0;\n }\n ReadSignals();\n\n for (const hdmap::PathOverlap* signal_light :\n signal_lights_along_reference_line_) {\n const TrafficLight signal = GetSignal(signal_light->object_id);\n double stop_deceleration =\n GetStopDeceleration(reference_line_info, signal_light);\n\n if ((signal.color() == TrafficLight::RED &&\n stop_deceleration < FLAGS_stop_max_deceleration) ||\n (signal.color() == TrafficLight::UNKNOWN &&\n stop_deceleration < FLAGS_stop_max_deceleration) ||\n (signal.color() == TrafficLight::YELLOW &&\n stop_deceleration < FLAGS_max_deacceleration_for_yellow_light_stop)) {\n CreateStopObstacle(frame, reference_line_info, signal_light);\n }\n }\n\n return 0;\n}\n\nbool SignalLightScenario::FindValidSignalLight(\n ReferenceLineInfo* const reference_line_info) {\n const std::vector& signal_lights =\n reference_line_info->reference_line().map_path().signal_overlaps();\n if (signal_lights.size() <= 0) {\n ADEBUG << \"No signal lights from reference line.\";\n return false;\n } else {\n AINFO << \"Found signal_lights size=\" << signal_lights.size();\n }\n signal_lights_along_reference_line_.clear();\n for (const hdmap::PathOverlap& signal_light : signal_lights) {\n if (signal_light.start_s + FLAGS_stop_max_distance_buffer >\n reference_line_info->AdcSlBoundary().end_s()) {\n signal_lights_along_reference_line_.push_back(&signal_light);\n }\n }\n return signal_lights_along_reference_line_.size() > 0;\n}\n\nvoid SignalLightScenario::ReadSignals() {\n detected_signals_.clear();\n detected_signals_.clear();\n if (AdapterManager::GetTrafficLightDetection()->Empty()) {\n return;\n }\n if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() >\n FLAGS_signal_expire_time_sec) {\n AWARN << \"traffic signals msg is expired: \"\n << AdapterManager::GetTrafficLightDetection()->GetDelaySec();\n return;\n }\n const TrafficLightDetection& detection =\n AdapterManager::GetTrafficLightDetection()->GetLatestObserved();\n for (int j = 0; j < detection.traffic_light_size(); j++) {\n const TrafficLight& signal = detection.traffic_light(j);\n detected_signals_[signal.id()] = &signal;\n }\n}\n\nTrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) {\n const auto* result =\n apollo::common::util::FindPtrOrNull(detected_signals_, signal_id);\n if (result == nullptr) {\n TrafficLight traffic_light;\n traffic_light.set_id(signal_id);\n traffic_light.set_color(TrafficLight::UNKNOWN);\n traffic_light.set_confidence(0.0);\n traffic_light.set_tracking_time(0.0);\n return traffic_light;\n }\n return *result;\n}\n\ndouble SignalLightScenario::GetStopDeceleration(\n ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n double adc_speed =\n common::VehicleStateProvider::instance()->linear_velocity();\n if (adc_speed < FLAGS_stop_min_speed) {\n return 0.0;\n }\n double stop_distance = 0.0;\n double adc_front_s = reference_line_info->AdcSlBoundary().end_s();\n double stop_line_s = signal_light->start_s;\n\n if (stop_line_s > adc_front_s) {\n stop_distance = stop_line_s - adc_front_s;\n } else {\n stop_distance = stop_line_s + FLAGS_stop_max_distance_buffer - adc_front_s;\n }\n if (stop_distance < 1e-5) {\n \/\/ longitudinal_acceleration_lower_bound is a negative value.\n return -FLAGS_longitudinal_acceleration_lower_bound;\n }\n return (adc_speed * adc_speed) \/ (2 * stop_distance);\n}\n\nvoid SignalLightScenario::CreateStopObstacle(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n const auto& reference_line = reference_line_info->reference_line();\n const double stop_s =\n signal_light->start_s - FLAGS_stop_distance_traffic_light;\n const double box_center_s =\n signal_light->start_s + FLAGS_virtual_stop_wall_length \/ 2.0;\n if (!WithinBound(0.0, reference_line.Length(), stop_s) ||\n !WithinBound(0.0, reference_line.Length(), box_center_s)) {\n ADEBUG << \"signal \" << signal_light->object_id\n << \" is not on reference line\";\n return;\n }\n \/\/ double heading = reference_line.GetReferencePoint(stop_s).heading();\n double left_lane_width = 0.0;\n double right_lane_width = 0.0;\n reference_line.GetLaneWidth(signal_light->start_s, &left_lane_width,\n &right_lane_width);\n\n \/*\n auto box_center = reference_line.GetReferencePoint(box_center_s);\n common::math::Box2d stop_box{box_center, heading,\n FLAGS_virtual_stop_wall_length,\n left_lane_width + right_lane_width};\n PathObstacle* stop_wall =\n reference_line_info->AddObstacle(frame->AddStaticVirtualObstacle(\n FLAGS_signal_light_virtual_object_id_prefix + signal_light->object_id,\n stop_box));\n *\/\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\nPlanning: [lattice] recover stop fence for red traffic light\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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\/**\n * @file\n **\/\n\n#include \"modules\/planning\/lattice\/behavior_decider\/signal_light_scenario.h\"\n\n#include \n#include \n#include \n\n#include \"gflags\/gflags.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/util\/map_util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/proto\/planning_internal.pb.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::adapter::AdapterManager;\nusing apollo::perception::TrafficLight;\nusing apollo::perception::TrafficLightDetection;\nusing apollo::common::util::WithinBound;\n\nvoid SignalLightScenario::Reset() {}\n\nbool SignalLightScenario::Init() {\n exist_ = true;\n return exist_;\n}\n\nint SignalLightScenario::ComputeScenarioDecision(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n PlanningTarget* planning_target) {\n CHECK(frame != nullptr);\n\n if (!FindValidSignalLight(reference_line_info)) {\n AINFO << \"No valid signal light along reference line\";\n return 0;\n }\n ReadSignals();\n\n for (const hdmap::PathOverlap* signal_light :\n signal_lights_along_reference_line_) {\n const TrafficLight signal = GetSignal(signal_light->object_id);\n double stop_deceleration =\n GetStopDeceleration(reference_line_info, signal_light);\n\n if ((signal.color() == TrafficLight::RED &&\n stop_deceleration < FLAGS_stop_max_deceleration) ||\n (signal.color() == TrafficLight::UNKNOWN &&\n stop_deceleration < FLAGS_stop_max_deceleration) ||\n (signal.color() == TrafficLight::YELLOW &&\n stop_deceleration < FLAGS_max_deacceleration_for_yellow_light_stop)) {\n CreateStopObstacle(frame, reference_line_info, signal_light);\n }\n }\n\n return 0;\n}\n\nbool SignalLightScenario::FindValidSignalLight(\n ReferenceLineInfo* const reference_line_info) {\n const std::vector& signal_lights =\n reference_line_info->reference_line().map_path().signal_overlaps();\n if (signal_lights.size() <= 0) {\n ADEBUG << \"No signal lights from reference line.\";\n return false;\n } else {\n AINFO << \"Found signal_lights size=\" << signal_lights.size();\n }\n signal_lights_along_reference_line_.clear();\n for (const hdmap::PathOverlap& signal_light : signal_lights) {\n if (signal_light.start_s + FLAGS_stop_max_distance_buffer >\n reference_line_info->AdcSlBoundary().end_s()) {\n signal_lights_along_reference_line_.push_back(&signal_light);\n }\n }\n return signal_lights_along_reference_line_.size() > 0;\n}\n\nvoid SignalLightScenario::ReadSignals() {\n detected_signals_.clear();\n detected_signals_.clear();\n if (AdapterManager::GetTrafficLightDetection()->Empty()) {\n return;\n }\n if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() >\n FLAGS_signal_expire_time_sec) {\n AWARN << \"traffic signals msg is expired: \"\n << AdapterManager::GetTrafficLightDetection()->GetDelaySec();\n return;\n }\n const TrafficLightDetection& detection =\n AdapterManager::GetTrafficLightDetection()->GetLatestObserved();\n for (int j = 0; j < detection.traffic_light_size(); j++) {\n const TrafficLight& signal = detection.traffic_light(j);\n detected_signals_[signal.id()] = &signal;\n }\n}\n\nTrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) {\n const auto* result =\n apollo::common::util::FindPtrOrNull(detected_signals_, signal_id);\n if (result == nullptr) {\n TrafficLight traffic_light;\n traffic_light.set_id(signal_id);\n traffic_light.set_color(TrafficLight::UNKNOWN);\n traffic_light.set_confidence(0.0);\n traffic_light.set_tracking_time(0.0);\n return traffic_light;\n }\n return *result;\n}\n\ndouble SignalLightScenario::GetStopDeceleration(\n ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n double adc_speed =\n common::VehicleStateProvider::instance()->linear_velocity();\n if (adc_speed < FLAGS_stop_min_speed) {\n return 0.0;\n }\n double stop_distance = 0.0;\n double adc_front_s = reference_line_info->AdcSlBoundary().end_s();\n double stop_line_s = signal_light->start_s;\n\n if (stop_line_s > adc_front_s) {\n stop_distance = stop_line_s - adc_front_s;\n } else {\n stop_distance = stop_line_s + FLAGS_stop_max_distance_buffer - adc_front_s;\n }\n if (stop_distance < 1e-5) {\n \/\/ longitudinal_acceleration_lower_bound is a negative value.\n return -FLAGS_longitudinal_acceleration_lower_bound;\n }\n return (adc_speed * adc_speed) \/ (2 * stop_distance);\n}\n\nvoid SignalLightScenario::CreateStopObstacle(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n const auto& reference_line = reference_line_info->reference_line();\n const double stop_s =\n signal_light->start_s - FLAGS_stop_distance_traffic_light;\n const double box_center_s =\n signal_light->start_s + FLAGS_virtual_stop_wall_length \/ 2.0;\n if (!WithinBound(0.0, reference_line.Length(), stop_s) ||\n !WithinBound(0.0, reference_line.Length(), box_center_s)) {\n ADEBUG << \"signal \" << signal_light->object_id\n << \" is not on reference line\";\n return;\n }\n double heading = reference_line.GetReferencePoint(stop_s).heading();\n double left_lane_width = 0.0;\n double right_lane_width = 0.0;\n reference_line.GetLaneWidth(signal_light->start_s, &left_lane_width,\n &right_lane_width);\n\n auto box_center = reference_line.GetReferencePoint(box_center_s);\n common::math::Box2d stop_box{box_center, heading,\n FLAGS_virtual_stop_wall_length,\n left_lane_width + right_lane_width};\n reference_line_info->AddObstacle(frame->AddStaticVirtualObstacle(\n FLAGS_signal_light_virtual_object_id_prefix + signal_light->object_id,\n stop_box));\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/\/ Original class author: A.M. Jokisaari, O. Heinonen\n\n#include \"SimpleEigenStrainMaterial.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"epsilon0\", \"Initial eigen strain value\");\n params.addParam(\"c0\", 0.0, \"Initial concentration value\");\n params.addRequiredCoupledVar(\"c\", \"Concentration\");\n return params;\n}\n\nSimpleEigenStrainMaterial::SimpleEigenStrainMaterial(const std::string & name,\n InputParameters parameters) :\n EigenStrainBaseMaterial(name, parameters),\n _epsilon0(getParam(\"epsilon0\")),\n _c0(getParam(\"c0\"))\n{\n}\n\nvoid SimpleEigenStrainMaterial::computeEigenStrain()\n{\n _eigenstrain[_qp].zero();\n _eigenstrain[_qp].addIa(_epsilon0 * (_c[_qp] - _c0));\n\n \/\/ first derivative w.r.t. c\n _deigenstrain_dc[_qp].zero();\n _deigenstrain_dc[_qp].addIa(_epsilon0);\n\n \/\/ second derivative w.r.t. c (vanishes)\n _d2eigenstrain_dc2[_qp].zero();\n}\n\nvoid SimpleEigenStrainMaterial::computeQpElasticityTensor()\n{\n _Jacobian_mult[_qp] = _elasticity_tensor[_qp] = _Cijkl;\n\n \/\/ the elasticity tensor is independent of c\n _delasticity_tensor_dc[_qp].zero();\n _d2elasticity_tensor_dc2[_qp].zero();\n}\nFix derivative (#4501)\/\/ Original class author: A.M. Jokisaari, O. Heinonen\n\n#include \"SimpleEigenStrainMaterial.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"epsilon0\", \"Initial eigen strain value\");\n params.addParam(\"c0\", 0.0, \"Initial concentration value\");\n params.addRequiredCoupledVar(\"c\", \"Concentration\");\n return params;\n}\n\nSimpleEigenStrainMaterial::SimpleEigenStrainMaterial(const std::string & name,\n InputParameters parameters) :\n EigenStrainBaseMaterial(name, parameters),\n _epsilon0(getParam(\"epsilon0\")),\n _c0(getParam(\"c0\"))\n{\n}\n\nvoid SimpleEigenStrainMaterial::computeEigenStrain()\n{\n _eigenstrain[_qp].zero();\n _eigenstrain[_qp].addIa(_epsilon0 * (_c[_qp] - _c0));\n\n \/\/ first derivative w.r.t. c\n _deigenstrain_dc[_qp].zero();\n _deigenstrain_dc[_qp].addIa(-_epsilon0); \/\/ actually delastic_strain\/dc\n\n \/\/ second derivative w.r.t. c (vanishes)\n _d2eigenstrain_dc2[_qp].zero();\n}\n\nvoid SimpleEigenStrainMaterial::computeQpElasticityTensor()\n{\n _Jacobian_mult[_qp] = _elasticity_tensor[_qp] = _Cijkl;\n\n \/\/ the elasticity tensor is independent of c\n _delasticity_tensor_dc[_qp].zero();\n _d2elasticity_tensor_dc2[_qp].zero();\n}\n<|endoftext|>"} {"text":"#include \n#include \"datapool.h\"\n\nusing namespace ys;\n\nint main() {\n dataPool intpool(10, 1000);\n \/\/intpool.push_back(1);\n \/\/intpool.push_back(2);\n \/\/intpool.push_back(3);\n \/\/intpool.push_back(4);\n \/\/intpool.push_back(5);\n \/\/intpool.push_back(6);\n \/\/intpool.push_back(7);\n\n unsigned int arr[] = {5, 322, 445,23,664,23576,443,84,37, 1};\n\n intpool.push_back(arr, sizeof(arr)\/sizeof(int));\n\n for (int i = 0; i < intpool.getCurLen(); ++i) {\n printf (\"%u\\n\", intpool[i]);\n }\n\n for (int i = 0; i < 10000000; ++i) {\n intpool.push_back(i);\n }\n printf (\"size = %d\\n\", intpool.getCurLen());\n\n for (int i = 0; i < intpool.getCurLen(); ++i) {\n printf (\"%u\\n\", intpool[i]);\n }\n\n return 0;\n}\n\nDelete datapool.cpp<|endoftext|>"} {"text":"#include \"main.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nFile dataFile;\r\nuint32_t last_tick;\r\nchar filename[16];\r\n\r\nvoid initLogger() {\r\n\tif (!SD.begin(10)) {\r\n\t Serial.println(\"Card failed, or not present\");\r\n\t \/\/ don't do anything more:\r\n\t return;\r\n\t}\r\n\tSerial.println(\"card initialized.\");\r\n\r\n\tbLog = true;\r\n\tdigitalWrite(LED, bLog);\r\n\tif (bLog)\r\n\t\tstartLog();\r\n\telse\r\n\t\tstopLog();\r\n}\r\n\r\nvoid printDouble( double val, byte precision){\r\n\t\/\/ http:\/\/forum.arduino.cc\/index.php\/topic,44216.0.html#11\r\n \/\/ prints val with number of decimal places determine by precision\r\n \/\/ precision is a number from 0 to 6 indicating the desired decimial places\r\n \/\/ example: printDouble( 3.1415, 2); \/\/ prints 3.14 (two decimal places)\r\n\r\n Serial.print (int(val)); \/\/prints the int part\r\n if( precision > 0) {\r\n Serial.print(\".\"); \/\/ print the decimal point\r\n unsigned long frac;\r\n unsigned long mult = 1;\r\n byte padding = precision -1;\r\n while(precision--)\r\n mult *=10;\r\n\r\n if(val >= 0)\r\n frac = (val - int(val)) * mult;\r\n else\r\n frac = (int(val)- val ) * mult;\r\n unsigned long frac1 = frac;\r\n while( frac1 \/= 10 )\r\n padding--;\r\n while( padding--)\r\n Serial.print(\"0\");\r\n Serial.print(frac,DEC) ;\r\n }\r\n}\r\n\r\nvoid cmdAcquire(char *cmd) {\r\n\tint N, n, i, v;\r\n\tint static cnt = 0;\r\n\r\n\tN = cmd[1]-'0';\r\n\tfor(n=i=v=0; n> 8);\r\n\tEEPROM.write(1, nFile & 0xFF);\r\n}\r\n\r\n#define PERIOD 100\r\n\r\nvoid tickLog() {\r\n\tuint32_t t = millis();\r\n\tif (t > last_tick + PERIOD) {\r\n\t\tlast_tick += PERIOD;\r\n\t\tcmdAcquire(\"a1\");\r\n\t}\r\n}\r\n\r\nvoid stopLog() {\r\n}\r\nDados em csv#include \"main.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nFile dataFile;\r\nuint32_t last_tick;\r\nint sample;\r\n\r\nvoid initLogger() {\r\n\tif (!SD.begin(10)) {\r\n\t Serial.println(\"Card failed, or not present\");\r\n\t \/\/ don't do anything more:\r\n\t return;\r\n\t}\r\n\tSerial.println(\"card initialized.\");\r\n\r\n\tbLog = true;\r\n\tdigitalWrite(LED, bLog);\r\n\tif (bLog)\r\n\t\tstartLog();\r\n\telse\r\n\t\tstopLog();\r\n}\r\n\r\nvoid cmdAcquire(char *cmd) {\r\n\tint N, n, i, v;\r\n\r\n\tN = cmd[1]-'0';\r\n\tfor(n=i=v=0; n> 8);\r\n\tEEPROM.write(1, nFile & 0xFF);\r\n\r\n\tSerial.println(filename);\r\n\tdataFile = SD.open(filename, FILE_WRITE);\r\n\tdataFile.println(\"t(1\/10s),I(0..1023)\");\r\n\r\n}\r\n\r\nvoid tickLog() {\r\n\tuint32_t t = millis();\r\n\tif (t > last_tick + PERIOD) {\r\n\t\tlast_tick += PERIOD;\r\n\t\tcmdAcquire(\"a4\");\r\n\t}\r\n}\r\n\r\nvoid stopLog() {\r\n\tdataFile.close();\r\n\tsample = 0;\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nnamespace vscode\n{\n\tvoid debugger_impl::response_initialize(rprotocol& req)\n\t{\n\t\tif (req.HasMember(\"__norepl\") && req[\"__norepl\"].IsBool() && req[\"__norepl\"].GetBool())\n\t\t{\n\t\t\tseq++;\n\t\t\treturn;\n\t\t}\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(1);\n\t\t\tres(\"command\").String(\"initialize\");\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tcapabilities(res);\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_thread(rprotocol& req)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tfor (auto _ : res(\"threads\").Array())\n\t\t\t\t{\n\t\t\t\t\tfor (auto _ : res.Object())\n\t\t\t\t\t{\n\t\t\t\t\t\tres(\"name\").String(\"LuaThread\");\n\t\t\t\t\t\tres(\"id\").Int(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_source(rprotocol& req, const char* content)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"content\").String(content);\n\t\t\t\tres(\"mimeType\").String(\"text\/x-lua\");\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_stopped(luathread* thread, const char *msg)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"stopped\");\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"reason\").String(msg);\n\t\t\t\tres(\"threadId\").Int(thread->id);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_thread(luathread* thread, bool started)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"thread\");\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"reason\").String(started ? \"started\" : \"exited\");\n\t\t\t\tres(\"threadId\").Int(thread->id);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_terminated()\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"terminated\");\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"restart\").Bool(false);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_initialized()\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"initialized\");\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_capabilities()\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"capabilities\");\n\t\t\tcapabilities(res);\n\t\t}\n\t\tio_output(res);\n\t}\n\tvoid debugger_impl::response_error(rprotocol& req, const char *msg)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(false);\n\t\t\tres(\"message\").String(msg);\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_success(rprotocol& req)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_success(rprotocol& req, std::function body)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tbody(res);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n}\n修正线程列表不对的问题#include \n#include \n#include \n#include \n\nnamespace vscode\n{\n\tvoid debugger_impl::response_initialize(rprotocol& req)\n\t{\n\t\tif (req.HasMember(\"__norepl\") && req[\"__norepl\"].IsBool() && req[\"__norepl\"].GetBool())\n\t\t{\n\t\t\tseq++;\n\t\t\treturn;\n\t\t}\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(1);\n\t\t\tres(\"command\").String(\"initialize\");\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tcapabilities(res);\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_thread(rprotocol& req)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tfor (auto _ : res(\"threads\").Array())\n\t\t\t\t{\n\t\t\t\t\tfor (auto& lt : luathreads_) \n\t\t\t\t\t{\n\t\t\t\t\t\tfor (auto _ : res.Object())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres(\"name\").String(\"LuaThread\");\n\t\t\t\t\t\t\tres(\"id\").Int(lt.second->id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_source(rprotocol& req, const char* content)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"content\").String(content);\n\t\t\t\tres(\"mimeType\").String(\"text\/x-lua\");\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_stopped(luathread* thread, const char *msg)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"stopped\");\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"reason\").String(msg);\n\t\t\t\tres(\"threadId\").Int(thread->id);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_thread(luathread* thread, bool started)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"thread\");\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"reason\").String(started ? \"started\" : \"exited\");\n\t\t\t\tres(\"threadId\").Int(thread->id);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_terminated()\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"terminated\");\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tres(\"restart\").Bool(false);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_initialized()\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"initialized\");\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::event_capabilities()\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"event\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"event\").String(\"capabilities\");\n\t\t\tcapabilities(res);\n\t\t}\n\t\tio_output(res);\n\t}\n\tvoid debugger_impl::response_error(rprotocol& req, const char *msg)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(false);\n\t\t\tres(\"message\").String(msg);\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_success(rprotocol& req)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t}\n\t\tio_output(res);\n\t}\n\n\tvoid debugger_impl::response_success(rprotocol& req, std::function body)\n\t{\n\t\twprotocol res;\n\t\tfor (auto _ : res.Object())\n\t\t{\n\t\t\tres(\"type\").String(\"response\");\n\t\t\tres(\"seq\").Int64(seq++);\n\t\t\tres(\"command\").String(req[\"command\"]);\n\t\t\tres(\"request_seq\").Int64(req[\"seq\"].GetInt64());\n\t\t\tres(\"success\").Bool(true);\n\t\t\tfor (auto _ : res(\"body\").Object())\n\t\t\t{\n\t\t\t\tbody(res);\n\t\t\t}\n\t\t}\n\t\tio_output(res);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/===-- examples\/clang-interpreter\/main.cpp - Clang C Interpreter Example -===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/CodeGenAction.h\"\n#include \"clang\/Frontend\/CompilerInvocation.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Host.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\nusing namespace clang;\nusing namespace clang::driver;\n\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);\n}\n\nint Execute(llvm::Module *Mod, char * const *envp) {\n llvm::InitializeNativeTarget();\n\n std::string Error;\n llvm::OwningPtr EE(\n llvm::ExecutionEngine::createJIT(Mod, &Error));\n if (!EE) {\n llvm::errs() << \"unable to make execution engine: \" << Error << \"\\n\";\n return 255;\n }\n\n llvm::Function *EntryFn = Mod->getFunction(\"main\");\n if (!EntryFn) {\n llvm::errs() << \"'main' function not found in module.\\n\";\n return 255;\n }\n\n \/\/ FIXME: Support passing arguments.\n std::vector Args;\n Args.push_back(Mod->getModuleIdentifier());\n\n return EE->runFunctionAsMain(EntryFn, Args, envp);\n}\n\nint main(int argc, const char **argv, char * const *envp) {\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n llvm::sys::Path Path = GetExecutablePath(argv[0]);\n TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());\n\n Diagnostic Diags(&DiagClient);\n Driver TheDriver(Path.getBasename(), Path.getDirname(),\n llvm::sys::getHostTriple(),\n \"a.out\", \/*IsProduction=*\/false, \/*CXXIsProduction=*\/false,\n Diags);\n TheDriver.setTitle(\"clang interpreter\");\n\n \/\/ FIXME: This is a hack to try to force the driver to do something we can\n \/\/ recognize. We need to extend the driver library to support this use model\n \/\/ (basically, exactly one input, and the operation mode is hard wired).\n llvm::SmallVector Args(argv, argv + argc);\n Args.push_back(\"-fsyntax-only\");\n llvm::OwningPtr C(TheDriver.BuildCompilation(Args.size(),\n Args.data()));\n if (!C)\n return 0;\n\n \/\/ FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.\n\n \/\/ We expect to get back exactly one command job, if we didn't something\n \/\/ failed. Extract that job from the compilation.\n const driver::JobList &Jobs = C->getJobs();\n if (Jobs.size() != 1 || !isa(Jobs.begin())) {\n llvm::SmallString<256> Msg;\n llvm::raw_svector_ostream OS(Msg);\n C->PrintJob(OS, C->getJobs(), \"; \", true);\n Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();\n return 1;\n }\n\n const driver::Command *Cmd = cast(*Jobs.begin());\n if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n Diags.Report(diag::err_fe_expected_clang_command);\n return 1;\n }\n\n \/\/ Initialize a compiler invocation object from the clang (-cc1) arguments.\n const driver::ArgStringList &CCArgs = Cmd->getArguments();\n llvm::OwningPtr CI(new CompilerInvocation);\n CompilerInvocation::CreateFromArgs(*CI, (const char**) CCArgs.data(),\n (const char**) CCArgs.data()+CCArgs.size(),\n Diags);\n\n \/\/ Show the invocation, with -v.\n if (CI->getHeaderSearchOpts().Verbose) {\n llvm::errs() << \"clang invocation:\\n\";\n C->PrintJob(llvm::errs(), C->getJobs(), \"\\n\", true);\n llvm::errs() << \"\\n\";\n }\n\n \/\/ FIXME: This is copied from cc1_main.cpp; simplify and eliminate.\n\n \/\/ Create a compiler instance to handle the actual work.\n CompilerInstance Clang;\n Clang.setLLVMContext(new llvm::LLVMContext);\n Clang.setInvocation(CI.take());\n\n \/\/ Create the compilers actual diagnostics engine.\n Clang.createDiagnostics(int(CCArgs.size()), (char**) CCArgs.data());\n if (!Clang.hasDiagnostics())\n return 1;\n\n \/\/ Infer the builtin include path if unspecified.\n if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&\n Clang.getHeaderSearchOpts().ResourceDir.empty())\n Clang.getHeaderSearchOpts().ResourceDir =\n CompilerInvocation::GetResourcesPath(argv[0], MainAddr);\n\n \/\/ Create and execute the frontend to generate an LLVM bitcode module.\n llvm::OwningPtr Act(new EmitLLVMOnlyAction());\n if (!Clang.ExecuteAction(*Act))\n return 1;\n\n int Res = 255;\n if (llvm::Module *Module = Act->takeModule())\n Res = Execute(Module, envp);\n\n \/\/ Shutdown.\n\n llvm::llvm_shutdown();\n\n return Res;\n}\nFix -Wcast-qual warnings.\/\/===-- examples\/clang-interpreter\/main.cpp - Clang C Interpreter Example -===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/CodeGenAction.h\"\n#include \"clang\/Frontend\/CompilerInvocation.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Host.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\nusing namespace clang;\nusing namespace clang::driver;\n\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);\n}\n\nint Execute(llvm::Module *Mod, char * const *envp) {\n llvm::InitializeNativeTarget();\n\n std::string Error;\n llvm::OwningPtr EE(\n llvm::ExecutionEngine::createJIT(Mod, &Error));\n if (!EE) {\n llvm::errs() << \"unable to make execution engine: \" << Error << \"\\n\";\n return 255;\n }\n\n llvm::Function *EntryFn = Mod->getFunction(\"main\");\n if (!EntryFn) {\n llvm::errs() << \"'main' function not found in module.\\n\";\n return 255;\n }\n\n \/\/ FIXME: Support passing arguments.\n std::vector Args;\n Args.push_back(Mod->getModuleIdentifier());\n\n return EE->runFunctionAsMain(EntryFn, Args, envp);\n}\n\nint main(int argc, const char **argv, char * const *envp) {\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n llvm::sys::Path Path = GetExecutablePath(argv[0]);\n TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());\n\n Diagnostic Diags(&DiagClient);\n Driver TheDriver(Path.getBasename(), Path.getDirname(),\n llvm::sys::getHostTriple(),\n \"a.out\", \/*IsProduction=*\/false, \/*CXXIsProduction=*\/false,\n Diags);\n TheDriver.setTitle(\"clang interpreter\");\n\n \/\/ FIXME: This is a hack to try to force the driver to do something we can\n \/\/ recognize. We need to extend the driver library to support this use model\n \/\/ (basically, exactly one input, and the operation mode is hard wired).\n llvm::SmallVector Args(argv, argv + argc);\n Args.push_back(\"-fsyntax-only\");\n llvm::OwningPtr C(TheDriver.BuildCompilation(Args.size(),\n Args.data()));\n if (!C)\n return 0;\n\n \/\/ FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.\n\n \/\/ We expect to get back exactly one command job, if we didn't something\n \/\/ failed. Extract that job from the compilation.\n const driver::JobList &Jobs = C->getJobs();\n if (Jobs.size() != 1 || !isa(Jobs.begin())) {\n llvm::SmallString<256> Msg;\n llvm::raw_svector_ostream OS(Msg);\n C->PrintJob(OS, C->getJobs(), \"; \", true);\n Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();\n return 1;\n }\n\n const driver::Command *Cmd = cast(*Jobs.begin());\n if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n Diags.Report(diag::err_fe_expected_clang_command);\n return 1;\n }\n\n \/\/ Initialize a compiler invocation object from the clang (-cc1) arguments.\n const driver::ArgStringList &CCArgs = Cmd->getArguments();\n llvm::OwningPtr CI(new CompilerInvocation);\n CompilerInvocation::CreateFromArgs(*CI,\n const_cast(CCArgs.data()),\n const_cast(CCArgs.data()) +\n CCArgs.size(),\n *Diags);\n\n \/\/ Show the invocation, with -v.\n if (CI->getHeaderSearchOpts().Verbose) {\n llvm::errs() << \"clang invocation:\\n\";\n C->PrintJob(llvm::errs(), C->getJobs(), \"\\n\", true);\n llvm::errs() << \"\\n\";\n }\n\n \/\/ FIXME: This is copied from cc1_main.cpp; simplify and eliminate.\n\n \/\/ Create a compiler instance to handle the actual work.\n CompilerInstance Clang;\n Clang.setLLVMContext(new llvm::LLVMContext);\n Clang.setInvocation(CI.take());\n\n \/\/ Create the compilers actual diagnostics engine.\n Clang.createDiagnostics(int(CCArgs.size()), (char**) CCArgs.data());\n if (!Clang.hasDiagnostics())\n return 1;\n\n \/\/ Infer the builtin include path if unspecified.\n if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&\n Clang.getHeaderSearchOpts().ResourceDir.empty())\n Clang.getHeaderSearchOpts().ResourceDir =\n CompilerInvocation::GetResourcesPath(argv[0], MainAddr);\n\n \/\/ Create and execute the frontend to generate an LLVM bitcode module.\n llvm::OwningPtr Act(new EmitLLVMOnlyAction());\n if (!Clang.ExecuteAction(*Act))\n return 1;\n\n int Res = 255;\n if (llvm::Module *Module = Act->takeModule())\n Res = Execute(Module, envp);\n\n \/\/ Shutdown.\n\n llvm::llvm_shutdown();\n\n return Res;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved.\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\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_binding_c\/internal\/cpp2c_enum_translation.hpp\"\n#include \"iceoryx_binding_c\/enums.h\"\n\nusing namespace iox;\nusing namespace iox::popo;\n\nnamespace cpp2c\n{\niox_SubscribeState SubscribeState(const iox::SubscribeState value)\n{\n switch (value)\n {\n case iox::SubscribeState::NOT_SUBSCRIBED:\n return iox_SubscribeState::SubscribeState_NOT_SUBSCRIBED;\n case iox::SubscribeState::SUBSCRIBE_REQUESTED:\n return iox_SubscribeState::SubscribeState_SUBSCRIBE_REQUESTED;\n case iox::SubscribeState::SUBSCRIBED:\n return iox_SubscribeState::SubscribeState_SUBSCRIBED;\n case iox::SubscribeState::UNSUBSCRIBE_REQUESTED:\n return iox_SubscribeState::SubscribeState_UNSUBSCRIBE_REQUESTED;\n case iox::SubscribeState::WAIT_FOR_OFFER:\n return iox_SubscribeState::SubscribeState_WAIT_FOR_OFFER;\n default:\n return iox_SubscribeState::SubscribeState_UNDEFINED_ERROR;\n }\n}\n\niox_ChunkReceiveResult ChunkReceiveResult(const iox::popo::ChunkReceiveResult value)\n{\n switch (value)\n {\n case ChunkReceiveResult::NO_CHUNK_AVAILABLE:\n return ChunkReceiveResult_NO_CHUNK_AVAILABLE;\n case ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL:\n return ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL;\n default:\n return ChunkReceiveResult_UNDEFINED_ERROR;\n }\n}\n\niox_AllocationResult AllocationResult(const iox::popo::AllocationError value)\n{\n switch (value)\n {\n case AllocationError::RUNNING_OUT_OF_CHUNKS:\n return AllocationResult_RUNNING_OUT_OF_CHUNKS;\n case AllocationError::TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL:\n return AllocationResult_TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL;\n default:\n return AllocationResult_UNDEFINED_ERROR;\n }\n}\n\niox_WaitSetResult WaitSetResult(const iox::popo::WaitSetError value)\n{\n switch (value)\n {\n case WaitSetError::WAIT_SET_FULL:\n return WaitSetResult_WAIT_SET_FULL;\n case WaitSetError::EVENT_ALREADY_ATTACHED:\n return WaitSetResult_EVENT_ALREADY_ATTACHED;\n default:\n return WaitSetResult_UNDEFINED_ERROR;\n }\n}\n\n} \/\/ namespace cpp2c\niox-#495 Add namespace to enum\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved.\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\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_binding_c\/internal\/cpp2c_enum_translation.hpp\"\n#include \"iceoryx_binding_c\/enums.h\"\n\nusing namespace iox;\nusing namespace iox::popo;\n\nnamespace cpp2c\n{\niox_SubscribeState SubscribeState(const iox::SubscribeState value)\n{\n switch (value)\n {\n case iox::SubscribeState::NOT_SUBSCRIBED:\n return iox_SubscribeState::SubscribeState_NOT_SUBSCRIBED;\n case iox::SubscribeState::SUBSCRIBE_REQUESTED:\n return iox_SubscribeState::SubscribeState_SUBSCRIBE_REQUESTED;\n case iox::SubscribeState::SUBSCRIBED:\n return iox_SubscribeState::SubscribeState_SUBSCRIBED;\n case iox::SubscribeState::UNSUBSCRIBE_REQUESTED:\n return iox_SubscribeState::SubscribeState_UNSUBSCRIBE_REQUESTED;\n case iox::SubscribeState::WAIT_FOR_OFFER:\n return iox_SubscribeState::SubscribeState_WAIT_FOR_OFFER;\n default:\n return iox_SubscribeState::SubscribeState_UNDEFINED_ERROR;\n }\n}\n\niox_ChunkReceiveResult ChunkReceiveResult(const iox::popo::ChunkReceiveResult value)\n{\n switch (value)\n {\n case iox::popo::ChunkReceiveResult::NO_CHUNK_AVAILABLE:\n return ChunkReceiveResult_NO_CHUNK_AVAILABLE;\n case iox::popo::ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL:\n return ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL;\n default:\n return ChunkReceiveResult_UNDEFINED_ERROR;\n }\n}\n\niox_AllocationResult AllocationResult(const iox::popo::AllocationError value)\n{\n switch (value)\n {\n case AllocationError::RUNNING_OUT_OF_CHUNKS:\n return AllocationResult_RUNNING_OUT_OF_CHUNKS;\n case AllocationError::TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL:\n return AllocationResult_TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL;\n default:\n return AllocationResult_UNDEFINED_ERROR;\n }\n}\n\niox_WaitSetResult WaitSetResult(const iox::popo::WaitSetError value)\n{\n switch (value)\n {\n case WaitSetError::WAIT_SET_FULL:\n return WaitSetResult_WAIT_SET_FULL;\n case WaitSetError::EVENT_ALREADY_ATTACHED:\n return WaitSetResult_EVENT_ALREADY_ATTACHED;\n default:\n return WaitSetResult_UNDEFINED_ERROR;\n }\n}\n\n} \/\/ namespace cpp2c\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"otbBCOInterpolateImageFunction.h\"\n#include \"itkNearestNeighborInterpolateImageFunction.h\"\n\n\/\/Transform\n#include \"otbCompositeTransform.h\"\n#include \"itkScalableAffineTransform.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkIdentityTransform.h\"\n#include \"itkScaleTransform.h\"\n#include \"itkCenteredRigid2DTransform.h\"\n\n#include \"otbStreamingResampleImageFilter.h\"\n\nnamespace otb\n{\nenum\n{\n Interpolator_NNeighbor,\n Interpolator_Linear,\n Interpolator_BCO\n};\n\nenum\n{\n Transform_Translation,\n Transform_Rotation,\n};\n\nnamespace Wrapper\n{\n\nclass RigidTransformResample : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef RigidTransformResample Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n typedef itk::TranslationTransform TransformType;\n typedef otb::StreamingResampleImageFilter ResampleFilterType;\n\n \/\/typedef itk::IdentityTransform IdentityTransformType;\n\n typedef itk::ScalableAffineTransform ScalableTransformType;\n typedef ScalableTransformType::OutputVectorType OutputVectorType;\n\n \/** Rotation transform *\/\n typedef itk::CenteredRigid2DTransform< double > RotationTransformType;\n typedef RotationTransformType::ScalarType ScalarType;\n\n itkTypeMacro(RigidTransformResample, otb::Application);\n\nprivate:\n\n void DoInit()\n {\n SetName(\"RigidTransformResample\");\n SetDescription(\"Resample an image with a rigid transform\");\n \/\/ Documentation\n SetDocName(\"Image resampling with a rigid transform\");\n SetDocLongDescription(\"This application performs an translation on the input image.\\n Parameters of the translation can be set with tx and ty options.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"Translation\");\n\n AddDocTag(\"Conversion\");\n AddDocTag(Tags::Geometry);\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input image\");\n SetParameterDescription(\"in\",\"The input image to translate.\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output image\");\n SetParameterDescription(\"out\",\"The translated output image.\");\n\n \/\/Transform\n AddParameter(ParameterType_Group,\"transform\",\"Transform parameters\");\n SetParameterDescription(\"transform\",\"This group of parameters allows to set the transformation to apply.\");\n\n AddParameter(ParameterType_Choice, \"transform.type\", \"Type of transformation\");\n SetParameterDescription(\"transform.type\",\"Type of transformation. Available transformations are translation and rotation with scaling factor\");\n\n AddChoice(\"transform.type.translation\", \"translation\");\n SetParameterDescription(\"transform.type.translation\",\"translation\");\n\n AddParameter(ParameterType_Float,\"transform.type.translation.tx\", \"The X translation (in physical units)\");\n SetParameterDescription(\"transform.type.translation.tx\",\"The translation value along X axis (in physical units).\");\n SetDefaultParameterFloat(\"transform.type.translation.tx\",0.);\n AddParameter(ParameterType_Float,\"transform.type.translation.ty\", \"The Y translation (in physical units)\");\n SetParameterDescription(\"transform.type.translation.ty\",\"The translation value along Y axis (in physical units)\");\n SetDefaultParameterFloat(\"transform.type.translation.tx\",0.);\n\n AddChoice(\"transform.type.rotation\", \"rotation\");\n SetParameterDescription(\"transform.type.rotation\",\"rotation\");\n\n AddParameter(ParameterType_Float, \"transform.type.rotation.angle\", \"Rotation angle\");\n SetParameterDescription(\"transform.type.rotation.angle\",\"The rotation angle in degree (values between -180 and 180)\");\n SetDefaultParameterFloat(\"transform.type.rotation.angle\",0.);\n\n AddParameter(ParameterType_Float, \"transform.type.rotation.scalex\", \"X factor\");\n SetParameterDescription(\"transform.type.rotation.scalex\",\"X factor\");\n SetDefaultParameterFloat(\"transform.type.rotation.scalex\",1.);\n\n AddParameter(ParameterType_Float, \"transform.type.rotation.scaley\", \"Y factor\");\n SetParameterDescription(\"transform.type.rotation.scaley\",\"Y factor\");\n SetDefaultParameterFloat(\"transform.type.rotation.scaley\",1.);\n\n \/\/ Interpolators\n AddParameter(ParameterType_Choice, \"interpolator\", \"Interpolation\");\n SetParameterDescription(\"interpolator\",\"This group of parameters allows to define how the input image will be interpolated during resampling.\");\n AddChoice(\"interpolator.nn\", \"Nearest Neighbor interpolation\");\n SetParameterDescription(\"interpolator.nn\",\"Nearest neighbor interpolation leads to poor image quality, but it is very fast.\");\n AddChoice(\"interpolator.linear\", \"Linear interpolation\");\n SetParameterDescription(\"interpolator.linear\",\"Linear interpolation leads to average image quality but is quite fast\");\n AddChoice(\"interpolator.bco\", \"Bicubic interpolation\");\n AddParameter(ParameterType_Radius, \"interpolator.bco.radius\", \"Radius for bicubic interpolation\");\n SetParameterDescription(\"interpolator.bco.radius\",\"This parameter allows to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.\");\n SetDefaultParameterInt(\"interpolator.bco.radius\", 2);\n SetParameterString(\"interpolator\",\"bco\");\n\n \/\/ RAM available\n AddRAMParameter(\"ram\");\n SetParameterDescription(\"ram\",\"This allows to set the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities)\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"qb_toulouse_sub.tif\");\n SetDocExampleParameterValue(\"out\", \"rigitTransformImage.tif\");\n SetDocExampleParameterValue(\"transform.type\", \"rotation\");\n SetDocExampleParameterValue(\"transform.type.scalex\", \"4.\");\n SetDocExampleParameterValue(\"transform.type.scaley\", \"4.\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n FloatVectorImageType* inputImage = GetParameterImage(\"in\");\n\n m_Resampler = ResampleFilterType::New();\n m_Resampler->SetInput(inputImage);\n\n \/\/ Get Interpolator\n switch ( GetParameterInt(\"interpolator\") )\n {\n case Interpolator_Linear:\n {\n typedef itk::LinearInterpolateImageFunction LinearInterpolationType;\n LinearInterpolationType::Pointer interpolator = LinearInterpolationType::New();\n m_Resampler->SetInterpolator(interpolator);\n }\n break;\n case Interpolator_NNeighbor:\n {\n typedef itk::NearestNeighborInterpolateImageFunction NearestNeighborInterpolationType;\n NearestNeighborInterpolationType::Pointer interpolator = NearestNeighborInterpolationType::New();\n m_Resampler->SetInterpolator(interpolator);\n }\n break;\n case Interpolator_BCO:\n {\n typedef otb::BCOInterpolateImageFunction BCOInterpolationType;\n BCOInterpolationType::Pointer interpolator = BCOInterpolationType::New();\n interpolator->SetRadius(GetParameterInt(\"interpolator.bco.radius\"));\n m_Resampler->SetInterpolator(interpolator);\n }\n break;\n }\n\n \/\/ Get Transform\n switch ( GetParameterInt(\"transform.type\") )\n {\n case Transform_Translation:\n {\n TransformType::Pointer transform = TransformType::New();\n TransformType::OutputVectorType offset;\n offset[0] = GetParameterFloat(\"transform.type.translation.tx\");\n offset[1] = GetParameterFloat(\"transform.type.translation.ty\");\n otbAppLogINFO( << \"Offset : \" << offset );\n transform->SetOffset(offset);\n m_Resampler->SetTransform(transform);\n m_Resampler->SetOutputParametersFromImage(inputImage);\n }\n break;\n\n case Transform_Rotation:\n {\n ScalableTransformType::Pointer transform = ScalableTransformType::New();\n\n FloatVectorImageType::IndexType origin = inputImage->GetLargestPossibleRegion().GetIndex();\n FloatVectorImageType::SpacingType spacing = inputImage->GetSpacing();\n\n FloatVectorImageType::IndexType center;\n center[0] = origin[0] + inputImage->GetLargestPossibleRegion().GetSize()[0] \/ 2.0;\n center[1] = origin[1] + inputImage->GetLargestPossibleRegion().GetSize()[1] \/ 2.0;\n\n\n FloatVectorImageType::PointType centerPoint;\n inputImage->TransformIndexToPhysicalPoint(center, centerPoint);\n\n \/\/image boundary\n FloatVectorImageType::IndexType ULindex, URindex, LRindex, LLindex;\n\n ULindex[0]=origin[0];\n ULindex[1]=origin[1];\n URindex[0]=origin[0]+ inputImage->GetLargestPossibleRegion().GetSize()[0];\n URindex[1]=origin[1];\n LRindex[0]=origin[0]+ inputImage->GetLargestPossibleRegion().GetSize()[0];\n LRindex[1]=origin[1]+ inputImage->GetLargestPossibleRegion().GetSize()[1];\n LLindex[0]=origin[0];\n LLindex[1]=origin[1]+ inputImage->GetLargestPossibleRegion().GetSize()[1];\n\n FloatVectorImageType::PointType orig, ULpoint, URpoint, LRpoint, LLpoint;\n inputImage->TransformIndexToPhysicalPoint(ULindex, ULpoint);\n inputImage->TransformIndexToPhysicalPoint(URindex, URpoint);\n inputImage->TransformIndexToPhysicalPoint(LRindex, LRpoint);\n inputImage->TransformIndexToPhysicalPoint(LLindex, LLpoint);\n\n \/\/ Scale Transform\n OutputVectorType scale;\n scale[0] = 1.0 \/ GetParameterFloat(\"transform.type.rotation.scalex\");\n scale[1] = 1.0 \/ GetParameterFloat(\"transform.type.rotation.scaley\");\n\n \/\/angle of rotation\n ScalarType rot_angle = GetParameterFloat(\"transform.type.rotation.angle\");\n if (rot_angle < -180 || rot_angle > 180)\n {\n itkExceptionMacro(<<\"The rotation angle must value be between -180 and 180.\");\n }\n\n transform->SetIdentity();\n if(spacing[0] > 0 && spacing[1] > 0) transform->Rotate2D( rot_angle * CONST_PI_180 );\n else transform->Rotate2D( - rot_angle * CONST_PI_180 );\n\n transform->SetCenter( centerPoint );\n transform->Scale( scale );\n\n \/\/inverse transform\n ScalableTransformType::Pointer inverseTransform = ScalableTransformType::New();\n transform->GetInverse(inverseTransform);\n m_Resampler->SetTransform(transform);\n\n\n FloatVectorImageType::PointType ULpointTrans, URpointTrans, LRpointTrans, LLpointTrans, CenterPointTrans;\n\n ULpointTrans=inverseTransform->TransformPoint(ULpoint);\n URpointTrans=inverseTransform->TransformPoint(URpoint);\n LRpointTrans=inverseTransform->TransformPoint(LRpoint);\n LLpointTrans=inverseTransform->TransformPoint(LLpoint);\n CenterPointTrans=inverseTransform->TransformPoint(centerPoint);\n\n \/\/compute min and max\n std::vector voutput;\n voutput.push_back(ULpointTrans);\n voutput.push_back(URpointTrans);\n voutput.push_back(LRpointTrans);\n voutput.push_back(LLpointTrans);\n\n double minX = voutput[0][0];\n double maxX = voutput[0][0];\n double minY = voutput[0][1];\n double maxY = voutput[0][1];\n\n for(unsigned int i = 0; i voutput[i][0] )\n {\n minX = voutput[i][0];\n }\n if ( minY > voutput[i][1] )\n {\n minY = voutput[i][1];\n }\n\n \/\/ Sizes\n if ( maxX < voutput[i][0] )\n {\n maxX = voutput[i][0];\n }\n if ( maxY < voutput[i][1] )\n {\n maxY = voutput[i][1];\n }\n }\n\n if( spacing[0] > 0 ) orig[0] = minX;\n else orig[0] = maxX;\n\n if( spacing[1] > 0 ) orig[1] = minY;\n else orig[1] = maxY;\n\n m_Resampler->SetOutputOrigin(orig);\n\n \/\/size of output image\n ResampleFilterType::SizeType size;\n size[0]=vcl_abs(maxX-minX);\n size[1]=vcl_abs(maxY-minY);\n\n \/\/ Evaluate spacing\n FloatVectorImageType::SpacingType OutputSpacing;\n OutputSpacing=spacing;\n\n \/\/FIXME Find a way to update the output image spacing after resampling\n \/\/OutputSpacing[0] = scale[0] * spacing[0];\n \/\/OutputSpacing[1] = scale[1] * spacing[1];\n\n m_Resampler->SetOutputSpacing(OutputSpacing);\n\n \/\/ Evaluate size\n ResampleFilterType::SizeType recomputedSize;\n recomputedSize[0] = static_cast(vcl_floor(vcl_abs(size[0]\/OutputSpacing[0])));\n recomputedSize[1] = static_cast(vcl_floor(vcl_abs(size[1]\/OutputSpacing[1])));\n m_Resampler->SetOutputSize( recomputedSize );\n otbAppLogINFO( << \"Output image size : \" << recomputedSize );\n }\n break;\n }\n\n FloatVectorImageType::PixelType defaultValue;\n itk::PixelBuilder::Zero(defaultValue,\n inputImage->GetNumberOfComponentsPerPixel());\n m_Resampler->SetEdgePaddingValue(defaultValue);\n\n m_Resampler->UpdateOutputInformation();\n \/\/ Output Image\n SetParameterOutputImage(\"out\", m_Resampler->GetOutput());\n }\n\n ResampleFilterType::Pointer m_Resampler;\n}; \/\/class\n\n\n} \/\/namespace wrapper\n} \/\/namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::RigidTransformResample)\nENH: add identity transform to allow zoom\/dezoom with correct output spacing\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"otbBCOInterpolateImageFunction.h\"\n#include \"itkNearestNeighborInterpolateImageFunction.h\"\n\n\/\/Transform\n#include \"otbCompositeTransform.h\"\n#include \"itkScalableAffineTransform.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkIdentityTransform.h\"\n#include \"itkScaleTransform.h\"\n#include \"itkCenteredRigid2DTransform.h\"\n\n#include \"otbStreamingResampleImageFilter.h\"\n\nnamespace otb\n{\nenum\n{\n Interpolator_NNeighbor,\n Interpolator_Linear,\n Interpolator_BCO\n};\n\nenum\n{\n Transform_Identity,\n Transform_Translation,\n Transform_Rotation,\n};\n\nnamespace Wrapper\n{\n\nclass RigidTransformResample : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef RigidTransformResample Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n typedef itk::TranslationTransform TransformType;\n typedef otb::StreamingResampleImageFilter ResampleFilterType;\n\n typedef itk::IdentityTransform IdentityTransformType;\n\n typedef itk::ScalableAffineTransform ScalableTransformType;\n typedef ScalableTransformType::OutputVectorType OutputVectorType;\n\n \/** Rotation transform *\/\n typedef itk::CenteredRigid2DTransform< double > RotationTransformType;\n typedef RotationTransformType::ScalarType ScalarType;\n\n itkTypeMacro(RigidTransformResample, otb::Application);\n\nprivate:\n\n void DoInit()\n {\n SetName(\"RigidTransformResample\");\n SetDescription(\"Resample an image with a rigid transform\");\n \/\/ Documentation\n SetDocName(\"Image resampling with a rigid transform\");\n SetDocLongDescription(\"This application performs an translation on the input image.\\n Parameters of the translation can be set with tx and ty options.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"Translation\");\n\n AddDocTag(\"Conversion\");\n AddDocTag(Tags::Geometry);\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input image\");\n SetParameterDescription(\"in\",\"The input image to translate.\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output image\");\n SetParameterDescription(\"out\",\"The translated output image.\");\n\n \/\/Transform\n AddParameter(ParameterType_Group,\"transform\",\"Transform parameters\");\n SetParameterDescription(\"transform\",\"This group of parameters allows to set the transformation to apply.\");\n\n AddParameter(ParameterType_Choice, \"transform.type\", \"Type of transformation\");\n SetParameterDescription(\"transform.type\",\"Type of transformation. Available transformations are translation and rotation with scaling factor\");\n\n AddChoice(\"transform.type.id\", \"translation\");\n SetParameterDescription(\"transform.type.id\",\"translation\");\n\n AddParameter(ParameterType_Float,\"transform.type.id.scalex\", \"The X translation (in physical units)\");\n SetParameterDescription(\"transform.type.id.scalex\",\"The translation value along X axis (in physical units).\");\n SetDefaultParameterFloat(\"transform.type.id.scalex\",1.);\n AddParameter(ParameterType_Float,\"transform.type.id.scaley\", \"The Y translation (in physical units)\");\n SetParameterDescription(\"transform.type.id.scaley\",\"The translation value along Y axis (in physical units)\");\n SetDefaultParameterFloat(\"transform.type.id.scaley\",1.);\n\n AddChoice(\"transform.type.translation\", \"translation\");\n SetParameterDescription(\"transform.type.translation\",\"translation\");\n\n AddParameter(ParameterType_Float,\"transform.type.translation.tx\", \"The X translation (in physical units)\");\n SetParameterDescription(\"transform.type.translation.tx\",\"The translation value along X axis (in physical units).\");\n SetDefaultParameterFloat(\"transform.type.translation.tx\",0.);\n AddParameter(ParameterType_Float,\"transform.type.translation.ty\", \"The Y translation (in physical units)\");\n SetParameterDescription(\"transform.type.translation.ty\",\"The translation value along Y axis (in physical units)\");\n SetDefaultParameterFloat(\"transform.type.translation.tx\",0.);\n\n AddChoice(\"transform.type.rotation\", \"rotation\");\n SetParameterDescription(\"transform.type.rotation\",\"rotation\");\n\n AddParameter(ParameterType_Float, \"transform.type.rotation.angle\", \"Rotation angle\");\n SetParameterDescription(\"transform.type.rotation.angle\",\"The rotation angle in degree (values between -180 and 180)\");\n SetDefaultParameterFloat(\"transform.type.rotation.angle\",0.);\n\n AddParameter(ParameterType_Float, \"transform.type.rotation.scalex\", \"X factor\");\n SetParameterDescription(\"transform.type.rotation.scalex\",\"X factor\");\n SetDefaultParameterFloat(\"transform.type.rotation.scalex\",1.);\n\n AddParameter(ParameterType_Float, \"transform.type.rotation.scaley\", \"Y factor\");\n SetParameterDescription(\"transform.type.rotation.scaley\",\"Y factor\");\n SetDefaultParameterFloat(\"transform.type.rotation.scaley\",1.);\n\n \/\/ Interpolators\n AddParameter(ParameterType_Choice, \"interpolator\", \"Interpolation\");\n SetParameterDescription(\"interpolator\",\"This group of parameters allows to define how the input image will be interpolated during resampling.\");\n AddChoice(\"interpolator.nn\", \"Nearest Neighbor interpolation\");\n SetParameterDescription(\"interpolator.nn\",\"Nearest neighbor interpolation leads to poor image quality, but it is very fast.\");\n AddChoice(\"interpolator.linear\", \"Linear interpolation\");\n SetParameterDescription(\"interpolator.linear\",\"Linear interpolation leads to average image quality but is quite fast\");\n AddChoice(\"interpolator.bco\", \"Bicubic interpolation\");\n AddParameter(ParameterType_Radius, \"interpolator.bco.radius\", \"Radius for bicubic interpolation\");\n SetParameterDescription(\"interpolator.bco.radius\",\"This parameter allows to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.\");\n SetDefaultParameterInt(\"interpolator.bco.radius\", 2);\n SetParameterString(\"interpolator\",\"bco\");\n\n \/\/ RAM available\n AddRAMParameter(\"ram\");\n SetParameterDescription(\"ram\",\"This allows to set the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities)\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"qb_toulouse_sub.tif\");\n SetDocExampleParameterValue(\"out\", \"rigitTransformImage.tif\");\n SetDocExampleParameterValue(\"transform.type\", \"rotation\");\n SetDocExampleParameterValue(\"transform.type.scalex\", \"4.\");\n SetDocExampleParameterValue(\"transform.type.scaley\", \"4.\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n FloatVectorImageType* inputImage = GetParameterImage(\"in\");\n\n m_Resampler = ResampleFilterType::New();\n m_Resampler->SetInput(inputImage);\n\n \/\/ Get Interpolator\n switch ( GetParameterInt(\"interpolator\") )\n {\n case Interpolator_Linear:\n {\n typedef itk::LinearInterpolateImageFunction LinearInterpolationType;\n LinearInterpolationType::Pointer interpolator = LinearInterpolationType::New();\n m_Resampler->SetInterpolator(interpolator);\n }\n break;\n case Interpolator_NNeighbor:\n {\n typedef itk::NearestNeighborInterpolateImageFunction NearestNeighborInterpolationType;\n NearestNeighborInterpolationType::Pointer interpolator = NearestNeighborInterpolationType::New();\n m_Resampler->SetInterpolator(interpolator);\n }\n break;\n case Interpolator_BCO:\n {\n typedef otb::BCOInterpolateImageFunction BCOInterpolationType;\n BCOInterpolationType::Pointer interpolator = BCOInterpolationType::New();\n interpolator->SetRadius(GetParameterInt(\"interpolator.bco.radius\"));\n m_Resampler->SetInterpolator(interpolator);\n }\n break;\n }\n\n \/\/ Get Transform\n switch ( GetParameterInt(\"transform.type\") )\n {\n case Transform_Identity:\n {\n IdentityTransformType::Pointer transform = IdentityTransformType::New();\n\n \/\/ Scale Transform\n OutputVectorType scale;\n scale[0] = 1.0 \/ GetParameterFloat(\"transform.type.id.scalex\");\n scale[1] = 1.0 \/ GetParameterFloat(\"transform.type.id.scaley\");\n\n \/\/ Evaluate spacing\n FloatVectorImageType::SpacingType spacing = inputImage->GetSpacing();\n FloatVectorImageType::SpacingType OutputSpacing;\n OutputSpacing=spacing;\n\n \/\/FIXME Find a way to update the output image spacing after resampling\n OutputSpacing[0] = spacing[0] * scale[0];\n OutputSpacing[1] = spacing[1] * scale[1];\n\n m_Resampler->SetOutputSpacing(OutputSpacing);\n m_Resampler->SetTransform(transform);\n\n \/\/ Evaluate size\n ResampleFilterType::SizeType recomputedSize;\n recomputedSize[0] = inputImage->GetLargestPossibleRegion().GetSize()[0] \/ scale[0];\n recomputedSize[1] = inputImage->GetLargestPossibleRegion().GetSize()[1] \/ scale[1];\n\n m_Resampler->SetOutputSize(recomputedSize);\n otbAppLogINFO( << \"Output image size : \" << recomputedSize );\n }\n break;\n\n case Transform_Translation:\n {\n TransformType::Pointer transform = TransformType::New();\n TransformType::OutputVectorType offset;\n offset[0] = GetParameterFloat(\"transform.type.translation.tx\");\n offset[1] = GetParameterFloat(\"transform.type.translation.ty\");\n otbAppLogINFO( << \"Offset : \" << offset );\n transform->SetOffset(offset);\n m_Resampler->SetTransform(transform);\n m_Resampler->SetOutputParametersFromImage(inputImage);\n }\n break;\n\n case Transform_Rotation:\n {\n ScalableTransformType::Pointer transform = ScalableTransformType::New();\n\n FloatVectorImageType::IndexType origin = inputImage->GetLargestPossibleRegion().GetIndex();\n FloatVectorImageType::SpacingType spacing = inputImage->GetSpacing();\n\n FloatVectorImageType::IndexType center;\n center[0] = origin[0] + inputImage->GetLargestPossibleRegion().GetSize()[0] \/ 2.0;\n center[1] = origin[1] + inputImage->GetLargestPossibleRegion().GetSize()[1] \/ 2.0;\n\n\n FloatVectorImageType::PointType centerPoint;\n inputImage->TransformIndexToPhysicalPoint(center, centerPoint);\n\n \/\/image boundary\n FloatVectorImageType::IndexType ULindex, URindex, LRindex, LLindex;\n\n ULindex[0]=origin[0];\n ULindex[1]=origin[1];\n URindex[0]=origin[0]+ inputImage->GetLargestPossibleRegion().GetSize()[0];\n URindex[1]=origin[1];\n LRindex[0]=origin[0]+ inputImage->GetLargestPossibleRegion().GetSize()[0];\n LRindex[1]=origin[1]+ inputImage->GetLargestPossibleRegion().GetSize()[1];\n LLindex[0]=origin[0];\n LLindex[1]=origin[1]+ inputImage->GetLargestPossibleRegion().GetSize()[1];\n\n FloatVectorImageType::PointType orig, ULpoint, URpoint, LRpoint, LLpoint;\n inputImage->TransformIndexToPhysicalPoint(ULindex, ULpoint);\n inputImage->TransformIndexToPhysicalPoint(URindex, URpoint);\n inputImage->TransformIndexToPhysicalPoint(LRindex, LRpoint);\n inputImage->TransformIndexToPhysicalPoint(LLindex, LLpoint);\n\n \/\/ Scale Transform\n OutputVectorType scale;\n scale[0] = 1.0 \/ GetParameterFloat(\"transform.type.rotation.scalex\");\n scale[1] = 1.0 \/ GetParameterFloat(\"transform.type.rotation.scaley\");\n\n \/\/angle of rotation\n ScalarType rot_angle = GetParameterFloat(\"transform.type.rotation.angle\");\n if (rot_angle < -180 || rot_angle > 180)\n {\n itkExceptionMacro(<<\"The rotation angle must value be between -180 and 180.\");\n }\n\n transform->SetIdentity();\n if(spacing[0] > 0 && spacing[1] > 0) transform->Rotate2D( rot_angle * CONST_PI_180 );\n else transform->Rotate2D( - rot_angle * CONST_PI_180 );\n\n transform->SetCenter( centerPoint );\n transform->Scale( scale );\n\n \/\/inverse transform\n ScalableTransformType::Pointer inverseTransform = ScalableTransformType::New();\n transform->GetInverse(inverseTransform);\n m_Resampler->SetTransform(transform);\n\n\n FloatVectorImageType::PointType ULpointTrans, URpointTrans, LRpointTrans, LLpointTrans, CenterPointTrans;\n\n ULpointTrans=inverseTransform->TransformPoint(ULpoint);\n URpointTrans=inverseTransform->TransformPoint(URpoint);\n LRpointTrans=inverseTransform->TransformPoint(LRpoint);\n LLpointTrans=inverseTransform->TransformPoint(LLpoint);\n CenterPointTrans=inverseTransform->TransformPoint(centerPoint);\n\n \/\/compute min and max\n std::vector voutput;\n voutput.push_back(ULpointTrans);\n voutput.push_back(URpointTrans);\n voutput.push_back(LRpointTrans);\n voutput.push_back(LLpointTrans);\n\n double minX = voutput[0][0];\n double maxX = voutput[0][0];\n double minY = voutput[0][1];\n double maxY = voutput[0][1];\n\n for(unsigned int i = 0; i voutput[i][0] )\n {\n minX = voutput[i][0];\n }\n if ( minY > voutput[i][1] )\n {\n minY = voutput[i][1];\n }\n\n \/\/ Sizes\n if ( maxX < voutput[i][0] )\n {\n maxX = voutput[i][0];\n }\n if ( maxY < voutput[i][1] )\n {\n maxY = voutput[i][1];\n }\n }\n\n if( spacing[0] > 0 ) orig[0] = minX;\n else orig[0] = maxX;\n\n if( spacing[1] > 0 ) orig[1] = minY;\n else orig[1] = maxY;\n\n m_Resampler->SetOutputOrigin(orig);\n\n \/\/size of output image\n ResampleFilterType::SizeType size;\n size[0]=vcl_abs(maxX-minX);\n size[1]=vcl_abs(maxY-minY);\n\n \/\/ Evaluate spacing\n FloatVectorImageType::SpacingType OutputSpacing;\n OutputSpacing=spacing;\n\n \/\/FIXME Find a way to update the output image spacing after resampling\n \/\/OutputSpacing[0] = scale[0] * spacing[0];\n \/\/OutputSpacing[1] = scale[1] * spacing[1];\n\n m_Resampler->SetOutputSpacing(OutputSpacing);\n\n \/\/ Evaluate size\n ResampleFilterType::SizeType recomputedSize;\n recomputedSize[0] = static_cast(vcl_floor(vcl_abs(size[0]\/OutputSpacing[0])));\n recomputedSize[1] = static_cast(vcl_floor(vcl_abs(size[1]\/OutputSpacing[1])));\n m_Resampler->SetOutputSize( recomputedSize );\n otbAppLogINFO( << \"Output image size : \" << recomputedSize );\n }\n break;\n }\n\n FloatVectorImageType::PixelType defaultValue;\n itk::PixelBuilder::Zero(defaultValue,\n inputImage->GetNumberOfComponentsPerPixel());\n m_Resampler->SetEdgePaddingValue(defaultValue);\n\n m_Resampler->UpdateOutputInformation();\n \/\/ Output Image\n SetParameterOutputImage(\"out\", m_Resampler->GetOutput());\n }\n\n ResampleFilterType::Pointer m_Resampler;\n}; \/\/class\n\n\n} \/\/namespace wrapper\n} \/\/namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::RigidTransformResample)\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\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ THIS EXAMPLE MUST BE BUILT WITH A VERSION\n\/\/ OF GASNET CONFIGURED WITH MPI COMPATIBILITY\n\/\/\n\/\/ NOTE THAT GASNET ONLY SUPPORTS MPI-COMPATIBILITY\n\/\/ ON SOME CONDUITS. CURRENTLY THESE ARE IBV, GEMINI,\n\/\/ ARIES, MXM, and OFI. IF YOU WOULD LIKE ADDITIONAL\n\/\/ CONDUITS SUPPORTED PLEASE CONTACT THE MAINTAINERS\n\/\/ OF GASNET.\n\/\/\n\/\/ Note: there is a way to use this example with the\n\/\/ MPI conduit, but you have to have a version of \n\/\/ MPI that supports MPI_THREAD_MULTIPLE. See the \n\/\/ macro GASNET_CONDUIT_MPI below.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\/\/ Need MPI header file\n#include \n\n#include \"legion.h\"\n\nusing namespace Legion;\n\nenum TaskID\n{\n TOP_LEVEL_TASK_ID,\n MPI_INTEROP_TASK_ID,\n WORKER_TASK_ID,\n};\n\n\/\/ Here is our global MPI-Legion handshake\n\/\/ You can have as many of these as you \n\/\/ want but the common case is just to\n\/\/ have one per Legion-MPI rank pair\nMPILegionHandshake handshake;\n\n\/\/ Have a global static number of iterations for\n\/\/ this example, but you can easily configure it\n\/\/ from command line arguments which get passed \n\/\/ to both MPI and Legion\nconst int total_iterations = 10;\n\nvoid worker_task(const Task *task, \n const std::vector ®ions,\n Context ctx, Runtime *runtime)\n{\n printf(\"Legion Doing Work in Rank %lld\\n\", \n task->parent_task->index_point[0]);\n}\n\nvoid mpi_interop_task(const Task *task, \n const std::vector ®ions,\n Context ctx, Runtime *runtime)\n{\n printf(\"Hello from Legion MPI-Interop Task %lld\\n\", task->index_point[0]);\n for (int i = 0; i < total_iterations; i++)\n {\n \/\/ Legion can interop with MPI in blocking and non-blocking\n \/\/ ways. You can use the calls to 'legion_wait_on_mpi' and\n \/\/ 'legion_handoff_to_mpi' in the same way as the MPI thread\n \/\/ does. Alternatively, you can get a phase barrier associated\n \/\/ with a LegionMPIHandshake object which will allow you to\n \/\/ continue launching more sub-tasks without blocking. \n \/\/ For deferred execution we prefer the later style, but\n \/\/ both will work correctly.\n if (i < (total_iterations\/2))\n {\n \/\/ This is the blocking way of using handshakes, it\n \/\/ is not the ideal way, but it works correctly\n \/\/ Wait for MPI to give us control to run our worker\n \/\/ This is a blocking call\n handshake.legion_wait_on_mpi();\n \/\/ Launch our worker task\n TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0));\n Future f = runtime->execute_task(ctx, worker_launcher);\n \/\/ Have to wait for the result before signaling MPI\n f.get_void_result();\n \/\/ Perform a non-blocking call to signal\n \/\/ MPI that we are giving it control back\n handshake.legion_handoff_to_mpi();\n }\n else\n {\n \/\/ This is the preferred way of using handshakes in Legion\n TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0));\n \/\/ We can user our handshake as a phase barrier\n \/\/ Record that we will wait on this handshake\n worker_launcher.add_wait_handshake(handshake);\n \/\/ Advance the handshake to the next version\n handshake.advance_legion_handshake();\n \/\/ Then record that we will arrive on this versions\n worker_launcher.add_arrival_handshake(handshake);\n \/\/ Launch our worker task\n \/\/ No need to wait for anything\n runtime->execute_task(ctx, worker_launcher);\n }\n }\n}\n\nvoid top_level_task(const Task *task, \n const std::vector ®ions,\n Context ctx, Runtime *runtime)\n{\n printf(\"Hello from Legion Top-Level Task\\n\");\n \/\/ Both the application and Legion mappers have access to\n \/\/ the mappings between MPI Ranks and Legion address spaces\n \/\/ The reverse mapping goes the other way\n const std::map &forward_mapping = \n runtime->find_forward_MPI_mapping();\n for (std::map::const_iterator it = \n forward_mapping.begin(); it != forward_mapping.end(); it++)\n printf(\"MPI Rank %d maps to Legion Address Space %d\\n\", \n it->first, it->second);\n\n int rank = -1, size = -1;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n \/\/ Do a must epoch launch to align with the number of MPI ranks\n MustEpochLauncher must_epoch_launcher;\n Rect<1> launch_bounds(Point<1>(0),Point<1>(size - 1));\n Domain launch_domain = Domain::from_rect<1>(launch_bounds);\n ArgumentMap args_map;\n IndexLauncher index_launcher(MPI_INTEROP_TASK_ID, launch_domain, \n TaskArgument(NULL, 0), args_map);\n must_epoch_launcher.add_index_task(index_launcher);\n runtime->execute_must_epoch(ctx, must_epoch_launcher);\n}\n\nint main(int argc, char **argv)\n{\n#ifdef GASNET_CONDUIT_MPI\n \/\/ The GASNet MPI conduit requires special start-up\n \/\/ in order to handle MPI calls from multiple threads\n int provided;\n MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n \/\/ If you fail this assertion, then your version of MPI\n \/\/ does not support calls from multiple threads and you \n \/\/ cannot use the GASNet MPI conduit\n if (provided != MPI_THREAD_MULTIPLE)\n printf(\"ERROR: MPI_THREAD_MULTIPLE not supported!\\n\");\n assert(provided == MPI_THREAD_MULTIPLE);\n#else\n \/\/ Perform MPI start-up like normal for most GASNet conduits\n MPI_Init(&argc, &argv);\n#endif\n\n int rank = -1, size = -1;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n printf(\"Hello from MPI process %d of %d\\n\", rank, size);\n\n \/\/ Configure the Legion runtime with the rank of this process\n Runtime::configure_MPI_interoperability(rank);\n \/\/ Register our task variants\n {\n TaskVariantRegistrar top_level_registrar(TOP_LEVEL_TASK_ID);\n top_level_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));\n Runtime::preregister_task_variant(top_level_registrar, \n \"Top Level Task\");\n Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID);\n }\n {\n TaskVariantRegistrar mpi_interop_registrar(MPI_INTEROP_TASK_ID);\n mpi_interop_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));\n Runtime::preregister_task_variant(mpi_interop_registrar,\n \"MPI Interop Task\");\n }\n {\n TaskVariantRegistrar worker_task_registrar(WORKER_TASK_ID);\n worker_task_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));\n Runtime::preregister_task_variant(worker_task_registrar,\n \"Worker Task\");\n }\n \/\/ Create a handshake for passing control between Legion and MPI\n \/\/ Indicate that MPI has initial control and that there is one\n \/\/ participant on each side\n handshake = Runtime::create_handshake(true\/*MPI initial control*\/,\n 1\/*MPI participants*\/,\n 1\/*Legion participants*\/);\n \/\/ Start the Legion runtime in background mode\n \/\/ This call will return immediately\n Runtime::start(argc, argv, true\/*background*\/);\n \/\/ Run your MPI program like normal\n \/\/ If you want strict bulk-synchronous execution include\n \/\/ the barriers protected by this variable, otherwise\n \/\/ you can elide them, they are not required for correctness\n const bool strict_bulk_synchronous_execution = true;\n for (int i = 0; i < total_iterations; i++)\n {\n printf(\"MPI Doing Work on rank %d\\n\", rank);\n if (strict_bulk_synchronous_execution)\n MPI_Barrier(MPI_COMM_WORLD);\n \/\/ Perform a handoff to Legion, this call is\n \/\/ asynchronous and will return immediately\n handshake.mpi_handoff_to_legion();\n \/\/ You can put additional work in here if you like\n \/\/ but it may interfere with Legion work\n\n \/\/ Wait for Legion to hand control back,\n \/\/ This call will block until a Legion task\n \/\/ running in this same process hands control back\n handshake.mpi_wait_on_legion();\n if (strict_bulk_synchronous_execution)\n MPI_Barrier(MPI_COMM_WORLD);\n }\n \/\/ When you're done wait for the Legion runtime to shutdown\n Runtime::wait_for_shutdown();\n#ifndef GASNET_CONDUIT_MPI\n \/\/ Then finalize MPI like normal\n \/\/ Exception for the MPI conduit which does its own finalization\n MPI_Finalize();\n#endif\n\n return 0;\n}\nexamples: more tweaks to mpi interop example\/* 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\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ THIS EXAMPLE MUST BE BUILT WITH A VERSION\n\/\/ OF GASNET CONFIGURED WITH MPI COMPATIBILITY\n\/\/\n\/\/ NOTE THAT GASNET ONLY SUPPORTS MPI-COMPATIBILITY\n\/\/ ON SOME CONDUITS. CURRENTLY THESE ARE IBV, GEMINI,\n\/\/ ARIES, MXM, and OFI. IF YOU WOULD LIKE ADDITIONAL\n\/\/ CONDUITS SUPPORTED PLEASE CONTACT THE MAINTAINERS\n\/\/ OF GASNET.\n\/\/\n\/\/ Note: there is a way to use this example with the\n\/\/ MPI conduit, but you have to have a version of \n\/\/ MPI that supports MPI_THREAD_MULTIPLE. See the \n\/\/ macro GASNET_CONDUIT_MPI below.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\/\/ Need MPI header file\n#include \n\n#include \"legion.h\"\n\nusing namespace Legion;\n\nenum TaskID\n{\n TOP_LEVEL_TASK_ID,\n MPI_INTEROP_TASK_ID,\n WORKER_TASK_ID,\n};\n\n\/\/ Here is our global MPI-Legion handshake\n\/\/ You can have as many of these as you \n\/\/ want but the common case is just to\n\/\/ have one per Legion-MPI rank pair\nMPILegionHandshake handshake;\n\n\/\/ Have a global static number of iterations for\n\/\/ this example, but you can easily configure it\n\/\/ from command line arguments which get passed \n\/\/ to both MPI and Legion\nconst int total_iterations = 10;\n\nvoid worker_task(const Task *task, \n const std::vector ®ions,\n Context ctx, Runtime *runtime)\n{\n printf(\"Legion Doing Work in Rank %lld\\n\", \n task->parent_task->index_point[0]);\n}\n\nvoid mpi_interop_task(const Task *task, \n const std::vector ®ions,\n Context ctx, Runtime *runtime)\n{\n printf(\"Hello from Legion MPI-Interop Task %lld\\n\", task->index_point[0]);\n for (int i = 0; i < total_iterations; i++)\n {\n \/\/ Legion can interop with MPI in blocking and non-blocking\n \/\/ ways. You can use the calls to 'legion_wait_on_mpi' and\n \/\/ 'legion_handoff_to_mpi' in the same way as the MPI thread\n \/\/ does. Alternatively, you can get a phase barrier associated\n \/\/ with a LegionMPIHandshake object which will allow you to\n \/\/ continue launching more sub-tasks without blocking. \n \/\/ For deferred execution we prefer the later style, but\n \/\/ both will work correctly.\n if (i < (total_iterations\/2))\n {\n \/\/ This is the blocking way of using handshakes, it\n \/\/ is not the ideal way, but it works correctly\n \/\/ Wait for MPI to give us control to run our worker\n \/\/ This is a blocking call\n handshake.legion_wait_on_mpi();\n \/\/ Launch our worker task\n TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0));\n Future f = runtime->execute_task(ctx, worker_launcher);\n \/\/ Have to wait for the result before signaling MPI\n f.get_void_result();\n \/\/ Perform a non-blocking call to signal\n \/\/ MPI that we are giving it control back\n handshake.legion_handoff_to_mpi();\n }\n else\n {\n \/\/ This is the preferred way of using handshakes in Legion\n TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0));\n \/\/ We can user our handshake as a phase barrier\n \/\/ Record that we will wait on this handshake\n worker_launcher.add_wait_handshake(handshake);\n \/\/ Advance the handshake to the next version\n handshake.advance_legion_handshake();\n \/\/ Then record that we will arrive on this versions\n worker_launcher.add_arrival_handshake(handshake);\n \/\/ Launch our worker task\n \/\/ No need to wait for anything\n runtime->execute_task(ctx, worker_launcher);\n }\n }\n}\n\nvoid top_level_task(const Task *task, \n const std::vector ®ions,\n Context ctx, Runtime *runtime)\n{\n printf(\"Hello from Legion Top-Level Task\\n\");\n \/\/ Both the application and Legion mappers have access to\n \/\/ the mappings between MPI Ranks and Legion address spaces\n \/\/ The reverse mapping goes the other way\n const std::map &forward_mapping = \n runtime->find_forward_MPI_mapping();\n for (std::map::const_iterator it = \n forward_mapping.begin(); it != forward_mapping.end(); it++)\n printf(\"MPI Rank %d maps to Legion Address Space %d\\n\", \n it->first, it->second);\n\n int rank = -1, size = -1;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n \/\/ Do a must epoch launch to align with the number of MPI ranks\n MustEpochLauncher must_epoch_launcher;\n Rect<1> launch_bounds(Point<1>(0),Point<1>(size - 1));\n Domain launch_domain = Domain::from_rect<1>(launch_bounds);\n ArgumentMap args_map;\n IndexLauncher index_launcher(MPI_INTEROP_TASK_ID, launch_domain, \n TaskArgument(NULL, 0), args_map);\n must_epoch_launcher.add_index_task(index_launcher);\n runtime->execute_must_epoch(ctx, must_epoch_launcher);\n}\n\nint main(int argc, char **argv)\n{\n#ifdef GASNET_CONDUIT_MPI\n \/\/ The GASNet MPI conduit requires special start-up\n \/\/ in order to handle MPI calls from multiple threads\n int provided;\n MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n \/\/ If you fail this assertion, then your version of MPI\n \/\/ does not support calls from multiple threads and you \n \/\/ cannot use the GASNet MPI conduit\n if (provided < MPI_THREAD_MULTIPLE)\n printf(\"ERROR: Your implementation of MPI does not support \"\n \"MPI_THREAD_MULTIPLE which is required for use of the \"\n \"GASNet MPI conduit with the Legion-MPI Interop!\\n\");\n assert(provided == MPI_THREAD_MULTIPLE);\n#else\n \/\/ Perform MPI start-up like normal for most GASNet conduits\n MPI_Init(&argc, &argv);\n#endif\n\n int rank = -1, size = -1;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n printf(\"Hello from MPI process %d of %d\\n\", rank, size);\n\n \/\/ Configure the Legion runtime with the rank of this process\n Runtime::configure_MPI_interoperability(rank);\n \/\/ Register our task variants\n {\n TaskVariantRegistrar top_level_registrar(TOP_LEVEL_TASK_ID);\n top_level_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));\n Runtime::preregister_task_variant(top_level_registrar, \n \"Top Level Task\");\n Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID);\n }\n {\n TaskVariantRegistrar mpi_interop_registrar(MPI_INTEROP_TASK_ID);\n mpi_interop_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));\n Runtime::preregister_task_variant(mpi_interop_registrar,\n \"MPI Interop Task\");\n }\n {\n TaskVariantRegistrar worker_task_registrar(WORKER_TASK_ID);\n worker_task_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));\n Runtime::preregister_task_variant(worker_task_registrar,\n \"Worker Task\");\n }\n \/\/ Create a handshake for passing control between Legion and MPI\n \/\/ Indicate that MPI has initial control and that there is one\n \/\/ participant on each side\n handshake = Runtime::create_handshake(true\/*MPI initial control*\/,\n 1\/*MPI participants*\/,\n 1\/*Legion participants*\/);\n \/\/ Start the Legion runtime in background mode\n \/\/ This call will return immediately\n Runtime::start(argc, argv, true\/*background*\/);\n \/\/ Run your MPI program like normal\n \/\/ If you want strict bulk-synchronous execution include\n \/\/ the barriers protected by this variable, otherwise\n \/\/ you can elide them, they are not required for correctness\n const bool strict_bulk_synchronous_execution = true;\n for (int i = 0; i < total_iterations; i++)\n {\n printf(\"MPI Doing Work on rank %d\\n\", rank);\n if (strict_bulk_synchronous_execution)\n MPI_Barrier(MPI_COMM_WORLD);\n \/\/ Perform a handoff to Legion, this call is\n \/\/ asynchronous and will return immediately\n handshake.mpi_handoff_to_legion();\n \/\/ You can put additional work in here if you like\n \/\/ but it may interfere with Legion work\n\n \/\/ Wait for Legion to hand control back,\n \/\/ This call will block until a Legion task\n \/\/ running in this same process hands control back\n handshake.mpi_wait_on_legion();\n if (strict_bulk_synchronous_execution)\n MPI_Barrier(MPI_COMM_WORLD);\n }\n \/\/ When you're done wait for the Legion runtime to shutdown\n Runtime::wait_for_shutdown();\n#ifndef GASNET_CONDUIT_MPI\n \/\/ Then finalize MPI like normal\n \/\/ Exception for the MPI conduit which does its own finalization\n MPI_Finalize();\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts, clang::LangAS::Map& address_spaces) {\n\n clang::CompilerInstance c;\n clang::CompilerInvocation invocation;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw invalid_option_error();\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n c.getPreprocessorOpts().addMacroDef(\"cl_khr_fp64\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n \/\/ Get address spaces map to be able to find kernel argument address space\n memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), \n sizeof(address_spaces));\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n \/\/ This means there are no kernels in the program. The spec does not\n \/\/ require that we return an error here, but there will be an error if\n \/\/ the user tries to pass this program to a clCreateKernel() call.\n if (!kernel_node) {\n return;\n }\n\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n link(llvm::Module *mod, const std::string &triple,\n const std::string &processor,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n llvm::PassManagerBuilder Builder;\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n \/\/ Link the kernel with libclc\n#if HAVE_LLVM < 0x0303\n bool isNative;\n llvm::Linker linker(\"clover\", mod);\n linker.LinkInFile(llvm::sys::Path(libclc_path), isNative);\n mod = linker.releaseModule();\n#else\n std::string err_str;\n llvm::SMDiagnostic err;\n llvm::Module *libclc_mod = llvm::ParseIRFile(libclc_path, err,\n mod->getContext());\n if (llvm::Linker::LinkModules(mod, libclc_mod,\n llvm::Linker::DestroySource,\n &err_str)) {\n throw build_error(err_str);\n }\n#endif\n\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n\n \/\/ Run link time optimizations\n Builder.OptLevel = 2;\n Builder.populateLTOPassManager(PM, false, true);\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels,\n clang::LangAS::Map& address_spaces) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#else\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#endif\n\n llvm::Type *arg_type = arg.getType();\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n llvm::Type *target_type = arg_type->isIntegerTy() ?\n TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) :\n arg_type;\n unsigned target_size = TD.getTypeStoreSize(target_type);\n unsigned target_align = TD.getABITypeAlignment(target_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n if (address_space == address_spaces[clang::LangAS::opencl_local\n - clang::LangAS::Offset]) {\n args.push_back(module::argument(module::argument::local,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n } else {\n \/\/ XXX: Correctly handle constant address space. There is no\n \/\/ way for r600g to pass a handle for constant buffers back\n \/\/ to clover like it can for global buffers, so\n \/\/ creating constant arguements will break r600g. For now,\n \/\/ continue treating constant buffers as global buffers\n \/\/ until we can come up with a way to create handles for\n \/\/ constant buffers.\n args.push_back(module::argument(module::argument::global,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n }\n\n } else {\n llvm::AttributeSet attrs = kernel_func->getAttributes();\n enum module::argument::ext_type ext_type =\n (attrs.hasAttribute(arg.getArgNo() + 1,\n llvm::Attribute::SExt) ?\n module::argument::sign_ext :\n module::argument::zero_ext);\n\n args.push_back(\n module::argument(module::argument::scalar, arg_size,\n target_size, target_align, ext_type));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n clang::LangAS::Map address_spaces;\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts,\n address_spaces);\n\n find_kernels(mod, kernels);\n\n link(mod, triple, processor, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels, address_spaces);\n }\n}\nclover: fix building with llvm-3.4 since rev191922\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts, clang::LangAS::Map& address_spaces) {\n\n clang::CompilerInstance c;\n clang::CompilerInvocation invocation;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw invalid_option_error();\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n c.getPreprocessorOpts().addMacroDef(\"cl_khr_fp64\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n \/\/ Get address spaces map to be able to find kernel argument address space\n memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), \n sizeof(address_spaces));\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n \/\/ This means there are no kernels in the program. The spec does not\n \/\/ require that we return an error here, but there will be an error if\n \/\/ the user tries to pass this program to a clCreateKernel() call.\n if (!kernel_node) {\n return;\n }\n\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n link(llvm::Module *mod, const std::string &triple,\n const std::string &processor,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n llvm::PassManagerBuilder Builder;\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n \/\/ Link the kernel with libclc\n#if HAVE_LLVM < 0x0303\n bool isNative;\n llvm::Linker linker(\"clover\", mod);\n linker.LinkInFile(llvm::sys::Path(libclc_path), isNative);\n mod = linker.releaseModule();\n#else\n std::string err_str;\n llvm::SMDiagnostic err;\n llvm::Module *libclc_mod = llvm::ParseIRFile(libclc_path, err,\n mod->getContext());\n if (llvm::Linker::LinkModules(mod, libclc_mod,\n llvm::Linker::DestroySource,\n &err_str)) {\n throw build_error(err_str);\n }\n#endif\n\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n#if HAVE_LLVM < 0x0304\n PM.add(llvm::createInternalizePass(export_list));\n#else\n std::vector dso_list;\n PM.add(llvm::createInternalizePass(export_list, dso_list));\n#endif\n \/\/ Run link time optimizations\n Builder.OptLevel = 2;\n Builder.populateLTOPassManager(PM, false, true);\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels,\n clang::LangAS::Map& address_spaces) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#else\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#endif\n\n llvm::Type *arg_type = arg.getType();\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n llvm::Type *target_type = arg_type->isIntegerTy() ?\n TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) :\n arg_type;\n unsigned target_size = TD.getTypeStoreSize(target_type);\n unsigned target_align = TD.getABITypeAlignment(target_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n if (address_space == address_spaces[clang::LangAS::opencl_local\n - clang::LangAS::Offset]) {\n args.push_back(module::argument(module::argument::local,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n } else {\n \/\/ XXX: Correctly handle constant address space. There is no\n \/\/ way for r600g to pass a handle for constant buffers back\n \/\/ to clover like it can for global buffers, so\n \/\/ creating constant arguements will break r600g. For now,\n \/\/ continue treating constant buffers as global buffers\n \/\/ until we can come up with a way to create handles for\n \/\/ constant buffers.\n args.push_back(module::argument(module::argument::global,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n }\n\n } else {\n llvm::AttributeSet attrs = kernel_func->getAttributes();\n enum module::argument::ext_type ext_type =\n (attrs.hasAttribute(arg.getArgNo() + 1,\n llvm::Attribute::SExt) ?\n module::argument::sign_ext :\n module::argument::zero_ext);\n\n args.push_back(\n module::argument(module::argument::scalar, arg_size,\n target_size, target_align, ext_type));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n clang::LangAS::Map address_spaces;\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts,\n address_spaces);\n\n find_kernels(mod, kernels);\n\n link(mod, triple, processor, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels, address_spaces);\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbDSFuzzyModelEstimation.h\"\n\n#include \n#include \"otbCommandLineArgumentParser.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n\n#include \"otbVectorData.h\"\n#include \"otbVectorDataFileReader.h\"\n#include \"otbImageToEnvelopeVectorDataFilter.h\"\n#include \"otbVectorDataToRandomLineGenerator.h\"\n\n#include \"otbVectorDataProjectionFilter.h\" \/\/Envelope TO WGS84 (OSM friendly)\n#include \"otbVectorDataIntoImageProjectionFilter.h\" \/\/WGS84 to index\n\n#include \"otbVectorDataToRoadDescriptionFilter.h\"\n#include \"otbVectorDataToDSValidatedVectorDataFilter.h\"\n\n#include \"itkAmoebaOptimizer.h\"\n#include \"otbStandardDSCostFunction.h\"\n\n#include \"otbFuzzyDescriptorsModelManager.h\"\n\n\n\/\/ The following piece of code implements an observer\n\/\/ that will monitor the evolution of the registration process.\n#include \"itkCommand.h\"\nclass CommandIterationUpdate : public itk::Command\n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() {};\npublic:\n typedef itk::AmoebaOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer =\n dynamic_cast< OptimizerPointer >( object );\n if( ! itk::IterationEvent().CheckEvent( &event ) )\n {\n return;\n }\n std::cout << optimizer->GetCachedValue() << \" \";\n std::cout << optimizer->GetCachedCurrentPosition() << std::endl;\n }\n};\n\n\n\/\/TESTING\n#include \"otbVectorDataFileWriter.h\"\n\n\n\/\/namespace otb\n\/\/{\n\nint otb::DSFuzzyModelEstimation::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"DSFuzzyModelEstimation\");\n descriptor->SetDescription(\"Estimate feature fuzzy model parameters using an image and an VectorData\");\n descriptor->AddOption(\"InputImage\", \"Support to estimate the models on\",\n \"in\", 1, true, ApplicationDescriptor::InputImage);\n descriptor->AddOption(\"InputVectorData\", \"Ground Truth Vector Data\",\n \"vdin\", 1, true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"Hypothesis\", \"Dempster Shafer study hypothesis\",\n \"hyp\", 2, false, ApplicationDescriptor::StringList);\n \/\/descriptor->AddOption(\"Criterion\", \"Dempster Shafer Criterion (by default (Belief+Plausibility)\/2 >= 0.5))\",\n \/\/ \"cri\", 1, false, ApplicationDescriptor::String);\n descriptor->AddOption(\"weighting\", \"Coefficient between 0 and 1 to promote false detections or undetection (default 0.5)\",\n \"wgt\", 1, false, ApplicationDescriptor::Real);\n descriptor->AddOption(\"MaximumNumberOfIterations\", \"Maximum Number os Optimizer Iteration\",\n \"MaxNbIt\", 1, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"DEMDirectory\", \"DEM directory\",\n \"dem\", 1, false, ApplicationDescriptor::DirectoryName);\n descriptor->AddOption(\"OptimizerObserver\", \"Activate or not the optimizer observer\",\n \"OptObs\", 1, true, ApplicationDescriptor::Integer);\n\n \/\/TESTING PURPOSE\n descriptor->AddOption(\"Output\", \"Output Model File Name\",\n \"out\", 1, true, ApplicationDescriptor::FileName);\n return EXIT_SUCCESS;\n}\n\n\nint otb::DSFuzzyModelEstimation::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n typedef otb::VectorData VectorDataType;\n typedef VectorDataType::ValuePrecisionType PrecisionType;\n typedef VectorDataType::PrecisionType CoordRepType;\n typedef otb::VectorDataFileReader VectorDataReaderType;\n typedef otb::VectorDataToRandomLineGenerator\n RandomGeneratorType;\n\n typedef otb::VectorImage ImageType;\n typedef otb::ImageFileReader ImageReaderType;\n\n typedef otb::ImageToEnvelopeVectorDataFilter\n EnvelopeFilterType;\n\n typedef otb::VectorDataProjectionFilter\n VectorDataProjFilter;\n\n typedef otb::VectorDataIntoImageProjectionFilter\n VectorDataReProjFilter;\n\n typedef otb::VectorDataToRoadDescriptionFilter\n DescriptionFilterType;\n\n typedef otb::VectorDataToDSValidatedVectorDataFilter\n ValidationFilterType;\n\n typedef otb::StandardDSCostFunction\n CostFunctionType;\n typedef CostFunctionType::LabelSetType LabelSetType;\n\n typedef itk::AmoebaOptimizer OptimizerType;\n\n typedef otb::VectorDataFileWriter VectorDataWriterType;\n\n\n \/\/Instantiate\n ImageReaderType::Pointer imgReader = ImageReaderType::New();\n VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();\n EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New();\n RandomGeneratorType::Pointer vdRandomGenerator = RandomGeneratorType::New();\n VectorDataReProjFilter::Pointer vdReProjFilterGT = VectorDataReProjFilter::New();\n VectorDataReProjFilter::Pointer vdReProjFilterRL = VectorDataReProjFilter::New();\n DescriptionFilterType::Pointer descriptionFilterGT = DescriptionFilterType::New();\n DescriptionFilterType::Pointer descriptionFilterNS = DescriptionFilterType::New();\n CostFunctionType::Pointer costFunction = CostFunctionType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n\n VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();\n\n \/\/Read the image\n imgReader->SetFileName(parseResult->GetParameterString(\"InputImage\"));\n imgReader->UpdateOutputInformation();\n\n imgReader->SetGlobalWarningDisplay(0);\n\n \/\/Read the vector data\n vdReader->SetFileName(parseResult->GetParameterString(\"InputVectorData\"));\n vdReader->Update();\n\n \/\/Generate the envelope\n envelopeFilter->SetInput(imgReader->GetOutput()); \/\/->Output in WGS84\n envelopeFilter->Update();\n\n \/\/Generate Random lines\n vdRandomGenerator->SetInput(envelopeFilter->GetOutput());\n vdRandomGenerator->SetNumberOfOutputLine(vdReader->GetOutput()->Size());\n vdRandomGenerator->SetMinLineSize(4);\n vdRandomGenerator->SetMaxLineSize(20);\n\n \/\/Reproject into image index coordinates\n vdReProjFilterGT->SetInputImage(imgReader->GetOutput());\n vdReProjFilterGT->SetInputVectorData(vdReader->GetOutput());\n vdReProjFilterGT->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n vdReProjFilterGT->SetUseOutputSpacingAndOriginFromImage(true);\n vdReProjFilterGT->Update();\n\n vdReProjFilterRL->SetInputImage(imgReader->GetOutput());\n vdReProjFilterRL->SetInputVectorData(vdRandomGenerator->GetOutput());\n vdReProjFilterRL->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n vdReProjFilterRL->SetUseOutputSpacingAndOriginFromImage(true);\n vdReProjFilterRL->Update();\n\n \/\/Add Description to VectorDatas\n descriptionFilterGT->SetInput(vdReProjFilterGT->GetOutput());\n descriptionFilterGT->AddOpticalImage(imgReader->GetOutput());\n descriptionFilterGT->Update();\n descriptionFilterNS->SetInput(vdReProjFilterRL->GetOutput());\n descriptionFilterNS->AddOpticalImage(imgReader->GetOutput());\n descriptionFilterNS->Update();\n\n \/\/Cost Function\n \/\/Format Hypothesis\n LabelSetType hyp;\n if (parseResult->IsOptionPresent(\"Hypothesis\"))\n {\n int NumberOfChannel = parseResult->GetNumberOfParameters(\"Hypothesis\");\n for (int i = 0; i < NumberOfChannel; i++)\n {\n std::string str = parseResult->GetParameterString(\"Hypothesis\", i);\n hyp.insert(str);\n }\n costFunction->SetHypothesis(hyp);\n }\n if (parseResult->IsOptionPresent(\"Weighting\"))\n {\n costFunction->SetWeight(parseResult->GetParameterDouble(\"Weighting\"));\n }\n costFunction->SetGTVectorData(descriptionFilterGT->GetOutput());\n costFunction->SetNSVectorData(descriptionFilterNS->GetOutput());\n\n \/\/Optimizer\n optimizer->SetCostFunction(costFunction);\n if (parseResult->IsOptionPresent(\"MaximumNumberOfIterations\"))\n {\n optimizer->SetMaximumNumberOfIterations(parseResult->GetParameterInt(\"MaximumNumberOfIterations\"));\n }\n else\n {\n optimizer->SetMaximumNumberOfIterations(200);\n }\n\/*\n optimizer->SetParametersConvergenceTolerance( 0.01 );\n optimizer->SetFunctionConvergenceTolerance(0.001);\n*\/\n OptimizerType::ParametersType\n simplexDelta( costFunction->GetNumberOfParameters() );\n simplexDelta.Fill(.25);\n \/*\n simplexDelta.SetElement(0, 0.25);\n simplexDelta.SetElement(1, 0.25);\n simplexDelta.SetElement(2, 0.25);\n simplexDelta.SetElement(3, 0.20);\n simplexDelta.SetElement(4, 0.25);\n simplexDelta.SetElement(5, 0.25);\n simplexDelta.SetElement(6, 0.25);\n simplexDelta.SetElement(7, 0.20);\n *\/\n optimizer->AutomaticInitialSimplexOff();\n optimizer->SetInitialSimplexDelta( simplexDelta );\n\n \/\/optimizer->SetScales()\n\n OptimizerType::ParametersType\n initialPosition( costFunction->GetNumberOfParameters() );\n \/\/initialPosition.Fill(0.25);\n initialPosition.SetElement(0, 0.25);\n initialPosition.SetElement(1, 0.50);\n initialPosition.SetElement(2, 0.75);\n initialPosition.SetElement(3, 0.99);\n initialPosition.SetElement(4, 0.25);\n initialPosition.SetElement(5, 0.50);\n initialPosition.SetElement(6, 0.75);\n initialPosition.SetElement(7, 0.99);\n\n \/\/initialPosition.SetElement();\n optimizer->SetInitialPosition(initialPosition);\n\n \/\/ Create the Command observer and register it with the optimizer.\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n if (parseResult->GetParameterInt(\"OptimizerObserver\"))\n {\n optimizer->AddObserver( itk::IterationEvent(), observer );\n }\n\n try\n {\n \/\/ do the optimization\n optimizer->StartOptimization();\n }\n catch( itk::ExceptionObject& err )\n {\n \/\/ An error has occurred in the optimization.\n \/\/ Update the parameters\n std::cout << \"ERROR: Exception Catched!\" << std::endl;\n std::cout << err.GetDescription() << std::endl;\n const unsigned int numberOfIterations\n = optimizer->GetOptimizer()->get_num_evaluations();\n std::cout << \"numberOfIterations : \" << numberOfIterations << std::endl;\n std::cout << \"Results : \" << optimizer->GetCurrentPosition() << std::endl;\n }\n \/\/ get the results\n const unsigned int numberOfIterations\n = optimizer->GetOptimizer()->get_num_evaluations();\n std::cout << \"numberOfIterations : \" << numberOfIterations << std::endl;\n std::cout << \"Results : \" << optimizer->GetCurrentPosition() << std::endl;\n\n otb::FuzzyDescriptorsModelManager::DescriptorsModelType model;\n otb::FuzzyDescriptorsModelManager::ParameterType ndvi, radiom;\n\n for (unsigned int i = 0; i<4; i++)\n {\n ndvi.push_back(optimizer->GetCurrentPosition()[i]);\n }\n for (unsigned int i = 0; i<4; i++)\n {\n radiom.push_back(optimizer->GetCurrentPosition()[i+4]);\n }\n otb::FuzzyDescriptorsModelManager::AddDescriptor(\"NDVI\", ndvi, model);\n otb::FuzzyDescriptorsModelManager::AddDescriptor(\"RADIOM\", radiom, model);\n otb::FuzzyDescriptorsModelManager::Save(parseResult->GetParameterString(\"Output\"),\n model);\n\n return EXIT_SUCCESS;\n}\n\n\/\/}\n\nREFAC: clean some comments\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbDSFuzzyModelEstimation.h\"\n\n#include \n#include \"otbCommandLineArgumentParser.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n\n#include \"otbVectorData.h\"\n#include \"otbVectorDataFileReader.h\"\n#include \"otbImageToEnvelopeVectorDataFilter.h\"\n#include \"otbVectorDataToRandomLineGenerator.h\"\n\n#include \"otbVectorDataProjectionFilter.h\" \/\/Envelope TO WGS84 (OSM friendly)\n#include \"otbVectorDataIntoImageProjectionFilter.h\" \/\/WGS84 to index\n\n#include \"otbVectorDataToRoadDescriptionFilter.h\"\n#include \"otbVectorDataToDSValidatedVectorDataFilter.h\"\n\n#include \"itkAmoebaOptimizer.h\"\n#include \"otbStandardDSCostFunction.h\"\n\n#include \"otbFuzzyDescriptorsModelManager.h\"\n\n\n\/\/ The following piece of code implements an observer\n\/\/ that will monitor the evolution of the registration process.\n#include \"itkCommand.h\"\nclass CommandIterationUpdate : public itk::Command\n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() {};\npublic:\n typedef itk::AmoebaOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer =\n dynamic_cast< OptimizerPointer >( object );\n if( ! itk::IterationEvent().CheckEvent( &event ) )\n {\n return;\n }\n std::cout << optimizer->GetCachedValue() << \" \";\n std::cout << optimizer->GetCachedCurrentPosition() << std::endl;\n }\n};\n\n\n\/\/TESTING\n#include \"otbVectorDataFileWriter.h\"\n\n\n\/\/namespace otb\n\/\/{\n\nint otb::DSFuzzyModelEstimation::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"DSFuzzyModelEstimation\");\n descriptor->SetDescription(\"Estimate feature fuzzy model parameters using an image and an VectorData\");\n descriptor->AddOption(\"InputImage\", \"Support to estimate the models on\",\n \"in\", 1, true, ApplicationDescriptor::InputImage);\n descriptor->AddOption(\"InputVectorData\", \"Ground Truth Vector Data\",\n \"vdin\", 1, true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"Hypothesis\", \"Dempster Shafer study hypothesis\",\n \"hyp\", 2, false, ApplicationDescriptor::StringList);\n \/\/descriptor->AddOption(\"Criterion\", \"Dempster Shafer Criterion (by default (Belief+Plausibility)\/2 >= 0.5))\",\n \/\/ \"cri\", 1, false, ApplicationDescriptor::String);\n descriptor->AddOption(\"weighting\", \"Coefficient between 0 and 1 to promote false detections or undetection (default 0.5)\",\n \"wgt\", 1, false, ApplicationDescriptor::Real);\n descriptor->AddOption(\"MaximumNumberOfIterations\", \"Maximum Number os Optimizer Iteration\",\n \"MaxNbIt\", 1, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"DEMDirectory\", \"DEM directory\",\n \"dem\", 1, false, ApplicationDescriptor::DirectoryName);\n descriptor->AddOption(\"OptimizerObserver\", \"Activate or not the optimizer observer\",\n \"OptObs\", 1, true, ApplicationDescriptor::Integer);\n\n \/\/TESTING PURPOSE\n descriptor->AddOption(\"Output\", \"Output Model File Name\",\n \"out\", 1, true, ApplicationDescriptor::FileName);\n return EXIT_SUCCESS;\n}\n\n\nint otb::DSFuzzyModelEstimation::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n typedef otb::VectorData VectorDataType;\n typedef VectorDataType::ValuePrecisionType PrecisionType;\n typedef VectorDataType::PrecisionType CoordRepType;\n typedef otb::VectorDataFileReader VectorDataReaderType;\n typedef otb::VectorDataToRandomLineGenerator\n RandomGeneratorType;\n\n typedef otb::VectorImage ImageType;\n typedef otb::ImageFileReader ImageReaderType;\n\n typedef otb::ImageToEnvelopeVectorDataFilter\n EnvelopeFilterType;\n\n typedef otb::VectorDataProjectionFilter\n VectorDataProjFilter;\n\n typedef otb::VectorDataIntoImageProjectionFilter\n VectorDataReProjFilter;\n\n typedef otb::VectorDataToRoadDescriptionFilter\n DescriptionFilterType;\n\n typedef otb::VectorDataToDSValidatedVectorDataFilter\n ValidationFilterType;\n\n typedef otb::StandardDSCostFunction\n CostFunctionType;\n typedef CostFunctionType::LabelSetType LabelSetType;\n\n typedef itk::AmoebaOptimizer OptimizerType;\n\n typedef otb::VectorDataFileWriter VectorDataWriterType;\n\n\n \/\/Instantiate\n ImageReaderType::Pointer imgReader = ImageReaderType::New();\n VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();\n EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New();\n RandomGeneratorType::Pointer vdRandomGenerator = RandomGeneratorType::New();\n VectorDataReProjFilter::Pointer vdReProjFilterGT = VectorDataReProjFilter::New();\n VectorDataReProjFilter::Pointer vdReProjFilterRL = VectorDataReProjFilter::New();\n DescriptionFilterType::Pointer descriptionFilterGT = DescriptionFilterType::New();\n DescriptionFilterType::Pointer descriptionFilterNS = DescriptionFilterType::New();\n CostFunctionType::Pointer costFunction = CostFunctionType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n\n VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();\n\n \/\/Read the image\n imgReader->SetFileName(parseResult->GetParameterString(\"InputImage\"));\n imgReader->UpdateOutputInformation();\n\n imgReader->SetGlobalWarningDisplay(0);\n\n \/\/Read the vector data\n vdReader->SetFileName(parseResult->GetParameterString(\"InputVectorData\"));\n vdReader->Update();\n\n \/\/Generate the envelope\n envelopeFilter->SetInput(imgReader->GetOutput()); \/\/->Output in WGS84\n envelopeFilter->Update();\n\n \/\/Generate Random lines\n vdRandomGenerator->SetInput(envelopeFilter->GetOutput());\n vdRandomGenerator->SetNumberOfOutputLine(vdReader->GetOutput()->Size());\n vdRandomGenerator->SetMinLineSize(4);\n vdRandomGenerator->SetMaxLineSize(20);\n\n \/\/Reproject into image index coordinates\n vdReProjFilterGT->SetInputImage(imgReader->GetOutput());\n vdReProjFilterGT->SetInputVectorData(vdReader->GetOutput());\n vdReProjFilterGT->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n vdReProjFilterGT->SetUseOutputSpacingAndOriginFromImage(true);\n vdReProjFilterGT->Update();\n\n vdReProjFilterRL->SetInputImage(imgReader->GetOutput());\n vdReProjFilterRL->SetInputVectorData(vdRandomGenerator->GetOutput());\n vdReProjFilterRL->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n vdReProjFilterRL->SetUseOutputSpacingAndOriginFromImage(true);\n vdReProjFilterRL->Update();\n\n \/\/Add Description to VectorDatas\n descriptionFilterGT->SetInput(vdReProjFilterGT->GetOutput());\n descriptionFilterGT->AddOpticalImage(imgReader->GetOutput());\n descriptionFilterGT->Update();\n descriptionFilterNS->SetInput(vdReProjFilterRL->GetOutput());\n descriptionFilterNS->AddOpticalImage(imgReader->GetOutput());\n descriptionFilterNS->Update();\n\n \/\/Cost Function\n \/\/Format Hypothesis\n LabelSetType hyp;\n if (parseResult->IsOptionPresent(\"Hypothesis\"))\n {\n int NumberOfChannel = parseResult->GetNumberOfParameters(\"Hypothesis\");\n for (int i = 0; i < NumberOfChannel; i++)\n {\n std::string str = parseResult->GetParameterString(\"Hypothesis\", i);\n hyp.insert(str);\n }\n costFunction->SetHypothesis(hyp);\n }\n if (parseResult->IsOptionPresent(\"Weighting\"))\n {\n costFunction->SetWeight(parseResult->GetParameterDouble(\"Weighting\"));\n }\n costFunction->SetGTVectorData(descriptionFilterGT->GetOutput());\n costFunction->SetNSVectorData(descriptionFilterNS->GetOutput());\n\n \/\/Optimizer\n optimizer->SetCostFunction(costFunction);\n if (parseResult->IsOptionPresent(\"MaximumNumberOfIterations\"))\n {\n optimizer->SetMaximumNumberOfIterations(parseResult->GetParameterInt(\"MaximumNumberOfIterations\"));\n }\n else\n {\n optimizer->SetMaximumNumberOfIterations(200);\n }\n\/*\n optimizer->SetParametersConvergenceTolerance( 0.01 );\n optimizer->SetFunctionConvergenceTolerance(0.001);\n*\/\n OptimizerType::ParametersType\n simplexDelta( costFunction->GetNumberOfParameters() );\n simplexDelta.Fill(.25);\n\n optimizer->AutomaticInitialSimplexOff();\n optimizer->SetInitialSimplexDelta( simplexDelta );\n\n OptimizerType::ParametersType\n initialPosition( costFunction->GetNumberOfParameters() );\n initialPosition.Fill(0.25);\n\n for (unsigned int i=0; i<(double)(costFunction->GetNumberOfParameters())\/4.0; i++)\n {\n initialPosition.SetElement(4*i+1, 0.50);\n initialPosition.SetElement(4*i+2, 0.75);\n initialPosition.SetElement(4*i+3, 0.99);\n }\n\n optimizer->SetInitialPosition(initialPosition);\n\n \/\/ Create the Command observer and register it with the optimizer.\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n if (parseResult->GetParameterInt(\"OptimizerObserver\"))\n {\n optimizer->AddObserver( itk::IterationEvent(), observer );\n }\n\n try\n {\n \/\/ do the optimization\n optimizer->StartOptimization();\n }\n catch( itk::ExceptionObject& err )\n {\n \/\/ An error has occurred in the optimization.\n \/\/ Update the parameters\n std::cout << \"ERROR: Exception Catched!\" << std::endl;\n std::cout << err.GetDescription() << std::endl;\n const unsigned int numberOfIterations\n = optimizer->GetOptimizer()->get_num_evaluations();\n std::cout << \"numberOfIterations : \" << numberOfIterations << std::endl;\n std::cout << \"Results : \" << optimizer->GetCurrentPosition() << std::endl;\n }\n \/\/ get the results\n const unsigned int numberOfIterations\n = optimizer->GetOptimizer()->get_num_evaluations();\n std::cout << \"numberOfIterations : \" << numberOfIterations << std::endl;\n std::cout << \"Results : \" << optimizer->GetCurrentPosition() << std::endl;\n\n otb::FuzzyDescriptorsModelManager::DescriptorsModelType model;\n otb::FuzzyDescriptorsModelManager::ParameterType ndvi, radiom;\n\n for (unsigned int i = 0; i<4; i++)\n {\n ndvi.push_back(optimizer->GetCurrentPosition()[i]);\n }\n for (unsigned int i = 0; i<4; i++)\n {\n radiom.push_back(optimizer->GetCurrentPosition()[i+4]);\n }\n\n otb::FuzzyDescriptorsModelManager::AddDescriptor(\"NDVI\", ndvi, model);\n otb::FuzzyDescriptorsModelManager::AddDescriptor(\"RADIOM\", radiom, model);\n otb::FuzzyDescriptorsModelManager::Save(parseResult->GetParameterString(\"Output\"),\n model);\n\n return EXIT_SUCCESS;\n}\n\n\/\/}\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"config.h\"\n#include \"input.h\"\n#include \"game.h\"\n#include \"draw.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TODO: Logger class from gurka\/gameserver\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing Window = std::unique_ptr;\n\nWindow initSDL()\n{\n \/\/ Init SDL\n if (SDL_Init(SDL_INIT_VIDEO) < 0)\n {\n fprintf(stderr, \"Could not initialize SDL: %s\\n\", SDL_GetError());\n return Window(nullptr, SDL_DestroyWindow);\n }\n\n \/\/ Init SDL_ttf\n if (TTF_Init() < 0)\n {\n fprintf(stderr, \"Could not initialize TTF: %s\\n\", TTF_GetError());\n return Window(nullptr, SDL_DestroyWindow);\n }\n\n atexit(SDL_Quit);\n\n return Window(SDL_CreateWindow(\"OpenCrystalCaves\",\n 0,\n 0,\n config::CAMERA_WIDTH * config::SCREEN_SCALE,\n config::CAMERA_HEIGHT * config::SCREEN_SCALE,\n SDL_WINDOW_SHOWN),\n SDL_DestroyWindow);\n}\n\nvoid readInput(Input* input)\n{\n assert(input != nullptr);\n\n \/\/ Set any input that is pressed as repeated here\n input->up.repeated = input->up.pressed;\n input->down.repeated = input->down.pressed;\n input->left.repeated = input->left.pressed;\n input->right.repeated = input->right.pressed;\n input->space.repeated = input->space.pressed;\n input->num_1.repeated = input->num_1.pressed;\n input->num_2.repeated = input->num_2.pressed;\n input->num_3.repeated = input->num_3.pressed;\n input->num_4.repeated = input->num_4.pressed;\n\n \/\/ Read events\n SDL_Event event;\n while (SDL_PollEvent(&event) != 0)\n {\n if (event.type == SDL_QUIT)\n {\n input->quit = true;\n return; \/\/ Quit asap\n }\n\n else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP)\n {\n switch (event.key.keysym.sym)\n {\n case SDLK_UP:\n if (event.type == SDL_KEYDOWN)\n {\n input->up.pressed = true;\n }\n else\n {\n input->up.pressed = false;\n input->up.repeated = false;\n }\n break;\n\n case SDLK_DOWN:\n if (event.type == SDL_KEYDOWN)\n {\n input->down.pressed = true;\n }\n else\n {\n input->down.pressed = false;\n input->down.repeated = false;\n }\n break;\n\n case SDLK_LEFT:\n if (event.type == SDL_KEYDOWN)\n {\n input->left.pressed = true;\n }\n else\n {\n input->left.pressed = false;\n input->left.repeated = false;\n }\n break;\n\n case SDLK_RIGHT:\n if (event.type == SDL_KEYDOWN)\n {\n input->right.pressed = true;\n }\n else\n {\n input->right.pressed = false;\n input->right.repeated = false;\n }\n break;\n\n case SDLK_SPACE:\n if (event.type == SDL_KEYDOWN)\n {\n input->space.pressed = true;\n }\n else\n {\n input->space.pressed = false;\n input->space.repeated = false;\n }\n break;\n\n case SDLK_1:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_1.pressed = true;\n }\n else\n {\n input->num_1.pressed = false;\n input->num_1.repeated = false;\n }\n break;\n\n case SDLK_2:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_2.pressed = true;\n }\n else\n {\n input->num_2.pressed = false;\n input->num_2.repeated = false;\n }\n break;\n\n case SDLK_3:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_3.pressed = true;\n }\n else\n {\n input->num_3.pressed = false;\n input->num_3.repeated = false;\n }\n break;\n\n case SDLK_4:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_4.pressed = true;\n }\n else\n {\n input->num_4.pressed = false;\n input->num_4.repeated = false;\n }\n break;\n\n case SDLK_ESCAPE:\n input->quit = true;\n return;\n\n default:\n break;\n }\n }\n }\n}\n\nint main(int argc, char* argv[])\n{\n \/\/ Unused for now\n (void)argc;\n (void)argv;\n\n Window window = initSDL();\n if (!window)\n {\n return 1;\n }\n auto* window_surface = SDL_GetWindowSurface(window.get());\n\n Game game;\n if (!game.init(window_surface))\n {\n fprintf(stderr, \"Could not initialize Game\\n\");\n return 1;\n }\n\n \/\/ Game loop\n {\n Input input;\n\n const auto current_tick = SDL_GetTicks();\n\n \/\/ Game loop logic\n const auto ms_per_update = 57; \/\/ 17.5~ ticks per second\n auto tick_last_update = current_tick;\n auto lag = 0u;\n\n \/\/ FPS logic\n auto fps_num_renders = 0u;\n auto fps_last_calc = current_tick;\n auto fps_start_time = current_tick;\n auto fps = 0u;\n\n while (true)\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\n \/\/\/ Logic\n \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n auto current_tick = SDL_GetTicks();\n auto elapsed_ticks = current_tick - tick_last_update;\n tick_last_update = current_tick;\n lag += elapsed_ticks;\n while (lag >= ms_per_update)\n {\n readInput(&input);\n game.update(input);\n lag -= ms_per_update;\n }\n if (input.quit)\n {\n break;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\n \/\/\/ Render\n \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Render game\n game.render(window_surface);\n\n \/\/ Render FPS\n auto fps_str = \"fps: \" + std::to_string(fps);\n draw::text(5, 5, fps_str, { 255u, 255u, 255u, 0u }, window_surface);\n\n \/\/ Update screen\n SDL_UpdateWindowSurface(window.get());\n\n fps_num_renders++;\n\n \/\/ Calculate FPS each second\n if (current_tick >= (fps_last_calc + 1000))\n {\n const auto total_time = current_tick - fps_start_time;\n fps = fps_num_renders \/ (total_time \/ 1000);\n fps_last_calc = current_tick;\n\n \/\/ Reset\n fps_num_renders = 0;\n fps_start_time = current_tick;\n }\n }\n }\n\n return 0;\n}\nUse main() instead of ignoring argc and argv#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"config.h\"\n#include \"input.h\"\n#include \"game.h\"\n#include \"draw.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TODO: Logger class from gurka\/gameserver\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing Window = std::unique_ptr;\n\nWindow initSDL()\n{\n \/\/ Init SDL\n if (SDL_Init(SDL_INIT_VIDEO) < 0)\n {\n fprintf(stderr, \"Could not initialize SDL: %s\\n\", SDL_GetError());\n return Window(nullptr, SDL_DestroyWindow);\n }\n\n \/\/ Init SDL_ttf\n if (TTF_Init() < 0)\n {\n fprintf(stderr, \"Could not initialize TTF: %s\\n\", TTF_GetError());\n return Window(nullptr, SDL_DestroyWindow);\n }\n\n atexit(SDL_Quit);\n\n return Window(SDL_CreateWindow(\"OpenCrystalCaves\",\n 0,\n 0,\n config::CAMERA_WIDTH * config::SCREEN_SCALE,\n config::CAMERA_HEIGHT * config::SCREEN_SCALE,\n SDL_WINDOW_SHOWN),\n SDL_DestroyWindow);\n}\n\nvoid readInput(Input* input)\n{\n assert(input != nullptr);\n\n \/\/ Set any input that is pressed as repeated here\n input->up.repeated = input->up.pressed;\n input->down.repeated = input->down.pressed;\n input->left.repeated = input->left.pressed;\n input->right.repeated = input->right.pressed;\n input->space.repeated = input->space.pressed;\n input->num_1.repeated = input->num_1.pressed;\n input->num_2.repeated = input->num_2.pressed;\n input->num_3.repeated = input->num_3.pressed;\n input->num_4.repeated = input->num_4.pressed;\n\n \/\/ Read events\n SDL_Event event;\n while (SDL_PollEvent(&event) != 0)\n {\n if (event.type == SDL_QUIT)\n {\n input->quit = true;\n return; \/\/ Quit asap\n }\n\n else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP)\n {\n switch (event.key.keysym.sym)\n {\n case SDLK_UP:\n if (event.type == SDL_KEYDOWN)\n {\n input->up.pressed = true;\n }\n else\n {\n input->up.pressed = false;\n input->up.repeated = false;\n }\n break;\n\n case SDLK_DOWN:\n if (event.type == SDL_KEYDOWN)\n {\n input->down.pressed = true;\n }\n else\n {\n input->down.pressed = false;\n input->down.repeated = false;\n }\n break;\n\n case SDLK_LEFT:\n if (event.type == SDL_KEYDOWN)\n {\n input->left.pressed = true;\n }\n else\n {\n input->left.pressed = false;\n input->left.repeated = false;\n }\n break;\n\n case SDLK_RIGHT:\n if (event.type == SDL_KEYDOWN)\n {\n input->right.pressed = true;\n }\n else\n {\n input->right.pressed = false;\n input->right.repeated = false;\n }\n break;\n\n case SDLK_SPACE:\n if (event.type == SDL_KEYDOWN)\n {\n input->space.pressed = true;\n }\n else\n {\n input->space.pressed = false;\n input->space.repeated = false;\n }\n break;\n\n case SDLK_1:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_1.pressed = true;\n }\n else\n {\n input->num_1.pressed = false;\n input->num_1.repeated = false;\n }\n break;\n\n case SDLK_2:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_2.pressed = true;\n }\n else\n {\n input->num_2.pressed = false;\n input->num_2.repeated = false;\n }\n break;\n\n case SDLK_3:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_3.pressed = true;\n }\n else\n {\n input->num_3.pressed = false;\n input->num_3.repeated = false;\n }\n break;\n\n case SDLK_4:\n if (event.type == SDL_KEYDOWN)\n {\n input->num_4.pressed = true;\n }\n else\n {\n input->num_4.pressed = false;\n input->num_4.repeated = false;\n }\n break;\n\n case SDLK_ESCAPE:\n input->quit = true;\n return;\n\n default:\n break;\n }\n }\n }\n}\n\nint main()\n{\n Window window = initSDL();\n if (!window)\n {\n return 1;\n }\n auto* window_surface = SDL_GetWindowSurface(window.get());\n\n Game game;\n if (!game.init(window_surface))\n {\n fprintf(stderr, \"Could not initialize Game\\n\");\n return 1;\n }\n\n \/\/ Game loop\n {\n Input input;\n\n const auto current_tick = SDL_GetTicks();\n\n \/\/ Game loop logic\n const auto ms_per_update = 57; \/\/ 17.5~ ticks per second\n auto tick_last_update = current_tick;\n auto lag = 0u;\n\n \/\/ FPS logic\n auto fps_num_renders = 0u;\n auto fps_last_calc = current_tick;\n auto fps_start_time = current_tick;\n auto fps = 0u;\n\n while (true)\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\n \/\/\/ Logic\n \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n auto current_tick = SDL_GetTicks();\n auto elapsed_ticks = current_tick - tick_last_update;\n tick_last_update = current_tick;\n lag += elapsed_ticks;\n while (lag >= ms_per_update)\n {\n readInput(&input);\n game.update(input);\n lag -= ms_per_update;\n }\n if (input.quit)\n {\n break;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\n \/\/\/ Render\n \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Render game\n game.render(window_surface);\n\n \/\/ Render FPS\n auto fps_str = \"fps: \" + std::to_string(fps);\n draw::text(5, 5, fps_str, { 255u, 255u, 255u, 0u }, window_surface);\n\n \/\/ Update screen\n SDL_UpdateWindowSurface(window.get());\n\n fps_num_renders++;\n\n \/\/ Calculate FPS each second\n if (current_tick >= (fps_last_calc + 1000))\n {\n const auto total_time = current_tick - fps_start_time;\n fps = fps_num_renders \/ (total_time \/ 1000);\n fps_last_calc = current_tick;\n\n \/\/ Reset\n fps_num_renders = 0;\n fps_start_time = current_tick;\n }\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inspectorhelpwindow.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2006-12-15 02:13:45 $\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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n#ifndef INSPECTORHELPWINDOW_HXX\n#include \"inspectorhelpwindow.hxx\"\n#endif\n#ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX\n#include \"modulepcr.hxx\"\n#endif\n#ifndef EXTENSIONS_PROPRESID_HRC\n#include \"propresid.hrc\"\n#endif\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace pcr\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n \/** === end UNO using === **\/\n\n \/\/====================================================================\n \/\/= InspectorHelpWindow\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n InspectorHelpWindow::InspectorHelpWindow( Window* _pParent )\n :Window( _pParent, WB_DIALOGCONTROL )\n ,m_aSeparator( this )\n ,m_aHelpText( this, WB_LEFT | WB_READONLY | WB_AUTOVSCROLL )\n ,m_nMinLines( 3 )\n ,m_nMaxLines( 8 )\n {\n m_aSeparator.SetText( String( PcrRes( RID_STR_HELP_SECTION_LABEL ) ) );\n m_aSeparator.Show();\n\n m_aHelpText.SetControlBackground( m_aSeparator.GetBackground().GetColor() );\n m_aHelpText.Show();\n }\n\n \/\/--------------------------------------------------------------------\n void InspectorHelpWindow::SetText( const XubString& _rStr )\n {\n m_aHelpText.SetText( _rStr );\n }\n\n \/\/--------------------------------------------------------------------\n void InspectorHelpWindow::SetLimits( sal_Int32 _nMinLines, sal_Int32 _nMaxLines )\n {\n m_nMinLines = _nMinLines;\n m_nMaxLines = _nMaxLines;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getHelpTextBorderHeight()\n {\n sal_Int32 nTop(0), nBottom(0), nDummy(0);\n m_aHelpText.GetBorder( nDummy, nTop, nDummy, nBottom );\n return nTop + nBottom;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getSpaceAboveTextWindow()\n {\n Size aSeparatorSize( LogicToPixel( Size( 0, 8 ), MAP_APPFONT ) );\n Size a3AppFontSize( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );\n return aSeparatorSize.Height() + a3AppFontSize.Height();\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::GetMinimalHeightPixel()\n {\n return impl_getMinimalTextWindowHeight() + impl_getSpaceAboveTextWindow();\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::GetMaximalHeightPixel()\n {\n return impl_getMaximalTextWindowHeight() + impl_getSpaceAboveTextWindow();\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getMinimalTextWindowHeight()\n {\n return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMinLines;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getMaximalTextWindowHeight()\n {\n return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMaxLines;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::GetOptimalHeightPixel()\n {\n \/\/ --- calc the height as needed for the mere text window\n long nMinTextWindowHeight = impl_getMinimalTextWindowHeight();\n long nMaxTextWindowHeight = impl_getMaximalTextWindowHeight();\n\n Rectangle aTextRect( Point( 0, 0 ), m_aHelpText.GetOutputSizePixel() );\n aTextRect = m_aHelpText.GetTextRect( aTextRect, m_aHelpText.GetText(),\n TEXT_DRAW_LEFT | TEXT_DRAW_TOP | TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK );\n long nActTextWindowHeight = impl_getHelpTextBorderHeight() + aTextRect.GetHeight();\n\n long nOptTextWindowHeight = ::std::max( nMinTextWindowHeight, ::std::min( nMaxTextWindowHeight, nActTextWindowHeight ) );\n\n \/\/ --- then add the space above the text window\n return nOptTextWindowHeight + impl_getSpaceAboveTextWindow();\n }\n\n \/\/--------------------------------------------------------------------\n void InspectorHelpWindow::Resize()\n {\n Size a3AppFont( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );\n\n Rectangle aPlayground( Point( 0, 0 ), GetOutputSizePixel() );\n\n Rectangle aSeparatorArea( aPlayground );\n aSeparatorArea.Bottom() = aSeparatorArea.Top() + LogicToPixel( Size( 0, 8 ), MAP_APPFONT ).Height();\n m_aSeparator.SetPosSizePixel( aSeparatorArea.TopLeft(), aSeparatorArea.GetSize() );\n\n Rectangle aTextArea( aPlayground );\n aTextArea.Top() = aSeparatorArea.Bottom() + a3AppFont.Height();\n m_aHelpText.SetPosSizePixel( aTextArea.TopLeft(), aTextArea.GetSize() );\n }\n\n\/\/........................................................................\n} \/\/ namespace pcr\n\/\/........................................................................\n\nINTEGRATION: CWS oj14 (1.3.10); FILE MERGED 2007\/02\/20 12:02:41 oj 1.3.10.1: set PaintTransparent to true\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inspectorhelpwindow.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2007-07-06 08:50:12 $\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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n#ifndef INSPECTORHELPWINDOW_HXX\n#include \"inspectorhelpwindow.hxx\"\n#endif\n#ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX\n#include \"modulepcr.hxx\"\n#endif\n#ifndef EXTENSIONS_PROPRESID_HRC\n#include \"propresid.hrc\"\n#endif\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace pcr\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n \/** === end UNO using === **\/\n\n \/\/====================================================================\n \/\/= InspectorHelpWindow\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n InspectorHelpWindow::InspectorHelpWindow( Window* _pParent )\n :Window( _pParent, WB_DIALOGCONTROL )\n ,m_aSeparator( this )\n ,m_aHelpText( this, WB_LEFT | WB_READONLY | WB_AUTOVSCROLL )\n ,m_nMinLines( 3 )\n ,m_nMaxLines( 8 )\n {\n SetBackground();\n SetPaintTransparent(TRUE);\n m_aSeparator.SetText( String( PcrRes( RID_STR_HELP_SECTION_LABEL ) ) );\n m_aSeparator.SetBackground();\n m_aSeparator.Show();\n\n m_aHelpText.SetControlBackground( \/*m_aSeparator.GetBackground().GetColor() *\/);\n m_aHelpText.SetBackground();\n m_aHelpText.SetPaintTransparent(TRUE);\n m_aHelpText.Show();\n }\n\n \/\/--------------------------------------------------------------------\n void InspectorHelpWindow::SetText( const XubString& _rStr )\n {\n m_aHelpText.SetText( _rStr );\n }\n\n \/\/--------------------------------------------------------------------\n void InspectorHelpWindow::SetLimits( sal_Int32 _nMinLines, sal_Int32 _nMaxLines )\n {\n m_nMinLines = _nMinLines;\n m_nMaxLines = _nMaxLines;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getHelpTextBorderHeight()\n {\n sal_Int32 nTop(0), nBottom(0), nDummy(0);\n m_aHelpText.GetBorder( nDummy, nTop, nDummy, nBottom );\n return nTop + nBottom;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getSpaceAboveTextWindow()\n {\n Size aSeparatorSize( LogicToPixel( Size( 0, 8 ), MAP_APPFONT ) );\n Size a3AppFontSize( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );\n return aSeparatorSize.Height() + a3AppFontSize.Height();\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::GetMinimalHeightPixel()\n {\n return impl_getMinimalTextWindowHeight() + impl_getSpaceAboveTextWindow();\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::GetMaximalHeightPixel()\n {\n return impl_getMaximalTextWindowHeight() + impl_getSpaceAboveTextWindow();\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getMinimalTextWindowHeight()\n {\n return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMinLines;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::impl_getMaximalTextWindowHeight()\n {\n return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMaxLines;\n }\n\n \/\/--------------------------------------------------------------------\n long InspectorHelpWindow::GetOptimalHeightPixel()\n {\n \/\/ --- calc the height as needed for the mere text window\n long nMinTextWindowHeight = impl_getMinimalTextWindowHeight();\n long nMaxTextWindowHeight = impl_getMaximalTextWindowHeight();\n\n Rectangle aTextRect( Point( 0, 0 ), m_aHelpText.GetOutputSizePixel() );\n aTextRect = m_aHelpText.GetTextRect( aTextRect, m_aHelpText.GetText(),\n TEXT_DRAW_LEFT | TEXT_DRAW_TOP | TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK );\n long nActTextWindowHeight = impl_getHelpTextBorderHeight() + aTextRect.GetHeight();\n\n long nOptTextWindowHeight = ::std::max( nMinTextWindowHeight, ::std::min( nMaxTextWindowHeight, nActTextWindowHeight ) );\n\n \/\/ --- then add the space above the text window\n return nOptTextWindowHeight + impl_getSpaceAboveTextWindow();\n }\n\n \/\/--------------------------------------------------------------------\n void InspectorHelpWindow::Resize()\n {\n Size a3AppFont( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );\n\n Rectangle aPlayground( Point( 0, 0 ), GetOutputSizePixel() );\n\n Rectangle aSeparatorArea( aPlayground );\n aSeparatorArea.Bottom() = aSeparatorArea.Top() + LogicToPixel( Size( 0, 8 ), MAP_APPFONT ).Height();\n m_aSeparator.SetPosSizePixel( aSeparatorArea.TopLeft(), aSeparatorArea.GetSize() );\n\n Rectangle aTextArea( aPlayground );\n aTextArea.Top() = aSeparatorArea.Bottom() + a3AppFont.Height();\n m_aHelpText.SetPosSizePixel( aTextArea.TopLeft(), aTextArea.GetSize() );\n }\n\n\/\/........................................................................\n} \/\/ namespace pcr\n\/\/........................................................................\n\n<|endoftext|>"} {"text":"\n#ifndef __BUFFER_CACHE_WRITEBACK_IMPL_HPP__\n#define __BUFFER_CACHE_WRITEBACK_IMPL_HPP__\n\ntemplate \nwriteback_tmpl_t::writeback_tmpl_t(cache_t *cache,\n bool wait_for_flush, unsigned int flush_interval_ms)\n : wait_for_flush(wait_for_flush),\n interval_ms(flush_interval_ms),\n cache(cache),\n num_txns(0),\n shutdown_callback(NULL),\n final_sync(NULL),\n state(state_none),\n transaction(NULL) {\n}\n\ntemplate \nwriteback_tmpl_t::~writeback_tmpl_t() {\n delete flush_lock;\n}\n\ntemplate \nvoid writeback_tmpl_t::start() {\n flush_lock =\n new rwi_lock_t(&get_cpu_context()->event_queue->message_hub,\n get_cpu_context()->event_queue->queue_id);\n start_flush_timer();\n}\n\ntemplate \nvoid writeback_tmpl_t::shutdown(sync_callback *callback) {\n assert(shutdown_callback == NULL);\n shutdown_callback = callback;\n if (!num_txns && state == state_none) \/\/ If num_txns, commit() will do this\n sync(callback);\n}\n\ntemplate \nvoid writeback_tmpl_t::sync(sync_callback *callback) {\n sync_callbacks.push_back(callback);\n \/\/ Start a new writeback process if one isn't in progress.\n if (state == state_none)\n writeback(NULL);\n}\n\ntemplate \nbool writeback_tmpl_t::begin_transaction(transaction_t *txn) {\n assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write);\n \/\/ TODO(NNW): If there's ever any asynchrony between socket reads and\n \/\/ begin_transaction, we'll need a better check here.\n assert(shutdown_callback == NULL || final_sync);\n num_txns++;\n if (txn->get_access() == rwi_read)\n return true;\n bool locked = flush_lock->lock(rwi_read, txn);\n return locked;\n}\n\ntemplate \nbool writeback_tmpl_t::commit(transaction_t *txn,\n transaction_commit_callback_t *callback) {\n if (!--num_txns && shutdown_callback != NULL) {\n sync(shutdown_callback); \/\/ All txns shut down, start final sync.\n }\n if (txn->get_access() == rwi_read)\n return true;\n flush_lock->unlock();\n if (!wait_for_flush)\n return true;\n txns.insert(txn_state_t(txn, callback));\n return false;\n}\n\ntemplate \nvoid writeback_tmpl_t::aio_complete(buf_t *buf, bool written) {\n if (written)\n writeback(buf);\n}\n\ntemplate \nvoid writeback_tmpl_t::local_buf_t::set_dirty(buf_t *super) {\n\t\/\/ 'super' is actually 'this', but as a buf_t* instead of a local_buf_t*\n dirty = true;\n \/\/ Maybe we should store a pointer to the block itself, instead of its ID; it shouldn't get\n \/\/ swapped out because it's dirty.\n writeback->dirty_blocks.insert(super->get_block_id());\n}\n\ntemplate \nvoid writeback_tmpl_t::start_flush_timer() {\n\tif (interval_ms != NEVER_FLUSH && interval_ms != 0) {\n\t\ttimespec ts;\n\t\tts.tv_sec = interval_ms \/ 1000;\n\t\tts.tv_nsec = (interval_ms % 1000) * 1000 * 1000;\n\t\tget_cpu_context()->event_queue->timer_once(&ts, timer_callback, this);\n\t}\n}\n\ntemplate \nvoid writeback_tmpl_t::timer_callback(void *ctx) {\n \/\/ TODO(NNW): We can't start writeback when it's already started, but we\n \/\/ may want a more thorough way of dealing with this case.\n if (static_cast(ctx)->state == state_none)\n static_cast(ctx)->writeback(NULL);\n}\n\ntemplate \nvoid writeback_tmpl_t::on_lock_available() {\n assert(state == state_locking);\n if (state == state_locking) {\n state = state_locked;\n writeback(NULL);\n }\n}\n\ntemplate \nvoid writeback_tmpl_t::writeback(buf_t *buf) {\n \/\/printf(\"Writeback being called, state %d\\n\", state);\n\n if (state == state_none) {\n assert(buf == NULL);\n\n \/* Start a read transaction so we can request bufs. *\/\n assert(transaction == NULL);\n if (shutdown_callback) \/\/ Backdoor around \"no new transactions\" assert.\n final_sync = true;\n transaction = cache->begin_transaction(rwi_read, NULL);\n final_sync = false;\n assert(transaction != NULL); \/\/ Read txns always start immediately.\n\n \/* Request exclusive flush_lock, forcing all write txns to complete. *\/\n state = state_locking;\n bool locked = flush_lock->lock(rwi_write, this);\n if (locked)\n state = state_locked;\n }\n if (state == state_locked) {\n assert(buf == NULL);\n assert(flush_bufs.empty());\n assert(flush_txns.empty());\n\n flush_txns = txns;\n txns.clear();\n\n \/* Request read locks on all of the blocks we need to flush. *\/\n for (typename std::set::iterator it = dirty_blocks.begin();\n it != dirty_blocks.end(); ++it) {\n buf_t *buf = transaction->acquire(*it, rwi_read, NULL);\n assert(buf); \/\/ Acquire must succeed since we hold the flush_lock.\n flush_bufs.insert(buf);\n }\n\n dirty_blocks.clear();\n flush_lock->unlock(); \/\/ Write transactions can now proceed again.\n\n \/* Start writing all the dirty bufs down, as a transaction. *\/\n typename serializer_t::write *writes =\n (typename serializer_t::write *)calloc(flush_bufs.size(),\n sizeof *writes);\n int i = 0;\n for (typename std::set::iterator it = flush_bufs.begin();\n it != flush_bufs.end(); ++it, i++) {\n writes[i].block_id = (*it)->get_block_id();\n writes[i].buf = (*it)->ptr();\n writes[i].callback = (*it);\n }\n \/\/ TODO(NNW): Now that the serializer\/aio-system breaks writes up into\n \/\/ chunks, we may want to worry about submitting more heavily contended\n \/\/ bufs earlier in the process so more write FSMs can proceed sooner.\n if (flush_bufs.size())\n cache->do_write(get_cpu_context()->event_queue, writes,\n flush_bufs.size());\n free(writes);\n state = state_write_bufs;\n }\n if (state == state_write_bufs) {\n if (buf) {\n assert(flush_bufs.find(buf) != flush_bufs.end());\n flush_bufs.erase(buf);\n buf->set_clean();\n buf->release();\n }\n if (flush_bufs.empty()) {\n \/* Notify all waiting transactions of completion. *\/\n for (typename std::set::iterator it =\n flush_txns.begin(); it != flush_txns.end(); ++it) {\n it->first->committed(it->second);\n }\n flush_txns.clear();\n\n for (typename std::vector::iterator it =\n sync_callbacks.begin(); it != sync_callbacks.end(); ++it)\n (*it)->on_sync();\n sync_callbacks.clear();\n\n \/* Reset all of our state. *\/\n bool committed = transaction->commit(NULL);\n assert(committed); \/\/ Read-only transactions commit immediately.\n transaction = NULL;\n state = state_none;\n \n \/\/ The timer for the next flush is not started until the current flush is complete. This\n \/\/ is a bit dangerous because if anything causes the current flush to abort prematurely,\n \/\/ the flush timer will never get restarted. As of 2010-06-28 this should never happen,\n \/\/ but keep it in mind when changing the behavior of the writeback.\n start_flush_timer();\n \n \/\/printf(\"Writeback complete\\n\");\n } else {\n \/\/printf(\"Flush bufs, waiting for %ld more\\n\", flush_bufs.size());\n }\n }\n}\n\n#endif \/\/ __BUFFER_CACHE_WRITEBACK_IMPL_HPP__\nFixing writeback to allocate rwi lock with gnew\n#ifndef __BUFFER_CACHE_WRITEBACK_IMPL_HPP__\n#define __BUFFER_CACHE_WRITEBACK_IMPL_HPP__\n\ntemplate \nwriteback_tmpl_t::writeback_tmpl_t(cache_t *cache,\n bool wait_for_flush, unsigned int flush_interval_ms)\n : wait_for_flush(wait_for_flush),\n interval_ms(flush_interval_ms),\n cache(cache),\n num_txns(0),\n shutdown_callback(NULL),\n final_sync(NULL),\n state(state_none),\n transaction(NULL) {\n}\n\ntemplate \nwriteback_tmpl_t::~writeback_tmpl_t() {\n gdelete(flush_lock);\n}\n\ntemplate \nvoid writeback_tmpl_t::start() {\n flush_lock =\n gnew(&get_cpu_context()->event_queue->message_hub,\n get_cpu_context()->event_queue->queue_id);\n start_flush_timer();\n}\n\ntemplate \nvoid writeback_tmpl_t::shutdown(sync_callback *callback) {\n assert(shutdown_callback == NULL);\n shutdown_callback = callback;\n if (!num_txns && state == state_none) \/\/ If num_txns, commit() will do this\n sync(callback);\n}\n\ntemplate \nvoid writeback_tmpl_t::sync(sync_callback *callback) {\n sync_callbacks.push_back(callback);\n \/\/ Start a new writeback process if one isn't in progress.\n if (state == state_none)\n writeback(NULL);\n}\n\ntemplate \nbool writeback_tmpl_t::begin_transaction(transaction_t *txn) {\n assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write);\n \/\/ TODO(NNW): If there's ever any asynchrony between socket reads and\n \/\/ begin_transaction, we'll need a better check here.\n assert(shutdown_callback == NULL || final_sync);\n num_txns++;\n if (txn->get_access() == rwi_read)\n return true;\n bool locked = flush_lock->lock(rwi_read, txn);\n return locked;\n}\n\ntemplate \nbool writeback_tmpl_t::commit(transaction_t *txn,\n transaction_commit_callback_t *callback) {\n if (!--num_txns && shutdown_callback != NULL) {\n sync(shutdown_callback); \/\/ All txns shut down, start final sync.\n }\n if (txn->get_access() == rwi_read)\n return true;\n flush_lock->unlock();\n if (!wait_for_flush)\n return true;\n txns.insert(txn_state_t(txn, callback));\n return false;\n}\n\ntemplate \nvoid writeback_tmpl_t::aio_complete(buf_t *buf, bool written) {\n if (written)\n writeback(buf);\n}\n\ntemplate \nvoid writeback_tmpl_t::local_buf_t::set_dirty(buf_t *super) {\n\t\/\/ 'super' is actually 'this', but as a buf_t* instead of a local_buf_t*\n dirty = true;\n \/\/ Maybe we should store a pointer to the block itself, instead of its ID; it shouldn't get\n \/\/ swapped out because it's dirty.\n writeback->dirty_blocks.insert(super->get_block_id());\n}\n\ntemplate \nvoid writeback_tmpl_t::start_flush_timer() {\n\tif (interval_ms != NEVER_FLUSH && interval_ms != 0) {\n\t\ttimespec ts;\n\t\tts.tv_sec = interval_ms \/ 1000;\n\t\tts.tv_nsec = (interval_ms % 1000) * 1000 * 1000;\n\t\tget_cpu_context()->event_queue->timer_once(&ts, timer_callback, this);\n\t}\n}\n\ntemplate \nvoid writeback_tmpl_t::timer_callback(void *ctx) {\n \/\/ TODO(NNW): We can't start writeback when it's already started, but we\n \/\/ may want a more thorough way of dealing with this case.\n if (static_cast(ctx)->state == state_none)\n static_cast(ctx)->writeback(NULL);\n}\n\ntemplate \nvoid writeback_tmpl_t::on_lock_available() {\n assert(state == state_locking);\n if (state == state_locking) {\n state = state_locked;\n writeback(NULL);\n }\n}\n\ntemplate \nvoid writeback_tmpl_t::writeback(buf_t *buf) {\n \/\/printf(\"Writeback being called, state %d\\n\", state);\n\n if (state == state_none) {\n assert(buf == NULL);\n\n \/* Start a read transaction so we can request bufs. *\/\n assert(transaction == NULL);\n if (shutdown_callback) \/\/ Backdoor around \"no new transactions\" assert.\n final_sync = true;\n transaction = cache->begin_transaction(rwi_read, NULL);\n final_sync = false;\n assert(transaction != NULL); \/\/ Read txns always start immediately.\n\n \/* Request exclusive flush_lock, forcing all write txns to complete. *\/\n state = state_locking;\n bool locked = flush_lock->lock(rwi_write, this);\n if (locked)\n state = state_locked;\n }\n if (state == state_locked) {\n assert(buf == NULL);\n assert(flush_bufs.empty());\n assert(flush_txns.empty());\n\n flush_txns = txns;\n txns.clear();\n\n \/* Request read locks on all of the blocks we need to flush. *\/\n for (typename std::set::iterator it = dirty_blocks.begin();\n it != dirty_blocks.end(); ++it) {\n buf_t *buf = transaction->acquire(*it, rwi_read, NULL);\n assert(buf); \/\/ Acquire must succeed since we hold the flush_lock.\n flush_bufs.insert(buf);\n }\n\n dirty_blocks.clear();\n flush_lock->unlock(); \/\/ Write transactions can now proceed again.\n\n \/* Start writing all the dirty bufs down, as a transaction. *\/\n typename serializer_t::write *writes =\n (typename serializer_t::write *)calloc(flush_bufs.size(),\n sizeof *writes);\n int i = 0;\n for (typename std::set::iterator it = flush_bufs.begin();\n it != flush_bufs.end(); ++it, i++) {\n writes[i].block_id = (*it)->get_block_id();\n writes[i].buf = (*it)->ptr();\n writes[i].callback = (*it);\n }\n \/\/ TODO(NNW): Now that the serializer\/aio-system breaks writes up into\n \/\/ chunks, we may want to worry about submitting more heavily contended\n \/\/ bufs earlier in the process so more write FSMs can proceed sooner.\n if (flush_bufs.size())\n cache->do_write(get_cpu_context()->event_queue, writes,\n flush_bufs.size());\n free(writes);\n state = state_write_bufs;\n }\n if (state == state_write_bufs) {\n if (buf) {\n assert(flush_bufs.find(buf) != flush_bufs.end());\n flush_bufs.erase(buf);\n buf->set_clean();\n buf->release();\n }\n if (flush_bufs.empty()) {\n \/* Notify all waiting transactions of completion. *\/\n for (typename std::set::iterator it =\n flush_txns.begin(); it != flush_txns.end(); ++it) {\n it->first->committed(it->second);\n }\n flush_txns.clear();\n\n for (typename std::vector::iterator it =\n sync_callbacks.begin(); it != sync_callbacks.end(); ++it)\n (*it)->on_sync();\n sync_callbacks.clear();\n\n \/* Reset all of our state. *\/\n bool committed = transaction->commit(NULL);\n assert(committed); \/\/ Read-only transactions commit immediately.\n transaction = NULL;\n state = state_none;\n \n \/\/ The timer for the next flush is not started until the current flush is complete. This\n \/\/ is a bit dangerous because if anything causes the current flush to abort prematurely,\n \/\/ the flush timer will never get restarted. As of 2010-06-28 this should never happen,\n \/\/ but keep it in mind when changing the behavior of the writeback.\n start_flush_timer();\n \n \/\/printf(\"Writeback complete\\n\");\n } else {\n \/\/printf(\"Flush bufs, waiting for %ld more\\n\", flush_bufs.size());\n }\n }\n}\n\n#endif \/\/ __BUFFER_CACHE_WRITEBACK_IMPL_HPP__\n<|endoftext|>"} {"text":"\/*\n * Satisfier.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n *\n * Author: Linas Vepstas January 2009\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program 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 General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n\n#include \"BindLinkAPI.h\"\n#include \"Satisfier.h\"\n\nusing namespace opencog;\n\nbool Satisfier::grounding(const HandleMap &var_soln,\n const HandleMap &term_soln)\n{\n\t\/\/ PatternMatchEngine::print_solution(var_soln, term_soln);\n\t_result = TruthValue::TRUE_TV();\n\n\t\/\/ Record the grounding; we cache this later.\n\tif (1 == _varseq.size())\n\t{\n\t\t_ground = var_soln.at(_varseq[0]);\n\t}\n\telse\n\t{\n\t\t\/\/ If more than one variable, encapsulate in sequential order,\n\t\t\/\/ in a ListLink.\n\t\tHandleSeq vargnds;\n\t\tfor (const Handle& hv : _varseq)\n\t\t{\n\t\t\tvargnds.push_back(var_soln.at(hv));\n\t\t}\n\t\t_ground = createLink(vargnds, LIST_LINK);\n\t}\n\n\t\/\/ No need to look for more groundings as _result isn't going to change\n\t\/\/ and opencog::satisfaction_link only needs the value of _result.\n\treturn true;\n}\n\n\/\/\/ This method handles the case of SequentialAnd, SequentialOr with\n\/\/\/ embedded AbsentLinks, NotLink-PresentLink and some weird\n\/\/\/ combinations of NotLink-ChoiceLink, and so-on. The idea here is\n\/\/\/ that, if the pattern matcher ran to exhaustion, and NO groundings\n\/\/\/ at all were found, then pattern evaluation may still need to\n\/\/\/ trigger evaluatable clauses that evaluate only when exhaustive\n\/\/\/ search fails. So, indeed, we do that here.\n\/\/\/\n\/\/\/ Of course, if the pattern had no variables (e.g. a SequenceLink or\n\/\/\/ FallbackLink with only evaluatables), then there cannot be a\n\/\/\/ grounding failure, by definition. And if there was a grounding,\n\/\/\/ there can be no grounding failure, either. So we only process the\n\/\/\/ case where there are variables, and grounding failed.\nbool Satisfier::search_finished(bool done)\n{\n\tif (done) return done;\n\n\t\/\/ If there were no variables to be grounded, we have nothing to do.\n\tif (not _have_variables) return done;\n\n\t\/\/ If there was a grounding, then don't re-run; we're here\n\t\/\/ only to handle the no-groundings case.\n\tif (TruthValue::TRUE_TV() == _result) return done;\n\n\t\/\/ _optionals_present will be set to true if some optional clause\n\t\/\/ was grounded. Ergo, its not the no-grounding case.\n\tif (_optionals_present) return done;\n\n\t\/\/ Multi-component patterns will not have distinct bodies.\n\t\/\/ A failure to match one of the components is benign, and is\n\t\/\/ treated appropriately upstream. Just return.\n\tif (nullptr == _pattern_body) return done;\n\n\t\/\/ Evaluating the pattern body only makes sense if it is sequential\n\t\/\/ (ordered) -- if the body is an unordered AndLink, or if its a\n\t\/\/ ChoiceLink, etc, this makes no sense.\n\tType btype = _pattern_body->getType();\n\tif (SEQUENTIAL_AND_LINK != btype and SEQUENTIAL_OR_LINK != btype)\n\t\treturn done;\n\n\tHandleMap empty;\n\tbool rc = eval_sentence(_pattern_body, empty);\n\tif (rc)\n\t\t_result = TruthValue::TRUE_TV();\n\n\treturn rc;\n}\n\n\/\/ ===========================================================\n\nbool SatisfyingSet::grounding(const HandleMap &var_soln,\n const HandleMap &term_soln)\n{\n\t\/\/ PatternMatchEngine::log_solution(var_soln, term_soln);\n\n\t\/\/ Do not accept new solution if maximum number has been already reached\n\tif (_satisfying_set.size() >= max_results)\n\t\treturn true;\n\n\tif (1 == _varseq.size())\n\t{\n\t\t_satisfying_set.emplace(var_soln.at(_varseq[0]));\n\n\t\t\/\/ If we found as many as we want, then stop looking for more.\n\t\treturn (_satisfying_set.size() >= max_results);\n\t}\n\n\t\/\/ If more than one variable, encapsulate in sequential order,\n\t\/\/ in a ListLink.\n\tHandleSeq vargnds;\n\tfor (const Handle& hv : _varseq)\n\t{\n\t\tvargnds.push_back(var_soln.at(hv));\n\t}\n\t_satisfying_set.emplace(Handle(createLink(vargnds, LIST_LINK)));\n\n\t\/\/ If we found as many as we want, then stop looking for more.\n\treturn (_satisfying_set.size() >= max_results);\n}\n\nTruthValuePtr opencog::satisfaction_link(AtomSpace* as, const Handle& hlink)\n{\n\tPatternLinkPtr plp(PatternLinkCast(hlink));\n\tif (NULL == plp)\n\t{\n\t\t\/\/ If it is a BindLink (for example), we want to use that ctor\n\t\t\/\/ instead of the default ctor.\n\t\tif (classserver().isA(hlink->getType(), SATISFACTION_LINK))\n\t\t\tplp = createPatternLink(*LinkCast(hlink));\n\t\telse\n\t\t\tplp = createPatternLink(hlink);\n\t}\n\n\tSatisfier sater(as);\n\tplp->satisfy(sater);\n\n\t\/\/ Cache the variable groundings. OpenPsi wants this.\n\tplp->set_groundings(sater._ground);\n\treturn sater._result;\n}\n\nHandle opencog::satisfying_set(AtomSpace* as, const Handle& hlink, size_t max_results)\n{\n\t\/\/ Special case the BindLink. We probably shouldn't have to, and\n\t\/\/ the C++ code for handling this case could maybe be refactored\n\t\/\/ to handle BindLink as well as GetLink in one place... but right\n\t\/\/ now, it doesn't.\n\tType blt = hlink->getType();\n\tif (BIND_LINK == blt)\n\t{\n\t\treturn bindlink(as, hlink, max_results);\n\t}\n\tif (DUAL_LINK == blt)\n\t{\n\t\treturn recognize(as, hlink);\n\t}\n\n\t\/\/ If we are here, then we are a GET_LINK, right?\n\tif (GET_LINK != blt)\n\t\tthrow RuntimeException(TRACE_INFO,\n\t\t\t\"Unexpected SatisfyingLink type!\");\n\n\tPatternLinkPtr bl(PatternLinkCast(hlink));\n\tif (NULL == bl)\n\t{\n\t\tbl = createPatternLink(*LinkCast(hlink));\n\t}\n\n\tSatisfyingSet sater(as);\n\tsater.max_results = max_results;\n\tbl->satisfy(sater);\n\n\t\/\/ Ugh. We used an std::set to avoid duplicates. But now, we need a\n\t\/\/ vector. Which means copying. Got a better idea?\n\tHandleSeq satvec;\n\tfor (const Handle& h : sater._satisfying_set)\n\t\tsatvec.push_back(h);\n\n\t\/\/ Create the satisfying set, and cache it.\n\tHandle satset(createLink(satvec, SET_LINK));\n\n#define PLACE_RESULTS_IN_ATOMSPACE\n#ifdef PLACE_RESULTS_IN_ATOMSPACE\n\t\/\/ Shoot. XXX FIXME. Most of the unit tests require that the atom\n\t\/\/ that we return is in the atomspace. But it would be nice if we\n\t\/\/ could defer this indefinitely, until its really needed.\n\tsatset = as->add_atom(satset);\n#endif \/* PLACE_RESULTS_IN_ATOMSPACE *\/\n\tbl->set_groundings(satset);\n\n\treturn satset;\n}\n\n\/* ===================== END OF FILE ===================== *\/\nPlace results in atomspace\/*\n * Satisfier.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n *\n * Author: Linas Vepstas January 2009\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program 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 General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n\n#include \"BindLinkAPI.h\"\n#include \"Satisfier.h\"\n\nusing namespace opencog;\n\nbool Satisfier::grounding(const HandleMap &var_soln,\n const HandleMap &term_soln)\n{\n\t\/\/ PatternMatchEngine::print_solution(var_soln, term_soln);\n\t_result = TruthValue::TRUE_TV();\n\n\t\/\/ Record the grounding; we cache this later.\n\tif (1 == _varseq.size())\n\t{\n\t\t_ground = var_soln.at(_varseq[0]);\n\t}\n\telse\n\t{\n\t\t\/\/ If more than one variable, encapsulate in sequential order,\n\t\t\/\/ in a ListLink.\n\t\tHandleSeq vargnds;\n\t\tfor (const Handle& hv : _varseq)\n\t\t{\n\t\t\tvargnds.push_back(var_soln.at(hv));\n\t\t}\n\t\t_ground = createLink(vargnds, LIST_LINK);\n\t}\n\n\t\/\/ No need to look for more groundings as _result isn't going to change\n\t\/\/ and opencog::satisfaction_link only needs the value of _result.\n\treturn true;\n}\n\n\/\/\/ This method handles the case of SequentialAnd, SequentialOr with\n\/\/\/ embedded AbsentLinks, NotLink-PresentLink and some weird\n\/\/\/ combinations of NotLink-ChoiceLink, and so-on. The idea here is\n\/\/\/ that, if the pattern matcher ran to exhaustion, and NO groundings\n\/\/\/ at all were found, then pattern evaluation may still need to\n\/\/\/ trigger evaluatable clauses that evaluate only when exhaustive\n\/\/\/ search fails. So, indeed, we do that here.\n\/\/\/\n\/\/\/ Of course, if the pattern had no variables (e.g. a SequenceLink or\n\/\/\/ FallbackLink with only evaluatables), then there cannot be a\n\/\/\/ grounding failure, by definition. And if there was a grounding,\n\/\/\/ there can be no grounding failure, either. So we only process the\n\/\/\/ case where there are variables, and grounding failed.\nbool Satisfier::search_finished(bool done)\n{\n\tif (done) return done;\n\n\t\/\/ If there were no variables to be grounded, we have nothing to do.\n\tif (not _have_variables) return done;\n\n\t\/\/ If there was a grounding, then don't re-run; we're here\n\t\/\/ only to handle the no-groundings case.\n\tif (TruthValue::TRUE_TV() == _result) return done;\n\n\t\/\/ _optionals_present will be set to true if some optional clause\n\t\/\/ was grounded. Ergo, its not the no-grounding case.\n\tif (_optionals_present) return done;\n\n\t\/\/ Multi-component patterns will not have distinct bodies.\n\t\/\/ A failure to match one of the components is benign, and is\n\t\/\/ treated appropriately upstream. Just return.\n\tif (nullptr == _pattern_body) return done;\n\n\t\/\/ Evaluating the pattern body only makes sense if it is sequential\n\t\/\/ (ordered) -- if the body is an unordered AndLink, or if its a\n\t\/\/ ChoiceLink, etc, this makes no sense.\n\tType btype = _pattern_body->getType();\n\tif (SEQUENTIAL_AND_LINK != btype and SEQUENTIAL_OR_LINK != btype)\n\t\treturn done;\n\n\tHandleMap empty;\n\tbool rc = eval_sentence(_pattern_body, empty);\n\tif (rc)\n\t\t_result = TruthValue::TRUE_TV();\n\n\treturn rc;\n}\n\n\/\/ ===========================================================\n\nbool SatisfyingSet::grounding(const HandleMap &var_soln,\n const HandleMap &term_soln)\n{\n\t\/\/ PatternMatchEngine::log_solution(var_soln, term_soln);\n\n\t\/\/ Do not accept new solution if maximum number has been already reached\n\tif (_satisfying_set.size() >= max_results)\n\t\treturn true;\n\n\tif (1 == _varseq.size())\n\t{\n\t\t_satisfying_set.emplace(var_soln.at(_varseq[0]));\n\n\t\t\/\/ If we found as many as we want, then stop looking for more.\n\t\treturn (_satisfying_set.size() >= max_results);\n\t}\n\n\t\/\/ If more than one variable, encapsulate in sequential order,\n\t\/\/ in a ListLink.\n\tHandleSeq vargnds;\n\tfor (const Handle& hv : _varseq)\n\t{\n\t\tvargnds.push_back(var_soln.at(hv));\n\t}\n\t_satisfying_set.emplace(Handle(createLink(vargnds, LIST_LINK)));\n\n\t\/\/ If we found as many as we want, then stop looking for more.\n\treturn (_satisfying_set.size() >= max_results);\n}\n\nTruthValuePtr opencog::satisfaction_link(AtomSpace* as, const Handle& hlink)\n{\n\tPatternLinkPtr plp(PatternLinkCast(hlink));\n\tif (NULL == plp)\n\t{\n\t\t\/\/ If it is a BindLink (for example), we want to use that ctor\n\t\t\/\/ instead of the default ctor.\n\t\tif (classserver().isA(hlink->getType(), SATISFACTION_LINK))\n\t\t\tplp = createPatternLink(*LinkCast(hlink));\n\t\telse\n\t\t\tplp = createPatternLink(hlink);\n\t}\n\n\tSatisfier sater(as);\n\tplp->satisfy(sater);\n\n#define PLACE_RESULTS_IN_ATOMSPACE\n#ifdef PLACE_RESULTS_IN_ATOMSPACE\n\t\/\/ Shoot. XXX FIXME. Most of the unit tests require that the atom\n\t\/\/ that we return is in the atomspace. But it would be nice if we\n\t\/\/ could defer this indefinitely, until its really needed.\n\tHandle satgrd = as->add_atom(sater._ground);\n#endif \/* PLACE_RESULTS_IN_ATOMSPACE *\/\n\n\t\/\/ Cache the variable groundings. OpenPsi wants this.\n\tplp->set_groundings(satgrd);\n\n\treturn sater._result;\n}\n\nHandle opencog::satisfying_set(AtomSpace* as, const Handle& hlink, size_t max_results)\n{\n\t\/\/ Special case the BindLink. We probably shouldn't have to, and\n\t\/\/ the C++ code for handling this case could maybe be refactored\n\t\/\/ to handle BindLink as well as GetLink in one place... but right\n\t\/\/ now, it doesn't.\n\tType blt = hlink->getType();\n\tif (BIND_LINK == blt)\n\t{\n\t\treturn bindlink(as, hlink, max_results);\n\t}\n\tif (DUAL_LINK == blt)\n\t{\n\t\treturn recognize(as, hlink);\n\t}\n\n\t\/\/ If we are here, then we are a GET_LINK, right?\n\tif (GET_LINK != blt)\n\t\tthrow RuntimeException(TRACE_INFO,\n\t\t\t\"Unexpected SatisfyingLink type!\");\n\n\tPatternLinkPtr bl(PatternLinkCast(hlink));\n\tif (NULL == bl)\n\t{\n\t\tbl = createPatternLink(*LinkCast(hlink));\n\t}\n\n\tSatisfyingSet sater(as);\n\tsater.max_results = max_results;\n\tbl->satisfy(sater);\n\n\t\/\/ Ugh. We used an std::set to avoid duplicates. But now, we need a\n\t\/\/ vector. Which means copying. Got a better idea?\n\tHandleSeq satvec;\n\tfor (const Handle& h : sater._satisfying_set)\n\t\tsatvec.push_back(h);\n\n\t\/\/ Create the satisfying set, and cache it.\n\tHandle satset(createLink(satvec, SET_LINK));\n\n#define PLACE_RESULTS_IN_ATOMSPACE\n#ifdef PLACE_RESULTS_IN_ATOMSPACE\n\t\/\/ Shoot. XXX FIXME. Most of the unit tests require that the atom\n\t\/\/ that we return is in the atomspace. But it would be nice if we\n\t\/\/ could defer this indefinitely, until its really needed.\n\tsatset = as->add_atom(satset);\n#endif \/* PLACE_RESULTS_IN_ATOMSPACE *\/\n\tbl->set_groundings(satset);\n\n\treturn satset;\n}\n\n\/* ===================== END OF FILE ===================== *\/\n<|endoftext|>"} {"text":"Revert of Remove unneeded DocumentLoader null check in WindowProxy. (patchset #1 id:1 of https:\/\/codereview.chromium.org\/797483003\/)<|endoftext|>"} {"text":"#include \"BarcodeFormat.h\"\n\n\/\/ Reader\n#include \"DecodeHints.h\"\n#include \"GenericLuminanceSource.h\"\n#include \"HybridBinarizer.h\"\n#include \"MultiFormatReader.h\"\n#include \"Result.h\"\n\n\/\/ Writer\n#include \"BitMatrix.h\"\n#include \"MultiFormatWriter.h\"\n#include \"TextUtfEncoding.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace ZXing;\nnamespace py = pybind11;\n\n\/\/ Numpy array wrapper class for images (either BGR or GRAYSCALE)\nusing Image = py::array_t;\n\nResult read_barcode(const Image& image, BarcodeFormats formats, bool fastMode, bool tryRotate, bool hybridBinarizer)\n{\n\tDecodeHints hints;\n\thints.setTryHarder(!fastMode);\n\thints.setTryRotate(tryRotate);\n\thints.setPossibleFormats(formats);\n\tMultiFormatReader reader(hints);\n\tconst auto height = static_cast(image.shape(0));\n\tconst auto width = static_cast(image.shape(1));\n\tconst auto bytes = image.data();\n\tstd::shared_ptr source;\n\n\tif (image.ndim() == 2) {\n\t\t\/\/ Grayscale image\n\t\tsource = std::make_shared(width, height, bytes, width);\n\t} else {\n\t\t\/\/ BGR image\n\t\tconst auto channels = image.shape(2);\n\t\tsource = std::make_shared(width, height, bytes, width * channels, channels, 2, 1, 0);\n\t}\n\n\tif (hybridBinarizer) {\n\t\treturn reader.read(HybridBinarizer(source));\n\t} else {\n\t\treturn reader.read(GlobalHistogramBinarizer(source));\n\t}\n}\n\nImage write_barcode(BarcodeFormat format, std::string text, int width, int height, int margin, int eccLevel)\n{\n\tauto writer = MultiFormatWriter(format).setMargin(margin).setEccLevel(eccLevel);\n\tauto bitmap = writer.encode(TextUtfEncoding::FromUtf8(text), width, height);\n\n\tauto result = Image({bitmap.width(), bitmap.height()});\n\tauto r = result.mutable_unchecked<2>();\n\tfor (ssize_t y = 0; y < r.shape(0); y++)\n\t\tfor (ssize_t x = 0; x < r.shape(1); x++)\n\t\t\tr(y, x) = bitmap.get(x, y) ? 0 : 255;\n\treturn result;\n}\n\nPYBIND11_MODULE(zxing, m)\n{\n\tm.doc() = \"python bindings for zxing-cpp\";\n\tpy::enum_(m, \"BarcodeFormat\")\n\t\t.value(\"AZTEC\", BarcodeFormat::AZTEC)\n\t\t.value(\"CODABAR\", BarcodeFormat::CODABAR)\n\t\t.value(\"CODE_39\", BarcodeFormat::CODE_39)\n\t\t.value(\"CODE_93\", BarcodeFormat::CODE_93)\n\t\t.value(\"CODE_128\", BarcodeFormat::CODE_128)\n\t\t.value(\"DATA_MATRIX\", BarcodeFormat::DATA_MATRIX)\n\t\t.value(\"EAN_8\", BarcodeFormat::EAN_8)\n\t\t.value(\"EAN_13\", BarcodeFormat::EAN_13)\n\t\t.value(\"ITF\", BarcodeFormat::ITF)\n\t\t.value(\"MAXICODE\", BarcodeFormat::MAXICODE)\n\t\t.value(\"PDF_417\", BarcodeFormat::PDF_417)\n\t\t.value(\"QR_CODE\", BarcodeFormat::QR_CODE)\n\t\t.value(\"RSS_14\", BarcodeFormat::RSS_14)\n\t\t.value(\"RSS_EXPANDED\", BarcodeFormat::RSS_EXPANDED)\n\t\t.value(\"UPC_A\", BarcodeFormat::UPC_A)\n\t\t.value(\"UPC_E\", BarcodeFormat::UPC_E)\n\t\t.value(\"UPC_EAN_EXTENSION\", BarcodeFormat::UPC_EAN_EXTENSION)\n\t\t.value(\"FORMAT_COUNT\", BarcodeFormat::FORMAT_COUNT)\n\t\t.value(\"INVALID\", BarcodeFormat::INVALID)\n\t\t.export_values();\n\tpy::class_(m, \"ResultPoint\")\n\t\t.def_property_readonly(\"x\", &ResultPoint::x)\n\t\t.def_property_readonly(\"y\", &ResultPoint::y);\n\tpy::class_(m, \"Result\")\n\t\t.def_property_readonly(\"valid\", &Result::isValid)\n\t\t.def_property_readonly(\"text\", &Result::text)\n\t\t.def_property_readonly(\"format\", &Result::format)\n\t\t.def_property_readonly(\"points\", &Result::resultPoints);\n\tm.def(\"barcode_format_from_str\", &BarcodeFormatFromString, \"Convert string to BarcodeFormat\", py::arg(\"str\"));\n\tm.def(\"barcode_formats_from_str\", &BarcodeFormatsFromString, \"Convert string to BarcodeFormats\", py::arg(\"str\"));\n\tm.def(\"read_barcode\", &read_barcode, \"Read (decode) a barcode from a numpy BGR or grayscale image array\",\n\t\tpy::arg(\"image\"),\n\t\tpy::arg(\"formats\") = BarcodeFormats{},\n\t\tpy::arg(\"fastMode\") = false,\n\t\tpy::arg(\"tryRotate\") = true,\n\t\tpy::arg(\"hybridBinarizer\") = true\n\t);\n\tm.def(\"write_barcode\", &write_barcode, \"Write (encode) a text into a barcode and return numpy image array\",\n\t\tpy::arg(\"format\"),\n\t\tpy::arg(\"text\"),\n\t\tpy::arg(\"width\") = 0,\n\t\tpy::arg(\"height\") = 0,\n\t\tpy::arg(\"margin\") = -1,\n\t\tpy::arg(\"eccLevel\") = -1\n\t);\n}\npython: fix more VS warnings (introduced with write_barcode function)#include \"BarcodeFormat.h\"\n\n\/\/ Reader\n#include \"DecodeHints.h\"\n#include \"GenericLuminanceSource.h\"\n#include \"HybridBinarizer.h\"\n#include \"MultiFormatReader.h\"\n#include \"Result.h\"\n\n\/\/ Writer\n#include \"BitMatrix.h\"\n#include \"MultiFormatWriter.h\"\n#include \"TextUtfEncoding.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace ZXing;\nnamespace py = pybind11;\n\n\/\/ Numpy array wrapper class for images (either BGR or GRAYSCALE)\nusing Image = py::array_t;\n\ntemplate\nOUT narrow(IN in)\n{\n\treturn static_cast(in);\n}\n\nResult read_barcode(const Image& image, BarcodeFormats formats, bool fastMode, bool tryRotate, bool hybridBinarizer)\n{\n\tDecodeHints hints;\n\thints.setTryHarder(!fastMode);\n\thints.setTryRotate(tryRotate);\n\thints.setPossibleFormats(formats);\n\tMultiFormatReader reader(hints);\n\tconst auto height = narrow(image.shape(0));\n\tconst auto width = narrow(image.shape(1));\n\tconst auto bytes = image.data();\n\tstd::shared_ptr source;\n\n\tif (image.ndim() == 2) {\n\t\t\/\/ Grayscale image\n\t\tsource = std::make_shared(width, height, bytes, width);\n\t} else {\n\t\t\/\/ BGR image\n\t\tconst auto channels = image.shape(2);\n\t\tsource = std::make_shared(width, height, bytes, width * channels, channels, 2, 1, 0);\n\t}\n\n\tif (hybridBinarizer) {\n\t\treturn reader.read(HybridBinarizer(source));\n\t} else {\n\t\treturn reader.read(GlobalHistogramBinarizer(source));\n\t}\n}\n\nImage write_barcode(BarcodeFormat format, std::string text, int width, int height, int margin, int eccLevel)\n{\n\tauto writer = MultiFormatWriter(format).setMargin(margin).setEccLevel(eccLevel);\n\tauto bitmap = writer.encode(TextUtfEncoding::FromUtf8(text), width, height);\n\n\tauto result = Image({bitmap.width(), bitmap.height()});\n\tauto r = result.mutable_unchecked<2>();\n\tfor (ssize_t y = 0; y < r.shape(0); y++)\n\t\tfor (ssize_t x = 0; x < r.shape(1); x++)\n\t\t\tr(y, x) = bitmap.get(narrow(x), narrow(y)) ? 0 : 255;\n\treturn result;\n}\n\nPYBIND11_MODULE(zxing, m)\n{\n\tm.doc() = \"python bindings for zxing-cpp\";\n\tpy::enum_(m, \"BarcodeFormat\")\n\t\t.value(\"AZTEC\", BarcodeFormat::AZTEC)\n\t\t.value(\"CODABAR\", BarcodeFormat::CODABAR)\n\t\t.value(\"CODE_39\", BarcodeFormat::CODE_39)\n\t\t.value(\"CODE_93\", BarcodeFormat::CODE_93)\n\t\t.value(\"CODE_128\", BarcodeFormat::CODE_128)\n\t\t.value(\"DATA_MATRIX\", BarcodeFormat::DATA_MATRIX)\n\t\t.value(\"EAN_8\", BarcodeFormat::EAN_8)\n\t\t.value(\"EAN_13\", BarcodeFormat::EAN_13)\n\t\t.value(\"ITF\", BarcodeFormat::ITF)\n\t\t.value(\"MAXICODE\", BarcodeFormat::MAXICODE)\n\t\t.value(\"PDF_417\", BarcodeFormat::PDF_417)\n\t\t.value(\"QR_CODE\", BarcodeFormat::QR_CODE)\n\t\t.value(\"RSS_14\", BarcodeFormat::RSS_14)\n\t\t.value(\"RSS_EXPANDED\", BarcodeFormat::RSS_EXPANDED)\n\t\t.value(\"UPC_A\", BarcodeFormat::UPC_A)\n\t\t.value(\"UPC_E\", BarcodeFormat::UPC_E)\n\t\t.value(\"UPC_EAN_EXTENSION\", BarcodeFormat::UPC_EAN_EXTENSION)\n\t\t.value(\"FORMAT_COUNT\", BarcodeFormat::FORMAT_COUNT)\n\t\t.value(\"INVALID\", BarcodeFormat::INVALID)\n\t\t.export_values();\n\tpy::class_(m, \"ResultPoint\")\n\t\t.def_property_readonly(\"x\", &ResultPoint::x)\n\t\t.def_property_readonly(\"y\", &ResultPoint::y);\n\tpy::class_(m, \"Result\")\n\t\t.def_property_readonly(\"valid\", &Result::isValid)\n\t\t.def_property_readonly(\"text\", &Result::text)\n\t\t.def_property_readonly(\"format\", &Result::format)\n\t\t.def_property_readonly(\"points\", &Result::resultPoints);\n\tm.def(\"barcode_format_from_str\", &BarcodeFormatFromString, \"Convert string to BarcodeFormat\", py::arg(\"str\"));\n\tm.def(\"barcode_formats_from_str\", &BarcodeFormatsFromString, \"Convert string to BarcodeFormats\", py::arg(\"str\"));\n\tm.def(\"read_barcode\", &read_barcode, \"Read (decode) a barcode from a numpy BGR or grayscale image array\",\n\t\tpy::arg(\"image\"),\n\t\tpy::arg(\"formats\") = BarcodeFormats{},\n\t\tpy::arg(\"fastMode\") = false,\n\t\tpy::arg(\"tryRotate\") = true,\n\t\tpy::arg(\"hybridBinarizer\") = true\n\t);\n\tm.def(\"write_barcode\", &write_barcode, \"Write (encode) a text into a barcode and return numpy image array\",\n\t\tpy::arg(\"format\"),\n\t\tpy::arg(\"text\"),\n\t\tpy::arg(\"width\") = 0,\n\t\tpy::arg(\"height\") = 0,\n\t\tpy::arg(\"margin\") = -1,\n\t\tpy::arg(\"eccLevel\") = -1\n\t);\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of the hdf5 data handler for the OPeNDAP data server.\n\/\/\n\/\/ Author: Hyo-Kyung Lee \n\/\/ Copyright (c) 2007 The HDF Group\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ #define DODS_DEBUG\n#include \n#include \n#include \n#include \n#include \n\n#include \"H5EOS.h\"\n\nusing namespace std;\n\nint hdfeoslex();\nint hdfeosparse(void *arg);\nstruct yy_buffer_state;\nyy_buffer_state *hdfeos_scan_string(const char *str);\nextern bool valid_projection;\nextern bool grid_structure_found;\nH5EOS::H5EOS()\n{\n TES = false;\n valid = false;\n point_lower = 0.0f;\n point_upper = 0.0f;\n point_left = 0.0f;\n point_right = 0.0f;\n gradient_x = 0.0f;\n gradient_y = 0.0f;\n dimension_data = NULL;\n bmetadata_Struct = false;\n#ifdef NASA_EOS_META\n bmetadata_Archived = false;\n bmetadata_Core = false;\n bmetadata_core = false;\n bmetadata_product = false;\n bmetadata_subset = false;\n#endif\n\n}\n\nH5EOS::~H5EOS()\n{\n}\n\n\nbool H5EOS::has_group(hid_t id, const char *name)\n{\n hid_t hid;\n H5E_BEGIN_TRY {\n hid = H5Gopen(id, name);\n } H5E_END_TRY;\n if (hid < 0) {\n return false;\n } else {\n return true;\n }\n\n}\n\nbool H5EOS::has_dataset(hid_t id, const char *name)\n{\n hid_t hid;\n H5E_BEGIN_TRY {\n hid = H5Dopen(id, name);\n } H5E_END_TRY; \/\/ \n if (hid < 0) {\n return false;\n } else {\n return true;\n }\n}\n\nvoid H5EOS::add_data_path(string full_path)\n{\n#ifdef CF\n string short_path = generate_short_name(full_path);\n DBG(cerr << \"Short path is:\" << short_path << endl); \n long_to_short[full_path] = short_path;\n#endif\n\n DBG(cerr << \"Full path is:\" << full_path << endl);\n full_data_paths.push_back(full_path);\n}\n\n\nvoid H5EOS::add_dimension_list(string full_path, string dimension_list)\n{\n full_data_path_to_dimension_list_map[full_path] = dimension_list;\n DBG(cerr << \"Dimension List is:\" <<\n full_data_path_to_dimension_list_map[full_path] << endl);\n}\n\nvoid H5EOS::add_dimension_map(string dimension_name, int dimension)\n{\n bool has_dimension = false;\n#ifdef CF\n dimension_name = cut_long_name(dimension_name);\n#endif\n\n int i;\n for (i = 0; i < (int) dimensions.size(); i++) {\n std::string str = dimensions.at(i);\n if (str == dimension_name) {\n has_dimension = true;\n break;\n }\n }\n\n if (!has_dimension) {\n dimensions.push_back(dimension_name);\n dimension_map[dimension_name] = dimension;\n }\n}\n\nbool H5EOS::check_eos(hid_t id)\n{\n\n reset();\n \n \/\/ Check if this file has the group called \"HDFEOS INFORMATION\".\n if (has_group(id, \"HDFEOS INFORMATION\")) {\n\n if (set_metadata(id, \"StructMetadata\", metadata_Struct)) {\n valid = true;\n } else {\n valid = false;\n }\n\n if (valid) {\n hdfeos_scan_string(metadata_Struct);\n hdfeosparse(this);\n#ifdef NASA_EOS_META\n set_metadata(id, \"coremetadata\", metadata_core);\n \/\/ cerr << metadata_core << endl;\n if(string(metadata_core).find(\"\\\"TES\\\"\") != string::npos){\n\tTES = true;\n }\n \n set_metadata(id, \"CoreMetadata\", metadata_Core);\n set_metadata(id, \"ArchivedMetadata\", metadata_Archived);\n set_metadata(id, \"subsetmetadata\", metadata_subset);\n set_metadata(id, \"productmetadata\", metadata_product);\n#endif\n }\n\n return valid;\n }\n return false;\n}\n\nvoid H5EOS::get_dimensions(string name, vector < string > &tokens)\n{\n string str = full_data_path_to_dimension_list_map[name];\n \/\/ Skip delimiters at beginning.\n string::size_type lastPos = str.find_first_not_of(',', 0);\n \/\/ Find first \"non-delimiter\".\n string::size_type pos = str.find_first_of(',', lastPos);\n\n while (string::npos != pos || string::npos != lastPos) {\n \/\/ Found a token, add it to the vector.\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n \/\/ Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of(',', pos);\n \/\/ Find next \"non-delimiter\"\n pos = str.find_first_of(',', lastPos);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Retrieve the dimension list from the argument \"name\" grid and tokenize the list into the string vector.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint H5EOS::get_dimension_size(string name)\n{\n return dimension_map[name];\n}\n\nbool H5EOS::is_grid(string name)\n{\n int i;\n for (i = 0; i < (int) full_data_paths.size(); i++) {\n std::string str = full_data_paths.at(i);\n if (str == name) {\n return true;\n }\n }\n return false;\n}\n\nbool H5EOS::is_TES()\n{\n return TES;\n}\n\nbool H5EOS::is_valid()\n{\n return valid;\n}\n\nvoid H5EOS::print()\n{\n\n cout << \"Left = \" << point_left << endl;\n cout << \"Right = \" << point_right << endl;\n cout << \"Lower = \" << point_lower << endl;\n cout << \"Upper = \" << point_upper << endl;\n\n cout << \"Total number of paths = \" << full_data_paths.size() << endl;\n for (int i = 0; i < (int) full_data_paths.size(); i++) {\n cout << \"Element \" << full_data_paths.at(i) << endl;\n }\n}\n\nbool H5EOS::set_dimension_array()\n{\n int i = 0;\n int j = 0;\n int size = dimensions.size();\n\n dods_float32 *convbuf = NULL;\n \n if (libdap::size_ok(sizeof(dods_float32), size))\n dimension_data = new dods_float32*[size];\n else\n throw InternalErr(__FILE__, __LINE__,\n\t\t \"Unable to allocate memory.\");\n DBG(cerr << \">set_dimension_array():Dimensions size = \" << size <<\n endl);\n for (j = 0; j < (int) dimensions.size(); j++) {\n string dim_name = dimensions.at(j);\n int dim_size = dimension_map[dim_name];\n\n DBG(cerr << \"=set_dimension_array():Dim name = \" << dim_name <<\n\tstd::endl);\n DBG(cerr << \"=set_dimension_array():Dim size = \" << dim_size <<\n\tstd::endl);\n\n if (dim_size > 0) {\n if (libdap::size_ok(sizeof(dods_float32), dim_size))\n\tconvbuf = new dods_float32[dim_size];\n else\n\tthrow InternalErr(__FILE__, __LINE__,\n\t\t\t \"Unable to allocate memory.\");\n\n if ((dim_name.find(\"XDim\", (int) dim_name.size() - 4)) !=\n\t string::npos) {\n\tgradient_x =\n\t (point_right - point_left) \/ (float) (dim_size);\n\tfor (i = 0; i < dim_size; i++) {\n\t if(!TES){\n\t convbuf[i] = (dods_float32)\n\t (point_left + (float) i * gradient_x + (gradient_x \/ 2.0)) \/ 1000000.0;\n\t }\n\t else{\n\t convbuf[i] = (dods_float32)\n\t (point_left + (float) i * gradient_x) \/ 1000000.0;\t \n\t }\n\t}\n } else if ((dim_name.find(\"YDim\", (int) dim_name.size() - 4))\n\t\t != string::npos) {\n\t\n\tif(TES){\n\t \/\/ swap the upper and lower points for TES products\n\t float temp = point_upper;\n\t point_upper = point_lower;\n\t point_lower = temp;\n\t}\n\t\n\tgradient_y =\n\t (point_upper - point_lower) \/ (float) (dim_size);\t\n\tfor (i = 0; i < dim_size; i++) {\n\t if(!TES){\n\t convbuf[i] = (dods_float32)\n\t (point_lower + (float) i * gradient_y + (gradient_y \/ 2.0)) \/ 1000000.0;\n\t }\n\t else{\n\t gradient_y = ceilf(gradient_y\/1000000.0f) * 1000000.0f;\n\t convbuf[i] = (dods_float32)\n\t (point_lower + (float) i * gradient_y) \/ 1000000.0;\t \n\t }\n\t}\n } else {\n\tfor (i = 0; i < dim_size; i++) {\n\t convbuf[i] = (dods_float32) i; \/\/ meaningless number.\n\t}\n }\n } \/\/ if dim_size > 0\n else {\n DBG(cerr << \"Negative dimension \" << endl);\n return false;\n }\n dimension_data[j] = convbuf;\n } \/\/ for\n DBG(cerr << \".0.\n \/\/ Forexample, \"coremetadata\" and then \"coremetadata.1\".\n if (i > 2)\n\tbreak;\n }\n }\n\n return valid;\n\n}\n\nvoid H5EOS::reset()\n{\n int j;\n grid_structure_found = false;\n valid_projection = false;\n valid = false;\n point_lower = 0.0;\n point_upper = 0.0;\n point_left = 0.0;\n point_right = 0.0;\n gradient_x = 0.0;\n gradient_y = 0.0;\n bmetadata_Struct = false;\n#ifdef NASA_EOS_META\n bmetadata_Archived = false;\n bmetadata_Core = false;\n bmetadata_core = false;\n bmetadata_product = false;\n bmetadata_subset = false;\n#endif\n \n if(dimension_data != NULL){\n for (j = 0; j < (int) dimensions.size(); j++) {\n if(dimension_data[j] != NULL)\n\tdelete dimension_data[j];\n }\n delete dimension_data;\n dimension_data = NULL;\n }\n\n if(!dimension_map.empty()){\n dimension_map.clear();\n }\n if(!full_data_path_to_dimension_list_map.empty()){\n full_data_path_to_dimension_list_map.clear();\n }\n \n if(!dimensions.empty()){\n dimensions.clear();\n }\n if(!full_data_paths.empty()){\n full_data_paths.clear();\n }\n \/\/ Clear the contents of the metadata string buffer.\n strcpy(metadata_Struct, \"\");\n strcpy(metadata_Archived, \"\");\n strcpy(metadata_Core, \"\");\n strcpy(metadata_core, \"\");\n strcpy(metadata_product, \"\");\n strcpy(metadata_subset, \"\");\n H5CF::reset();\n}\n\nvoid H5EOS::get_all_dimensions(vector < string > &tokens)\n{\n int j;\n for (j = 0; j < (int) dimensions.size(); j++) {\n string dim_name = dimensions.at(j);\n tokens.push_back(dim_name);\n DBG(cerr << \"=get_all_dimensions():Dim name = \" << dim_name <<\n\tstd::endl);\n }\n}\n\nAdded TES = false inside H5EOS::reset().\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of the hdf5 data handler for the OPeNDAP data server.\n\/\/\n\/\/ Author: Hyo-Kyung Lee \n\/\/ Copyright (c) 2007 The HDF Group\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ #define DODS_DEBUG\n#include \n#include \n#include \n#include \n#include \n\n#include \"H5EOS.h\"\n\nusing namespace std;\n\nint hdfeoslex();\nint hdfeosparse(void *arg);\nstruct yy_buffer_state;\nyy_buffer_state *hdfeos_scan_string(const char *str);\nextern bool valid_projection;\nextern bool grid_structure_found;\nH5EOS::H5EOS()\n{\n TES = false;\n valid = false;\n point_lower = 0.0f;\n point_upper = 0.0f;\n point_left = 0.0f;\n point_right = 0.0f;\n gradient_x = 0.0f;\n gradient_y = 0.0f;\n dimension_data = NULL;\n bmetadata_Struct = false;\n#ifdef NASA_EOS_META\n bmetadata_Archived = false;\n bmetadata_Core = false;\n bmetadata_core = false;\n bmetadata_product = false;\n bmetadata_subset = false;\n#endif\n\n}\n\nH5EOS::~H5EOS()\n{\n}\n\n\nbool H5EOS::has_group(hid_t id, const char *name)\n{\n hid_t hid;\n H5E_BEGIN_TRY {\n hid = H5Gopen(id, name);\n } H5E_END_TRY;\n if (hid < 0) {\n return false;\n } else {\n return true;\n }\n\n}\n\nbool H5EOS::has_dataset(hid_t id, const char *name)\n{\n hid_t hid;\n H5E_BEGIN_TRY {\n hid = H5Dopen(id, name);\n } H5E_END_TRY; \/\/ \n if (hid < 0) {\n return false;\n } else {\n return true;\n }\n}\n\nvoid H5EOS::add_data_path(string full_path)\n{\n#ifdef CF\n string short_path = generate_short_name(full_path);\n DBG(cerr << \"Short path is:\" << short_path << endl); \n long_to_short[full_path] = short_path;\n#endif\n\n DBG(cerr << \"Full path is:\" << full_path << endl);\n full_data_paths.push_back(full_path);\n}\n\n\nvoid H5EOS::add_dimension_list(string full_path, string dimension_list)\n{\n full_data_path_to_dimension_list_map[full_path] = dimension_list;\n DBG(cerr << \"Dimension List is:\" <<\n full_data_path_to_dimension_list_map[full_path] << endl);\n}\n\nvoid H5EOS::add_dimension_map(string dimension_name, int dimension)\n{\n bool has_dimension = false;\n#ifdef CF\n dimension_name = cut_long_name(dimension_name);\n#endif\n\n int i;\n for (i = 0; i < (int) dimensions.size(); i++) {\n std::string str = dimensions.at(i);\n if (str == dimension_name) {\n has_dimension = true;\n break;\n }\n }\n\n if (!has_dimension) {\n dimensions.push_back(dimension_name);\n dimension_map[dimension_name] = dimension;\n }\n}\n\nbool H5EOS::check_eos(hid_t id)\n{\n\n reset();\n \n \/\/ Check if this file has the group called \"HDFEOS INFORMATION\".\n if (has_group(id, \"HDFEOS INFORMATION\")) {\n\n if (set_metadata(id, \"StructMetadata\", metadata_Struct)) {\n valid = true;\n } else {\n valid = false;\n }\n\n if (valid) {\n hdfeos_scan_string(metadata_Struct);\n hdfeosparse(this);\n#ifdef NASA_EOS_META\n set_metadata(id, \"coremetadata\", metadata_core);\n \/\/ cerr << metadata_core << endl;\n if(string(metadata_core).find(\"\\\"TES\\\"\") != string::npos){\n\tTES = true;\n }\n \n set_metadata(id, \"CoreMetadata\", metadata_Core);\n set_metadata(id, \"ArchivedMetadata\", metadata_Archived);\n set_metadata(id, \"subsetmetadata\", metadata_subset);\n set_metadata(id, \"productmetadata\", metadata_product);\n#endif\n }\n\n return valid;\n }\n return false;\n}\n\nvoid H5EOS::get_dimensions(string name, vector < string > &tokens)\n{\n string str = full_data_path_to_dimension_list_map[name];\n \/\/ Skip delimiters at beginning.\n string::size_type lastPos = str.find_first_not_of(',', 0);\n \/\/ Find first \"non-delimiter\".\n string::size_type pos = str.find_first_of(',', lastPos);\n\n while (string::npos != pos || string::npos != lastPos) {\n \/\/ Found a token, add it to the vector.\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n \/\/ Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of(',', pos);\n \/\/ Find next \"non-delimiter\"\n pos = str.find_first_of(',', lastPos);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Retrieve the dimension list from the argument \"name\" grid and tokenize the list into the string vector.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint H5EOS::get_dimension_size(string name)\n{\n return dimension_map[name];\n}\n\nbool H5EOS::is_grid(string name)\n{\n int i;\n for (i = 0; i < (int) full_data_paths.size(); i++) {\n std::string str = full_data_paths.at(i);\n if (str == name) {\n return true;\n }\n }\n return false;\n}\n\nbool H5EOS::is_TES()\n{\n return TES;\n}\n\nbool H5EOS::is_valid()\n{\n return valid;\n}\n\nvoid H5EOS::print()\n{\n\n cout << \"Left = \" << point_left << endl;\n cout << \"Right = \" << point_right << endl;\n cout << \"Lower = \" << point_lower << endl;\n cout << \"Upper = \" << point_upper << endl;\n\n cout << \"Total number of paths = \" << full_data_paths.size() << endl;\n for (int i = 0; i < (int) full_data_paths.size(); i++) {\n cout << \"Element \" << full_data_paths.at(i) << endl;\n }\n}\n\nbool H5EOS::set_dimension_array()\n{\n int i = 0;\n int j = 0;\n int size = dimensions.size();\n\n dods_float32 *convbuf = NULL;\n \n if (libdap::size_ok(sizeof(dods_float32), size))\n dimension_data = new dods_float32*[size];\n else\n throw InternalErr(__FILE__, __LINE__,\n\t\t \"Unable to allocate memory.\");\n DBG(cerr << \">set_dimension_array():Dimensions size = \" << size <<\n endl);\n for (j = 0; j < (int) dimensions.size(); j++) {\n string dim_name = dimensions.at(j);\n int dim_size = dimension_map[dim_name];\n\n DBG(cerr << \"=set_dimension_array():Dim name = \" << dim_name <<\n\tstd::endl);\n DBG(cerr << \"=set_dimension_array():Dim size = \" << dim_size <<\n\tstd::endl);\n\n if (dim_size > 0) {\n if (libdap::size_ok(sizeof(dods_float32), dim_size))\n\tconvbuf = new dods_float32[dim_size];\n else\n\tthrow InternalErr(__FILE__, __LINE__,\n\t\t\t \"Unable to allocate memory.\");\n\n if ((dim_name.find(\"XDim\", (int) dim_name.size() - 4)) !=\n\t string::npos) {\n\tgradient_x =\n\t (point_right - point_left) \/ (float) (dim_size);\n\tfor (i = 0; i < dim_size; i++) {\n\t if(!TES){\n\t convbuf[i] = (dods_float32)\n\t (point_left + (float) i * gradient_x + (gradient_x \/ 2.0)) \/ 1000000.0;\n\t }\n\t else{\n\t convbuf[i] = (dods_float32)\n\t (point_left + (float) i * gradient_x) \/ 1000000.0;\t \n\t }\n\t}\n } else if ((dim_name.find(\"YDim\", (int) dim_name.size() - 4))\n\t\t != string::npos) {\n\t\n\tif(TES){\n\t \/\/ swap the upper and lower points for TES products\n\t float temp = point_upper;\n\t point_upper = point_lower;\n\t point_lower = temp;\n\t}\n\t\n\tgradient_y =\n\t (point_upper - point_lower) \/ (float) (dim_size);\t\n\tfor (i = 0; i < dim_size; i++) {\n\t if(!TES){\n\t convbuf[i] = (dods_float32)\n\t (point_lower + (float) i * gradient_y + (gradient_y \/ 2.0)) \/ 1000000.0;\n\t }\n\t else{\n\t gradient_y = ceilf(gradient_y\/1000000.0f) * 1000000.0f;\n\t convbuf[i] = (dods_float32)\n\t (point_lower + (float) i * gradient_y) \/ 1000000.0;\t \n\t }\n\t}\n } else {\n\tfor (i = 0; i < dim_size; i++) {\n\t convbuf[i] = (dods_float32) i; \/\/ meaningless number.\n\t}\n }\n } \/\/ if dim_size > 0\n else {\n DBG(cerr << \"Negative dimension \" << endl);\n return false;\n }\n dimension_data[j] = convbuf;\n } \/\/ for\n DBG(cerr << \".0.\n \/\/ Forexample, \"coremetadata\" and then \"coremetadata.1\".\n if (i > 2)\n\tbreak;\n }\n }\n\n return valid;\n\n}\n\nvoid H5EOS::reset()\n{\n int j;\n grid_structure_found = false;\n valid_projection = false;\n valid = false;\n TES = false;\n point_lower = 0.0;\n point_upper = 0.0;\n point_left = 0.0;\n point_right = 0.0;\n gradient_x = 0.0;\n gradient_y = 0.0;\n bmetadata_Struct = false;\n#ifdef NASA_EOS_META\n bmetadata_Archived = false;\n bmetadata_Core = false;\n bmetadata_core = false;\n bmetadata_product = false;\n bmetadata_subset = false;\n#endif\n \n if(dimension_data != NULL){\n for (j = 0; j < (int) dimensions.size(); j++) {\n if(dimension_data[j] != NULL)\n\tdelete dimension_data[j];\n }\n delete dimension_data;\n dimension_data = NULL;\n }\n\n if(!dimension_map.empty()){\n dimension_map.clear();\n }\n if(!full_data_path_to_dimension_list_map.empty()){\n full_data_path_to_dimension_list_map.clear();\n }\n \n if(!dimensions.empty()){\n dimensions.clear();\n }\n if(!full_data_paths.empty()){\n full_data_paths.clear();\n }\n \/\/ Clear the contents of the metadata string buffer.\n strcpy(metadata_Struct, \"\");\n strcpy(metadata_Archived, \"\");\n strcpy(metadata_Core, \"\");\n strcpy(metadata_core, \"\");\n strcpy(metadata_product, \"\");\n strcpy(metadata_subset, \"\");\n H5CF::reset();\n}\n\nvoid H5EOS::get_all_dimensions(vector < string > &tokens)\n{\n int j;\n for (j = 0; j < (int) dimensions.size(); j++) {\n string dim_name = dimensions.at(j);\n tokens.push_back(dim_name);\n DBG(cerr << \"=get_all_dimensions():Dim name = \" << dim_name <<\n\tstd::endl);\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2016-2017 Jean-Francois Poilpret\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 * Hardware UART example.\n * This program demonstrates usage of FastArduino Hardware UART support (on target supporting it) and formatted\n * input streams.\n * \n * Wiring:\n * - on Arduino UNO, Arduino NANO and Arduino MEGA:\n * - Use standard TX\/RX\n * - on ATmega328P based boards:\n * - Use standard TX\/RX connected to an Serial-USB converter\n * - on ATtinyX4 based boards:\n * - NOT SUPPORTED\n *\/\n\n#include \n#include \n\n\/\/ Define vectors we need in the example\nREGISTER_UART_ISR(0)\n\n\/\/ Buffers for UART\nstatic const uint8_t INPUT_BUFFER_SIZE = 64;\nstatic const uint8_t OUTPUT_BUFFER_SIZE = 64;\nstatic char input_buffer[INPUT_BUFFER_SIZE];\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\n\nusing namespace streams;\n\nusing INPUT = FormattedInput;\nusing OUTPUT = FormattedOutput;\n\ntemplate\nstatic void handle(OUTPUT& out, INPUT& in, const flash::FlashStorage* type)\n{\n\tout << type << F(\": \") << flush;\n\tT value{};\n\tin >> skipws >> value;\n\tout << value << endl;\n}\n\ntemplate\nstatic void display_num(OUTPUT& out, T value)\n{\n\tout << bin << value << endl;\n\tout << dec << value << endl;\n\tout << oct << value << endl;\n\tout << hex << value << endl;\n}\n\ntemplate\nstatic void handle_num(OUTPUT& out, T value, const flash::FlashStorage* type)\n{\n\tout << F(\"testing output of \") << type << F(\" (\") << dec << value << ')' << endl;\n\tdisplay_num(out, value);\n\n\tout << showbase;\n\tdisplay_num(out, value);\n\tout << noshowbase;\n\n\tout << uppercase;\n\tdisplay_num(out, value);\n\tout << nouppercase;\n\n\tout << uppercase << showbase;\n\tdisplay_num(out, value);\n\tout << nouppercase << noshowbase;\n\n\tout << showpos;\n\tdisplay_num(out, value);\n\tout << noshowpos;\n}\n\nint main() __attribute__((OS_main));\nint main()\n{\n\t\/\/ Enable interrupts at startup time\n\tsei();\n\t\n\t\/\/ Start UART\n\tserial::hard::UART uart{input_buffer, output_buffer};\n\tuart.register_handler();\n\tuart.begin(115200);\n\tINPUT in = uart.fin();\n\tOUTPUT out = uart.fout();\n\n\t\/\/ Check all output manipulators\n\thandle_num(out, 1234, F(\"uint16_t\"));\n\thandle_num(out, 1234, F(\"int16_t\"));\n\thandle_num(out, -1234, F(\"int16_t\"));\n\n\thandle_num(out, 123456, F(\"uint32_t\"));\n\thandle_num(out, 123456, F(\"int32_t\"));\n\thandle_num(out, -123456, F(\"int32_t\"));\n\n\t\/\/TODO check floats\n\t\/\/TODO check other types\n\n\t\/\/TODO check justification: setw(), setfill(), left, right...\n\n\t\/\/ Event Loop\n\twhile (true)\n\t{\n\t\thandle(out, in, F(\"char\"));\n\t\thandle(out, in, F(\"uint16_t\"));\n\t\thandle(out, in, F(\"int16_t\"));\n\t\thandle(out, in, F(\"uint32_t\"));\n\t\thandle(out, in, F(\"int32_t\"));\n\t\thandle(out, in, F(\"bool\"));\n\t\t\n\t\ttime::delay_ms(1000);\n\t}\n}\nStream refactoring: add float test cases to example.\/\/ Copyright 2016-2017 Jean-Francois Poilpret\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 * Hardware UART example.\n * This program demonstrates usage of FastArduino Hardware UART support (on target supporting it) and formatted\n * input streams.\n * \n * Wiring:\n * - on Arduino UNO, Arduino NANO and Arduino MEGA:\n * - Use standard TX\/RX\n * - on ATmega328P based boards:\n * - Use standard TX\/RX connected to an Serial-USB converter\n * - on ATtinyX4 based boards:\n * - NOT SUPPORTED\n *\/\n\n#include \n#include \n\n\/\/ Define vectors we need in the example\nREGISTER_UART_ISR(0)\n\n\/\/ Buffers for UART\nstatic const uint8_t INPUT_BUFFER_SIZE = 64;\nstatic const uint8_t OUTPUT_BUFFER_SIZE = 64;\nstatic char input_buffer[INPUT_BUFFER_SIZE];\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\n\nusing namespace streams;\n\nusing INPUT = FormattedInput;\nusing OUTPUT = FormattedOutput;\n\ntemplate\nstatic void handle(OUTPUT& out, INPUT& in, const flash::FlashStorage* type)\n{\n\tout << type << F(\": \") << flush;\n\tT value{};\n\tin >> skipws >> value;\n\tout << value << endl;\n}\n\ntemplate\nstatic void display_num(OUTPUT& out, T value)\n{\n\tout << bin << value << endl;\n\tout << dec << value << endl;\n\tout << oct << value << endl;\n\tout << hex << value << endl;\n}\n\ntemplate\nstatic void handle_num(OUTPUT& out, T value, const flash::FlashStorage* type)\n{\n\tout << F(\"testing output of \") << type << F(\" (\") << dec << value << ')' << endl;\n\tdisplay_num(out, value);\n\n\tout << showbase;\n\tdisplay_num(out, value);\n\tout << noshowbase;\n\n\tout << uppercase;\n\tdisplay_num(out, value);\n\tout << nouppercase;\n\n\tout << uppercase << showbase;\n\tdisplay_num(out, value);\n\tout << nouppercase << noshowbase;\n\n\tout << showpos;\n\tdisplay_num(out, value);\n\tout << noshowpos;\n}\n\nstatic void handle_float(OUTPUT& out, double value)\n{\n\tout << F(\"testing output of double (\") << defaultfloat << value << ')' << endl;\n\tdisplay_num(out, value);\n\n\tout << showbase;\n\tdisplay_num(out, value);\n\tout << noshowbase;\n\n\tout << defaultfloat << value << endl;\n\tout << fixed << value << endl;\n\tout << scientific << value << endl;\n\n\tout << uppercase;\n\tout << defaultfloat << value << endl;\n\tout << fixed << value << endl;\n\tout << scientific << value << endl;\n\tout << nouppercase;\n\n\tout << showpos;\n\tout << defaultfloat << value << endl;\n\tout << fixed << value << endl;\n\tout << scientific << value << endl;\n\tout << noshowpos;\n\n\t\/\/TODO check precision too\n}\n\nint main() __attribute__((OS_main));\nint main()\n{\n\t\/\/ Enable interrupts at startup time\n\tsei();\n\t\n\t\/\/ Start UART\n\tserial::hard::UART uart{input_buffer, output_buffer};\n\tuart.register_handler();\n\tuart.begin(115200);\n\tINPUT in = uart.fin();\n\tOUTPUT out = uart.fout();\n\n\t\/\/ Check all output manipulators\n\thandle_num(out, 1234, F(\"uint16_t\"));\n\thandle_num(out, 1234, F(\"int16_t\"));\n\thandle_num(out, -1234, F(\"int16_t\"));\n\n\thandle_num(out, 123456, F(\"uint32_t\"));\n\thandle_num(out, 123456, F(\"int32_t\"));\n\thandle_num(out, -123456, F(\"int32_t\"));\n\n\t\/\/ check floats\n\thandle_float(out, 123.456);\n\thandle_float(out, -123.456);\n\thandle_float(out, -12345678901234567890.12345);\n\n\t\/\/TODO check other types\n\n\t\/\/TODO check justification: setw(), setfill(), left, right...\n\n\t\/\/ Event Loop\n\twhile (true)\n\t{\n\t\thandle(out, in, F(\"char\"));\n\t\thandle(out, in, F(\"uint16_t\"));\n\t\thandle(out, in, F(\"int16_t\"));\n\t\thandle(out, in, F(\"uint32_t\"));\n\t\thandle(out, in, F(\"int32_t\"));\n\t\thandle(out, in, F(\"bool\"));\n\t\t\n\t\ttime::delay_ms(1000);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"third_party\/zlib\/google\/zip_reader.h\"\n\n#include \n\n#include \"base\/files\/file_path.h\"\n#include \"base\/strings\/string_util.h\"\n\n#include \"contrib\/minizip\/unzip.h\"\n\n\/\/ This file is a stripped down version of zip_reader.cc from Chromium: https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/zlib\/google\/zip_reader.cc.\n\/\/ It also contains code to wrap memory around the file interface from zip_internal.cc: https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/zlib\/google\/zip_internal.cc\n\/\/ It only contains code required to read a zip file using zlib and replaces the usage of other Chromium code not present in mini_chromium.\n\nnamespace zip {\n\nZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip,\n const unz_file_info& raw_file_info)\n : file_path_(file_name_in_zip),\n is_directory_(false) {\n\n original_size_ = raw_file_info.uncompressed_size;\n\n \/\/ Directory entries in zip files end with \"\/\".\n if (file_name_in_zip.size() > 0) {\n is_directory_ = file_name_in_zip.back() == '\/';\n }\n}\n\n\/\/ START from internal.cc\n\n\/\/ A struct that contains data required for zlib functions to extract files from\n\/\/ a zip archive stored in memory directly. The following I\/O API functions\n\/\/ expect their opaque parameters refer to this struct.\nstruct ZipBuffer {\n const char* data; \/\/ weak\n size_t length;\n size_t offset;\n};\n\n\/\/ Opens the specified file. When this function returns a non-NULL pointer, zlib\n\/\/ uses this pointer as a stream parameter while compressing or uncompressing\n\/\/ data. (Returning NULL represents an error.) This function initializes the\n\/\/ given opaque parameter and returns it because this parameter stores all\n\/\/ information needed for uncompressing data. (This function does not support\n\/\/ writing compressed data and it returns NULL for this case.)\nvoid* OpenZipBuffer(void* opaque, const char* \/*filename*\/, int mode) {\n if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) {\n return NULL;\n }\n ZipBuffer* buffer = static_cast(opaque);\n if (!buffer || !buffer->data || !buffer->length)\n return NULL;\n buffer->offset = 0;\n return opaque;\n}\n\n\/\/ Reads compressed data from the specified stream. This function copies data\n\/\/ refered by the opaque parameter and returns the size actually copied.\nuLong ReadZipBuffer(void* opaque, void* \/*stream*\/, void* buf, uLong size) {\n ZipBuffer* buffer = static_cast(opaque);\n DCHECK_LE(buffer->offset, buffer->length);\n size_t remaining_bytes = buffer->length - buffer->offset;\n if (!buffer || !buffer->data || !remaining_bytes)\n return 0;\n size = std::min(size, static_cast(remaining_bytes));\n memcpy(buf, &buffer->data[buffer->offset], size);\n buffer->offset += size;\n return size;\n}\n\n\/\/ Returns the offset from the beginning of the data.\nlong GetOffsetOfZipBuffer(void* opaque, void* \/*stream*\/) {\n ZipBuffer* buffer = static_cast(opaque);\n if (!buffer)\n return -1;\n return static_cast(buffer->offset);\n}\n\n\/\/ Moves the current offset to the specified position.\nlong SeekZipBuffer(void* opaque, void* \/*stream*\/, uLong offset, int origin) {\n ZipBuffer* buffer = static_cast(opaque);\n if (!buffer)\n return -1;\n if (origin == ZLIB_FILEFUNC_SEEK_CUR) {\n buffer->offset = std::min(buffer->offset + static_cast(offset),\n buffer->length);\n return 0;\n }\n if (origin == ZLIB_FILEFUNC_SEEK_END) {\n buffer->offset = (buffer->length > offset) ? buffer->length - offset : 0;\n return 0;\n }\n if (origin == ZLIB_FILEFUNC_SEEK_SET) {\n buffer->offset = std::min(buffer->length, static_cast(offset));\n return 0;\n }\n return -1;\n}\n\n\/\/ Closes the input offset and deletes all resources used for compressing or\n\/\/ uncompressing data. This function deletes the ZipBuffer object referred by\n\/\/ the opaque parameter since zlib deletes the unzFile object and it does not\n\/\/ use this object any longer.\nint CloseZipBuffer(void* opaque, void* \/*stream*\/) {\n if (opaque)\n free(opaque);\n return 0;\n}\n\n\/\/ Returns the last error happened when reading or writing data. This function\n\/\/ always returns zero, which means there are not any errors.\nint GetErrorOfZipBuffer(void* \/*opaque*\/, void* \/*stream*\/) {\n return 0;\n}\n\/\/ END from internal.cc\n\nZipReader::ZipReader() {\n Reset();\n}\n\nZipReader::~ZipReader() {\n Close();\n}\n\nbool ZipReader::OpenFromString(const std::string& data) {\n if (data.empty()) {\n return false;\n }\n\n ZipBuffer* buffer = static_cast(malloc(sizeof(ZipBuffer)));\n if (!buffer) {\n return false;\n }\n buffer->data = data.data();\n buffer->length = data.length();\n buffer->offset = 0;\n\n zlib_filefunc_def zip_functions;\n zip_functions.zopen_file = OpenZipBuffer;\n zip_functions.zread_file = ReadZipBuffer;\n \/\/ Removed WriteZipBuffer as it is not required for reading zip files.\n zip_functions.ztell_file = GetOffsetOfZipBuffer;\n zip_functions.zseek_file = SeekZipBuffer;\n zip_functions.zclose_file = CloseZipBuffer;\n zip_functions.zerror_file = GetErrorOfZipBuffer;\n zip_functions.opaque = static_cast(buffer);\n zip_file_ = unzOpen2(NULL, &zip_functions);\n\n unz_global_info zip_info = {}; \/\/ Zero-clear.\n if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) {\n return false;\n }\n num_entries_ = zip_info.number_entry;\n\n if (num_entries_ < 0)\n return false;\n\n \/\/ We are already at the end if the zip file is empty.\n reached_end_ = (num_entries_ == 0);\n\n return true;\n}\n\nvoid ZipReader::Close() {\n if (zip_file_) {\n unzClose(zip_file_);\n }\n Reset();\n}\n\nbool ZipReader::HasMore() {\n return !reached_end_;\n}\n\nbool ZipReader::AdvanceToNextEntry() {\n DCHECK(zip_file_);\n\n \/\/ Should not go further if we already reached the end.\n if (reached_end_)\n return false;\n\n unz_file_pos position = {};\n if (unzGetFilePos(zip_file_, &position) != UNZ_OK)\n return false;\n const int current_entry_index = position.num_of_file;\n \/\/ If we are currently at the last entry, then the next position is the\n \/\/ end of the zip file, so mark that we reached the end.\n if (current_entry_index + 1 == num_entries_) {\n reached_end_ = true;\n } else {\n DCHECK_LT(current_entry_index + 1, num_entries_);\n if (unzGoToNextFile(zip_file_) != UNZ_OK) {\n return false;\n }\n }\n current_entry_info_.reset();\n return true;\n}\n\nbool ZipReader::OpenCurrentEntryInZip() {\n DCHECK(zip_file_);\n\n unz_file_info raw_file_info = {};\n constexpr int kZipMaxPath = 256;\n char raw_file_name_in_zip[kZipMaxPath] = {};\n const int result = unzGetCurrentFileInfo(zip_file_,\n &raw_file_info,\n raw_file_name_in_zip,\n sizeof(raw_file_name_in_zip) - 1,\n NULL, \/\/ extraField.\n 0, \/\/ extraFieldBufferSize.\n NULL, \/\/ szComment.\n 0); \/\/ commentBufferSize.\n\n if (result != UNZ_OK)\n return false;\n if (raw_file_name_in_zip[0] == '\\0')\n return false;\n current_entry_info_.reset(\n new EntryInfo(raw_file_name_in_zip, raw_file_info));\n return true;\n}\n\nbool ZipReader::ExtractCurrentEntryToString(\/* not used*\/ uint64_t max_read_bytes,\n std::string* output) const {\n DCHECK(output);\n DCHECK(zip_file_);\n\n output->clear();\n\n if (max_read_bytes == 0) {\n return true;\n }\n\n if (current_entry_info_->is_directory()) {\n return true;\n }\n\n const int open_result = unzOpenCurrentFile(zip_file_);\n if (open_result != UNZ_OK) {\n return false;\n }\n\n constexpr int kZipBufSize = 8192;\n char buf[kZipBufSize];\n bool entire_file_extracted = false;\n\n while (true) {\n const int num_bytes_read =\n unzReadCurrentFile(zip_file_, buf, kZipBufSize);\n\n if (num_bytes_read == 0) {\n entire_file_extracted = true;\n break;\n } else if (num_bytes_read < 0) {\n \/\/ If num_bytes_read < 0, then it's a specific UNZ_* error code.\n break;\n } else if (num_bytes_read > 0) {\n output->append(buf, num_bytes_read);\n }\n }\n\n unzCloseCurrentFile(zip_file_);\n return entire_file_extracted;\n}\n\nvoid ZipReader::Reset() {\n zip_file_ = NULL;\n num_entries_ = 0;\n reached_end_ = false;\n current_entry_info_.reset();\n}\n} \/\/ namespace zip\nPorting zip_reader.cc to Windows (#37)\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"third_party\/zlib\/google\/zip_reader.h\"\n\n#include \n\n#include \"base\/files\/file_path.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n\n#include \"contrib\/minizip\/unzip.h\"\n\n\/\/ This file is a stripped down version of zip_reader.cc from Chromium: https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/zlib\/google\/zip_reader.cc.\n\/\/ It also contains code to wrap memory around the file interface from zip_internal.cc: https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/zlib\/google\/zip_internal.cc\n\/\/ It only contains code required to read a zip file using zlib and replaces the usage of other Chromium code not present in mini_chromium.\n\nnamespace zip {\n\nZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip,\n const unz_file_info& raw_file_info)\n#if defined(_WIN32)\n : file_path_(base::UTF8ToWide(file_name_in_zip)),\n#else\n : file_path_(file_name_in_zip),\n#endif \/\/ _WIN32\n is_directory_(false) {\n\n original_size_ = raw_file_info.uncompressed_size;\n\n \/\/ Directory entries in zip files end with \"\/\".\n if (file_name_in_zip.size() > 0) {\n is_directory_ = file_name_in_zip.back() == '\/';\n }\n}\n\n\/\/ START from internal.cc\n\n\/\/ A struct that contains data required for zlib functions to extract files from\n\/\/ a zip archive stored in memory directly. The following I\/O API functions\n\/\/ expect their opaque parameters refer to this struct.\nstruct ZipBuffer {\n const char* data; \/\/ weak\n size_t length;\n size_t offset;\n};\n\n\/\/ Opens the specified file. When this function returns a non-NULL pointer, zlib\n\/\/ uses this pointer as a stream parameter while compressing or uncompressing\n\/\/ data. (Returning NULL represents an error.) This function initializes the\n\/\/ given opaque parameter and returns it because this parameter stores all\n\/\/ information needed for uncompressing data. (This function does not support\n\/\/ writing compressed data and it returns NULL for this case.)\nvoid* OpenZipBuffer(void* opaque, const char* \/*filename*\/, int mode) {\n if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) {\n return NULL;\n }\n ZipBuffer* buffer = static_cast(opaque);\n if (!buffer || !buffer->data || !buffer->length)\n return NULL;\n buffer->offset = 0;\n return opaque;\n}\n\n\/\/ Reads compressed data from the specified stream. This function copies data\n\/\/ refered by the opaque parameter and returns the size actually copied.\nuLong ReadZipBuffer(void* opaque, void* \/*stream*\/, void* buf, uLong size) {\n ZipBuffer* buffer = static_cast(opaque);\n DCHECK_LE(buffer->offset, buffer->length);\n size_t remaining_bytes = buffer->length - buffer->offset;\n if (!buffer || !buffer->data || !remaining_bytes)\n return 0;\n size = std::min(size, static_cast(remaining_bytes));\n memcpy(buf, &buffer->data[buffer->offset], size);\n buffer->offset += size;\n return size;\n}\n\n\/\/ Returns the offset from the beginning of the data.\nlong GetOffsetOfZipBuffer(void* opaque, void* \/*stream*\/) {\n ZipBuffer* buffer = static_cast(opaque);\n if (!buffer)\n return -1;\n return static_cast(buffer->offset);\n}\n\n\/\/ Moves the current offset to the specified position.\nlong SeekZipBuffer(void* opaque, void* \/*stream*\/, uLong offset, int origin) {\n ZipBuffer* buffer = static_cast(opaque);\n if (!buffer)\n return -1;\n if (origin == ZLIB_FILEFUNC_SEEK_CUR) {\n buffer->offset = std::min(buffer->offset + static_cast(offset),\n buffer->length);\n return 0;\n }\n if (origin == ZLIB_FILEFUNC_SEEK_END) {\n buffer->offset = (buffer->length > offset) ? buffer->length - offset : 0;\n return 0;\n }\n if (origin == ZLIB_FILEFUNC_SEEK_SET) {\n buffer->offset = std::min(buffer->length, static_cast(offset));\n return 0;\n }\n return -1;\n}\n\n\/\/ Closes the input offset and deletes all resources used for compressing or\n\/\/ uncompressing data. This function deletes the ZipBuffer object referred by\n\/\/ the opaque parameter since zlib deletes the unzFile object and it does not\n\/\/ use this object any longer.\nint CloseZipBuffer(void* opaque, void* \/*stream*\/) {\n if (opaque)\n free(opaque);\n return 0;\n}\n\n\/\/ Returns the last error happened when reading or writing data. This function\n\/\/ always returns zero, which means there are not any errors.\nint GetErrorOfZipBuffer(void* \/*opaque*\/, void* \/*stream*\/) {\n return 0;\n}\n\/\/ END from internal.cc\n\nZipReader::ZipReader() {\n Reset();\n}\n\nZipReader::~ZipReader() {\n Close();\n}\n\nbool ZipReader::OpenFromString(const std::string& data) {\n if (data.empty()) {\n return false;\n }\n\n ZipBuffer* buffer = static_cast(malloc(sizeof(ZipBuffer)));\n if (!buffer) {\n return false;\n }\n buffer->data = data.data();\n buffer->length = data.length();\n buffer->offset = 0;\n\n zlib_filefunc_def zip_functions;\n zip_functions.zopen_file = OpenZipBuffer;\n zip_functions.zread_file = ReadZipBuffer;\n \/\/ Removed WriteZipBuffer as it is not required for reading zip files.\n zip_functions.ztell_file = GetOffsetOfZipBuffer;\n zip_functions.zseek_file = SeekZipBuffer;\n zip_functions.zclose_file = CloseZipBuffer;\n zip_functions.zerror_file = GetErrorOfZipBuffer;\n zip_functions.opaque = static_cast(buffer);\n zip_file_ = unzOpen2(NULL, &zip_functions);\n\n unz_global_info zip_info = {}; \/\/ Zero-clear.\n if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) {\n return false;\n }\n num_entries_ = zip_info.number_entry;\n\n if (num_entries_ < 0)\n return false;\n\n \/\/ We are already at the end if the zip file is empty.\n reached_end_ = (num_entries_ == 0);\n\n return true;\n}\n\nvoid ZipReader::Close() {\n if (zip_file_) {\n unzClose(zip_file_);\n }\n Reset();\n}\n\nbool ZipReader::HasMore() {\n return !reached_end_;\n}\n\nbool ZipReader::AdvanceToNextEntry() {\n DCHECK(zip_file_);\n\n \/\/ Should not go further if we already reached the end.\n if (reached_end_)\n return false;\n\n unz_file_pos position = {};\n if (unzGetFilePos(zip_file_, &position) != UNZ_OK)\n return false;\n const int current_entry_index = position.num_of_file;\n \/\/ If we are currently at the last entry, then the next position is the\n \/\/ end of the zip file, so mark that we reached the end.\n if (current_entry_index + 1 == num_entries_) {\n reached_end_ = true;\n } else {\n DCHECK_LT(current_entry_index + 1, num_entries_);\n if (unzGoToNextFile(zip_file_) != UNZ_OK) {\n return false;\n }\n }\n current_entry_info_.reset();\n return true;\n}\n\nbool ZipReader::OpenCurrentEntryInZip() {\n DCHECK(zip_file_);\n\n unz_file_info raw_file_info = {};\n constexpr int kZipMaxPath = 256;\n char raw_file_name_in_zip[kZipMaxPath] = {};\n const int result = unzGetCurrentFileInfo(zip_file_,\n &raw_file_info,\n raw_file_name_in_zip,\n sizeof(raw_file_name_in_zip) - 1,\n NULL, \/\/ extraField.\n 0, \/\/ extraFieldBufferSize.\n NULL, \/\/ szComment.\n 0); \/\/ commentBufferSize.\n\n if (result != UNZ_OK)\n return false;\n if (raw_file_name_in_zip[0] == '\\0')\n return false;\n current_entry_info_.reset(\n new EntryInfo(raw_file_name_in_zip, raw_file_info));\n return true;\n}\n\nbool ZipReader::ExtractCurrentEntryToString(\/* not used*\/ uint64_t max_read_bytes,\n std::string* output) const {\n DCHECK(output);\n DCHECK(zip_file_);\n\n output->clear();\n\n if (max_read_bytes == 0) {\n return true;\n }\n\n if (current_entry_info_->is_directory()) {\n return true;\n }\n\n const int open_result = unzOpenCurrentFile(zip_file_);\n if (open_result != UNZ_OK) {\n return false;\n }\n\n constexpr int kZipBufSize = 8192;\n char buf[kZipBufSize];\n bool entire_file_extracted = false;\n\n while (true) {\n const int num_bytes_read =\n unzReadCurrentFile(zip_file_, buf, kZipBufSize);\n\n if (num_bytes_read == 0) {\n entire_file_extracted = true;\n break;\n } else if (num_bytes_read < 0) {\n \/\/ If num_bytes_read < 0, then it's a specific UNZ_* error code.\n break;\n } else if (num_bytes_read > 0) {\n output->append(buf, num_bytes_read);\n }\n }\n\n unzCloseCurrentFile(zip_file_);\n return entire_file_extracted;\n}\n\nvoid ZipReader::Reset() {\n zip_file_ = NULL;\n num_entries_ = 0;\n reached_end_ = false;\n current_entry_info_.reset();\n}\n} \/\/ namespace zip\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: extendapplicationenvironment.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2008-01-07 09:48:23 $\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 2007 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 \"precompiled_tools.hxx\"\n#include \"sal\/config.h\"\n\n#include \n \/\/ not as putenv is POSIX-only; setenv instead of putenv would be\n \/\/ better but is not supported by Solaris 9 and earlier\n\n#if defined UNX\n#include \n#include \n#include \n#endif\n\n#include \"osl\/process.h\"\n#include \"osl\/thread.h\"\n#include \"rtl\/string.h\"\n#include \"rtl\/string.hxx\"\n#include \"rtl\/textcvt.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"tools\/extendapplicationenvironment.hxx\"\n\nnamespace tools {\n\nvoid extendApplicationEnvironment() {\n#if defined UNX\n \/\/ Try to set RLIMIT_NOFILE as large as possible (failure is harmless):\n rlimit l;\n if (getrlimit(RLIMIT_NOFILE, &l) == 0) {\n l.rlim_cur = l.rlim_max;\n setrlimit(RLIMIT_NOFILE, &l);\n }\n#endif\n\n \/\/ Make sure URE_BOOTSTRAP environment variable is set (failure is fatal):\n if (getenv(\"URE_BOOTSTRAP\") == NULL) {\n rtl::OUString p;\n if (osl_getExecutableFile(&p.pData) != osl_Process_E_None) {\n abort();\n }\n sal_Int32 i = p.lastIndexOf('\/');\n if (i >= 0) {\n p = p.copy(0, i + 1);\n }\n rtl::OString s;\n if (!p.convertToString(\n &s, osl_getThreadTextEncoding(),\n RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR\n | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR))\n {\n abort();\n }\n rtl::OString env(RTL_CONSTASCII_STRINGPARAM(\"URE_BOOTSTRAP=\"));\n env += s;\n env += SAL_CONFIGFILE(\"fundamental\");\n rtl_string_acquire(env.pData); \/\/ argument to putenv must leak\n if (putenv(const_cast< char * >(env.getStr())) != 0) {\n abort();\n }\n }\n}\n\n}\n#i10000# restore lost changes from sb83\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: extendapplicationenvironment.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2008-03-19 12:29:04 $\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 2007 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 \"precompiled_tools.hxx\"\n#include \"sal\/config.h\"\n\n#include \n \/\/ not as putenv is POSIX-only; setenv instead of putenv would be\n \/\/ better but is not supported by Solaris 9 and earlier\n\n#if defined UNX\n#include \n#include \n#include \n#endif\n\n#include \"osl\/process.h\"\n#include \"osl\/thread.h\"\n#include \"rtl\/bootstrap.hxx\"\n#include \"rtl\/string.hxx\"\n#include \"rtl\/textcvt.h\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"tools\/extendapplicationenvironment.hxx\"\n\nnamespace tools {\n\nvoid extendApplicationEnvironment() {\n#if defined UNX\n \/\/ Try to set RLIMIT_NOFILE as large as possible (failure is harmless):\n rlimit l;\n if (getrlimit(RLIMIT_NOFILE, &l) == 0) {\n l.rlim_cur = l.rlim_max;\n setrlimit(RLIMIT_NOFILE, &l);\n }\n#endif\n\n \/\/ Make sure URE_BOOTSTRAP environment variable is set (failure is fatal):\n rtl::OUString env(RTL_CONSTASCII_USTRINGPARAM(\"URE_BOOTSTRAP=\"));\n rtl::OUString uri;\n if (rtl::Bootstrap::get(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"URE_BOOTSTRAP\")), uri))\n {\n env += uri;\n } else {\n if (osl_getExecutableFile(&uri.pData) != osl_Process_E_None) {\n abort();\n }\n sal_Int32 i = uri.lastIndexOf('\/');\n if (i >= 0) {\n uri = uri.copy(0, i + 1);\n }\n env += uri;\n env += rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(SAL_CONFIGFILE(\"fundamental\")));\n }\n rtl::OString s;\n if (!env.convertToString(\n &s, osl_getThreadTextEncoding(),\n RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR\n | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR))\n {\n abort();\n }\n rtl_string_acquire(s.pData); \/\/ argument to putenv must leak\n if (putenv(const_cast< char * >(s.getStr())) != 0) {\n abort();\n }\n}\n\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n\/** @file bts\/blockchain\/config.hpp\n * @brief Defines global constants that determine blockchain behavior\n *\/\n#define BTS_BLOCKCHAIN_VERSION (104)\n#define BTS_WALLET_VERSION (100)\n#define BTS_BLOCKCHAIN_DATABASE_VERSION (109)\n\n\/**\n * The address prepended to string representation of\n * addresses.\n *\n * Changing these parameters will result in a hard fork.\n *\/\n#define BTS_ADDRESS_PREFIX \"XTS\"\n#define BTS_BLOCKCHAIN_SYMBOL \"XTS\"\n#define BTS_BLOCKCHAIN_NAME \"BitShares XTS\"\n#define BTS_BLOCKCHAIN_DESCRIPTION \"Stake in future BitShares X chains\"\n#define BTS_BLOCKCHAIN_PRECISION (100000)\n#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC (60*60*24*2)\n#define BTS_BLOCKCHAIN_DEFAULT_TRANSACTION_EXPIRATION_SEC (60*60*2)\n\n\/**\n * The number of delegates that the blockchain is designed to support\n *\/\n#define BTS_BLOCKCHAIN_NUM_DELEGATES (101)\n#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE (BTS_BLOCKCHAIN_NUM_DELEGATES)\n\n\/**\n * To prevent a delegate from producing blocks on split network,\n * we check the connection count. This means no blocks get produced\n * until at least a minimum number of clients are on line.\n *\/\n#define BTS_MIN_DELEGATE_CONNECTION_COUNT (5)\n\n\/**\n * Defines the number of seconds that should elapse between blocks\n *\/\n#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC int64_t(15)\n\n\/**\n * The maximum size of the raw data contained in the blockchain, this size is\n * notional based upon the serilized size of all user-generated transactions in\n * all blocks for one year.\n *\n * Actual size on disk will likely be 2 or 3x this size due to indexes and other\n * storeage overhead.\n *\n * Adjusting this value will change the effective fee charged on transactions\n *\/\n#define BTS_BLOCKCHAIN_MAX_SIZE (1024*1024*1024*100ll) \/\/ 100 GB\n#define BTS_BLOCKCHAIN_MIN_NAME_SIZE (1)\n#define BTS_BLOCKCHAIN_MAX_NAME_SIZE (63)\n#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE (1024*64)\n#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE (19) \/\/ bytes\n#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE (5) \/\/ characters\n#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE (3) \/\/ characters\n#define BTS_BLOCKCHAIN_PROPOSAL_VOTE_MESSAGE_MAX_SIZE (1024) \/\/ bytes\n\n\/**\n * The maximum amount that can be issued for user assets.\n *\n * 10^18 \/ 2^63 < 1\n *\/\n#define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*1000ll*1000*1000ll)\n\n\/**\n * Initial shares read from the genesis block are scaled to this number. It is divided\n * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES\n *\/\n#define BTS_BLOCKCHAIN_INITIAL_SHARES (BTS_BLOCKCHAIN_MAX_SHARES \/ 5)\n\n\/**\n * The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC\n *\/\n#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR ((60*60)\/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)\n\n\/**\n * The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC\n *\/\n#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*24ll)\n\n\/**\n * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC\n *\/\n#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*365ll)\n\n\/** defines the maximum block size allowed, 24 MB per hour *\/\n\/\/#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (24 * 1024*1024 \/ BTS_BLOCKCHAIN_BLOCKS_PER_HOUR)\n#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (30*64*1024) \/\/ 2 min blocks, this is 64K max block size\n\n\/** defines the target block size, fees will be adjusted to maintain this target *\/\n#define BTS_BLOCKCHAIN_TARGET_BLOCK_SIZE (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE\/2)\n\n#define BTS_BLOCKCHAIN_BLOCK_REWARD (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE) \/\/10000 \/\/ (BTS_BLOCKCHAIN_INITIAL_SHARES\/BTS_BLOCKCHAIN_BLOCKS_PER_YEAR)\n#define BTS_BLOCKCHAIN_INACTIVE_FEE_APR (10) \/\/ 10% per year\n\n\/**\n * defines the min fee in milli-shares per byte\n *\/\n#define BTS_BLOCKCHAIN_MIN_FEE (1000)\n\n\/**\n * Defined so that a delegate must produce 100 blocks to break even.\n *\/\n#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE (BTS_BLOCKCHAIN_BLOCK_REWARD)\n\n\/**\n * Defines the fee required to register a asset, this fee is set to discourage anyone from\n * registering all of the symbols. If the asset is not worth at least 100 blocks worth\n * of mining fees then it really isn't worth the networks time.\n *\/\n#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE (BTS_BLOCKCHAIN_BLOCK_REWARD)\nadjust max block size to yield about 2 trx\/sec maximum#pragma once\n\n#include \n\n\/** @file bts\/blockchain\/config.hpp\n * @brief Defines global constants that determine blockchain behavior\n *\/\n#define BTS_BLOCKCHAIN_VERSION (104)\n#define BTS_WALLET_VERSION (100)\n#define BTS_BLOCKCHAIN_DATABASE_VERSION (109)\n\n\/**\n * The address prepended to string representation of\n * addresses.\n *\n * Changing these parameters will result in a hard fork.\n *\/\n#define BTS_ADDRESS_PREFIX \"XTS\"\n#define BTS_BLOCKCHAIN_SYMBOL \"XTS\"\n#define BTS_BLOCKCHAIN_NAME \"BitShares XTS\"\n#define BTS_BLOCKCHAIN_DESCRIPTION \"Stake in future BitShares X chains\"\n#define BTS_BLOCKCHAIN_PRECISION (100000)\n#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC (60*60*24*2)\n#define BTS_BLOCKCHAIN_DEFAULT_TRANSACTION_EXPIRATION_SEC (60*60*2)\n\n\/**\n * The number of delegates that the blockchain is designed to support\n *\/\n#define BTS_BLOCKCHAIN_NUM_DELEGATES (101)\n#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE (BTS_BLOCKCHAIN_NUM_DELEGATES)\n\n\/**\n * To prevent a delegate from producing blocks on split network,\n * we check the connection count. This means no blocks get produced\n * until at least a minimum number of clients are on line.\n *\/\n#define BTS_MIN_DELEGATE_CONNECTION_COUNT (5)\n\n\/**\n * Defines the number of seconds that should elapse between blocks\n *\/\n#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC int64_t(15)\n\n\/**\n * The maximum size of the raw data contained in the blockchain, this size is\n * notional based upon the serilized size of all user-generated transactions in\n * all blocks for one year.\n *\n * Actual size on disk will likely be 2 or 3x this size due to indexes and other\n * storeage overhead.\n *\n * Adjusting this value will change the effective fee charged on transactions\n *\/\n#define BTS_BLOCKCHAIN_MAX_SIZE (1024*1024*1024*100ll) \/\/ 100 GB\n#define BTS_BLOCKCHAIN_MIN_NAME_SIZE (1)\n#define BTS_BLOCKCHAIN_MAX_NAME_SIZE (63)\n#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE (1024*64)\n#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE (19) \/\/ bytes\n#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE (5) \/\/ characters\n#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE (3) \/\/ characters\n#define BTS_BLOCKCHAIN_PROPOSAL_VOTE_MESSAGE_MAX_SIZE (1024) \/\/ bytes\n\n\/**\n * The maximum amount that can be issued for user assets.\n *\n * 10^18 \/ 2^63 < 1\n *\/\n#define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*1000ll*1000*1000ll)\n\n\/**\n * Initial shares read from the genesis block are scaled to this number. It is divided\n * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES\n *\/\n#define BTS_BLOCKCHAIN_INITIAL_SHARES (BTS_BLOCKCHAIN_MAX_SHARES \/ 5)\n\n\/**\n * The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC\n *\/\n#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR ((60*60)\/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)\n\n\/**\n * The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC\n *\/\n#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*24ll)\n\n\/**\n * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC\n *\/\n#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*365ll)\n\n\/** defines the maximum block size allowed, 2 MB per hour *\/\n#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE ( 2 * 1024*1024 \/ BTS_BLOCKCHAIN_BLOCKS_PER_HOUR)\n\n\/** defines the target block size, fees will be adjusted to maintain this target *\/\n#define BTS_BLOCKCHAIN_TARGET_BLOCK_SIZE (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE\/2)\n\n#define BTS_BLOCKCHAIN_BLOCK_REWARD (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE) \/\/10000 \/\/ (BTS_BLOCKCHAIN_INITIAL_SHARES\/BTS_BLOCKCHAIN_BLOCKS_PER_YEAR)\n#define BTS_BLOCKCHAIN_INACTIVE_FEE_APR (10) \/\/ 10% per year\n\n\/**\n * defines the min fee in milli-shares per byte\n *\/\n#define BTS_BLOCKCHAIN_MIN_FEE (1000)\n\n\/**\n * Defined so that a delegate must produce 100 blocks to break even.\n *\/\n#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE (BTS_BLOCKCHAIN_BLOCK_REWARD)\n\n\/**\n * Defines the fee required to register a asset, this fee is set to discourage anyone from\n * registering all of the symbols. If the asset is not worth at least 100 blocks worth\n * of mining fees then it really isn't worth the networks time.\n *\/\n#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE (BTS_BLOCKCHAIN_BLOCK_REWARD)\n<|endoftext|>"} {"text":"#include \"AutoGenerated.inc\"\n\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\nnamespace llvmc {\n extern char *ProgramName;\n}\n\n\/\/ Returns the platform specific directory separator via #ifdefs.\nstatic std::string GetDirSeparator(void) {\n return \"\/\";\n}\n\nnamespace hooks {\n\/\/ Get the dir where c16 executables reside.\nstd::string GetBinDir (void) {\n \/\/ Construct a Path object from the program name. \n void *P = (void*) (intptr_t) GetBinDir;\n sys::Path ProgramFullPath \n = sys::Path::GetMainExecutable(llvmc::ProgramName, P);\n\n \/\/ Get the dir name for the program. It's last component should be 'bin'.\n std::string BinDir = ProgramFullPath.getDirname();\n\n \/\/ llvm::errs() << \"BinDir: \" << BinDir << '\\n';\n return BinDir + GetDirSeparator();\n}\n\n\/\/ Get the Top-level Installation dir for c16.\nstd::string GetInstallDir (void) {\n sys::Path BinDirPath = sys::Path(GetBinDir());\n\n \/\/ Go one more level up to get the install dir.\n std::string InstallDir = BinDirPath.getDirname();\n \n return InstallDir + GetDirSeparator();\n}\n\n\/\/ Get the dir where the c16 header files reside.\nstd::string GetStdHeadersDir (void) {\n return GetInstallDir() + \"include\";\n}\n\n\/\/ Get the dir where the assembler header files reside.\nstd::string GetStdAsmHeadersDir (void) {\n return GetInstallDir() + \"inc\";\n}\n\n\/\/ Get the dir where the linker scripts reside.\nstd::string GetStdLinkerScriptsDir (void) {\n return GetInstallDir() + \"lkr\";\n}\n\n\/\/ Get the dir where startup code, intrinsics and lib reside.\nstd::string GetStdLibsDir (void) {\n return GetInstallDir() + \"lib\";\n}\n}\nReturn dir separator as per platform.#include \"AutoGenerated.inc\"\n\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\nnamespace llvmc {\n extern char *ProgramName;\n}\n\n\/\/ Returns the platform specific directory separator via #ifdefs.\nstatic std::string GetDirSeparator(void) {\n#ifdef __linux__\n return \"\/\";\n#else\n return \"\\\\\";\n#endif\n}\n\nnamespace hooks {\n\/\/ Get the dir where c16 executables reside.\nstd::string GetBinDir (void) {\n \/\/ Construct a Path object from the program name. \n void *P = (void*) (intptr_t) GetBinDir;\n sys::Path ProgramFullPath \n = sys::Path::GetMainExecutable(llvmc::ProgramName, P);\n\n \/\/ Get the dir name for the program. It's last component should be 'bin'.\n std::string BinDir = ProgramFullPath.getDirname();\n\n \/\/ llvm::errs() << \"BinDir: \" << BinDir << '\\n';\n return BinDir + GetDirSeparator();\n}\n\n\/\/ Get the Top-level Installation dir for c16.\nstd::string GetInstallDir (void) {\n sys::Path BinDirPath = sys::Path(GetBinDir());\n\n \/\/ Go one more level up to get the install dir.\n std::string InstallDir = BinDirPath.getDirname();\n \n return InstallDir + GetDirSeparator();\n}\n\n\/\/ Get the dir where the c16 header files reside.\nstd::string GetStdHeadersDir (void) {\n return GetInstallDir() + \"include\";\n}\n\n\/\/ Get the dir where the assembler header files reside.\nstd::string GetStdAsmHeadersDir (void) {\n return GetInstallDir() + \"inc\";\n}\n\n\/\/ Get the dir where the linker scripts reside.\nstd::string GetStdLinkerScriptsDir (void) {\n return GetInstallDir() + \"lkr\";\n}\n\n\/\/ Get the dir where startup code, intrinsics and lib reside.\nstd::string GetStdLibsDir (void) {\n return GetInstallDir() + \"lib\";\n}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/test\/live_sync\/live_autofill_sync_test.h\"\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutofillKeys keys;\n keys.insert(AutofillKey(\"name0\", \"value0\"));\n keys.insert(AutofillKey(\"name0\", \"value1\"));\n keys.insert(AutofillKey(\"name1\", \"value2\"));\n keys.insert(AutofillKey(WideToUTF16(L\"Sigur R\\u00F3s\"),\n WideToUTF16(L\"\\u00C1g\\u00E6tis byrjun\")));\n AddFormFieldsToWebData(GetWebDataService(0), keys);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n AutofillKeys wd1_keys;\n GetAllAutofillKeys(GetWebDataService(1), &wd1_keys);\n EXPECT_EQ(keys, wd1_keys);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutofillKeys keys1;\n keys1.insert(AutofillKey(\"name0\", \"value0\"));\n keys1.insert(AutofillKey(\"name0\", \"value1\"));\n keys1.insert(AutofillKey(\"name1\", \"value2\"));\n AddFormFieldsToWebData(GetWebDataService(0), keys1);\n\n AutofillKeys keys2;\n keys2.insert(AutofillKey(\"name0\", \"value1\"));\n keys2.insert(AutofillKey(\"name1\", \"value2\"));\n keys2.insert(AutofillKey(\"name2\", \"value3\"));\n keys2.insert(AutofillKey(\"name3\", \"value3\"));\n AddFormFieldsToWebData(GetWebDataService(1), keys2);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n EXPECT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name0\", \"value0\"));\n expected_keys.insert(AutofillKey(\"name0\", \"value1\"));\n expected_keys.insert(AutofillKey(\"name1\", \"value2\"));\n expected_keys.insert(AutofillKey(\"name2\", \"value3\"));\n expected_keys.insert(AutofillKey(\"name3\", \"value3\"));\n\n AutofillKeys wd0_keys;\n GetAllAutofillKeys(GetWebDataService(0), &wd0_keys);\n EXPECT_EQ(expected_keys, wd0_keys);\n\n AutofillKeys wd1_keys;\n GetAllAutofillKeys(GetWebDataService(1), &wd1_keys);\n EXPECT_EQ(expected_keys, wd1_keys);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n\n \/\/ Client0 adds a key.\n AutofillKeys add_one_key;\n add_one_key.insert(AutofillKey(\"name0\", \"value0\"));\n AddFormFieldsToWebData(GetWebDataService(0), add_one_key);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name0\", \"value0\"));\n\n AutofillKeys keys;\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client1 adds a key.\n add_one_key.clear();\n add_one_key.insert(AutofillKey(\"name1\", \"value1\"));\n AddFormFieldsToWebData(GetWebDataService(1), add_one_key);\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n expected_keys.insert(AutofillKey(\"name1\", \"value1\"));\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client0 adds a key with the same name.\n add_one_key.clear();\n add_one_key.insert(AutofillKey(\"name1\", \"value2\"));\n AddFormFieldsToWebData(GetWebDataService(0), add_one_key);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n expected_keys.insert(AutofillKey(\"name1\", \"value2\"));\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client1 removes a key.\n RemoveKeyFromWebData(GetWebDataService(1), AutofillKey(\"name1\", \"value1\"));\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n expected_keys.erase(AutofillKey(\"name1\", \"value1\"));\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client0 removes the rest.\n RemoveKeyFromWebData(GetWebDataService(0), AutofillKey(\"name0\", \"value0\"));\n RemoveKeyFromWebData(GetWebDataService(0), AutofillKey(\"name1\", \"value2\"));\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(0U, keys.size());\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(0U, keys.size());\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, ProfileClient1HasData) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutoFillProfiles expected_profiles;\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, expected_profiles[0]);\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[1]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[0]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[1]);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n STLDeleteElements(&expected_profiles);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest,\n ProfileSameLabelOnDifferentClients) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutoFillProfiles profiles1;\n profiles1.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, profiles1[0]);\n\n AutoFillProfiles profiles2;\n profiles2.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, profiles2[0]);\n profiles2[0]->set_label(ASCIIToUTF16(\"Shipping\"));\n\n AddProfile(GetPersonalDataManager(0), *profiles1[0]);\n AddProfile(GetPersonalDataManager(1), *profiles2[0]);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n \/\/ Since client1 associates first, client2's \"Shipping\" profile will\n \/\/ be overwritten by the one stored in the cloud by profile1.\n EXPECT_TRUE(CompareAutoFillProfiles(profiles1,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(profiles1,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n STLDeleteElements(&profiles1);\n STLDeleteElements(&profiles2);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest,\n ProfileSameLabelOnClient1) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutoFillProfiles expected_profiles;\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[0]);\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[1]);\n\n AddProfile(GetPersonalDataManager(0), *expected_profiles[0]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[1]);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n \/\/ One of the duplicate profiles will have its label renamed to\n \/\/ \"Shipping2\".\n expected_profiles[0]->set_label(ASCIIToUTF16(\"Shipping2\"));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n STLDeleteElements(&expected_profiles);\n}\n\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, ProfileSteady) {\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n\n \/\/ Client0 adds a profile.\n AutoFillProfiles expected_profiles;\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[0]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[0]);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client1 adds a profile.\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, expected_profiles[1]);\n AddProfile(GetPersonalDataManager(1), *expected_profiles[1]);\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client0 adds a conflicting profile.\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, expected_profiles[2]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[2]);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n \/\/ The conflicting profile's label will be made unique.\n expected_profiles[2]->set_label(ASCIIToUTF16(\"Billing2\"));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client1 removes a profile.\n delete expected_profiles.front();\n expected_profiles.erase(expected_profiles.begin());\n RemoveProfile(GetPersonalDataManager(1), ASCIIToUTF16(\"Shipping\"));\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client0 updates a profile.\n expected_profiles[0]->SetInfo(AutoFillType(NAME_FIRST),\n ASCIIToUTF16(\"Bart\"));\n UpdateProfile(GetPersonalDataManager(0),\n ASCIIToUTF16(\"Billing\"),\n AutoFillType(NAME_FIRST),\n ASCIIToUTF16(\"Bart\"));\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client1 removes everything.\n STLDeleteElements(&expected_profiles);\n RemoveProfile(GetPersonalDataManager(1), ASCIIToUTF16(\"Billing\"));\n RemoveProfile(GetPersonalDataManager(1), ASCIIToUTF16(\"Billing2\"));\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n}\nMarking Client1HasData test as failed due to bug 51956.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/test\/live_sync\/live_autofill_sync_test.h\"\n\n\/\/ TODO(rsimha): Remove FAILS prefix after crbug.com\/51956 is fixed.\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest,\n FAILS_Client1HasData) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutofillKeys keys;\n keys.insert(AutofillKey(\"name0\", \"value0\"));\n keys.insert(AutofillKey(\"name0\", \"value1\"));\n keys.insert(AutofillKey(\"name1\", \"value2\"));\n keys.insert(AutofillKey(WideToUTF16(L\"Sigur R\\u00F3s\"),\n WideToUTF16(L\"\\u00C1g\\u00E6tis byrjun\")));\n AddFormFieldsToWebData(GetWebDataService(0), keys);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n AutofillKeys wd1_keys;\n GetAllAutofillKeys(GetWebDataService(1), &wd1_keys);\n EXPECT_EQ(keys, wd1_keys);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutofillKeys keys1;\n keys1.insert(AutofillKey(\"name0\", \"value0\"));\n keys1.insert(AutofillKey(\"name0\", \"value1\"));\n keys1.insert(AutofillKey(\"name1\", \"value2\"));\n AddFormFieldsToWebData(GetWebDataService(0), keys1);\n\n AutofillKeys keys2;\n keys2.insert(AutofillKey(\"name0\", \"value1\"));\n keys2.insert(AutofillKey(\"name1\", \"value2\"));\n keys2.insert(AutofillKey(\"name2\", \"value3\"));\n keys2.insert(AutofillKey(\"name3\", \"value3\"));\n AddFormFieldsToWebData(GetWebDataService(1), keys2);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n EXPECT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name0\", \"value0\"));\n expected_keys.insert(AutofillKey(\"name0\", \"value1\"));\n expected_keys.insert(AutofillKey(\"name1\", \"value2\"));\n expected_keys.insert(AutofillKey(\"name2\", \"value3\"));\n expected_keys.insert(AutofillKey(\"name3\", \"value3\"));\n\n AutofillKeys wd0_keys;\n GetAllAutofillKeys(GetWebDataService(0), &wd0_keys);\n EXPECT_EQ(expected_keys, wd0_keys);\n\n AutofillKeys wd1_keys;\n GetAllAutofillKeys(GetWebDataService(1), &wd1_keys);\n EXPECT_EQ(expected_keys, wd1_keys);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n\n \/\/ Client0 adds a key.\n AutofillKeys add_one_key;\n add_one_key.insert(AutofillKey(\"name0\", \"value0\"));\n AddFormFieldsToWebData(GetWebDataService(0), add_one_key);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name0\", \"value0\"));\n\n AutofillKeys keys;\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client1 adds a key.\n add_one_key.clear();\n add_one_key.insert(AutofillKey(\"name1\", \"value1\"));\n AddFormFieldsToWebData(GetWebDataService(1), add_one_key);\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n expected_keys.insert(AutofillKey(\"name1\", \"value1\"));\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client0 adds a key with the same name.\n add_one_key.clear();\n add_one_key.insert(AutofillKey(\"name1\", \"value2\"));\n AddFormFieldsToWebData(GetWebDataService(0), add_one_key);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n expected_keys.insert(AutofillKey(\"name1\", \"value2\"));\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client1 removes a key.\n RemoveKeyFromWebData(GetWebDataService(1), AutofillKey(\"name1\", \"value1\"));\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n expected_keys.erase(AutofillKey(\"name1\", \"value1\"));\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(expected_keys, keys);\n\n \/\/ Client0 removes the rest.\n RemoveKeyFromWebData(GetWebDataService(0), AutofillKey(\"name0\", \"value0\"));\n RemoveKeyFromWebData(GetWebDataService(0), AutofillKey(\"name1\", \"value2\"));\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(0), &keys);\n EXPECT_EQ(0U, keys.size());\n keys.clear();\n GetAllAutofillKeys(GetWebDataService(1), &keys);\n EXPECT_EQ(0U, keys.size());\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, ProfileClient1HasData) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutoFillProfiles expected_profiles;\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, expected_profiles[0]);\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[1]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[0]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[1]);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n STLDeleteElements(&expected_profiles);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest,\n ProfileSameLabelOnDifferentClients) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutoFillProfiles profiles1;\n profiles1.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, profiles1[0]);\n\n AutoFillProfiles profiles2;\n profiles2.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, profiles2[0]);\n profiles2[0]->set_label(ASCIIToUTF16(\"Shipping\"));\n\n AddProfile(GetPersonalDataManager(0), *profiles1[0]);\n AddProfile(GetPersonalDataManager(1), *profiles2[0]);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n \/\/ Since client1 associates first, client2's \"Shipping\" profile will\n \/\/ be overwritten by the one stored in the cloud by profile1.\n EXPECT_TRUE(CompareAutoFillProfiles(profiles1,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(profiles1,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n STLDeleteElements(&profiles1);\n STLDeleteElements(&profiles2);\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest,\n ProfileSameLabelOnClient1) {\n ASSERT_TRUE(SetupClients()) << \"SetupClients() failed.\";\n\n AutoFillProfiles expected_profiles;\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[0]);\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[1]);\n\n AddProfile(GetPersonalDataManager(0), *expected_profiles[0]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[1]);\n\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n ASSERT_TRUE(ProfileSyncServiceTestHarness::AwaitQuiescence(clients()));\n\n \/\/ One of the duplicate profiles will have its label renamed to\n \/\/ \"Shipping2\".\n expected_profiles[0]->set_label(ASCIIToUTF16(\"Shipping2\"));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n STLDeleteElements(&expected_profiles);\n}\n\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, ProfileSteady) {\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n\n \/\/ Client0 adds a profile.\n AutoFillProfiles expected_profiles;\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(HOMER, expected_profiles[0]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[0]);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client1 adds a profile.\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, expected_profiles[1]);\n AddProfile(GetPersonalDataManager(1), *expected_profiles[1]);\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client0 adds a conflicting profile.\n expected_profiles.push_back(new AutoFillProfile(string16(), 0));\n FillProfile(MARION, expected_profiles[2]);\n AddProfile(GetPersonalDataManager(0), *expected_profiles[2]);\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n \/\/ The conflicting profile's label will be made unique.\n expected_profiles[2]->set_label(ASCIIToUTF16(\"Billing2\"));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client1 removes a profile.\n delete expected_profiles.front();\n expected_profiles.erase(expected_profiles.begin());\n RemoveProfile(GetPersonalDataManager(1), ASCIIToUTF16(\"Shipping\"));\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client0 updates a profile.\n expected_profiles[0]->SetInfo(AutoFillType(NAME_FIRST),\n ASCIIToUTF16(\"Bart\"));\n UpdateProfile(GetPersonalDataManager(0),\n ASCIIToUTF16(\"Billing\"),\n AutoFillType(NAME_FIRST),\n ASCIIToUTF16(\"Bart\"));\n EXPECT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n\n \/\/ Client1 removes everything.\n STLDeleteElements(&expected_profiles);\n RemoveProfile(GetPersonalDataManager(1), ASCIIToUTF16(\"Billing\"));\n RemoveProfile(GetPersonalDataManager(1), ASCIIToUTF16(\"Billing2\"));\n EXPECT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0)));\n\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(0))));\n EXPECT_TRUE(CompareAutoFillProfiles(expected_profiles,\n GetAllAutoFillProfiles(GetPersonalDataManager(1))));\n}\n<|endoftext|>"} {"text":"#include \"SampleCode.h\"\n#include \"SkCanvas.h\"\n#include \"SkParsePath.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkView.h\"\n\n#include \"SkBlurMaskFilter.h\"\n#include \"SkBlurMask.h\"\n\nstatic void test_blur() {\n uint8_t cell[9];\n memset(cell, 0xFF, sizeof(cell));\n SkMask src;\n src.fImage = cell;\n src.fFormat = SkMask::kA8_Format;\n SkMask dst;\n\n for (int y = 1; y <= 3; y++) {\n for (int x = 1; x <= 3; x++) {\n src.fBounds.set(0, 0, x, y);\n src.fRowBytes = src.fBounds.width();\n \n SkScalar radius = 1.f;\n\n printf(\"src [%d %d %d %d] radius %g\\n\", src.fBounds.fLeft, src.fBounds.fTop,\n src.fBounds.fRight, src.fBounds.fBottom, radius);\n\n SkBlurMask::Blur(&dst, src, radius, SkBlurMask::kNormal_Style);\n uint8_t* dstPtr = dst.fImage;\n\n for (int y = 0; y < dst.fBounds.height(); y++) {\n for (int x = 0; x < dst.fBounds.width(); x++) {\n printf(\" %02X\", dstPtr[x]);\n }\n printf(\"\\n\");\n dstPtr += dst.fRowBytes;\n }\n }\n }\n}\n\nstatic void scale_to_width(SkPath* path, SkScalar dstWidth) {\n const SkRect& bounds = path->getBounds();\n SkScalar scale = dstWidth \/ bounds.width();\n SkMatrix matrix;\n\n matrix.setScale(scale, scale);\n path->transform(matrix);\n}\n\nstatic const struct {\n SkPaint::Style fStyle;\n SkPaint::Join fJoin;\n int fStrokeWidth;\n} gRec[] = {\n { SkPaint::kFill_Style, SkPaint::kMiter_Join, 0 },\n { SkPaint::kStroke_Style, SkPaint::kMiter_Join, 0 },\n { SkPaint::kStroke_Style, SkPaint::kMiter_Join, 10 },\n { SkPaint::kStrokeAndFill_Style, SkPaint::kMiter_Join, 10 },\n};\n\nclass StrokePathView : public SkView {\n SkScalar fWidth;\n SkPath fPath;\npublic:\n\tStrokePathView() {\n test_blur();\n fWidth = SkIntToScalar(120);\n\n#if 0\n const char str[] =\n \"M 0, 3\"\n \"C 10, -10, 30, -10, 0, 28\"\n \"C -30, -10, -10, -10, 0, 3\"\n \"Z\";\n SkParsePath::FromSVGString(str, &fPath);\n#else\n fPath.addCircle(0, 0, SkIntToScalar(50), SkPath::kCW_Direction);\n fPath.addCircle(0, SkIntToScalar(-50), SkIntToScalar(30), SkPath::kCW_Direction);\n#endif\n \n scale_to_width(&fPath, fWidth);\n const SkRect& bounds = fPath.getBounds();\n fPath.offset(-bounds.fLeft, -bounds.fTop);\n }\n \nprotected:\n \/\/ overrides from SkEventSink\n virtual bool onQuery(SkEvent* evt) {\n if (SampleCode::TitleQ(*evt)) {\n SampleCode::TitleR(evt, \"StrokePath\");\n return true;\n }\n return this->INHERITED::onQuery(evt);\n }\n \n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFFDDDDDD);\n }\n \n SkRandom rand;\n \n void drawSet(SkCanvas* canvas, SkPaint* paint) {\n SkAutoCanvasRestore acr(canvas, true);\n\n for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); i++) {\n paint->setStyle(gRec[i].fStyle);\n paint->setStrokeJoin(gRec[i].fJoin);\n paint->setStrokeWidth(SkIntToScalar(gRec[i].fStrokeWidth));\n canvas->drawPath(fPath, *paint);\n canvas->translate(fWidth * 5 \/ 4, 0);\n }\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n drawBG(canvas);\n \/\/return;\n canvas->translate(SkIntToScalar(10), SkIntToScalar(10));\n\n SkPaint paint;\n paint.setAntiAlias(true);\n \n if (true) {\n canvas->drawColor(SK_ColorBLACK);\n\n paint.setTextSize(24);\n paint.setColor(SK_ColorWHITE);\n canvas->translate(10, 30);\n\n static const SkBlurMaskFilter::BlurStyle gStyle[] = {\n SkBlurMaskFilter::kNormal_BlurStyle,\n SkBlurMaskFilter::kInner_BlurStyle,\n SkBlurMaskFilter::kOuter_BlurStyle,\n SkBlurMaskFilter::kSolid_BlurStyle,\n };\n for (int x = 0; x < 5; x++) {\n SkMaskFilter* mf;\n SkScalar radius = 4;\n for (int y = 0; y < 10; y++) {\n if (x) {\n mf = SkBlurMaskFilter::Create(radius, gStyle[x - 1]);\n paint.setMaskFilter(mf)->unref();\n }\n canvas->drawText(\"Title Bar\", 9, x*100, y*30, paint);\n radius *= 0.75f;\n }\n \n }\n return;\n }\n\n paint.setColor(SK_ColorBLUE);\n\n#if 1\n SkPath p;\n float r = rand.nextUScalar1() + 0.5f;\n SkScalar x = 0, y = 0;\n p.moveTo(x, y);\n#if 0\n p.cubicTo(x-75*r, y+75*r, x-40*r, y+125*r, x, y+85*r);\n p.cubicTo(x+40*r, y+125*r, x+75*r, y+75*r, x, y);\n#else\n p.cubicTo(x+75*r, y+75*r, x+40*r, y+125*r, x, y+85*r);\n p.cubicTo(x-40*r, y+125*r, x-75*r, y+75*r, x, y);\n#endif\n p.close();\n fPath = p;\n fPath.offset(100, 0);\n#endif\n \n fPath.setFillType(SkPath::kWinding_FillType);\n drawSet(canvas, &paint);\n \n canvas->translate(0, fPath.getBounds().height() * 5 \/ 4);\n fPath.setFillType(SkPath::kEvenOdd_FillType);\n drawSet(canvas, &paint);\n }\n\n virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {\n this->inval(NULL);\n return this->INHERITED::onFindClickHandler(x, y);\n }\nprivate:\n typedef SkView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new StrokePathView; }\nstatic SkViewRegister reg(MyFactory);\n\n#if 0 test code for blur, since it references a private header#include \"SampleCode.h\"\n#include \"SkCanvas.h\"\n#include \"SkParsePath.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkView.h\"\n\n#include \"SkBlurMaskFilter.h\"\n\n#if 0\n#include \"SkBlurMask.h\"\nstatic void test_blur() {\n uint8_t cell[9];\n memset(cell, 0xFF, sizeof(cell));\n SkMask src;\n src.fImage = cell;\n src.fFormat = SkMask::kA8_Format;\n SkMask dst;\n\n for (int y = 1; y <= 3; y++) {\n for (int x = 1; x <= 3; x++) {\n src.fBounds.set(0, 0, x, y);\n src.fRowBytes = src.fBounds.width();\n \n SkScalar radius = 1.f;\n\n printf(\"src [%d %d %d %d] radius %g\\n\", src.fBounds.fLeft, src.fBounds.fTop,\n src.fBounds.fRight, src.fBounds.fBottom, radius);\n\n SkBlurMask::Blur(&dst, src, radius, SkBlurMask::kNormal_Style);\n uint8_t* dstPtr = dst.fImage;\n\n for (int y = 0; y < dst.fBounds.height(); y++) {\n for (int x = 0; x < dst.fBounds.width(); x++) {\n printf(\" %02X\", dstPtr[x]);\n }\n printf(\"\\n\");\n dstPtr += dst.fRowBytes;\n }\n }\n }\n}\n#endif\n\nstatic void scale_to_width(SkPath* path, SkScalar dstWidth) {\n const SkRect& bounds = path->getBounds();\n SkScalar scale = dstWidth \/ bounds.width();\n SkMatrix matrix;\n\n matrix.setScale(scale, scale);\n path->transform(matrix);\n}\n\nstatic const struct {\n SkPaint::Style fStyle;\n SkPaint::Join fJoin;\n int fStrokeWidth;\n} gRec[] = {\n { SkPaint::kFill_Style, SkPaint::kMiter_Join, 0 },\n { SkPaint::kStroke_Style, SkPaint::kMiter_Join, 0 },\n { SkPaint::kStroke_Style, SkPaint::kMiter_Join, 10 },\n { SkPaint::kStrokeAndFill_Style, SkPaint::kMiter_Join, 10 },\n};\n\nclass StrokePathView : public SkView {\n SkScalar fWidth;\n SkPath fPath;\npublic:\n\tStrokePathView() {\n\/\/ test_blur();\n fWidth = SkIntToScalar(120);\n\n#if 0\n const char str[] =\n \"M 0, 3\"\n \"C 10, -10, 30, -10, 0, 28\"\n \"C -30, -10, -10, -10, 0, 3\"\n \"Z\";\n SkParsePath::FromSVGString(str, &fPath);\n#else\n fPath.addCircle(0, 0, SkIntToScalar(50), SkPath::kCW_Direction);\n fPath.addCircle(0, SkIntToScalar(-50), SkIntToScalar(30), SkPath::kCW_Direction);\n#endif\n \n scale_to_width(&fPath, fWidth);\n const SkRect& bounds = fPath.getBounds();\n fPath.offset(-bounds.fLeft, -bounds.fTop);\n }\n \nprotected:\n \/\/ overrides from SkEventSink\n virtual bool onQuery(SkEvent* evt) {\n if (SampleCode::TitleQ(*evt)) {\n SampleCode::TitleR(evt, \"StrokePath\");\n return true;\n }\n return this->INHERITED::onQuery(evt);\n }\n \n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFFDDDDDD);\n }\n \n SkRandom rand;\n \n void drawSet(SkCanvas* canvas, SkPaint* paint) {\n SkAutoCanvasRestore acr(canvas, true);\n\n for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); i++) {\n paint->setStyle(gRec[i].fStyle);\n paint->setStrokeJoin(gRec[i].fJoin);\n paint->setStrokeWidth(SkIntToScalar(gRec[i].fStrokeWidth));\n canvas->drawPath(fPath, *paint);\n canvas->translate(fWidth * 5 \/ 4, 0);\n }\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n drawBG(canvas);\n \/\/return;\n canvas->translate(SkIntToScalar(10), SkIntToScalar(10));\n\n SkPaint paint;\n paint.setAntiAlias(true);\n \n if (true) {\n canvas->drawColor(SK_ColorBLACK);\n\n paint.setTextSize(24);\n paint.setColor(SK_ColorWHITE);\n canvas->translate(10, 30);\n\n static const SkBlurMaskFilter::BlurStyle gStyle[] = {\n SkBlurMaskFilter::kNormal_BlurStyle,\n SkBlurMaskFilter::kInner_BlurStyle,\n SkBlurMaskFilter::kOuter_BlurStyle,\n SkBlurMaskFilter::kSolid_BlurStyle,\n };\n for (int x = 0; x < 5; x++) {\n SkMaskFilter* mf;\n SkScalar radius = 4;\n for (int y = 0; y < 10; y++) {\n if (x) {\n mf = SkBlurMaskFilter::Create(radius, gStyle[x - 1]);\n paint.setMaskFilter(mf)->unref();\n }\n canvas->drawText(\"Title Bar\", 9, x*100, y*30, paint);\n radius *= 0.75f;\n }\n \n }\n return;\n }\n\n paint.setColor(SK_ColorBLUE);\n\n#if 1\n SkPath p;\n float r = rand.nextUScalar1() + 0.5f;\n SkScalar x = 0, y = 0;\n p.moveTo(x, y);\n#if 0\n p.cubicTo(x-75*r, y+75*r, x-40*r, y+125*r, x, y+85*r);\n p.cubicTo(x+40*r, y+125*r, x+75*r, y+75*r, x, y);\n#else\n p.cubicTo(x+75*r, y+75*r, x+40*r, y+125*r, x, y+85*r);\n p.cubicTo(x-40*r, y+125*r, x-75*r, y+75*r, x, y);\n#endif\n p.close();\n fPath = p;\n fPath.offset(100, 0);\n#endif\n \n fPath.setFillType(SkPath::kWinding_FillType);\n drawSet(canvas, &paint);\n \n canvas->translate(0, fPath.getBounds().height() * 5 \/ 4);\n fPath.setFillType(SkPath::kEvenOdd_FillType);\n drawSet(canvas, &paint);\n }\n\n virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {\n this->inval(NULL);\n return this->INHERITED::onFindClickHandler(x, y);\n }\nprivate:\n typedef SkView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new StrokePathView; }\nstatic SkViewRegister reg(MyFactory);\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n** Copyright (c) 2000-2003 Wayne Roth\n** Copyright (c) 2004-2007 Stefan Sander\n** Copyright (c) 2007 Michal Policht\n** Copyright (c) 2008 Brandon Fosdick\n** Copyright (c) 2009-2010 Liam Staskawicz\n** Copyright (c) 2011 Debao Zhang\n** Copyright (c) 2012 Doug Brown\n** All right reserved.\n** Web: http:\/\/code.google.com\/p\/qextserialport\/\n**\n** Permission is hereby granted, free of charge, to any person obtaining\n** a copy of this software and associated documentation files (the\n** \"Software\"), to deal in the Software without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and\/or sell copies of the Software, and to\n** permit persons to whom the Software is furnished to do so, subject to\n** the following conditions:\n**\n** The above copyright notice and this permission notice shall be\n** included in all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n**\n****************************************************************************\/\n\n#include \"qextserialenumerator.h\"\n#include \"qextserialenumerator_p.h\"\n#include \n#include \n#include \n\nvoid QextSerialEnumeratorPrivate::platformSpecificInit()\n{\n#ifndef QESP_NO_UDEV\n monitor = NULL;\n notifierFd = -1;\n notifier = NULL;\n\n udev = udev_new();\n if (!udev)\n qCritical() << \"Unable to initialize udev notifications\";\n#endif\n}\n\nvoid QextSerialEnumeratorPrivate::platformSpecificDestruct()\n{\n#ifndef QESP_NO_UDEV\n if (notifier) {\n notifier->setEnabled(false);\n delete notifier;\n }\n\n if (monitor)\n udev_monitor_unref(monitor);\n\n if (udev)\n udev_unref(udev);\n#endif\n}\n\n#ifndef QESP_NO_UDEV\nstatic QextPortInfo portInfoFromDevice(struct udev_device *dev)\n{\n QString vendor = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_VENDOR_ID\"));\n QString product = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_MODEL_ID\"));\n\n QextPortInfo pi;\n pi.vendorID = vendor.toInt(0, 16);\n pi.productID = product.toInt(0, 16);\n pi.portName = QString::fromLatin1(udev_device_get_devnode(dev));\n pi.physName = pi.portName;\n\n return pi;\n}\n#endif\n\nQList QextSerialEnumeratorPrivate::getPorts_sys()\n{\n QList infoList;\n#ifndef QESP_NO_UDEV\n struct udev *ud = udev_new();\n if (!ud) {\n qCritical() << \"Unable to enumerate ports because udev is not initialized.\";\n return infoList;\n }\n\n struct udev_enumerate *enumerate = udev_enumerate_new(ud);\n udev_enumerate_add_match_subsystem(enumerate, \"tty\");\n udev_enumerate_scan_devices(enumerate);\n struct udev_list_entry *list = udev_enumerate_get_list_entry(enumerate);\n struct udev_list_entry *entry;\n udev_list_entry_foreach(entry, list) {\n const char *path;\n struct udev_device *dev;\n\n \/\/ Have to grab the actual udev device here...\n path = udev_list_entry_get_name(entry);\n dev = udev_device_new_from_syspath(ud, path);\n\n infoList.append(portInfoFromDevice(dev));\n\n \/\/ Done with this device\n udev_device_unref(dev);\n }\n \/\/ Done with the list and this udev\n udev_enumerate_unref(enumerate);\n udev_unref(ud);\n\n \/\/ get the non standard serial ports names\n \/\/ (USB-serial, bluetooth-serial, 18F PICs, and so on)\n \/\/ if you know an other name prefix for serial ports please let us know\n \/\/ portNamePrefixes.clear();\n \/\/ portNamePrefixes << QLatin1String(\"rfcomm*\");\n \/\/ portNamePrefixes << QLatin1String(\"serial\/by-id\/usb-*\");\n \/\/ portNameList += dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n \/\/ foreach (QString str , portNameList) {\n \/\/ QextPortInfo inf;\n \/\/ inf.physName = QLatin1String(\"\/dev\/\")+str;\n \/\/ inf.portName = str;\n\n \/\/ if (str.contains(QLatin1String(\"rfcomm\"))) {\n \/\/ inf.friendName = QLatin1String(\"Bluetooth-serial adapter \")+str.remove(0, 6);\n \/\/ }\n \/\/ else if (str.contains(QLatin1String(\"serial\/by-id\/usb-\"))) {\n \/\/ inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 17);\n \/\/ }\n \/\/ inf.enumName = QLatin1String(\"\/dev\"); \/\/ is there a more helpful name for this?\n \/\/ infoList.append(inf);\n \/\/ }\n\n QList::iterator it = infoList.begin();\n while (it != infoList.end()) {\n if (it->portName.contains(QString(\"ttyACM\")))\n {\n qDebug() << __FILE__ << __LINE__ << \"Found: \" << it->portName;\n ++it;\n }\n else\n {\n it = infoList.erase(it);\n }\n }\n\n\n#else\n QStringList portNamePrefixes, portNameList;\n portNamePrefixes << QLatin1String(\"ttyS*\"); \/\/ list normal serial ports first\n\n QDir dir(QLatin1String(\"\/dev\"));\n portNameList = dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n \/\/ remove the values which are not serial ports for e.g. \/dev\/ttysa\n for (int i = 0; i < portNameList.size(); i++) {\n bool ok;\n QString current = portNameList.at(i);\n \/\/ remove the ttyS part, and check, if the other part is a number\n current.remove(0,4).toInt(&ok, 10);\n if (!ok) {\n portNameList.removeAt(i);\n i--;\n }\n }\n\n \/\/ get the non standard serial ports names\n \/\/ (USB-serial, bluetooth-serial, 18F PICs, and so on)\n \/\/ if you know an other name prefix for serial ports please let us know\n portNamePrefixes.clear();\n portNamePrefixes << QLatin1String(\"ttyACM*\") << QLatin1String(\"ttyUSB*\") << QLatin1String(\"rfcomm*\");\n portNamePrefixes << QLatin1String(\"serial\/by-id\/usb-*\");\n portNameList += dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n foreach (QString str , portNameList) {\n QextPortInfo inf;\n inf.physName = QLatin1String(\"\/dev\/\")+str;\n inf.portName = str;\n\n if (str.contains(QLatin1String(\"ttyS\"))) {\n inf.friendName = QLatin1String(\"Serial port \")+str.remove(0, 4);\n }\n else if (str.contains(QLatin1String(\"ttyUSB\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"rfcomm\"))) {\n inf.friendName = QLatin1String(\"Bluetooth-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"serial\/by-id\/usb-\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 17);\n }\n inf.enumName = QLatin1String(\"\/dev\"); \/\/ is there a more helpful name for this?\n infoList.append(inf);\n }\n#endif\n\n return infoList;\n}\n\nbool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool setup)\n{\n Q_UNUSED(setup);\n#ifndef QESP_NO_UDEV\n Q_Q(QextSerialEnumerator);\n if (!udev) {\n qCritical() << \"Unable to initialize notifications because udev is not initialized.\";\n return false;\n }\n\n \/\/ Emit signals immediately for devices already connected (Windows version seems to behave\n \/\/ this way)\n foreach (QextPortInfo i, getPorts_sys())\n Q_EMIT q->deviceDiscovered(i);\n\n \/\/ Look for tty devices from udev.\n monitor = udev_monitor_new_from_netlink(udev, \"udev\");\n udev_monitor_filter_add_match_subsystem_devtype(monitor, \"tty\", NULL);\n udev_monitor_enable_receiving(monitor);\n notifierFd = udev_monitor_get_fd(monitor);\n notifier = new QSocketNotifier(notifierFd, QSocketNotifier::Read);\n q->connect(notifier, SIGNAL(activated(int)), q, SLOT(_q_deviceEvent()));\n notifier->setEnabled(true);\n\n return true;\n#else\n return false;\n#endif\n}\n\n#ifndef QESP_NO_UDEV\nvoid QextSerialEnumeratorPrivate::_q_deviceEvent()\n{\n Q_Q(QextSerialEnumerator);\n struct udev_device *dev = udev_monitor_receive_device(monitor);\n if (dev) {\n QextPortInfo pi = portInfoFromDevice(dev);\n QLatin1String action(udev_device_get_action(dev));\n\n if (action == QLatin1String(\"add\"))\n Q_EMIT q->deviceDiscovered(pi);\n else if (action == QLatin1String(\"remove\"))\n Q_EMIT q->deviceRemoved(pi);\n\n udev_device_unref(dev);\n }\n}\n#endif\nMore qextserial hacking\/****************************************************************************\n** Copyright (c) 2000-2003 Wayne Roth\n** Copyright (c) 2004-2007 Stefan Sander\n** Copyright (c) 2007 Michal Policht\n** Copyright (c) 2008 Brandon Fosdick\n** Copyright (c) 2009-2010 Liam Staskawicz\n** Copyright (c) 2011 Debao Zhang\n** Copyright (c) 2012 Doug Brown\n** All right reserved.\n** Web: http:\/\/code.google.com\/p\/qextserialport\/\n**\n** Permission is hereby granted, free of charge, to any person obtaining\n** a copy of this software and associated documentation files (the\n** \"Software\"), to deal in the Software without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and\/or sell copies of the Software, and to\n** permit persons to whom the Software is furnished to do so, subject to\n** the following conditions:\n**\n** The above copyright notice and this permission notice shall be\n** included in all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n**\n****************************************************************************\/\n\n#include \"qextserialenumerator.h\"\n#include \"qextserialenumerator_p.h\"\n#include \n#include \n#include \n\nvoid QextSerialEnumeratorPrivate::platformSpecificInit()\n{\n\/\/ #ifndef QESP_NO_UDEV\n\/\/ monitor = NULL;\n\/\/ notifierFd = -1;\n\/\/ notifier = NULL;\n\n\/\/ udev = udev_new();\n\/\/ if (!udev)\n\/\/ qCritical() << \"Unable to initialize udev notifications\";\n\/\/ #endif\n}\n\nvoid QextSerialEnumeratorPrivate::platformSpecificDestruct()\n{\n\/\/ #ifndef QESP_NO_UDEV\n\/\/ if (notifier) {\n\/\/ notifier->setEnabled(false);\n\/\/ delete notifier;\n\/\/ }\n\n\/\/ if (monitor)\n\/\/ udev_monitor_unref(monitor);\n\n\/\/ if (udev)\n\/\/ udev_unref(udev);\n\/\/ #endif\n}\n\n#ifndef QESP_NO_UDEV\nstatic QextPortInfo portInfoFromDevice(struct udev_device *dev)\n{\n QString vendor = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_VENDOR_ID\"));\n QString product = QString::fromLatin1(udev_device_get_property_value(dev, \"ID_MODEL_ID\"));\n\n QextPortInfo pi;\n pi.vendorID = vendor.toInt(0, 16);\n pi.productID = product.toInt(0, 16);\n pi.portName = QString::fromLatin1(udev_device_get_devnode(dev));\n pi.physName = pi.portName;\n\n return pi;\n}\n#endif\n\nQList QextSerialEnumeratorPrivate::getPorts_sys()\n{\n QList infoList;\n\/\/ #ifndef QESP_NO_UDEV\n\/\/ struct udev *ud = udev_new();\n\/\/ if (!ud) {\n\/\/ qCritical() << \"Unable to enumerate ports because udev is not initialized.\";\n\/\/ return infoList;\n\/\/ }\n\n\/\/ struct udev_enumerate *enumerate = udev_enumerate_new(ud);\n\/\/ udev_enumerate_add_match_subsystem(enumerate, \"tty\");\n\/\/ udev_enumerate_scan_devices(enumerate);\n\/\/ struct udev_list_entry *list = udev_enumerate_get_list_entry(enumerate);\n\/\/ struct udev_list_entry *entry;\n\/\/ udev_list_entry_foreach(entry, list) {\n\/\/ const char *path;\n\/\/ struct udev_device *dev;\n\n\/\/ \/\/ Have to grab the actual udev device here...\n\/\/ path = udev_list_entry_get_name(entry);\n\/\/ dev = udev_device_new_from_syspath(ud, path);\n\n\/\/ infoList.append(portInfoFromDevice(dev));\n\n\/\/ \/\/ Done with this device\n\/\/ udev_device_unref(dev);\n\/\/ }\n\/\/ \/\/ Done with the list and this udev\n\/\/ udev_enumerate_unref(enumerate);\n\/\/ udev_unref(ud);\n\n\/\/ \/\/ get the non standard serial ports names\n\/\/ \/\/ (USB-serial, bluetooth-serial, 18F PICs, and so on)\n\/\/ \/\/ if you know an other name prefix for serial ports please let us know\n\/\/ \/\/ portNamePrefixes.clear();\n\/\/ \/\/ portNamePrefixes << QLatin1String(\"rfcomm*\");\n\/\/ \/\/ portNamePrefixes << QLatin1String(\"serial\/by-id\/usb-*\");\n\/\/ \/\/ portNameList += dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n\/\/ \/\/ foreach (QString str , portNameList) {\n\/\/ \/\/ QextPortInfo inf;\n\/\/ \/\/ inf.physName = QLatin1String(\"\/dev\/\")+str;\n\/\/ \/\/ inf.portName = str;\n\n\/\/ \/\/ if (str.contains(QLatin1String(\"rfcomm\"))) {\n\/\/ \/\/ inf.friendName = QLatin1String(\"Bluetooth-serial adapter \")+str.remove(0, 6);\n\/\/ \/\/ }\n\/\/ \/\/ else if (str.contains(QLatin1String(\"serial\/by-id\/usb-\"))) {\n\/\/ \/\/ inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 17);\n\/\/ \/\/ }\n\/\/ \/\/ inf.enumName = QLatin1String(\"\/dev\"); \/\/ is there a more helpful name for this?\n\/\/ \/\/ infoList.append(inf);\n\/\/ \/\/ }\n\n\/\/ QList::iterator it = infoList.begin();\n\/\/ while (it != infoList.end()) {\n\/\/ if (it->portName.contains(QString(\"ttyACM\")))\n\/\/ {\n\/\/ qDebug() << __FILE__ << __LINE__ << \"Found: \" << it->portName;\n\/\/ ++it;\n\/\/ }\n\/\/ else\n\/\/ {\n\/\/ it = infoList.erase(it);\n\/\/ }\n\/\/ }\n\n\n\/\/ #else\n QStringList portNamePrefixes, portNameList;\n portNamePrefixes << QLatin1String(\"ttyS*\"); \/\/ list normal serial ports first\n\n QDir dir(QLatin1String(\"\/dev\"));\n portNameList = dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n \/\/ remove the values which are not serial ports for e.g. \/dev\/ttysa\n for (int i = 0; i < portNameList.size(); i++) {\n bool ok;\n QString current = portNameList.at(i);\n \/\/ remove the ttyS part, and check, if the other part is a number\n current.remove(0,4).toInt(&ok, 10);\n if (!ok) {\n portNameList.removeAt(i);\n i--;\n }\n }\n\n \/\/ get the non standard serial ports names\n \/\/ (USB-serial, bluetooth-serial, 18F PICs, and so on)\n \/\/ if you know an other name prefix for serial ports please let us know\n portNamePrefixes.clear();\n portNamePrefixes << QLatin1String(\"ttyACM*\") << QLatin1String(\"ttyUSB*\") << QLatin1String(\"rfcomm*\");\n portNamePrefixes << QLatin1String(\"serial\/by-id\/usb-*\");\n portNameList += dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);\n\n foreach (QString str , portNameList) {\n QextPortInfo inf;\n inf.physName = QLatin1String(\"\/dev\/\")+str;\n inf.portName = str;\n\n if (str.contains(QLatin1String(\"ttyS\"))) {\n inf.friendName = QLatin1String(\"Serial port \")+str.remove(0, 4);\n }\n else if (str.contains(QLatin1String(\"ttyUSB\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"rfcomm\"))) {\n inf.friendName = QLatin1String(\"Bluetooth-serial adapter \")+str.remove(0, 6);\n }\n else if (str.contains(QLatin1String(\"serial\/by-id\/usb-\"))) {\n inf.friendName = QLatin1String(\"USB-serial adapter \")+str.remove(0, 17);\n }\n inf.enumName = QLatin1String(\"\/dev\"); \/\/ is there a more helpful name for this?\n infoList.append(inf);\n }\n\/\/ #endif\n\n return infoList;\n}\n\nbool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool setup)\n{\n Q_UNUSED(setup);\n\/\/ #ifndef QESP_NO_UDEV\n\/\/ Q_Q(QextSerialEnumerator);\n\/\/ if (!udev) {\n\/\/ qCritical() << \"Unable to initialize notifications because udev is not initialized.\";\n\/\/ return false;\n\/\/ }\n\n\/\/ \/\/ Emit signals immediately for devices already connected (Windows version seems to behave\n\/\/ \/\/ this way)\n\/\/ foreach (QextPortInfo i, getPorts_sys())\n\/\/ Q_EMIT q->deviceDiscovered(i);\n\n\/\/ \/\/ Look for tty devices from udev.\n\/\/ monitor = udev_monitor_new_from_netlink(udev, \"udev\");\n\/\/ udev_monitor_filter_add_match_subsystem_devtype(monitor, \"tty\", NULL);\n\/\/ udev_monitor_enable_receiving(monitor);\n\/\/ notifierFd = udev_monitor_get_fd(monitor);\n\/\/ notifier = new QSocketNotifier(notifierFd, QSocketNotifier::Read);\n\/\/ q->connect(notifier, SIGNAL(activated(int)), q, SLOT(_q_deviceEvent()));\n\/\/ notifier->setEnabled(true);\n\n\/\/ return true;\n\/\/ #else\n return false;\n\/\/ #endif\n}\n\n\/\/ #ifndef QESP_NO_UDEV\n\/\/ void QextSerialEnumeratorPrivate::_q_deviceEvent()\n\/\/ {\n\/\/ Q_Q(QextSerialEnumerator);\n\/\/ struct udev_device *dev = udev_monitor_receive_device(monitor);\n\/\/ if (dev) {\n\/\/ QextPortInfo pi = portInfoFromDevice(dev);\n\/\/ QLatin1String action(udev_device_get_action(dev));\n\n\/\/ if (action == QLatin1String(\"add\"))\n\/\/ Q_EMIT q->deviceDiscovered(pi);\n\/\/ else if (action == QLatin1String(\"remove\"))\n\/\/ Q_EMIT q->deviceRemoved(pi);\n\n\/\/ udev_device_unref(dev);\n\/\/ }\n\/\/ }\n\/\/ #endif\n<|endoftext|>"} {"text":"\/\/ Main.cpp\n\/\/ UniversalPauseButton\n\/\/ Ryan Ries, 2015\n\/\/ ryan@myotherpcisacloud.com\n\/\/\n\/\/ Must compile in Unicode.\n\n#include \n#include \n#include \n#include \"resource.h\"\n\n#define WM_TRAYICON (WM_USER + 1)\n\n\/\/ WARNING: Undocumented Win32 API functions!\n\/\/ Microsoft may change these at any time; they are not guaranteed to work on the next version of Windows.\ntypedef LONG(NTAPI* _NtSuspendProcess) (IN HANDLE ProcessHandle);\ntypedef LONG(NTAPI* _NtResumeProcess) (IN HANDLE ProcessHandle);\n\n_NtSuspendProcess NtSuspendProcess = (_NtSuspendProcess)GetProcAddress(GetModuleHandle(L\"ntdll\"), \"NtSuspendProcess\");\n_NtResumeProcess NtResumeProcess = (_NtResumeProcess)GetProcAddress(GetModuleHandle(L\"ntdll\"), \"NtResumeProcess\");\n\nNOTIFYICONDATA G_TrayNotifyIconData;\nHANDLE G_Mutex;\n\n\/\/ NOTE(Ryan): This function returns true if the string ends with the specified Suffix\/substring.\n\/\/ Uses wide characters. Not case sensitive.\nint StringEndsWithW(_In_ const wchar_t *Str, _In_ const wchar_t *Suffix)\n{\n\tif (Str == NULL || Suffix == NULL)\n\t{\n\t\treturn 0;\n\t}\n\n\tsize_t str_len = wcslen(Str);\n\tsize_t suffix_len = wcslen(Suffix);\n\n\tif (suffix_len > str_len)\n\t{\n\t\treturn 0;\n\t}\n\t\n\treturn 0 == _wcsnicmp(Str + str_len - suffix_len, Suffix, suffix_len);\n}\n\n\/\/ The WindowProc (callback) for WinMain's WindowClass.\n\/\/ Basically the system tray does nothing except lets the user know that it's running.\n\/\/ If the user clicks the tray icon it will ask if they want to exit the app.\nLRESULT CALLBACK WindowClassCallback(_In_ HWND Window, _In_ UINT Message, _In_ WPARAM WParam, _In_ LPARAM LParam)\n{\n\tLRESULT Result = 0;\n\tstatic BOOL QuitMessageBoxIsShowing = FALSE;\n\n\tswitch (Message)\n\t{\n\t\tcase WM_TRAYICON:\n\t\t{\n\t\t\tif (!QuitMessageBoxIsShowing && (LParam == WM_LBUTTONDOWN || LParam == WM_RBUTTONDOWN || LParam == WM_MBUTTONDOWN))\n\t\t\t{\n\t\t\t\tQuitMessageBoxIsShowing = TRUE;\n\t\t\t\tif (MessageBox(Window, L\"Quit UniversalPauseButton?\", L\"Are you sure?\", MB_YESNO | MB_ICONQUESTION | MB_SYSTEMMODAL) == IDYES)\n\t\t\t\t{\n\t\t\t\t\tShell_NotifyIcon(NIM_DELETE, &G_TrayNotifyIconData);\n\t\t\t\t\tPostQuitMessage(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tQuitMessageBoxIsShowing = FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\tResult = DefWindowProc(Window, Message, WParam, LParam);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn(Result);\n}\n\n\/\/ Entry point.\nint CALLBACK WinMain(_In_ HINSTANCE Instance, _In_opt_ HINSTANCE, _In_ LPSTR, _In_ int)\n{\n\tG_Mutex = CreateMutex(NULL, FALSE, L\"UniversalPauseButton\");\n\tif (GetLastError() == ERROR_ALREADY_EXISTS)\n\t{\n\t\tMessageBox(NULL, L\"An instance of the program is already running.\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(ERROR_ALREADY_EXISTS);\n\t}\n\n\tWNDCLASS SysTrayWindowClass = { 0 };\n\n\tSysTrayWindowClass.style = CS_HREDRAW | CS_VREDRAW;\n\tSysTrayWindowClass.hInstance = Instance;\n\tSysTrayWindowClass.lpszClassName = L\"UniversalPauseButton_Systray_WindowClass\";\n\tSysTrayWindowClass.hbrBackground = CreateSolidBrush(RGB(255, 0, 255));\n\tSysTrayWindowClass.lpfnWndProc = WindowClassCallback;\n\n\tif (RegisterClass(&SysTrayWindowClass) == 0)\n\t{\n\t\tMessageBox(NULL, L\"Failed to register WindowClass!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tHWND SystrayWindow = CreateWindowEx(\n\t\tWS_EX_TOOLWINDOW,\n\t\tSysTrayWindowClass.lpszClassName,\n\t\tL\"UniversalPauseButton_Systray_Window\",\n\t\tWS_ICONIC,\n\t\tCW_USEDEFAULT,\n\t\tCW_USEDEFAULT,\n\t\tCW_USEDEFAULT,\n\t\tCW_USEDEFAULT,\n\t\t0,\n\t\t0,\n\t\tInstance,\n\t\t0);\n\n\tif (SystrayWindow == 0)\n\t{\n\t\tMessageBox(NULL, L\"Failed to create SystrayWindow!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tG_TrayNotifyIconData.cbSize = sizeof(NOTIFYICONDATA);\n\tG_TrayNotifyIconData.hWnd = SystrayWindow;\n\tG_TrayNotifyIconData.uID = 1982;\n\tG_TrayNotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;\n\tG_TrayNotifyIconData.uCallbackMessage = WM_TRAYICON;\n\n\twcscpy_s(G_TrayNotifyIconData.szTip, L\"Universal Pause Button v1.0.1\");\n\n\tG_TrayNotifyIconData.hIcon = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 0, 0, NULL);\n\n\tif (G_TrayNotifyIconData.hIcon == NULL)\n\t{\n\t\tMessageBox(NULL, L\"Failed to load systray icon resource!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tif (Shell_NotifyIcon(NIM_ADD, &G_TrayNotifyIconData) == FALSE)\n\t{\n\t\tMessageBox(NULL, L\"Failed to register systray icon!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tMSG SysTrayWindowMessage = { 0 };\n\tstatic int PauseKeyWasDown = 0;\n\tDWORD PreviouslySuspendedProcessID = 0;\t\n\twchar_t PreviouslySuspendedProcessText[256] = { 0 };\t\n\tHANDLE ProcessHandle = 0;\n\n\twhile (SysTrayWindowMessage.message != WM_QUIT)\n\t{\n\t\twhile (PeekMessage(&SysTrayWindowMessage, SystrayWindow, 0, 0, PM_REMOVE))\n\t\t{\n\t\t\tDispatchMessage(&SysTrayWindowMessage);\n\t\t}\n\n\t\tint PauseKeyIsDown = GetAsyncKeyState(VK_PAUSE);\n\n\t\tif (PauseKeyIsDown && !PauseKeyWasDown)\n\t\t{\n\t\t\tHWND ForegroundWindow = GetForegroundWindow();\n\t\t\tif (!ForegroundWindow)\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"Unable to detect foreground window!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\tgoto EndOfLoop;\n\t\t\t}\n\n\t\t\tDWORD ProcessID = 0;\n\t\t\tGetWindowThreadProcessId(ForegroundWindow, &ProcessID);\n\t\t\tif (ProcessID == 0)\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"Unable to get process ID of foreground window!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\tgoto EndOfLoop;\n\t\t\t}\n\t\t\t\n\t\t\tProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);\n\t\t\tif (ProcessHandle == 0)\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"OpenProcess failed!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\tgoto EndOfLoop;\n\t\t\t}\n\n\t\t\tif (PreviouslySuspendedProcessID == 0)\n\t\t\t{\n\t\t\t\t\/\/ I won't let you pause your shell. Nothing good will come of that.\n\t\t\t\t\/\/ Later I will get the user's shell from the registry, just to cover the 0.001% case\n\t\t\t\t\/\/ that the user has a custom shell.\n\t\t\t\twchar_t ImageFileName[MAX_PATH] = { 0 };\n\t\t\t\tGetProcessImageFileName(ProcessHandle, ImageFileName, sizeof(ImageFileName) \/ sizeof(wchar_t));\n\t\t\t\tif (!StringEndsWithW(ImageFileName, L\"explorer.exe\"))\n\t\t\t\t{\n\t\t\t\t\tNtSuspendProcess(ProcessHandle);\n\t\t\t\t\tPreviouslySuspendedProcessID = ProcessID;\n\t\t\t\t\tGetWindowText(ForegroundWindow, PreviouslySuspendedProcessText, sizeof(PreviouslySuspendedProcessText) \/ sizeof(wchar_t));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMessageBox(NULL, L\"You cannot pause your shell.\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (PreviouslySuspendedProcessID == ProcessID)\n\t\t\t{\n\t\t\t\tNtResumeProcess(ProcessHandle);\n\t\t\t\tPreviouslySuspendedProcessID = 0;\n\t\t\t\tmemset(PreviouslySuspendedProcessText, 0, sizeof(PreviouslySuspendedProcessText));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ The user pressed the pause button while focused on another process than what was\n\t\t\t\t\/\/ originally paused and the first process is still paused.\n\t\t\t\tDWORD AllProcesses[2048] = { 0 };\n\t\t\t\tDWORD BytesReturned = 0;\n\t\t\t\tBOOL PreviouslySuspendedProcessIsStillRunning = FALSE;\n\n\t\t\t\tif (EnumProcesses(AllProcesses, sizeof(AllProcesses), &BytesReturned) != 0)\n\t\t\t\t{\n\t\t\t\t\tfor (DWORD Counter = 0; Counter < (BytesReturned \/ sizeof(DWORD)); Counter++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((AllProcesses[Counter] != 0) && AllProcesses[Counter] == PreviouslySuspendedProcessID)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPreviouslySuspendedProcessIsStillRunning = TRUE;\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (PreviouslySuspendedProcessIsStillRunning)\n\t\t\t\t\t{\n\t\t\t\t\t\twchar_t MessageBoxBuffer[1024] = { 0 };\n\t\t\t\t\t\t_snwprintf_s(MessageBoxBuffer, sizeof(MessageBoxBuffer), L\"You must first unpause %s (PID %d) before pausing another program.\", PreviouslySuspendedProcessText, PreviouslySuspendedProcessID);\n\t\t\t\t\t\tMessageBox(ForegroundWindow, MessageBoxBuffer, L\"Universal Pause Button\", MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ The paused process is no more, so reset.\n\t\t\t\t\t\tPreviouslySuspendedProcessID = 0;\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tmemset(PreviouslySuspendedProcessText, 0, sizeof(PreviouslySuspendedProcessText));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMessageBox(NULL, L\"EnumProcesses failed!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ http:\/\/stackoverflow.com\/questions\/245742\/examples-of-good-gotos-in-c-or-c\n\t\n\tEndOfLoop:\n\t\tif (ProcessHandle)\n\t\t{\n\t\t\tCloseHandle(ProcessHandle);\n\t\t}\n\t\t\n\t\tPauseKeyWasDown = PauseKeyIsDown;\n\t\tSleep(10);\n\t}\n\n\treturn(S_OK);\n}Update version number\/\/ Main.cpp\n\/\/ UniversalPauseButton\n\/\/ Ryan Ries, 2015\n\/\/ ryan@myotherpcisacloud.com\n\/\/\n\/\/ Must compile in Unicode.\n\n#include \n#include \n#include \n#include \"resource.h\"\n\n#define WM_TRAYICON (WM_USER + 1)\n\n\/\/ WARNING: Undocumented Win32 API functions!\n\/\/ Microsoft may change these at any time; they are not guaranteed to work on the next version of Windows.\ntypedef LONG(NTAPI* _NtSuspendProcess) (IN HANDLE ProcessHandle);\ntypedef LONG(NTAPI* _NtResumeProcess) (IN HANDLE ProcessHandle);\n\n_NtSuspendProcess NtSuspendProcess = (_NtSuspendProcess)GetProcAddress(GetModuleHandle(L\"ntdll\"), \"NtSuspendProcess\");\n_NtResumeProcess NtResumeProcess = (_NtResumeProcess)GetProcAddress(GetModuleHandle(L\"ntdll\"), \"NtResumeProcess\");\n\nNOTIFYICONDATA G_TrayNotifyIconData;\nHANDLE G_Mutex;\n\n\/\/ NOTE(Ryan): This function returns true if the string ends with the specified Suffix\/substring.\n\/\/ Uses wide characters. Not case sensitive.\nint StringEndsWithW(_In_ const wchar_t *Str, _In_ const wchar_t *Suffix)\n{\n\tif (Str == NULL || Suffix == NULL)\n\t{\n\t\treturn 0;\n\t}\n\n\tsize_t str_len = wcslen(Str);\n\tsize_t suffix_len = wcslen(Suffix);\n\n\tif (suffix_len > str_len)\n\t{\n\t\treturn 0;\n\t}\n\t\n\treturn 0 == _wcsnicmp(Str + str_len - suffix_len, Suffix, suffix_len);\n}\n\n\/\/ The WindowProc (callback) for WinMain's WindowClass.\n\/\/ Basically the system tray does nothing except lets the user know that it's running.\n\/\/ If the user clicks the tray icon it will ask if they want to exit the app.\nLRESULT CALLBACK WindowClassCallback(_In_ HWND Window, _In_ UINT Message, _In_ WPARAM WParam, _In_ LPARAM LParam)\n{\n\tLRESULT Result = 0;\n\tstatic BOOL QuitMessageBoxIsShowing = FALSE;\n\n\tswitch (Message)\n\t{\n\t\tcase WM_TRAYICON:\n\t\t{\n\t\t\tif (!QuitMessageBoxIsShowing && (LParam == WM_LBUTTONDOWN || LParam == WM_RBUTTONDOWN || LParam == WM_MBUTTONDOWN))\n\t\t\t{\n\t\t\t\tQuitMessageBoxIsShowing = TRUE;\n\t\t\t\tif (MessageBox(Window, L\"Quit UniversalPauseButton?\", L\"Are you sure?\", MB_YESNO | MB_ICONQUESTION | MB_SYSTEMMODAL) == IDYES)\n\t\t\t\t{\n\t\t\t\t\tShell_NotifyIcon(NIM_DELETE, &G_TrayNotifyIconData);\n\t\t\t\t\tPostQuitMessage(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tQuitMessageBoxIsShowing = FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\tResult = DefWindowProc(Window, Message, WParam, LParam);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn(Result);\n}\n\n\/\/ Entry point.\nint CALLBACK WinMain(_In_ HINSTANCE Instance, _In_opt_ HINSTANCE, _In_ LPSTR, _In_ int)\n{\n\tG_Mutex = CreateMutex(NULL, FALSE, L\"UniversalPauseButton\");\n\tif (GetLastError() == ERROR_ALREADY_EXISTS)\n\t{\n\t\tMessageBox(NULL, L\"An instance of the program is already running.\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(ERROR_ALREADY_EXISTS);\n\t}\n\n\tWNDCLASS SysTrayWindowClass = { 0 };\n\n\tSysTrayWindowClass.style = CS_HREDRAW | CS_VREDRAW;\n\tSysTrayWindowClass.hInstance = Instance;\n\tSysTrayWindowClass.lpszClassName = L\"UniversalPauseButton_Systray_WindowClass\";\n\tSysTrayWindowClass.hbrBackground = CreateSolidBrush(RGB(255, 0, 255));\n\tSysTrayWindowClass.lpfnWndProc = WindowClassCallback;\n\n\tif (RegisterClass(&SysTrayWindowClass) == 0)\n\t{\n\t\tMessageBox(NULL, L\"Failed to register WindowClass!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tHWND SystrayWindow = CreateWindowEx(\n\t\tWS_EX_TOOLWINDOW,\n\t\tSysTrayWindowClass.lpszClassName,\n\t\tL\"UniversalPauseButton_Systray_Window\",\n\t\tWS_ICONIC,\n\t\tCW_USEDEFAULT,\n\t\tCW_USEDEFAULT,\n\t\tCW_USEDEFAULT,\n\t\tCW_USEDEFAULT,\n\t\t0,\n\t\t0,\n\t\tInstance,\n\t\t0);\n\n\tif (SystrayWindow == 0)\n\t{\n\t\tMessageBox(NULL, L\"Failed to create SystrayWindow!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tG_TrayNotifyIconData.cbSize = sizeof(NOTIFYICONDATA);\n\tG_TrayNotifyIconData.hWnd = SystrayWindow;\n\tG_TrayNotifyIconData.uID = 1982;\n\tG_TrayNotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;\n\tG_TrayNotifyIconData.uCallbackMessage = WM_TRAYICON;\n\n\twcscpy_s(G_TrayNotifyIconData.szTip, L\"Universal Pause Button v1.0.2\");\n\n\tG_TrayNotifyIconData.hIcon = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 0, 0, NULL);\n\n\tif (G_TrayNotifyIconData.hIcon == NULL)\n\t{\n\t\tMessageBox(NULL, L\"Failed to load systray icon resource!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tif (Shell_NotifyIcon(NIM_ADD, &G_TrayNotifyIconData) == FALSE)\n\t{\n\t\tMessageBox(NULL, L\"Failed to register systray icon!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\treturn(E_FAIL);\n\t}\n\n\tMSG SysTrayWindowMessage = { 0 };\n\tstatic int PauseKeyWasDown = 0;\n\tDWORD PreviouslySuspendedProcessID = 0;\t\n\twchar_t PreviouslySuspendedProcessText[256] = { 0 };\t\n\tHANDLE ProcessHandle = 0;\n\n\twhile (SysTrayWindowMessage.message != WM_QUIT)\n\t{\n\t\twhile (PeekMessage(&SysTrayWindowMessage, SystrayWindow, 0, 0, PM_REMOVE))\n\t\t{\n\t\t\tDispatchMessage(&SysTrayWindowMessage);\n\t\t}\n\n\t\tint PauseKeyIsDown = GetAsyncKeyState(VK_PAUSE);\n\n\t\tif (PauseKeyIsDown && !PauseKeyWasDown)\n\t\t{\n\t\t\tHWND ForegroundWindow = GetForegroundWindow();\n\t\t\tif (!ForegroundWindow)\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"Unable to detect foreground window!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\tgoto EndOfLoop;\n\t\t\t}\n\n\t\t\tDWORD ProcessID = 0;\n\t\t\tGetWindowThreadProcessId(ForegroundWindow, &ProcessID);\n\t\t\tif (ProcessID == 0)\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"Unable to get process ID of foreground window!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\tgoto EndOfLoop;\n\t\t\t}\n\t\t\t\n\t\t\tProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);\n\t\t\tif (ProcessHandle == 0)\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"OpenProcess failed!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\tgoto EndOfLoop;\n\t\t\t}\n\n\t\t\tif (PreviouslySuspendedProcessID == 0)\n\t\t\t{\n\t\t\t\t\/\/ I won't let you pause your shell. Nothing good will come of that.\n\t\t\t\t\/\/ Later I will get the user's shell from the registry, just to cover the 0.001% case\n\t\t\t\t\/\/ that the user has a custom shell.\n\t\t\t\twchar_t ImageFileName[MAX_PATH] = { 0 };\n\t\t\t\tGetProcessImageFileName(ProcessHandle, ImageFileName, sizeof(ImageFileName) \/ sizeof(wchar_t));\n\t\t\t\tif (!StringEndsWithW(ImageFileName, L\"explorer.exe\"))\n\t\t\t\t{\n\t\t\t\t\tNtSuspendProcess(ProcessHandle);\n\t\t\t\t\tPreviouslySuspendedProcessID = ProcessID;\n\t\t\t\t\tGetWindowText(ForegroundWindow, PreviouslySuspendedProcessText, sizeof(PreviouslySuspendedProcessText) \/ sizeof(wchar_t));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMessageBox(NULL, L\"You cannot pause your shell.\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (PreviouslySuspendedProcessID == ProcessID)\n\t\t\t{\n\t\t\t\tNtResumeProcess(ProcessHandle);\n\t\t\t\tPreviouslySuspendedProcessID = 0;\n\t\t\t\tmemset(PreviouslySuspendedProcessText, 0, sizeof(PreviouslySuspendedProcessText));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ The user pressed the pause button while focused on another process than what was\n\t\t\t\t\/\/ originally paused and the first process is still paused.\n\t\t\t\tDWORD AllProcesses[2048] = { 0 };\n\t\t\t\tDWORD BytesReturned = 0;\n\t\t\t\tBOOL PreviouslySuspendedProcessIsStillRunning = FALSE;\n\n\t\t\t\tif (EnumProcesses(AllProcesses, sizeof(AllProcesses), &BytesReturned) != 0)\n\t\t\t\t{\n\t\t\t\t\tfor (DWORD Counter = 0; Counter < (BytesReturned \/ sizeof(DWORD)); Counter++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((AllProcesses[Counter] != 0) && AllProcesses[Counter] == PreviouslySuspendedProcessID)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPreviouslySuspendedProcessIsStillRunning = TRUE;\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (PreviouslySuspendedProcessIsStillRunning)\n\t\t\t\t\t{\n\t\t\t\t\t\twchar_t MessageBoxBuffer[1024] = { 0 };\n\t\t\t\t\t\t_snwprintf_s(MessageBoxBuffer, sizeof(MessageBoxBuffer), L\"You must first unpause %s (PID %d) before pausing another program.\", PreviouslySuspendedProcessText, PreviouslySuspendedProcessID);\n\t\t\t\t\t\tMessageBox(ForegroundWindow, MessageBoxBuffer, L\"Universal Pause Button\", MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ The paused process is no more, so reset.\n\t\t\t\t\t\tPreviouslySuspendedProcessID = 0;\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tmemset(PreviouslySuspendedProcessText, 0, sizeof(PreviouslySuspendedProcessText));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMessageBox(NULL, L\"EnumProcesses failed!\", L\"UniversalPauseButton Error\", MB_OK | MB_ICONERROR);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ http:\/\/stackoverflow.com\/questions\/245742\/examples-of-good-gotos-in-c-or-c\n\t\n\tEndOfLoop:\n\t\tif (ProcessHandle)\n\t\t{\n\t\t\tCloseHandle(ProcessHandle);\n\t\t}\n\t\t\n\t\tPauseKeyWasDown = PauseKeyIsDown;\n\t\tSleep(10);\n\t}\n\n\treturn(S_OK);\n}<|endoftext|>"} {"text":"#include \"Players\/Genetic_AI.h\"\n\n#include \n#include \n#include \n\n#include \"Moves\/Move.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n\n#include \"Exceptions\/Checkmate_Exception.h\"\n#include \"Exceptions\/Game_Ending_Exception.h\"\n#include \"Exceptions\/End_Of_File_Exception.h\"\n\n#include \"Utility.h\"\n\nint Genetic_AI::next_id = 0;\n\nGenetic_AI::Genetic_AI() :\n genome(),\n id(next_id++)\n{\n}\n\n\/\/ Sexual reproduction\nGenetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :\n genome(A.genome, B.genome),\n id(next_id++)\n{\n}\n\nGenetic_AI::~Genetic_AI()\n{\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name)\n{\n std::ifstream ifs(file_name);\n if( ! ifs)\n {\n throw std::runtime_error(\"Could not read: \" + file_name);\n }\n\n read_from(ifs);\n}\n\nGenetic_AI::Genetic_AI(std::istream& is)\n{\n read_from(is);\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)\n{\n std::ifstream ifs(file_name);\n if( ! ifs)\n {\n throw std::runtime_error(\"Could not read: \" + file_name);\n }\n\n std::string line;\n while(std::getline(ifs, line))\n {\n if( ! String::starts_with(line, \"ID:\"))\n {\n continue;\n }\n\n auto param_value = String::split(line, \":\", 1);\n if(id_in == std::stoi(param_value[1]))\n {\n genome.read_from(ifs);\n return;\n }\n }\n\n throw std::runtime_error(\"Could not locate ID \" + std::to_string(id_in) + \" inside file \" + file_name);\n}\n\nvoid Genetic_AI::read_from(std::istream& is)\n{\n std::string line;\n id = -1;\n while(std::getline(is, line))\n {\n if(line.empty())\n {\n continue;\n }\n\n if(String::starts_with(line, \"ID:\"))\n {\n id = std::stoi(String::split(line)[1]);\n break;\n }\n else\n {\n throw std::runtime_error(\"Invalid Genetic_AI line: \" + line);\n }\n }\n\n if( ! is)\n {\n if(id > -1)\n {\n throw std::runtime_error(\"Incomplete Genetic_AI spec in file for ID \" + std::to_string(id));\n }\n else\n {\n throw End_Of_File_Exception();\n }\n }\n\n if(id >= next_id)\n {\n next_id = id + 1;\n }\n\n genome.read_from(is);\n}\n\nconst Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const\n{\n const auto& legal_moves = board.all_legal_moves();\n if(legal_moves.size() == 1)\n {\n return legal_moves.front(); \/\/ If there's only one legal move, take it.\n }\n\n auto positions_to_examine = genome.positions_to_examine(board, clock);\n auto result = search_game_tree(board,\n positions_to_examine,\n clock,\n 0);\n if(result.depth > 0)\n {\n board.add_commentary_to_next_move(result.commentary);\n }\n return result.move;\n}\n\nGame_Tree_Node_Result Genetic_AI::search_game_tree(const Board& board,\n int& positions_to_examine,\n const Clock& clock,\n const int depth) const\n{\n \/\/ Every call to search_game_tree() after the first\n \/\/ costs a position_to_examine.\n if(depth > 0 && positions_to_examine > 0)\n {\n --positions_to_examine;\n }\n\n auto perspective = board.whose_turn();\n\n std::vector results;\n\n \/\/ Moves worth examining further\n std::vector> further_examine; \/\/ move, resulting board, score\n\n \/\/ Find moves worth examining\n for(const auto& move : board.all_legal_moves())\n {\n if(clock.time_left(clock.running_for()) < 0.0)\n {\n return {board.all_legal_moves().front(),\n 0.0,\n perspective,\n depth,\n \"Out of time\"};\n }\n\n auto next_board = board;\n\n try\n {\n next_board.submit_move(move);\n\n if(next_board.all_legal_moves().size() > 1 &&\n (positions_to_examine <= 0\n || ! genome.good_enough_to_examine(board, next_board, perspective)))\n {\n \/\/ Record immediate result without looking ahead further\n results.push_back({move,\n genome.evaluate(next_board, perspective),\n perspective,\n depth,\n next_board.get_game_record().back()});\n }\n else\n {\n further_examine.push_back({move, next_board, genome.evaluate(next_board, perspective)});\n }\n }\n catch(const Checkmate_Exception&)\n {\n \/\/ Mate in one (try to pick the shortest path to checkmate)\n auto score = genome.evaluate(next_board, perspective);\n auto comment = next_board.get_game_record().back();\n\n return {move,\n score,\n perspective,\n depth,\n comment};\n }\n catch(const Game_Ending_Exception&)\n {\n \/\/ Draw\n results.push_back({move,\n genome.evaluate(next_board, perspective),\n perspective,\n depth,\n next_board.get_game_record().back()});\n }\n }\n\n \/\/ Sort moves by score so higher scores get more moves for examination\n std::sort(further_examine.begin(),\n further_examine.end(),\n [](const auto& x, const auto& y)\n {\n return std::get(x) < std::get(y);\n });\n\n \/\/ Look ahead through moves found above\n for(size_t i = 0; i < further_examine.size(); ++i)\n {\n int moves_left = further_examine.size() - i;\n int positions_for_this_move = positions_to_examine\/moves_left;\n\n if(positions_for_this_move > 0 || std::get(further_examine[i]).all_legal_moves().size() == 1)\n {\n positions_to_examine -= positions_for_this_move;\n\n results.push_back(search_game_tree(std::get(further_examine[i]),\n positions_for_this_move,\n clock,\n depth + 1));\n \/\/ Update last result with this game tree node's data\n results.back().move = std::get(further_examine[i]);\n results.back().commentary = std::get(further_examine[i]).get_game_record().back()\n + \" \"\n + results.back().commentary;\n\n positions_to_examine += positions_for_this_move;\n }\n else\n {\n results.push_back({std::get(further_examine[i]),\n std::get(further_examine[i]),\n perspective,\n depth,\n std::get(further_examine[i]).get_game_record().back()});\n }\n }\n\n \/\/ Consider all results and return best\n auto best_score = -Math::infinity;\n auto best_move = board.all_legal_moves().front();\n auto best_depth = 0;\n std::string comments_on_best_move;\n\n for(const auto& result : results)\n {\n auto score = result.score;\n if(result.perspective != perspective)\n {\n score = -score;\n }\n\n \/\/ Prefer ...\n if(score > best_score \/\/ ... better score\n || (score == Math::infinity && result.depth < best_depth) \/\/ shortest path to victory\n || (best_score == -Math::infinity && result.depth > best_depth)) \/\/ longest path to defeat\n {\n best_score = score;\n best_move = result.move;\n best_depth = result.depth;\n comments_on_best_move = result.commentary;\n }\n }\n\n return {best_move,\n best_score,\n perspective,\n best_depth,\n comments_on_best_move};\n}\n\nvoid Genetic_AI::mutate()\n{\n genome.mutate();\n}\n\nvoid Genetic_AI::print_genome(const std::string& file_name) const\n{\n if(file_name.empty())\n {\n print_genome(std::cout);\n }\n else\n {\n auto dest = std::ofstream(file_name, std::ofstream::app);\n print_genome(dest);\n }\n}\n\nvoid Genetic_AI::print_genome(std::ostream& os) const\n{\n os << \"ID: \" << get_id() << std::endl;\n genome.print(os);\n os << \"END\" << std::endl << std::endl;\n}\n\nstd::string Genetic_AI::name() const\n{\n return \"Genetic AI \" + std::to_string(get_id());\n}\n\nint Genetic_AI::get_id() const\n{\n return id;\n}\n\nbool Genetic_AI::operator<(const Genetic_AI& other) const\n{\n return get_id() < other.get_id();\n}\n\nbool Genetic_AI::operator==(const Genetic_AI& other) const\n{\n return get_id() == other.get_id();\n}\nExtra ellipsis in comment#include \"Players\/Genetic_AI.h\"\n\n#include \n#include \n#include \n\n#include \"Moves\/Move.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n\n#include \"Exceptions\/Checkmate_Exception.h\"\n#include \"Exceptions\/Game_Ending_Exception.h\"\n#include \"Exceptions\/End_Of_File_Exception.h\"\n\n#include \"Utility.h\"\n\nint Genetic_AI::next_id = 0;\n\nGenetic_AI::Genetic_AI() :\n genome(),\n id(next_id++)\n{\n}\n\n\/\/ Sexual reproduction\nGenetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :\n genome(A.genome, B.genome),\n id(next_id++)\n{\n}\n\nGenetic_AI::~Genetic_AI()\n{\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name)\n{\n std::ifstream ifs(file_name);\n if( ! ifs)\n {\n throw std::runtime_error(\"Could not read: \" + file_name);\n }\n\n read_from(ifs);\n}\n\nGenetic_AI::Genetic_AI(std::istream& is)\n{\n read_from(is);\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)\n{\n std::ifstream ifs(file_name);\n if( ! ifs)\n {\n throw std::runtime_error(\"Could not read: \" + file_name);\n }\n\n std::string line;\n while(std::getline(ifs, line))\n {\n if( ! String::starts_with(line, \"ID:\"))\n {\n continue;\n }\n\n auto param_value = String::split(line, \":\", 1);\n if(id_in == std::stoi(param_value[1]))\n {\n genome.read_from(ifs);\n return;\n }\n }\n\n throw std::runtime_error(\"Could not locate ID \" + std::to_string(id_in) + \" inside file \" + file_name);\n}\n\nvoid Genetic_AI::read_from(std::istream& is)\n{\n std::string line;\n id = -1;\n while(std::getline(is, line))\n {\n if(line.empty())\n {\n continue;\n }\n\n if(String::starts_with(line, \"ID:\"))\n {\n id = std::stoi(String::split(line)[1]);\n break;\n }\n else\n {\n throw std::runtime_error(\"Invalid Genetic_AI line: \" + line);\n }\n }\n\n if( ! is)\n {\n if(id > -1)\n {\n throw std::runtime_error(\"Incomplete Genetic_AI spec in file for ID \" + std::to_string(id));\n }\n else\n {\n throw End_Of_File_Exception();\n }\n }\n\n if(id >= next_id)\n {\n next_id = id + 1;\n }\n\n genome.read_from(is);\n}\n\nconst Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const\n{\n const auto& legal_moves = board.all_legal_moves();\n if(legal_moves.size() == 1)\n {\n return legal_moves.front(); \/\/ If there's only one legal move, take it.\n }\n\n auto positions_to_examine = genome.positions_to_examine(board, clock);\n auto result = search_game_tree(board,\n positions_to_examine,\n clock,\n 0);\n if(result.depth > 0)\n {\n board.add_commentary_to_next_move(result.commentary);\n }\n return result.move;\n}\n\nGame_Tree_Node_Result Genetic_AI::search_game_tree(const Board& board,\n int& positions_to_examine,\n const Clock& clock,\n const int depth) const\n{\n \/\/ Every call to search_game_tree() after the first\n \/\/ costs a position_to_examine.\n if(depth > 0 && positions_to_examine > 0)\n {\n --positions_to_examine;\n }\n\n auto perspective = board.whose_turn();\n\n std::vector results;\n\n \/\/ Moves worth examining further\n std::vector> further_examine; \/\/ move, resulting board, score\n\n \/\/ Find moves worth examining\n for(const auto& move : board.all_legal_moves())\n {\n if(clock.time_left(clock.running_for()) < 0.0)\n {\n return {board.all_legal_moves().front(),\n 0.0,\n perspective,\n depth,\n \"Out of time\"};\n }\n\n auto next_board = board;\n\n try\n {\n next_board.submit_move(move);\n\n if(next_board.all_legal_moves().size() > 1 &&\n (positions_to_examine <= 0\n || ! genome.good_enough_to_examine(board, next_board, perspective)))\n {\n \/\/ Record immediate result without looking ahead further\n results.push_back({move,\n genome.evaluate(next_board, perspective),\n perspective,\n depth,\n next_board.get_game_record().back()});\n }\n else\n {\n further_examine.push_back({move, next_board, genome.evaluate(next_board, perspective)});\n }\n }\n catch(const Checkmate_Exception&)\n {\n \/\/ Mate in one (try to pick the shortest path to checkmate)\n auto score = genome.evaluate(next_board, perspective);\n auto comment = next_board.get_game_record().back();\n\n return {move,\n score,\n perspective,\n depth,\n comment};\n }\n catch(const Game_Ending_Exception&)\n {\n \/\/ Draw\n results.push_back({move,\n genome.evaluate(next_board, perspective),\n perspective,\n depth,\n next_board.get_game_record().back()});\n }\n }\n\n \/\/ Sort moves by score so higher scores get more moves for examination\n std::sort(further_examine.begin(),\n further_examine.end(),\n [](const auto& x, const auto& y)\n {\n return std::get(x) < std::get(y);\n });\n\n \/\/ Look ahead through moves found above\n for(size_t i = 0; i < further_examine.size(); ++i)\n {\n int moves_left = further_examine.size() - i;\n int positions_for_this_move = positions_to_examine\/moves_left;\n\n if(positions_for_this_move > 0 || std::get(further_examine[i]).all_legal_moves().size() == 1)\n {\n positions_to_examine -= positions_for_this_move;\n\n results.push_back(search_game_tree(std::get(further_examine[i]),\n positions_for_this_move,\n clock,\n depth + 1));\n \/\/ Update last result with this game tree node's data\n results.back().move = std::get(further_examine[i]);\n results.back().commentary = std::get(further_examine[i]).get_game_record().back()\n + \" \"\n + results.back().commentary;\n\n positions_to_examine += positions_for_this_move;\n }\n else\n {\n results.push_back({std::get(further_examine[i]),\n std::get(further_examine[i]),\n perspective,\n depth,\n std::get(further_examine[i]).get_game_record().back()});\n }\n }\n\n \/\/ Consider all results and return best\n auto best_score = -Math::infinity;\n auto best_move = board.all_legal_moves().front();\n auto best_depth = 0;\n std::string comments_on_best_move;\n\n for(const auto& result : results)\n {\n auto score = result.score;\n if(result.perspective != perspective)\n {\n score = -score;\n }\n\n \/\/ Prefer ...\n if(score > best_score \/\/ better score\n || (score == Math::infinity && result.depth < best_depth) \/\/ shortest path to victory\n || (best_score == -Math::infinity && result.depth > best_depth)) \/\/ longest path to defeat\n {\n best_score = score;\n best_move = result.move;\n best_depth = result.depth;\n comments_on_best_move = result.commentary;\n }\n }\n\n return {best_move,\n best_score,\n perspective,\n best_depth,\n comments_on_best_move};\n}\n\nvoid Genetic_AI::mutate()\n{\n genome.mutate();\n}\n\nvoid Genetic_AI::print_genome(const std::string& file_name) const\n{\n if(file_name.empty())\n {\n print_genome(std::cout);\n }\n else\n {\n auto dest = std::ofstream(file_name, std::ofstream::app);\n print_genome(dest);\n }\n}\n\nvoid Genetic_AI::print_genome(std::ostream& os) const\n{\n os << \"ID: \" << get_id() << std::endl;\n genome.print(os);\n os << \"END\" << std::endl << std::endl;\n}\n\nstd::string Genetic_AI::name() const\n{\n return \"Genetic AI \" + std::to_string(get_id());\n}\n\nint Genetic_AI::get_id() const\n{\n return id;\n}\n\nbool Genetic_AI::operator<(const Genetic_AI& other) const\n{\n return get_id() < other.get_id();\n}\n\nbool Genetic_AI::operator==(const Genetic_AI& other) const\n{\n return get_id() == other.get_id();\n}\n<|endoftext|>"} {"text":"#include \"Players\/Minimax_AI.h\"\n\n#include \n\n#include \"Players\/Game_Tree_Node_Result.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n#include \"Game\/Game_Result.h\"\n#include \"Moves\/Move.h\"\n\n#include \"Utility.h\"\n\nconst Move& Minimax_AI::choose_move(const Board& board, const Clock& clock) const\n{\n \/\/ Erase data from previous board when starting new game\n if(board.game_record().size() <= 1)\n {\n principal_variation.clear();\n commentary.clear();\n }\n\n nodes_searched = 0;\n clock_start_time = clock.running_time_left();\n maximum_depth = 0;\n\n nodes_evaluated = 0;\n total_evaluation_time = 0.0;\n time_at_last_output = clock.running_time_left();\n\n const auto& legal_moves = board.legal_moves();\n if(legal_moves.size() == 1)\n {\n if(principal_variation.size() > 3 && principal_variation[1] == board.game_record().back())\n {\n \/\/ search_game_tree() assumes the principal variation starts\n \/\/ with the previous move of this player. If a move was forced,\n \/\/ then the principal variation needs to be updated to start with\n \/\/ the next move of this side after checking that the immediately\n \/\/ preceding move was the expected one.\n principal_variation.erase(principal_variation.begin(),\n principal_variation.begin() + 2);\n }\n else\n {\n principal_variation.clear();\n }\n\n commentary.push_back(principal_variation);\n\n return *legal_moves.front(); \/\/ If there's only one legal move, take it.\n }\n\n auto time_to_use = time_to_examine(board, clock);\n\n \/\/ alpha = highest score found that opponent will allow\n Game_Tree_Node_Result alpha_start = {Math::lose_score,\n board.whose_turn(),\n {}};\n\n \/\/ beta = score that will cause opponent to choose a different prior move\n Game_Tree_Node_Result beta_start = {Math::win_score,\n board.whose_turn(),\n {}};\n\n auto result = search_game_tree(board,\n time_to_use,\n clock,\n 1,\n alpha_start,\n beta_start,\n ! principal_variation.empty());\n\n if(board.thinking_mode() == CECP)\n {\n output_thinking_cecp(result, clock, board.whose_turn());\n }\n\n if(result.depth() > 1)\n {\n commentary.push_back(result.variation);\n }\n else\n {\n commentary.push_back({});\n }\n\n if(result.depth() > 2)\n {\n principal_variation = result.variation;\n }\n else\n {\n principal_variation.clear();\n }\n\n if(nodes_evaluated > 0)\n {\n evaluation_speed = nodes_evaluated \/ total_evaluation_time;\n }\n\n return *result.variation.front();\n}\n\nGame_Tree_Node_Result Minimax_AI::search_game_tree(const Board& board,\n const double time_to_examine,\n const Clock& clock,\n const size_t depth,\n Game_Tree_Node_Result alpha,\n const Game_Tree_Node_Result& beta,\n bool still_on_principal_variation) const\n{\n const auto time_start = clock.running_time_left();\n maximum_depth = std::max(maximum_depth, depth);\n auto all_legal_moves = board.legal_moves();\n\n \/\/ The two items in the principal variation are the last two moves of\n \/\/ the non-hypothetical board. So, the first item in the principal variation to\n \/\/ consider is at index depth + 1 (since depth starts at 1).\n still_on_principal_variation = (still_on_principal_variation && principal_variation.size() > depth + 1);\n auto start_offset = 0;\n if(still_on_principal_variation)\n {\n auto next_principal_variation_move = principal_variation[depth + 1];\n auto move_iter = std::find(all_legal_moves.begin(),\n all_legal_moves.end(),\n next_principal_variation_move);\n\n still_on_principal_variation = (move_iter != all_legal_moves.end());\n if(still_on_principal_variation)\n {\n \/\/ Put principal variation move at start of list to allow\n \/\/ the most pruning later.\n std::iter_swap(all_legal_moves.begin(), move_iter);\n start_offset = 1;\n }\n }\n\n \/\/ Consider capturing moves first after principal variation move\n auto partition_start = std::next(all_legal_moves.begin(), start_offset);\n std::partition(partition_start, all_legal_moves.end(),\n [&board](auto move){ return board.move_captures(*move); });\n\n const auto perspective = board.whose_turn();\n auto moves_left = all_legal_moves.size();\n\n Game_Tree_Node_Result best_result = {Math::lose_score,\n perspective,\n {all_legal_moves.front()}};\n\n for(const auto& move : all_legal_moves)\n {\n auto evaluate_start_time = clock.running_time_left();\n ++nodes_searched;\n\n auto next_board = board;\n\n auto move_result = next_board.submit_move(*move);\n if(move_result.winner() != NONE)\n {\n \/\/ This move results in checkmate, no other move can be better.\n return create_result(next_board, perspective, move_result, depth);\n }\n\n if(alpha.depth() <= depth + 2 && alpha.is_winning_for(perspective))\n {\n \/\/ This move will take a longer path to victory\n \/\/ than one already found. Use \"depth + 2\" since,\n \/\/ if this move isn't winning (and it isn't, since\n \/\/ we're here), then the earliest move that can\n \/\/ win is the next one, which is two away (after\n \/\/ opponent's move).\n continue;\n }\n\n double time_left = time_to_examine - (time_start - clock.running_time_left());\n double time_allotted_for_this_move = (time_left \/ moves_left)*speculation_time_factor(next_board);\n time_allotted_for_this_move = std::min(time_allotted_for_this_move, clock.running_time_left());\n\n bool recurse;\n if(move_result.game_has_ended())\n {\n recurse = false;\n }\n else if(still_on_principal_variation)\n {\n recurse = true;\n }\n else if(depth > 300)\n {\n recurse = false; \/\/ prevent stack overflow\n }\n else\n {\n auto minimum_time_to_recurse = next_board.legal_moves().size() \/ evaluation_speed;\n recurse = (time_allotted_for_this_move > minimum_time_to_recurse);\n }\n\n Game_Tree_Node_Result result;\n if(recurse)\n {\n result = search_game_tree(next_board,\n time_allotted_for_this_move,\n clock,\n depth + 1,\n beta,\n alpha,\n still_on_principal_variation);\n }\n else\n {\n \/\/ Record immediate result without looking ahead further\n result = create_result(next_board, perspective, move_result, depth);\n }\n\n if(result.value(perspective) > best_result.value(perspective))\n {\n best_result = result;\n\n if(best_result.value(perspective) > alpha.value(perspective))\n {\n alpha = best_result;\n if(alpha.value(perspective) >= beta.value(perspective))\n {\n break;\n }\n else if(board.thinking_mode() == CECP && time_since_last_output(clock) > 0.1)\n {\n output_thinking_cecp(alpha, clock,\n depth % 2 == 1 ? perspective : opposite(perspective));\n time_at_last_output = clock.running_time_left();\n }\n }\n }\n\n --moves_left;\n still_on_principal_variation = false; \/\/ only the first move is part of the principal variation\n\n if(clock.running_time_left() < 0)\n {\n break;\n }\n\n if( ! recurse) \/\/ This move was scored by genome.evaluate().\n {\n ++nodes_evaluated;\n total_evaluation_time += evaluate_start_time - clock.running_time_left();\n }\n }\n\n return best_result;\n}\n\nvoid Minimax_AI::output_thinking_cecp(const Game_Tree_Node_Result& thought,\n const Clock& clock,\n Color perspective) const\n{\n auto score = thought.corrected_score(perspective) \/ centipawn_value();\n\n \/\/ Indicate \"mate in N moves\" where N == thought.depth\n if(thought.is_winning_for(perspective))\n {\n score = 10000.0 - thought.depth() + 1;\n }\n else if(thought.is_losing_for(perspective))\n {\n score = -(10000.0 - thought.depth() + 1);\n }\n\n auto time_so_far = clock_start_time - clock.running_time_left();\n std::cout << thought.depth() \/\/ ply\n << \" \"\n << int(score) \/\/ score in what should be centipawns\n << \" \"\n << int(time_so_far * 100) \/\/ search time in centiseconds\n << \" \"\n << nodes_searched\n << \" \"\n << maximum_depth\n << \" \"\n << int(nodes_searched \/ time_so_far)\n << '\\t';\n\n \/\/ Principal variation\n for(const auto& move : thought.variation)\n {\n std::cout << move->coordinate_move() << ' ';\n }\n\n std::cout << std::endl;\n}\n\ndouble Minimax_AI::time_since_last_output(const Clock& clock) const\n{\n return time_at_last_output - clock.running_time_left();\n}\n\nGame_Tree_Node_Result Minimax_AI::create_result(const Board& board,\n Color perspective,\n const Game_Result& move_result,\n size_t depth) const\n{\n return {evaluate(board, move_result, perspective, depth),\n perspective,\n {board.game_record().end() - depth,\n board.game_record().end()}};\n}\n\nvoid Minimax_AI::calibrate_thinking_speed() const\n{\n evaluation_speed = 100; \/\/ very conservative initial guess\n auto calibration_time = 1.0; \/\/ seconds\n Board board;\n Clock clock(calibration_time, 1, 0.0);\n clock.start();\n choose_move(board, clock);\n \/\/ choose_move() keeps track of the time it takes and the number of positions\n \/\/ it sees, so this practice move will update the positions_per_second to a\n \/\/ more reasonable value.\n}\n\ndouble Minimax_AI::evaluate(const Board & board, const Game_Result& move_result, Color perspective, size_t depth) const\n{\n if(move_result.game_has_ended())\n {\n if(move_result.winner() == NONE) \/\/ stalemate\n {\n return 0;\n }\n else if(move_result.winner() == perspective) \/\/ checkmate win\n {\n return Math::win_score;\n }\n else \/\/ checkmate loss\n {\n return Math::lose_score;\n }\n }\n\n return internal_evaluate(board, perspective, depth);\n}\n\ndouble Minimax_AI::centipawn_value() const\n{\n return value_of_centipawn;\n}\n\nvoid Minimax_AI::calculate_centipawn_value()\n{\n auto board_with_pawns = Board(\"4k3\/pppppppp\/8\/8\/8\/8\/PPPPPPPP\/4K3 w - - 0 1\");\n auto board_with_no_white_pawns = Board(\"4k3\/pppppppp\/8\/8\/8\/8\/8\/4K3 w - - 0 1\");\n value_of_centipawn = std::abs(evaluate(board_with_pawns, {}, WHITE, 0) - evaluate(board_with_no_white_pawns, {}, WHITE, 0)) \/ 800;\n}\n\nstd::string Minimax_AI::commentary_for_move(size_t move_number) const\n{\n std::string result;\n if(move_number < commentary.size() && !commentary.at(move_number).empty())\n {\n result = commentary.at(move_number).front()->coordinate_move();\n for(size_t i = 1; i < commentary.at(move_number).size(); ++i)\n {\n result += \" \" + commentary.at(move_number).at(i)->coordinate_move();\n }\n }\n\n return result;\n}\nDelete redundant comment#include \"Players\/Minimax_AI.h\"\n\n#include \n\n#include \"Players\/Game_Tree_Node_Result.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n#include \"Game\/Game_Result.h\"\n#include \"Moves\/Move.h\"\n\n#include \"Utility.h\"\n\nconst Move& Minimax_AI::choose_move(const Board& board, const Clock& clock) const\n{\n \/\/ Erase data from previous board when starting new game\n if(board.game_record().size() <= 1)\n {\n principal_variation.clear();\n commentary.clear();\n }\n\n nodes_searched = 0;\n clock_start_time = clock.running_time_left();\n maximum_depth = 0;\n\n nodes_evaluated = 0;\n total_evaluation_time = 0.0;\n time_at_last_output = clock.running_time_left();\n\n const auto& legal_moves = board.legal_moves();\n if(legal_moves.size() == 1)\n {\n if(principal_variation.size() > 3 && principal_variation[1] == board.game_record().back())\n {\n \/\/ search_game_tree() assumes the principal variation starts\n \/\/ with the previous move of this player. If a move was forced,\n \/\/ then the principal variation needs to be updated to start with\n \/\/ the next move of this side after checking that the immediately\n \/\/ preceding move was the expected one.\n principal_variation.erase(principal_variation.begin(),\n principal_variation.begin() + 2);\n }\n else\n {\n principal_variation.clear();\n }\n\n commentary.push_back(principal_variation);\n\n return *legal_moves.front(); \/\/ If there's only one legal move, take it.\n }\n\n auto time_to_use = time_to_examine(board, clock);\n\n \/\/ alpha = highest score found that opponent will allow\n Game_Tree_Node_Result alpha_start = {Math::lose_score,\n board.whose_turn(),\n {}};\n\n \/\/ beta = score that will cause opponent to choose a different prior move\n Game_Tree_Node_Result beta_start = {Math::win_score,\n board.whose_turn(),\n {}};\n\n auto result = search_game_tree(board,\n time_to_use,\n clock,\n 1,\n alpha_start,\n beta_start,\n ! principal_variation.empty());\n\n if(board.thinking_mode() == CECP)\n {\n output_thinking_cecp(result, clock, board.whose_turn());\n }\n\n if(result.depth() > 1)\n {\n commentary.push_back(result.variation);\n }\n else\n {\n commentary.push_back({});\n }\n\n if(result.depth() > 2)\n {\n principal_variation = result.variation;\n }\n else\n {\n principal_variation.clear();\n }\n\n if(nodes_evaluated > 0)\n {\n evaluation_speed = nodes_evaluated \/ total_evaluation_time;\n }\n\n return *result.variation.front();\n}\n\nGame_Tree_Node_Result Minimax_AI::search_game_tree(const Board& board,\n const double time_to_examine,\n const Clock& clock,\n const size_t depth,\n Game_Tree_Node_Result alpha,\n const Game_Tree_Node_Result& beta,\n bool still_on_principal_variation) const\n{\n const auto time_start = clock.running_time_left();\n maximum_depth = std::max(maximum_depth, depth);\n auto all_legal_moves = board.legal_moves();\n\n \/\/ The two items in the principal variation are the last two moves of\n \/\/ the non-hypothetical board. So, the first item in the principal variation to\n \/\/ consider is at index depth + 1 (since depth starts at 1).\n still_on_principal_variation = (still_on_principal_variation && principal_variation.size() > depth + 1);\n auto start_offset = 0;\n if(still_on_principal_variation)\n {\n auto next_principal_variation_move = principal_variation[depth + 1];\n auto move_iter = std::find(all_legal_moves.begin(),\n all_legal_moves.end(),\n next_principal_variation_move);\n\n still_on_principal_variation = (move_iter != all_legal_moves.end());\n if(still_on_principal_variation)\n {\n \/\/ Put principal variation move at start of list to allow\n \/\/ the most pruning later.\n std::iter_swap(all_legal_moves.begin(), move_iter);\n start_offset = 1;\n }\n }\n\n \/\/ Consider capturing moves first after principal variation move\n auto partition_start = std::next(all_legal_moves.begin(), start_offset);\n std::partition(partition_start, all_legal_moves.end(),\n [&board](auto move){ return board.move_captures(*move); });\n\n const auto perspective = board.whose_turn();\n auto moves_left = all_legal_moves.size();\n\n Game_Tree_Node_Result best_result = {Math::lose_score,\n perspective,\n {all_legal_moves.front()}};\n\n for(const auto& move : all_legal_moves)\n {\n auto evaluate_start_time = clock.running_time_left();\n ++nodes_searched;\n\n auto next_board = board;\n\n auto move_result = next_board.submit_move(*move);\n if(move_result.winner() != NONE)\n {\n \/\/ This move results in checkmate, no other move can be better.\n return create_result(next_board, perspective, move_result, depth);\n }\n\n if(alpha.depth() <= depth + 2 && alpha.is_winning_for(perspective))\n {\n \/\/ This move will take a longer path to victory\n \/\/ than one already found. Use \"depth + 2\" since,\n \/\/ if this move isn't winning (and it isn't, since\n \/\/ we're here), then the earliest move that can\n \/\/ win is the next one, which is two away (after\n \/\/ opponent's move).\n continue;\n }\n\n double time_left = time_to_examine - (time_start - clock.running_time_left());\n double time_allotted_for_this_move = (time_left \/ moves_left)*speculation_time_factor(next_board);\n time_allotted_for_this_move = std::min(time_allotted_for_this_move, clock.running_time_left());\n\n bool recurse;\n if(move_result.game_has_ended())\n {\n recurse = false;\n }\n else if(still_on_principal_variation)\n {\n recurse = true;\n }\n else if(depth > 300)\n {\n recurse = false; \/\/ prevent stack overflow\n }\n else\n {\n auto minimum_time_to_recurse = next_board.legal_moves().size() \/ evaluation_speed;\n recurse = (time_allotted_for_this_move > minimum_time_to_recurse);\n }\n\n Game_Tree_Node_Result result;\n if(recurse)\n {\n result = search_game_tree(next_board,\n time_allotted_for_this_move,\n clock,\n depth + 1,\n beta,\n alpha,\n still_on_principal_variation);\n }\n else\n {\n result = create_result(next_board, perspective, move_result, depth);\n }\n\n if(result.value(perspective) > best_result.value(perspective))\n {\n best_result = result;\n\n if(best_result.value(perspective) > alpha.value(perspective))\n {\n alpha = best_result;\n if(alpha.value(perspective) >= beta.value(perspective))\n {\n break;\n }\n else if(board.thinking_mode() == CECP && time_since_last_output(clock) > 0.1)\n {\n output_thinking_cecp(alpha, clock,\n depth % 2 == 1 ? perspective : opposite(perspective));\n time_at_last_output = clock.running_time_left();\n }\n }\n }\n\n --moves_left;\n still_on_principal_variation = false; \/\/ only the first move is part of the principal variation\n\n if(clock.running_time_left() < 0)\n {\n break;\n }\n\n if( ! recurse) \/\/ This move was scored by genome.evaluate().\n {\n ++nodes_evaluated;\n total_evaluation_time += evaluate_start_time - clock.running_time_left();\n }\n }\n\n return best_result;\n}\n\nvoid Minimax_AI::output_thinking_cecp(const Game_Tree_Node_Result& thought,\n const Clock& clock,\n Color perspective) const\n{\n auto score = thought.corrected_score(perspective) \/ centipawn_value();\n\n \/\/ Indicate \"mate in N moves\" where N == thought.depth\n if(thought.is_winning_for(perspective))\n {\n score = 10000.0 - thought.depth() + 1;\n }\n else if(thought.is_losing_for(perspective))\n {\n score = -(10000.0 - thought.depth() + 1);\n }\n\n auto time_so_far = clock_start_time - clock.running_time_left();\n std::cout << thought.depth() \/\/ ply\n << \" \"\n << int(score) \/\/ score in what should be centipawns\n << \" \"\n << int(time_so_far * 100) \/\/ search time in centiseconds\n << \" \"\n << nodes_searched\n << \" \"\n << maximum_depth\n << \" \"\n << int(nodes_searched \/ time_so_far)\n << '\\t';\n\n \/\/ Principal variation\n for(const auto& move : thought.variation)\n {\n std::cout << move->coordinate_move() << ' ';\n }\n\n std::cout << std::endl;\n}\n\ndouble Minimax_AI::time_since_last_output(const Clock& clock) const\n{\n return time_at_last_output - clock.running_time_left();\n}\n\nGame_Tree_Node_Result Minimax_AI::create_result(const Board& board,\n Color perspective,\n const Game_Result& move_result,\n size_t depth) const\n{\n return {evaluate(board, move_result, perspective, depth),\n perspective,\n {board.game_record().end() - depth,\n board.game_record().end()}};\n}\n\nvoid Minimax_AI::calibrate_thinking_speed() const\n{\n evaluation_speed = 100; \/\/ very conservative initial guess\n auto calibration_time = 1.0; \/\/ seconds\n Board board;\n Clock clock(calibration_time, 1, 0.0);\n clock.start();\n choose_move(board, clock);\n \/\/ choose_move() keeps track of the time it takes and the number of positions\n \/\/ it sees, so this practice move will update the positions_per_second to a\n \/\/ more reasonable value.\n}\n\ndouble Minimax_AI::evaluate(const Board & board, const Game_Result& move_result, Color perspective, size_t depth) const\n{\n if(move_result.game_has_ended())\n {\n if(move_result.winner() == NONE) \/\/ stalemate\n {\n return 0;\n }\n else if(move_result.winner() == perspective) \/\/ checkmate win\n {\n return Math::win_score;\n }\n else \/\/ checkmate loss\n {\n return Math::lose_score;\n }\n }\n\n return internal_evaluate(board, perspective, depth);\n}\n\ndouble Minimax_AI::centipawn_value() const\n{\n return value_of_centipawn;\n}\n\nvoid Minimax_AI::calculate_centipawn_value()\n{\n auto board_with_pawns = Board(\"4k3\/pppppppp\/8\/8\/8\/8\/PPPPPPPP\/4K3 w - - 0 1\");\n auto board_with_no_white_pawns = Board(\"4k3\/pppppppp\/8\/8\/8\/8\/8\/4K3 w - - 0 1\");\n value_of_centipawn = std::abs(evaluate(board_with_pawns, {}, WHITE, 0) - evaluate(board_with_no_white_pawns, {}, WHITE, 0)) \/ 800;\n}\n\nstd::string Minimax_AI::commentary_for_move(size_t move_number) const\n{\n std::string result;\n if(move_number < commentary.size() && !commentary.at(move_number).empty())\n {\n result = commentary.at(move_number).front()->coordinate_move();\n for(size_t i = 1; i < commentary.at(move_number).size(); ++i)\n {\n result += \" \" + commentary.at(move_number).at(i)->coordinate_move();\n }\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"reffind.hxx\"\n#include \"global.hxx\"\n#include \"compiler.hxx\"\n#include \"document.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nnamespace {\n\n\/\/ Include colon; addresses in range reference are handled individually.\nconst sal_Unicode pDelimiters[] = {\n '=','(',')','+','-','*','\/','^','&',' ','{','}','<','>',':', 0\n};\n\n\/\/ =======================================================================\n\ninline bool IsText( sal_Unicode c )\n{\n bool bFound = ScGlobal::UnicodeStrChr( pDelimiters, c );\n if (bFound)\n \/\/ This is one of delimiters, therefore not text.\n return false;\n\n \/\/ argument separator is configurable.\n const sal_Unicode sep = ScCompiler::GetNativeSymbol(ocSep).GetChar(0);\n return c != sep;\n}\n\ninline bool IsText( bool& bQuote, sal_Unicode c )\n{\n if (c == '\\'')\n {\n bQuote = !bQuote;\n return true;\n }\n if (bQuote)\n return true;\n\n return IsText(c);\n}\n\n\/**\n * Find first character position that is considered text. A character is\n * considered a text when it's within the ascii range and when it's not a\n * delimiter.\n *\/\nsal_Int32 FindStartPos(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos)\n{\n while (nStartPos <= nEndPos && !IsText(p[nStartPos]))\n ++nStartPos;\n\n return nStartPos;\n}\n\nsal_Int32 FindEndPosA1(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos)\n{\n bool bQuote = false;\n sal_Int32 nNewEnd = nStartPos;\n while (nNewEnd <= nEndPos && IsText(bQuote, p[nNewEnd]))\n ++nNewEnd;\n\n return nNewEnd;\n}\n\nsal_Int32 FindEndPosR1C1(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos)\n{\n sal_Int32 nNewEnd = nStartPos;\n p = &p[nStartPos];\n for (; nNewEnd <= nEndPos; ++p, ++nNewEnd)\n {\n if (*p == '\\'')\n {\n \/\/ Skip until the closing quote.\n for (; nNewEnd <= nEndPos; ++p, ++nNewEnd)\n if (*p == '\\'')\n break;\n if (nNewEnd > nEndPos)\n break;\n }\n else if (*p == '[')\n {\n \/\/ Skip until the closing braket.\n for (; nNewEnd <= nEndPos; ++p, ++nNewEnd)\n if (*p == ']')\n break;\n if (nNewEnd > nEndPos)\n break;\n }\n else if (!IsText(*p))\n break;\n }\n\n return nNewEnd;\n}\n\n\/**\n * Find last character position that is considred text, from the specified\n * start position.\n *\/\nsal_Int32 FindEndPos(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos,\n formula::FormulaGrammar::AddressConvention eConv)\n{\n switch (eConv)\n {\n case formula::FormulaGrammar::CONV_XL_R1C1:\n return FindEndPosR1C1(p, nStartPos, nEndPos);\n case formula::FormulaGrammar::CONV_OOO:\n case formula::FormulaGrammar::CONV_XL_A1:\n default:\n return FindEndPosA1(p, nStartPos, nEndPos);\n }\n}\n\nvoid ExpandToTextA1(const sal_Unicode* p, sal_Int32 nLen, sal_Int32& rStartPos, sal_Int32& rEndPos)\n{\n while (rStartPos > 0 && IsText(p[rStartPos - 1]) )\n --rStartPos;\n if (rEndPos)\n --rEndPos;\n while (rEndPos+1 < nLen && IsText(p[rEndPos + 1]) )\n ++rEndPos;\n}\n\nvoid ExpandToTextR1C1(const sal_Unicode* p, sal_Int32 nLen, sal_Int32& rStartPos, sal_Int32& rEndPos)\n{\n \/\/ move back the start position to the first text character.\n if (rStartPos > 0)\n {\n for (--rStartPos; rStartPos > 0; --rStartPos)\n {\n sal_Unicode c = p[rStartPos];\n if (c == '\\'')\n {\n \/\/ Skip until the opening quote.\n for (--rStartPos; rStartPos > 0; --rStartPos)\n {\n c = p[rStartPos];\n if (c == '\\'')\n break;\n }\n if (rStartPos == 0)\n break;\n }\n else if (c == ']')\n {\n \/\/ Skip until the opening braket.\n for (--rStartPos; rStartPos > 0; --rStartPos)\n {\n c = p[rStartPos];\n if (c == '[')\n break;\n }\n if (rStartPos == 0)\n break;\n }\n else if (!IsText(c))\n {\n ++rStartPos;\n break;\n }\n }\n }\n\n \/\/ move forward the end position to the last text character.\n rEndPos = FindEndPosR1C1(p, rEndPos, nLen-1);\n}\n\nvoid ExpandToText(const sal_Unicode* p, sal_Int32 nLen, sal_Int32& rStartPos, sal_Int32& rEndPos,\n formula::FormulaGrammar::AddressConvention eConv)\n{\n switch (eConv)\n {\n case formula::FormulaGrammar::CONV_XL_R1C1:\n ExpandToTextR1C1(p, nLen, rStartPos, rEndPos);\n break;\n case formula::FormulaGrammar::CONV_OOO:\n case formula::FormulaGrammar::CONV_XL_A1:\n default:\n ExpandToTextA1(p, nLen, rStartPos, rEndPos);\n }\n}\n\n}\n\nScRefFinder::ScRefFinder(\n const OUString& rFormula, const ScAddress& rPos,\n ScDocument* pDoc, formula::FormulaGrammar::AddressConvention eConvP) :\n maFormula(rFormula),\n meConv(eConvP),\n mpDoc(pDoc),\n maPos(rPos),\n mnFound(0),\n mnSelStart(0),\n mnSelEnd(0)\n{\n}\n\nScRefFinder::~ScRefFinder()\n{\n}\n\nstatic sal_uInt16 lcl_NextFlags( sal_uInt16 nOld )\n{\n sal_uInt16 nNew = nOld & 7; \/\/ die drei Abs-Flags\n nNew = ( nNew - 1 ) & 7; \/\/ weiterzaehlen\n\n if (!(nOld & SCA_TAB_3D))\n nNew &= ~SCA_TAB_ABSOLUTE; \/\/ not 3D -> never absolute!\n\n return ( nOld & 0xfff8 ) | nNew;\n}\n\nvoid ScRefFinder::ToggleRel( sal_Int32 nStartPos, sal_Int32 nEndPos )\n{\n sal_Int32 nLen = maFormula.getLength();\n if (nLen <= 0)\n return;\n const sal_Unicode* pSource = maFormula.getStr(); \/\/ for quick access\n\n \/\/ expand selection, and instead of selection start- and end-index\n\n if ( nEndPos < nStartPos )\n ::std::swap(nEndPos, nStartPos);\n\n ExpandToText(pSource, nLen, nStartPos, nEndPos, meConv);\n\n OUString aResult;\n OUString aExpr;\n OUString aSep;\n ScAddress aAddr;\n mnFound = 0;\n\n sal_Int32 nLoopStart = nStartPos;\n while ( nLoopStart <= nEndPos )\n {\n \/\/ Determine the stard and end positions of a text segment. Note that\n \/\/ the end position returned from FindEndPos may be one position after\n \/\/ the last character position in case of the last segment.\n sal_Int32 nEStart = FindStartPos(pSource, nLoopStart, nEndPos);\n sal_Int32 nEEnd = FindEndPos(pSource, nEStart, nEndPos, meConv);\n\n aSep = maFormula.copy(nLoopStart, nEStart-nLoopStart);\n if (nEEnd < maFormula.getLength())\n aExpr = maFormula.copy(nEStart, nEEnd-nEStart);\n else\n aExpr = maFormula.copy(nEStart);\n\n \/\/ Check the validity of the expression, and toggle the relative flag.\n ScAddress::Details aDetails(meConv, maPos.Row(), maPos.Col());\n sal_uInt16 nResult = aAddr.Parse(aExpr, mpDoc, aDetails);\n if ( nResult & SCA_VALID )\n {\n sal_uInt16 nFlags = lcl_NextFlags( nResult );\n aAddr.Format(aExpr, nFlags, mpDoc, aDetails);\n\n sal_Int32 nAbsStart = nStartPos+aResult.getLength()+aSep.getLength();\n\n if (!mnFound) \/\/ first reference ?\n mnSelStart = nAbsStart;\n mnSelEnd = nAbsStart + aExpr.getLength(); \/\/ selection, no indizes\n ++mnFound;\n }\n\n \/\/ assemble\n\n aResult += aSep;\n aResult += aExpr;\n\n nLoopStart = nEEnd;\n }\n\n OUString aTotal = maFormula.copy(0, nStartPos);\n aTotal += aResult;\n if (nEndPos < maFormula.getLength()-1)\n aTotal += maFormula.copy(nEndPos);\n\n maFormula = aTotal;\n}\n\n\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nFix erroneous reference conversion.\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"reffind.hxx\"\n#include \"global.hxx\"\n#include \"compiler.hxx\"\n#include \"document.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nnamespace {\n\n\/\/ Include colon; addresses in range reference are handled individually.\nconst sal_Unicode pDelimiters[] = {\n '=','(',')','+','-','*','\/','^','&',' ','{','}','<','>',':', 0\n};\n\n\/\/ =======================================================================\n\ninline bool IsText( sal_Unicode c )\n{\n bool bFound = ScGlobal::UnicodeStrChr( pDelimiters, c );\n if (bFound)\n \/\/ This is one of delimiters, therefore not text.\n return false;\n\n \/\/ argument separator is configurable.\n const sal_Unicode sep = ScCompiler::GetNativeSymbol(ocSep).GetChar(0);\n return c != sep;\n}\n\ninline bool IsText( bool& bQuote, sal_Unicode c )\n{\n if (c == '\\'')\n {\n bQuote = !bQuote;\n return true;\n }\n if (bQuote)\n return true;\n\n return IsText(c);\n}\n\n\/**\n * Find first character position that is considered text. A character is\n * considered a text when it's within the ascii range and when it's not a\n * delimiter.\n *\/\nsal_Int32 FindStartPos(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos)\n{\n while (nStartPos <= nEndPos && !IsText(p[nStartPos]))\n ++nStartPos;\n\n return nStartPos;\n}\n\nsal_Int32 FindEndPosA1(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos)\n{\n bool bQuote = false;\n sal_Int32 nNewEnd = nStartPos;\n while (nNewEnd <= nEndPos && IsText(bQuote, p[nNewEnd]))\n ++nNewEnd;\n\n return nNewEnd;\n}\n\nsal_Int32 FindEndPosR1C1(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos)\n{\n sal_Int32 nNewEnd = nStartPos;\n p = &p[nStartPos];\n for (; nNewEnd <= nEndPos; ++p, ++nNewEnd)\n {\n if (*p == '\\'')\n {\n \/\/ Skip until the closing quote.\n for (; nNewEnd <= nEndPos; ++p, ++nNewEnd)\n if (*p == '\\'')\n break;\n if (nNewEnd > nEndPos)\n break;\n }\n else if (*p == '[')\n {\n \/\/ Skip until the closing braket.\n for (; nNewEnd <= nEndPos; ++p, ++nNewEnd)\n if (*p == ']')\n break;\n if (nNewEnd > nEndPos)\n break;\n }\n else if (!IsText(*p))\n break;\n }\n\n return nNewEnd;\n}\n\n\/**\n * Find last character position that is considred text, from the specified\n * start position.\n *\/\nsal_Int32 FindEndPos(const sal_Unicode* p, sal_Int32 nStartPos, sal_Int32 nEndPos,\n formula::FormulaGrammar::AddressConvention eConv)\n{\n switch (eConv)\n {\n case formula::FormulaGrammar::CONV_XL_R1C1:\n return FindEndPosR1C1(p, nStartPos, nEndPos);\n case formula::FormulaGrammar::CONV_OOO:\n case formula::FormulaGrammar::CONV_XL_A1:\n default:\n return FindEndPosA1(p, nStartPos, nEndPos);\n }\n}\n\nvoid ExpandToTextA1(const sal_Unicode* p, sal_Int32 nLen, sal_Int32& rStartPos, sal_Int32& rEndPos)\n{\n while (rStartPos > 0 && IsText(p[rStartPos - 1]) )\n --rStartPos;\n if (rEndPos)\n --rEndPos;\n while (rEndPos+1 < nLen && IsText(p[rEndPos + 1]) )\n ++rEndPos;\n}\n\nvoid ExpandToTextR1C1(const sal_Unicode* p, sal_Int32 nLen, sal_Int32& rStartPos, sal_Int32& rEndPos)\n{\n \/\/ move back the start position to the first text character.\n if (rStartPos > 0)\n {\n for (--rStartPos; rStartPos > 0; --rStartPos)\n {\n sal_Unicode c = p[rStartPos];\n if (c == '\\'')\n {\n \/\/ Skip until the opening quote.\n for (--rStartPos; rStartPos > 0; --rStartPos)\n {\n c = p[rStartPos];\n if (c == '\\'')\n break;\n }\n if (rStartPos == 0)\n break;\n }\n else if (c == ']')\n {\n \/\/ Skip until the opening braket.\n for (--rStartPos; rStartPos > 0; --rStartPos)\n {\n c = p[rStartPos];\n if (c == '[')\n break;\n }\n if (rStartPos == 0)\n break;\n }\n else if (!IsText(c))\n {\n ++rStartPos;\n break;\n }\n }\n }\n\n \/\/ move forward the end position to the last text character.\n rEndPos = FindEndPosR1C1(p, rEndPos, nLen-1);\n}\n\nvoid ExpandToText(const sal_Unicode* p, sal_Int32 nLen, sal_Int32& rStartPos, sal_Int32& rEndPos,\n formula::FormulaGrammar::AddressConvention eConv)\n{\n switch (eConv)\n {\n case formula::FormulaGrammar::CONV_XL_R1C1:\n ExpandToTextR1C1(p, nLen, rStartPos, rEndPos);\n break;\n case formula::FormulaGrammar::CONV_OOO:\n case formula::FormulaGrammar::CONV_XL_A1:\n default:\n ExpandToTextA1(p, nLen, rStartPos, rEndPos);\n }\n}\n\n}\n\nScRefFinder::ScRefFinder(\n const OUString& rFormula, const ScAddress& rPos,\n ScDocument* pDoc, formula::FormulaGrammar::AddressConvention eConvP) :\n maFormula(rFormula),\n meConv(eConvP),\n mpDoc(pDoc),\n maPos(rPos),\n mnFound(0),\n mnSelStart(0),\n mnSelEnd(0)\n{\n}\n\nScRefFinder::~ScRefFinder()\n{\n}\n\nstatic sal_uInt16 lcl_NextFlags( sal_uInt16 nOld )\n{\n sal_uInt16 nNew = nOld & 7; \/\/ die drei Abs-Flags\n nNew = ( nNew - 1 ) & 7; \/\/ weiterzaehlen\n\n if (!(nOld & SCA_TAB_3D))\n nNew &= ~SCA_TAB_ABSOLUTE; \/\/ not 3D -> never absolute!\n\n return ( nOld & 0xfff8 ) | nNew;\n}\n\nvoid ScRefFinder::ToggleRel( sal_Int32 nStartPos, sal_Int32 nEndPos )\n{\n sal_Int32 nLen = maFormula.getLength();\n if (nLen <= 0)\n return;\n const sal_Unicode* pSource = maFormula.getStr(); \/\/ for quick access\n\n \/\/ expand selection, and instead of selection start- and end-index\n\n if ( nEndPos < nStartPos )\n ::std::swap(nEndPos, nStartPos);\n\n ExpandToText(pSource, nLen, nStartPos, nEndPos, meConv);\n\n OUString aResult;\n OUString aExpr;\n OUString aSep;\n ScAddress aAddr;\n mnFound = 0;\n\n sal_Int32 nLoopStart = nStartPos;\n while ( nLoopStart <= nEndPos )\n {\n \/\/ Determine the stard and end positions of a text segment. Note that\n \/\/ the end position returned from FindEndPos may be one position after\n \/\/ the last character position in case of the last segment.\n sal_Int32 nEStart = FindStartPos(pSource, nLoopStart, nEndPos);\n sal_Int32 nEEnd = FindEndPos(pSource, nEStart, nEndPos, meConv);\n\n aSep = maFormula.copy(nLoopStart, nEStart-nLoopStart);\n if (nEEnd < maFormula.getLength())\n aExpr = maFormula.copy(nEStart, nEEnd-nEStart);\n else\n aExpr = maFormula.copy(nEStart);\n\n \/\/ Check the validity of the expression, and toggle the relative flag.\n ScAddress::Details aDetails(meConv, maPos.Row(), maPos.Col());\n sal_uInt16 nResult = aAddr.Parse(aExpr, mpDoc, aDetails);\n if ( nResult & SCA_VALID )\n {\n sal_uInt16 nFlags = lcl_NextFlags( nResult );\n aAddr.Format(aExpr, nFlags, mpDoc, aDetails);\n\n sal_Int32 nAbsStart = nStartPos+aResult.getLength()+aSep.getLength();\n\n if (!mnFound) \/\/ first reference ?\n mnSelStart = nAbsStart;\n mnSelEnd = nAbsStart + aExpr.getLength(); \/\/ selection, no indizes\n ++mnFound;\n }\n\n \/\/ assemble\n\n aResult += aSep;\n aResult += aExpr;\n\n nLoopStart = nEEnd;\n }\n\n OUString aTotal = maFormula.copy(0, nStartPos);\n aTotal += aResult;\n if (nEndPos < maFormula.getLength()-1)\n aTotal += maFormula.copy(nEndPos+1);\n\n maFormula = aTotal;\n}\n\n\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \"Energia.h\"\n\n#include \"Ethernet.h\"\n#include \"EthernetClient.h\"\n#include \"EthernetServer.h\"\n\n#include \"driverlib\/interrupt.h\"\n\n\/* directives for disabling and enabling interrupts *\/\n#define INT_PROTECT_INIT(x) int x = 0\n#define INT_PROTECT(x) x=IntMasterDisable()\n#define INT_UNPROTECT(x) do{if(!x)IntMasterEnable();}while(0)\n\n\/* SYNC_FETCH_AND_NULL: atomic{ tmp=*x; *x=NULL; return tmp; } *\/\n#define SYNC_FETCH_AND_NULL(x) (__sync_fetch_and_and(x, NULL))\n\nEthernetClient::EthernetClient() {\n\t_connected = false;\n\tcs = &client_state;\n\tcs->mode = true;\n\tcs->cpcb = NULL;\n\tcs->p = NULL;\n}\n\nEthernetClient::EthernetClient(struct client *c) {\n\tif (c == NULL) {\n\t\t_connected = false;\n\t\tcs = &client_state;\n\t\tcs->cpcb = NULL;\n\t\tcs->p = NULL;\n\t\treturn;\n\t}\n\t_connected = true;\n\tcs = c;\n\tcs->mode = false;\n}\n\nerr_t EthernetClient::do_poll(void *arg, struct tcp_pcb *cpcb) {\n\tEthernetClient *client = static_cast(arg);\n\n\tif (client->_connected) {\n\t\tif (cpcb->keep_cnt_sent++ > 4) {\n\t\t\tcpcb->keep_cnt_sent = 0;\n\t\t\t\/* Stop polling *\/\n\t\t\ttcp_poll(cpcb, NULL, 0);\n\t\t\ttcp_abort(cpcb);\n\t\t\tif (client->cs->cpcb == cpcb) \/* cs may be already re-used by another connection *\/\n\t\t\t{\n\t\t\t\tclient->cs->port = 0;\n\t\t\t\tclient->cs->cpcb = 0;\n\t\t\t}\n\t\t\treturn ERR_ABRT; \/* calling tcp_abort() must return ERR_ABRT *\/\n\t\t}\n\t\t\/* Send tcp keep alive probe *\/\n\t\ttcp_keepalive(cpcb);\n\t\treturn ERR_OK;\n\t}\n\n\t\/* We only end up here if the connection failed to close\n\t * in an earlier call to tcp_close *\/\n\terr_t err = tcp_close(cpcb);\n\n\tif (err != ERR_OK) {\n\t\t\/* error closing, try again later in poll (every 2 sec) *\/\n\t\ttcp_poll(cpcb, do_poll, 4);\n\t}\n\n\tif (client->cs->cpcb == cpcb) \/* cs may be already re-used by another connection *\/\n\t{\n\t\tclient->cs->cpcb = 0;\n\t\tclient->cs->port = 0;\n\t}\n\n\treturn err;\n}\n\nvoid EthernetClient::do_err(void * arg, err_t err) {\n\tEthernetClient *client = static_cast(arg);\n\n\tif (client->_connected) {\n\t\tclient->_connected = false;\n\t\treturn;\n\t}\n\n\t\/*\n\t * Set connected to true to finish connecting.\n\t * ::connect wil take care of figuring out if we are truly connected\n\t * by looking at the socket state\n\t *\/\n\tclient->_connected = true;\n}\n\nerr_t EthernetClient::do_connected(void * arg, struct tcp_pcb * tpcb,\n\t\terr_t err) {\n\tEthernetClient *client = static_cast(arg);\n\n\tclient->_connected = true;\n\n\treturn err;\n}\n\nerr_t EthernetClient::do_recv(void *arg, struct tcp_pcb *cpcb, struct pbuf *p,\n\t\terr_t err) {\n\t\/*\n\t * Get the client object from the argument\n\t * to get access to variables and functions\n\t *\/\n\tEthernetClient *client = static_cast(arg);\n\n\t\/* p==0 for end-of-connection (TCP_FIN packet) *\/\n\tif (p == 0) {\n\t\tclient->_connected = false;\n\t\treturn ERR_OK;\n\t}\n\n\tif (client->cs->p != 0)\n\t\tpbuf_cat((pbuf*)client->cs->p, p);\n\telse\n\t\tclient->cs->p = p;\n\n\treturn ERR_OK;\n}\n\nvoid EthernetClient::do_dns(const char *name, struct ip_addr *ipaddr,\n\t\tvoid *arg) {\n\tip_addr_t *result = (ip_addr_t *) arg;\n\n\t\/* BEWARE: lwip stack has been modified to set ipaddr\n\t * to IPADDR_NONE if the lookup failed *\/\n\tresult->addr = ipaddr->addr;\n}\n\nint EthernetClient::connect(const char* host, uint16_t port) {\n\tip_addr_t ip;\n\tip.addr = 0;\n\n\tdns_gethostbyname(host, &ip, do_dns, &ip);\n\n\twhile (!ip.addr) {\n\t\tdelay(10);\n\t}\n\n\tif (ip.addr == IPADDR_NONE)\n\t\treturn false;\n\n\treturn (connect(IPAddress(ip.addr), port));\n}\n\nint EthernetClient::connect(IPAddress ip, uint16_t port) {\n\tip_addr_t dest;\n\tdest.addr = ip;\n\n\tcs->cpcb = tcp_new();\n\tcs->read = 0;\n\tcs->p = NULL;\n\n\tif (cs->cpcb == NULL) {\n\t\treturn false;\n\t}\n\n\ttcp_arg((tcp_pcb*)cs->cpcb, this);\n\ttcp_recv((tcp_pcb*)cs->cpcb, do_recv);\n\ttcp_err((tcp_pcb*)cs->cpcb, do_err);\n\n\tuint8_t val = tcp_connect((tcp_pcb *)cs->cpcb, &dest, port, do_connected);\n\n\tif (val != ERR_OK) {\n\t\treturn false;\n\t}\n\n\t\/* Wait for the connection.\n\t * Abort if the connection does not succeed within 10 sec *\/\n\tunsigned long then = millis();\n\n\twhile (!_connected) {\n\t\tunsigned long now = millis();\n\t\tdelay(10);\n\t\tif (now - then > CONNECTION_TIMEOUT) {\n\t\t\ttcp_close((tcp_pcb*)cs->cpcb);\n\t\t\tcs->cpcb = NULL;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (cs->cpcb->state != ESTABLISHED) {\n\t\t_connected = false;\n\t}\n\n\t\/* Poll to determine if the peer is still alive *\/\n\ttcp_poll((tcp_pcb*)cs->cpcb, do_poll, 10);\n\treturn _connected;\n}\n\nsize_t EthernetClient::write(uint8_t b) {\n\treturn write(&b, 1);\n}\n\nsize_t EthernetClient::write(const uint8_t *buf, size_t size) {\n\tuint32_t i = 0, inc = 0;\n\tboolean stuffed_buffer = false;\n\n\tstruct tcp_pcb * cpcb = (tcp_pcb*)cs->cpcb; \/* cs->cpcb may change to NULL during interrupt servicing *\/\n\n\tif (!cpcb)\n\t\treturn 0;\n\n\t\/\/ Attempt to write in 1024-byte increments.\n\twhile (i < size) {\n\t\tinc = (size - i) < 1024 ? size - i : 1024;\n\t\terr_t err = tcp_write(cpcb, buf + i, inc, TCP_WRITE_FLAG_COPY);\n\t\tif (err != ERR_MEM) {\n\t\t\t\/\/ Keep enqueueing the lwIP buffer until it's full...\n\t\t\ti += inc;\n\t\t\tstuffed_buffer = false;\n\t\t} else {\n\t\t\tif (!stuffed_buffer) {\n\t\t\t\t\/\/ Buffer full; force output\n\t\t\t\tif (cs->mode)\n\t\t\t\t\ttcp_output(cpcb);\n\t\t\t\tstuffed_buffer = true;\n\t\t\t} else {\n\t\t\t\tdelay(1); \/\/ else wait a little bit for lwIP to flush its buffers\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ flush any remaining queue contents\n\tif (!stuffed_buffer) {\n\t\tif (cs->mode)\n\t\t\ttcp_output(cpcb);\n\t}\n\n\treturn size;\n}\n\nint EthernetClient::available() {\n\tstruct pbuf * p = (pbuf*)cs->p; \/* cs->p may change to NULL during interrupt servicing *\/\n\tif (!p)\n\t\treturn 0;\n\treturn p->tot_len - cs->read;\n}\n\nint EthernetClient::port() {\n\treturn cs->port;\n}\n\nint EthernetClient::readLocked() {\n\tINT_PROTECT_INIT(oldLevel);\n\n\t\/* protect the code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\n\tif (!available()) {\n\t\tINT_UNPROTECT(oldLevel);\n\t\treturn -1;\n\t}\n\n\tif (!cs->cpcb) {\n\t\tINT_UNPROTECT(oldLevel);\n\t\treturn -1;\n\t}\n\n\tuint8_t *buf = (uint8_t *) cs->p->payload;\n\tuint8_t b = buf[cs->read];\n\tcs->read++;\n\n\ttcp_recved((tcp_pcb*)cs->cpcb, cs->read);\n\n\tif ((cs->read == cs->p->len) && cs->p->next) {\n\t\tcs->read = 0;\n\t\tstruct pbuf * q = (pbuf*)cs->p;\n\t\tcs->p = cs->p->next;\n\t\t\/* Increase ref count on p->next\n\t\t * 1->3->1->etc *\/\n\t\tpbuf_ref((pbuf*)cs->p);\n\t\t\/* Free p which decreases ref count of the chain\n\t\t * and frees up to p->next in this case\n\t\t * ...->1->1->etc *\/\n\t\tpbuf_free(q);\n\t} else if (cs->read == cs->p->len) {\n\t\tcs->read = 0;\n\t\tpbuf_free((pbuf*)cs->p);\n\t\tcs->p = NULL;\n\t}\n\n\tINT_UNPROTECT(oldLevel);\n\n\treturn b;\n}\n\nint EthernetClient::read() {\n\treturn readLocked();\n}\n\nint EthernetClient::read(uint8_t *buf, size_t size) {\n\tuint16_t i;\n\tint b;\n\n\tif (available() <= 0)\n\t\treturn -1;\n\n\t\/* TODO: Replace lazy method with optimized on *\/\n\tfor (i = 0; i < size; i++) {\n\t\tb = read();\n\t\tif (b == -1)\n\t\t\tbreak;\n\t\tbuf[i] = b;\n\t}\n\n\treturn i;\n}\n\nint EthernetClient::peek() {\n\tINT_PROTECT_INIT(oldLevel);\n\tuint8_t b;\n\n\t\/* protect code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\n\tif (!available()) {\n\t\tINT_UNPROTECT(oldLevel);\n\t\treturn -1;\n\t}\n\n\tuint8_t *buf = (uint8_t *) cs->p->payload;\n\tb = buf[cs->read];\n\n\tINT_UNPROTECT(oldLevel);\n\n\treturn b;\n}\n\nvoid EthernetClient::flush() {\n\tINT_PROTECT_INIT(oldLevel);\n\t\/* protect code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\tif (available()) {\n\t\tcs->read = cs->p->tot_len;\n\t\ttcp_recved((tcp_pcb*)cs->cpcb, 0);\n\t}\n\tINT_UNPROTECT(oldLevel);\n}\n\nvoid EthernetClient::stop() {\n\t\/* Stop frees any resources including any unread buffers *\/\n\terr_t err;\n\n\tINT_PROTECT_INIT(oldLevel);\n\n\t\/* protect the code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\n\tstruct tcp_pcb * cpcb_copy = (tcp_pcb *) SYNC_FETCH_AND_NULL(&cs->cpcb);\n\tstruct pbuf * p_copy = (pbuf *) SYNC_FETCH_AND_NULL(&cs->p);\n\t_connected = false;\n\tcs->port = 0;\n\n\tif (cpcb_copy) {\n\t\ttcp_err(cpcb_copy, NULL);\n\n\t\tif (p_copy) {\n\t\t\ttcp_recved(cpcb_copy, p_copy->tot_len);\n\t\t\tpbuf_free(p_copy);\n\t\t}\n\n\t\terr = tcp_close(cpcb_copy);\n\n\t\tif (err != ERR_OK) {\n\t\t\t\/* Error closing, try again later in poll (every 2 sec) *\/\n\t\t\ttcp_poll(cpcb_copy, do_poll, 4);\n\t\t}\n\t}\n\n\tINT_UNPROTECT(oldLevel);\n}\n\nuint8_t EthernetClient::connected() {\n\t\/* TODO: test the local client mode and _connected flag *\/\n\treturn (available() || (status() == ESTABLISHED) || _connected);\n}\n\nuint8_t EthernetClient::status() {\n\tstruct tcp_pcb * cpcb = (tcp_pcb*)cs->cpcb;\n\tif (cpcb == NULL)\n\t\treturn CLOSED;\n\treturn cpcb->state;\n}\n\nEthernetClient::operator bool() {\n\treturn (status() == ESTABLISHED);\n}\nFix read() issue when other end closes the connection#include \"Energia.h\"\n\n#include \"Ethernet.h\"\n#include \"EthernetClient.h\"\n#include \"EthernetServer.h\"\n\n#include \"driverlib\/interrupt.h\"\n\n\/* directives for disabling and enabling interrupts *\/\n#define INT_PROTECT_INIT(x) int x = 0\n#define INT_PROTECT(x) x=IntMasterDisable()\n#define INT_UNPROTECT(x) do{if(!x)IntMasterEnable();}while(0)\n\n\/* SYNC_FETCH_AND_NULL: atomic{ tmp=*x; *x=NULL; return tmp; } *\/\n#define SYNC_FETCH_AND_NULL(x) (__sync_fetch_and_and(x, NULL))\n\nEthernetClient::EthernetClient() {\n\t_connected = false;\n\tcs = &client_state;\n\tcs->mode = true;\n\tcs->cpcb = NULL;\n\tcs->p = NULL;\n}\n\nEthernetClient::EthernetClient(struct client *c) {\n\tif (c == NULL) {\n\t\t_connected = false;\n\t\tcs = &client_state;\n\t\tcs->cpcb = NULL;\n\t\tcs->p = NULL;\n\t\treturn;\n\t}\n\t_connected = true;\n\tcs = c;\n\tcs->mode = false;\n}\n\nerr_t EthernetClient::do_poll(void *arg, struct tcp_pcb *cpcb) {\n\tEthernetClient *client = static_cast(arg);\n\n\tif (client->_connected) {\n\t\tif (cpcb->keep_cnt_sent++ > 4) {\n\t\t\tcpcb->keep_cnt_sent = 0;\n\t\t\t\/* Stop polling *\/\n\t\t\ttcp_poll(cpcb, NULL, 0);\n\t\t\ttcp_abort(cpcb);\n\t\t\tif (client->cs->cpcb == cpcb) \/* cs may be already re-used by another connection *\/\n\t\t\t{\n\t\t\t\tclient->cs->port = 0;\n\t\t\t\tclient->cs->cpcb = 0;\n\t\t\t}\n\t\t\treturn ERR_ABRT; \/* calling tcp_abort() must return ERR_ABRT *\/\n\t\t}\n\t\t\/* Send tcp keep alive probe *\/\n\t\ttcp_keepalive(cpcb);\n\t\treturn ERR_OK;\n\t}\n\n\t\/* We only end up here if the connection failed to close\n\t * in an earlier call to tcp_close *\/\n\terr_t err = tcp_close(cpcb);\n\n\tif (err != ERR_OK) {\n\t\t\/* error closing, try again later in poll (every 2 sec) *\/\n\t\ttcp_poll(cpcb, do_poll, 4);\n\t}\n\n\tif (client->cs->cpcb == cpcb) \/* cs may be already re-used by another connection *\/\n\t{\n\t\tclient->cs->cpcb = 0;\n\t\tclient->cs->port = 0;\n\t}\n\n\treturn err;\n}\n\nvoid EthernetClient::do_err(void * arg, err_t err) {\n\tEthernetClient *client = static_cast(arg);\n\n\tif (client->_connected) {\n\t\tclient->_connected = false;\n\t\treturn;\n\t}\n\n\t\/*\n\t * Set connected to true to finish connecting.\n\t * ::connect wil take care of figuring out if we are truly connected\n\t * by looking at the socket state\n\t *\/\n\tclient->_connected = true;\n}\n\nerr_t EthernetClient::do_connected(void * arg, struct tcp_pcb * tpcb,\n\t\terr_t err) {\n\tEthernetClient *client = static_cast(arg);\n\n\tclient->_connected = true;\n\n\treturn err;\n}\n\nerr_t EthernetClient::do_recv(void *arg, struct tcp_pcb *cpcb, struct pbuf *p,\n\t\terr_t err) {\n\t\/*\n\t * Get the client object from the argument\n\t * to get access to variables and functions\n\t *\/\n\tEthernetClient *client = static_cast(arg);\n\n\t\/* p==0 for end-of-connection (TCP_FIN packet) *\/\n\tif (p == 0) {\n\t\tclient->_connected = false;\n\t\treturn ERR_OK;\n\t}\n\n\tif (client->cs->p != 0)\n\t\tpbuf_cat((pbuf*)client->cs->p, p);\n\telse\n\t\tclient->cs->p = p;\n\n\treturn ERR_OK;\n}\n\nvoid EthernetClient::do_dns(const char *name, struct ip_addr *ipaddr,\n\t\tvoid *arg) {\n\tip_addr_t *result = (ip_addr_t *) arg;\n\n\t\/* BEWARE: lwip stack has been modified to set ipaddr\n\t * to IPADDR_NONE if the lookup failed *\/\n\tresult->addr = ipaddr->addr;\n}\n\nint EthernetClient::connect(const char* host, uint16_t port) {\n\tip_addr_t ip;\n\tip.addr = 0;\n\n\tdns_gethostbyname(host, &ip, do_dns, &ip);\n\n\twhile (!ip.addr) {\n\t\tdelay(10);\n\t}\n\n\tif (ip.addr == IPADDR_NONE)\n\t\treturn false;\n\n\treturn (connect(IPAddress(ip.addr), port));\n}\n\nint EthernetClient::connect(IPAddress ip, uint16_t port) {\n\tip_addr_t dest;\n\tdest.addr = ip;\n\n\tcs->cpcb = tcp_new();\n\tcs->read = 0;\n\tcs->p = NULL;\n\n\tif (cs->cpcb == NULL) {\n\t\treturn false;\n\t}\n\n\ttcp_arg((tcp_pcb*)cs->cpcb, this);\n\ttcp_recv((tcp_pcb*)cs->cpcb, do_recv);\n\ttcp_err((tcp_pcb*)cs->cpcb, do_err);\n\n\tuint8_t val = tcp_connect((tcp_pcb *)cs->cpcb, &dest, port, do_connected);\n\n\tif (val != ERR_OK) {\n\t\treturn false;\n\t}\n\n\t\/* Wait for the connection.\n\t * Abort if the connection does not succeed within 10 sec *\/\n\tunsigned long then = millis();\n\n\twhile (!_connected) {\n\t\tunsigned long now = millis();\n\t\tdelay(10);\n\t\tif (now - then > CONNECTION_TIMEOUT) {\n\t\t\ttcp_close((tcp_pcb*)cs->cpcb);\n\t\t\tcs->cpcb = NULL;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (cs->cpcb->state != ESTABLISHED) {\n\t\t_connected = false;\n\t}\n\n\t\/* Poll to determine if the peer is still alive *\/\n\ttcp_poll((tcp_pcb*)cs->cpcb, do_poll, 10);\n\treturn _connected;\n}\n\nsize_t EthernetClient::write(uint8_t b) {\n\treturn write(&b, 1);\n}\n\nsize_t EthernetClient::write(const uint8_t *buf, size_t size) {\n\tuint32_t i = 0, inc = 0;\n\tboolean stuffed_buffer = false;\n\n\tstruct tcp_pcb * cpcb = (tcp_pcb*)cs->cpcb; \/* cs->cpcb may change to NULL during interrupt servicing *\/\n\n\tif (!cpcb)\n\t\treturn 0;\n\n\t\/\/ Attempt to write in 1024-byte increments.\n\twhile (i < size) {\n\t\tinc = (size - i) < 1024 ? size - i : 1024;\n\t\terr_t err = tcp_write(cpcb, buf + i, inc, TCP_WRITE_FLAG_COPY);\n\t\tif (err != ERR_MEM) {\n\t\t\t\/\/ Keep enqueueing the lwIP buffer until it's full...\n\t\t\ti += inc;\n\t\t\tstuffed_buffer = false;\n\t\t} else {\n\t\t\tif (!stuffed_buffer) {\n\t\t\t\t\/\/ Buffer full; force output\n\t\t\t\tif (cs->mode)\n\t\t\t\t\ttcp_output(cpcb);\n\t\t\t\tstuffed_buffer = true;\n\t\t\t} else {\n\t\t\t\tdelay(1); \/\/ else wait a little bit for lwIP to flush its buffers\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ flush any remaining queue contents\n\tif (!stuffed_buffer) {\n\t\tif (cs->mode)\n\t\t\ttcp_output(cpcb);\n\t}\n\n\treturn size;\n}\n\nint EthernetClient::available() {\n\tstruct pbuf * p = (pbuf*)cs->p; \/* cs->p may change to NULL during interrupt servicing *\/\n\tif (!p)\n\t\treturn 0;\n\treturn p->tot_len - cs->read;\n}\n\nint EthernetClient::port() {\n\treturn cs->port;\n}\n\nint EthernetClient::readLocked() {\n\tINT_PROTECT_INIT(oldLevel);\n\n\t\/* protect the code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\n\tif (!available()) {\n\t\tINT_UNPROTECT(oldLevel);\n\t\treturn -1;\n\t}\n\n\tuint8_t *buf = (uint8_t *) cs->p->payload;\n\tuint8_t b = buf[cs->read];\n\tcs->read++;\n\n\t\/* Indicate data was received only if still connected *\/\n\tif (cs->cpcb) {\n\t\ttcp_recved((tcp_pcb*)cs->cpcb, cs->read);\n\t}\n\n\t\/* Read any data still in the buffer regardless of connection state *\/\n\tif ((cs->read == cs->p->len) && cs->p->next) {\n\t\tcs->read = 0;\n\t\tstruct pbuf * q = (pbuf*)cs->p;\n\t\tcs->p = cs->p->next;\n\t\t\/* Increase ref count on p->next\n\t\t * 1->3->1->etc *\/\n\t\tpbuf_ref((pbuf*)cs->p);\n\t\t\/* Free p which decreases ref count of the chain\n\t\t * and frees up to p->next in this case\n\t\t * ...->1->1->etc *\/\n\t\tpbuf_free(q);\n\t} else if (cs->read == cs->p->len) {\n\t\tcs->read = 0;\n\t\tpbuf_free((pbuf*)cs->p);\n\t\tcs->p = NULL;\n\t}\n\n\tINT_UNPROTECT(oldLevel);\n\n\treturn b;\n}\n\nint EthernetClient::read() {\n\treturn readLocked();\n}\n\nint EthernetClient::read(uint8_t *buf, size_t size) {\n\tuint16_t i;\n\tint b;\n\n\tif (available() <= 0)\n\t\treturn -1;\n\n\t\/* TODO: Replace lazy method with optimized on *\/\n\tfor (i = 0; i < size; i++) {\n\t\tb = read();\n\t\tif (b == -1)\n\t\t\tbreak;\n\t\tbuf[i] = b;\n\t}\n\n\treturn i;\n}\n\nint EthernetClient::peek() {\n\tINT_PROTECT_INIT(oldLevel);\n\tuint8_t b;\n\n\t\/* protect code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\n\tif (!available()) {\n\t\tINT_UNPROTECT(oldLevel);\n\t\treturn -1;\n\t}\n\n\tuint8_t *buf = (uint8_t *) cs->p->payload;\n\tb = buf[cs->read];\n\n\tINT_UNPROTECT(oldLevel);\n\n\treturn b;\n}\n\nvoid EthernetClient::flush() {\n\tINT_PROTECT_INIT(oldLevel);\n\t\/* protect code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\tif (available()) {\n\t\tcs->read = cs->p->tot_len;\n\t\ttcp_recved((tcp_pcb*)cs->cpcb, 0);\n\t}\n\tINT_UNPROTECT(oldLevel);\n}\n\nvoid EthernetClient::stop() {\n\t\/* Stop frees any resources including any unread buffers *\/\n\terr_t err;\n\n\tINT_PROTECT_INIT(oldLevel);\n\n\t\/* protect the code from preemption of the ethernet interrupt servicing *\/\n\tINT_PROTECT(oldLevel);\n\n\tstruct tcp_pcb * cpcb_copy = (tcp_pcb *) SYNC_FETCH_AND_NULL(&cs->cpcb);\n\tstruct pbuf * p_copy = (pbuf *) SYNC_FETCH_AND_NULL(&cs->p);\n\t_connected = false;\n\tcs->port = 0;\n\n\tif (cpcb_copy) {\n\t\ttcp_err(cpcb_copy, NULL);\n\n\t\tif (p_copy) {\n\t\t\ttcp_recved(cpcb_copy, p_copy->tot_len);\n\t\t\tpbuf_free(p_copy);\n\t\t}\n\n\t\terr = tcp_close(cpcb_copy);\n\n\t\tif (err != ERR_OK) {\n\t\t\t\/* Error closing, try again later in poll (every 2 sec) *\/\n\t\t\ttcp_poll(cpcb_copy, do_poll, 4);\n\t\t}\n\t}\n\n\tINT_UNPROTECT(oldLevel);\n}\n\nuint8_t EthernetClient::connected() {\n\t\/* TODO: test the local client mode and _connected flag *\/\n\treturn (available() || (status() == ESTABLISHED) || _connected);\n}\n\nuint8_t EthernetClient::status() {\n\tstruct tcp_pcb * cpcb = (tcp_pcb*)cs->cpcb;\n\tif (cpcb == NULL)\n\t\treturn CLOSED;\n\treturn cpcb->state;\n}\n\nEthernetClient::operator bool() {\n\treturn (status() == ESTABLISHED);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtCore module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"mock_cntdb.h\"\n\nCContactDatabase* CContactDatabase::OpenL()\n{\n return new CContactDatabase;\n}\n\nCContactDatabase* CContactDatabase::CreateL()\n{\n return new CContactDatabase;\n}\n\nvoid CContactDatabase::AddObserverL(MContactDbObserver& aObserver)\n{\n iObserver = &aObserver;\n}\n\nvoid CContactDatabase::sendEventsL()\n{\n if (!iObserver)\n User::Leave(KErrBadHandle);\n TContactDbObserverEvent event;\n event.iType = EContactDbObserverEventContactAdded;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventOwnCardDeleted;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventContactDeleted;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventContactChanged;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventGroupAdded;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventGroupDeleted;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventGroupChanged;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventOwnCardChanged;\n iObserver->HandleDatabaseEventL(event);\n}\n\nCContactChangeNotifier::CContactChangeNotifier(CContactDatabase& aDbase, MContactDbObserver* aObserver)\n{\n iDbase = &aDbase;\n iDbase->AddObserverL(*aObserver);\n}\n\nCContactChangeNotifier* CContactChangeNotifier::NewL(CContactDatabase& aDatabase, MContactDbObserver *aObserver)\n{\n return new CContactChangeNotifier(aDatabase, aObserver);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFix build break in unit test\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtCore module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"mock_cntdb.h\"\n\n#include \n\nCContactDatabase* CContactDatabase::OpenL()\n{\n return new CContactDatabase;\n}\n\nCContactDatabase* CContactDatabase::CreateL()\n{\n return new CContactDatabase;\n}\n\nvoid CContactDatabase::AddObserverL(MContactDbObserver& aObserver)\n{\n iObserver = &aObserver;\n}\n\nvoid CContactDatabase::sendEventsL()\n{\n if (!iObserver)\n User::Leave(KErrBadHandle);\n TContactDbObserverEvent event;\n event.iType = EContactDbObserverEventContactAdded;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventOwnCardDeleted;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventContactDeleted;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventContactChanged;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventGroupAdded;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventGroupDeleted;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventGroupChanged;\n iObserver->HandleDatabaseEventL(event);\n event.iType = EContactDbObserverEventOwnCardChanged;\n iObserver->HandleDatabaseEventL(event);\n}\n\nCContactChangeNotifier::CContactChangeNotifier(CContactDatabase& aDbase, MContactDbObserver* aObserver)\n{\n iDbase = &aDbase;\n iDbase->AddObserverL(*aObserver);\n}\n\nCContactChangeNotifier* CContactChangeNotifier::NewL(CContactDatabase& aDatabase, MContactDbObserver *aObserver)\n{\n return new CContactChangeNotifier(aDatabase, aObserver);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace sensor_msgs;\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\nusing namespace pcl::registration;\nPointCloud::Ptr src, tgt;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nestimateKeypoints (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n PointCloud &keypoints_src,\n PointCloud &keypoints_tgt)\n{\n PointCloud keypoints_src_idx, keypoints_tgt_idx;\n \/\/ Get an uniform grid of keypoints\n UniformSampling uniform;\n uniform.setRadiusSearch (1); \/\/ 1m\n\n uniform.setInputCloud (src);\n uniform.compute (keypoints_src_idx);\n copyPointCloud (*src, keypoints_src_idx.points, keypoints_src);\n\n uniform.setInputCloud (tgt);\n uniform.compute (keypoints_tgt_idx);\n copyPointCloud (*tgt, keypoints_tgt_idx.points, keypoints_tgt);\n\n \/\/ For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:\n \/\/ pcd_viewer source_pcd keypoints_src.pcd -ps 1 -ps 10\n savePCDFileBinary (\"keypoints_src.pcd\", keypoints_src);\n savePCDFileBinary (\"keypoints_tgt.pcd\", keypoints_tgt);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nestimateNormals (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n PointCloud &normals_src,\n PointCloud &normals_tgt)\n{\n NormalEstimation normal_est;\n normal_est.setInputCloud (src);\n normal_est.setRadiusSearch (0.5); \/\/ 50cm\n normal_est.compute (normals_src);\n\n normal_est.setInputCloud (tgt);\n normal_est.compute (normals_tgt);\n\n \/\/ For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:\n \/\/ pcd_viewer normals_src.pcd \n PointCloud s, t;\n copyPointCloud (*src, s);\n copyPointCloud (normals_src, s);\n copyPointCloud (*tgt, t);\n copyPointCloud (normals_tgt, t);\n savePCDFileBinary (\"normals_src.pcd\", s);\n savePCDFileBinary (\"normals_tgt.pcd\", t);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nestimateFPFH (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n const PointCloud::Ptr &normals_src,\n const PointCloud::Ptr &normals_tgt,\n const PointCloud::Ptr &keypoints_src,\n const PointCloud::Ptr &keypoints_tgt,\n PointCloud &fpfhs_src,\n PointCloud &fpfhs_tgt)\n{\n FPFHEstimation fpfh_est;\n fpfh_est.setInputCloud (keypoints_src);\n fpfh_est.setInputNormals (normals_src);\n fpfh_est.setRadiusSearch (1); \/\/ 1m\n fpfh_est.setSearchSurface (src);\n fpfh_est.compute (fpfhs_src);\n\n fpfh_est.setInputCloud (keypoints_tgt);\n fpfh_est.setInputNormals (normals_tgt);\n fpfh_est.setSearchSurface (tgt);\n fpfh_est.compute (fpfhs_tgt);\n\n \/\/ For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:\n \/\/ pcd_viewer fpfhs_src.pcd \n PointCloud2 s, t, out;\n toROSMsg (*src, s); toROSMsg (fpfhs_src, t); concatenateFields (s, t, out);\n savePCDFile (\"fpfhs_src.pcd\", out);\n toROSMsg (*tgt, s); toROSMsg (fpfhs_tgt, t); concatenateFields (s, t, out);\n savePCDFile (\"fpfhs_tgt.pcd\", out);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nfindCorrespondences (const PointCloud::Ptr &fpfhs_src,\n const PointCloud::Ptr &fpfhs_tgt,\n Correspondences &all_correspondences)\n{\n CorrespondenceEstimation est;\n est.setInputCloud (fpfhs_src);\n est.setInputTarget (fpfhs_tgt);\n est.determineReciprocalCorrespondences (all_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nrejectBadCorrespondences (const CorrespondencesPtr &all_correspondences,\n const PointCloud::Ptr &keypoints_src,\n const PointCloud::Ptr &keypoints_tgt,\n Correspondences &remaining_correspondences)\n{\n CorrespondenceRejectorDistance rej;\n rej.setInputCloud (keypoints_src);\n rej.setInputTarget (keypoints_tgt);\n rej.setMaximumDistance (1); \/\/ 1m\n rej.setInputCorrespondences (all_correspondences);\n rej.getCorrespondences (remaining_correspondences);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\ncomputeTransformation (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n Eigen::Matrix4f &transform)\n{\n \/\/ Get an uniform grid of keypoints\n PointCloud::Ptr keypoints_src (new PointCloud), \n keypoints_tgt (new PointCloud);\n\n estimateKeypoints (src, tgt, *keypoints_src, *keypoints_tgt);\n print_info (\"Found %zu and %zu keypoints for the source and target datasets.\\n\", keypoints_src->points.size (), keypoints_tgt->points.size ());\n\n \/\/ Compute normals for all points keypoint\n PointCloud::Ptr normals_src (new PointCloud), \n normals_tgt (new PointCloud);\n estimateNormals (src, tgt, *normals_src, *normals_tgt);\n print_info (\"Estimated %zu and %zu normals for the source and target datasets.\\n\", normals_src->points.size (), normals_tgt->points.size ());\n\n \/\/ Compute FPFH features at each keypoint\n PointCloud::Ptr fpfhs_src (new PointCloud), \n fpfhs_tgt (new PointCloud);\n estimateFPFH (src, tgt, normals_src, normals_tgt, keypoints_src, keypoints_tgt, *fpfhs_src, *fpfhs_tgt);\n\n \/\/ Copy the data and save it to disk\n\/* PointCloud s, t;\n copyPointCloud (*keypoints_src, s);\n copyPointCloud (normals_src, s);\n copyPointCloud (*keypoints_tgt, t);\n copyPointCloud (normals_tgt, t);*\/\n\n \/\/ Find correspondences between keypoints in FPFH space\n CorrespondencesPtr all_correspondences (new Correspondences), \n good_correspondences (new Correspondences);\n findCorrespondences (fpfhs_src, fpfhs_tgt, *all_correspondences);\n\n \/\/ Reject correspondences based on their XYZ distance\n rejectBadCorrespondences (all_correspondences, keypoints_src, keypoints_tgt, *good_correspondences);\n\n for (int i = 0; i < good_correspondences->size (); ++i)\n std::cerr << good_correspondences->at (i) << std::endl;\n \/\/ Obtain the best transformation between the two sets of keypoints given the remaining correspondences\n TransformationEstimationSVD trans_est;\n trans_est.estimateRigidTransformation (*keypoints_src, *keypoints_tgt, *good_correspondences, transform);\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n \/\/ Parse the command line arguments for .pcd files\n std::vector p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input source PCD file and one input target PCD file to continue.\\n\");\n print_error (\"Example: %s source.pcd target.pcd\\n\", argv[0]);\n return (-1);\n }\n\n \/\/ Load the files\n print_info (\"Loading %s as source and %s as target...\\n\", argv[p_file_indices[0]], argv[p_file_indices[1]]);\n src.reset (new PointCloud);\n tgt.reset (new PointCloud);\n if (loadPCDFile (argv[p_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_file_indices[1]], *tgt) == -1)\n {\n print_error (\"Error reading the input files!\\n\");\n return (-1);\n }\n\n \/\/ Compute the best transformtion\n Eigen::Matrix4f transform;\n computeTransformation (src, tgt, transform);\n\n std::cerr << transform << std::endl;\n \/\/ Transform the data and write it to disk\n PointCloud output;\n transformPointCloud (*src, output, transform);\n savePCDFileBinary (\"source_transformed.pcd\", output);\n}\n\/* ]--- *\/\nMinor bug fixed in registration_api tutorial code#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace sensor_msgs;\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\nusing namespace pcl::registration;\nPointCloud::Ptr src, tgt;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nestimateKeypoints (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n PointCloud &keypoints_src,\n PointCloud &keypoints_tgt)\n{\n PointCloud keypoints_src_idx, keypoints_tgt_idx;\n \/\/ Get an uniform grid of keypoints\n UniformSampling uniform;\n uniform.setRadiusSearch (1); \/\/ 1m\n\n uniform.setInputCloud (src);\n uniform.compute (keypoints_src_idx);\n copyPointCloud (*src, keypoints_src_idx.points, keypoints_src);\n\n uniform.setInputCloud (tgt);\n uniform.compute (keypoints_tgt_idx);\n copyPointCloud (*tgt, keypoints_tgt_idx.points, keypoints_tgt);\n\n \/\/ For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:\n \/\/ pcd_viewer source_pcd keypoints_src.pcd -ps 1 -ps 10\n savePCDFileBinary (\"keypoints_src.pcd\", keypoints_src);\n savePCDFileBinary (\"keypoints_tgt.pcd\", keypoints_tgt);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nestimateNormals (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n PointCloud &normals_src,\n PointCloud &normals_tgt)\n{\n NormalEstimation normal_est;\n normal_est.setInputCloud (src);\n normal_est.setRadiusSearch (0.5); \/\/ 50cm\n normal_est.compute (normals_src);\n\n normal_est.setInputCloud (tgt);\n normal_est.compute (normals_tgt);\n\n \/\/ For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:\n \/\/ pcd_viewer normals_src.pcd \n PointCloud s, t;\n copyPointCloud (*src, s);\n copyPointCloud (normals_src, s);\n copyPointCloud (*tgt, t);\n copyPointCloud (normals_tgt, t);\n savePCDFileBinary (\"normals_src.pcd\", s);\n savePCDFileBinary (\"normals_tgt.pcd\", t);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nestimateFPFH (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n const PointCloud::Ptr &normals_src,\n const PointCloud::Ptr &normals_tgt,\n const PointCloud::Ptr &keypoints_src,\n const PointCloud::Ptr &keypoints_tgt,\n PointCloud &fpfhs_src,\n PointCloud &fpfhs_tgt)\n{\n FPFHEstimation fpfh_est;\n fpfh_est.setInputCloud (keypoints_src);\n fpfh_est.setInputNormals (normals_src);\n fpfh_est.setRadiusSearch (1); \/\/ 1m\n fpfh_est.setSearchSurface (src);\n fpfh_est.compute (fpfhs_src);\n\n fpfh_est.setInputCloud (keypoints_tgt);\n fpfh_est.setInputNormals (normals_tgt);\n fpfh_est.setSearchSurface (tgt);\n fpfh_est.compute (fpfhs_tgt);\n\n \/\/ For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:\n \/\/ pcd_viewer fpfhs_src.pcd \n PointCloud2 s, t, out;\n toROSMsg (*keypoints_src, s); toROSMsg (fpfhs_src, t); concatenateFields (s, t, out);\n savePCDFile (\"fpfhs_src.pcd\", out);\n toROSMsg (*keypoints_tgt, s); toROSMsg (fpfhs_tgt, t); concatenateFields (s, t, out);\n savePCDFile (\"fpfhs_tgt.pcd\", out);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nfindCorrespondences (const PointCloud::Ptr &fpfhs_src,\n const PointCloud::Ptr &fpfhs_tgt,\n Correspondences &all_correspondences)\n{\n CorrespondenceEstimation est;\n est.setInputCloud (fpfhs_src);\n est.setInputTarget (fpfhs_tgt);\n est.determineReciprocalCorrespondences (all_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nrejectBadCorrespondences (const CorrespondencesPtr &all_correspondences,\n const PointCloud::Ptr &keypoints_src,\n const PointCloud::Ptr &keypoints_tgt,\n Correspondences &remaining_correspondences)\n{\n CorrespondenceRejectorDistance rej;\n rej.setInputCloud (keypoints_src);\n rej.setInputTarget (keypoints_tgt);\n rej.setMaximumDistance (1); \/\/ 1m\n rej.setInputCorrespondences (all_correspondences);\n rej.getCorrespondences (remaining_correspondences);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\ncomputeTransformation (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n Eigen::Matrix4f &transform)\n{\n \/\/ Get an uniform grid of keypoints\n PointCloud::Ptr keypoints_src (new PointCloud), \n keypoints_tgt (new PointCloud);\n\n estimateKeypoints (src, tgt, *keypoints_src, *keypoints_tgt);\n print_info (\"Found %zu and %zu keypoints for the source and target datasets.\\n\", keypoints_src->points.size (), keypoints_tgt->points.size ());\n\n \/\/ Compute normals for all points keypoint\n PointCloud::Ptr normals_src (new PointCloud), \n normals_tgt (new PointCloud);\n estimateNormals (src, tgt, *normals_src, *normals_tgt);\n print_info (\"Estimated %zu and %zu normals for the source and target datasets.\\n\", normals_src->points.size (), normals_tgt->points.size ());\n\n \/\/ Compute FPFH features at each keypoint\n PointCloud::Ptr fpfhs_src (new PointCloud), \n fpfhs_tgt (new PointCloud);\n estimateFPFH (src, tgt, normals_src, normals_tgt, keypoints_src, keypoints_tgt, *fpfhs_src, *fpfhs_tgt);\n\n \/\/ Copy the data and save it to disk\n\/* PointCloud s, t;\n copyPointCloud (*keypoints_src, s);\n copyPointCloud (normals_src, s);\n copyPointCloud (*keypoints_tgt, t);\n copyPointCloud (normals_tgt, t);*\/\n\n \/\/ Find correspondences between keypoints in FPFH space\n CorrespondencesPtr all_correspondences (new Correspondences), \n good_correspondences (new Correspondences);\n findCorrespondences (fpfhs_src, fpfhs_tgt, *all_correspondences);\n\n \/\/ Reject correspondences based on their XYZ distance\n rejectBadCorrespondences (all_correspondences, keypoints_src, keypoints_tgt, *good_correspondences);\n\n for (int i = 0; i < good_correspondences->size (); ++i)\n std::cerr << good_correspondences->at (i) << std::endl;\n \/\/ Obtain the best transformation between the two sets of keypoints given the remaining correspondences\n TransformationEstimationSVD trans_est;\n trans_est.estimateRigidTransformation (*keypoints_src, *keypoints_tgt, *good_correspondences, transform);\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n \/\/ Parse the command line arguments for .pcd files\n std::vector p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input source PCD file and one input target PCD file to continue.\\n\");\n print_error (\"Example: %s source.pcd target.pcd\\n\", argv[0]);\n return (-1);\n }\n\n \/\/ Load the files\n print_info (\"Loading %s as source and %s as target...\\n\", argv[p_file_indices[0]], argv[p_file_indices[1]]);\n src.reset (new PointCloud);\n tgt.reset (new PointCloud);\n if (loadPCDFile (argv[p_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_file_indices[1]], *tgt) == -1)\n {\n print_error (\"Error reading the input files!\\n\");\n return (-1);\n }\n\n \/\/ Compute the best transformtion\n Eigen::Matrix4f transform;\n computeTransformation (src, tgt, transform);\n\n std::cerr << transform << std::endl;\n \/\/ Transform the data and write it to disk\n PointCloud output;\n transformPointCloud (*src, output, transform);\n savePCDFileBinary (\"source_transformed.pcd\", output);\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"config\/config.hpp\"\n#include \"base\/type.h\"\n\nnamespace autocxxpy\n{\n template \n struct get_string\n {\n auto &operator()(string_literal &val) const noexcept\n {\n return val;\n }\n };\n\n template \n struct set_string\n {\n void operator()(string_literal &val, const char *str)\n {\n#ifdef _MSC_VER\n strcpy_s(val, str);\n#else\n strcpy(val, str);\n#endif\n }\n };\n\n\n template \n inline constexpr auto default_getter_wrap(value_type class_type::*member)\n { \/\/ match normal case\n return [member](class_type &instance)->const value_type & {\n return instance.*member;\n };\n }\n\n template \n inline constexpr auto default_setter_wrap(value_type class_type::*member)\n { \/\/ match normal case\n return [member](class_type &instance, const value_type &value) {\n instance.*member = value;\n };\n }\n\n \/\/ specialization for const setter\n template \n inline constexpr auto default_setter_wrap(const value_type class_type::*member)\n { \/\/ match const\n return nullptr;\n }\n\n \/\/ specialization for any []\n template \n inline constexpr auto default_getter_wrap(literal_array class_type::*member)\n { \/\/ match get any []\n return [member](class_type &instance) {\n auto es = std::vector(size);\n for (size_t i = 0; i < size ; i++)\n {\n es[i] = instance.*member + i;\n }\n return std::move(es);\n };\n }\n\n template \n inline constexpr auto default_setter_wrap(literal_array class_type::*member)\n { \/\/ match set any []\n return [member](class_type &instance, const std::vector &value) {\n if (value.size() >= size)\n {\n auto s = std::string(\"Array too large, maximum size : \") + std::to_string(size) + \" your size: \" + std::to_string(value.size());\n throw std::runtime_error(s);\n }\n for (int i = 0; i < value.size(); i++)\n {\n (instance.*member)[i] = value.at(i);\n }\n };\n }\n\n \/\/ specialization for any *[]\n template \n inline constexpr auto default_getter_wrap(literal_array class_type::*member)\n { \/\/ match get (any *)[]\n return [member](class_type &instance) {\n std::vector arr;\n for (auto &v : instance.*member)\n {\n arr.push_back(v);\n }\n return arr;\n };\n }\n\n \/\/ specialization for char[]\n template \n inline constexpr auto default_getter_wrap(string_literal class_type::*member)\n { \/\/ match get char []\n return [member](class_type &instance) {\n return get_string{}(instance.*member);\n };\n }\n\n template \n inline constexpr auto default_setter_wrap(string_literal class_type::*member)\n { \/\/ match set char []\n return [member](class_type &instance, const std::string_view &value) {\n return set_string{}(instance.*member, value.data());\n };\n }\n\n template \n struct getter_wrap\n {\n using value_type = decltype(default_getter_wrap(MemberConstant::value));\n static constexpr value_type value = default_getter_wrap(MemberConstant::value);\n };\n\n\n template \n struct setter_wrap\n {\n using value_type = decltype(default_setter_wrap(MemberConstant::value));\n static constexpr value_type value = default_setter_wrap(MemberConstant::value);\n };\n}\n#define AUTOCXXPY_DEF_PROPERTY(cls, name, member) \\\n def_property(name, autocxxpy::getter_wrap>::value,\\\n autocxxpy::setter_wrap>::value)\n[Fix] 更新autocxxpy脚本#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"config\/config.hpp\"\n#include \"base\/type.h\"\n\nnamespace autocxxpy\n{\n template \n struct get_string\n {\n auto &operator()(string_literal &val) const noexcept\n {\n return val;\n }\n auto &operator()(const string_literal &val) const noexcept\n {\n return val;\n }\n };\n\n template \n struct set_string\n {\n void operator()(string_literal &val, const char *str)\n {\n#ifdef _MSC_VER\n strcpy_s(val, str);\n#else\n strcpy(val, str);\n#endif\n }\n };\n\n\n template \n inline constexpr auto default_getter_wrap(value_type class_type::*member)\n { \/\/ match normal case\n return [member](class_type &instance)->const value_type & {\n return instance.*member;\n };\n }\n\n template \n inline constexpr auto default_setter_wrap(value_type class_type::*member)\n { \/\/ match normal case\n return [member](class_type &instance, const value_type &value) {\n instance.*member = value;\n };\n }\n\n \/\/ specialization for const setter\n template \n inline constexpr auto default_setter_wrap(const value_type class_type::*member)\n { \/\/ match const\n return nullptr;\n }\n\n \/\/ specialization for any []\n template \n inline constexpr auto default_getter_wrap(literal_array class_type::*member)\n { \/\/ match get any []\n return [member](class_type &instance) {\n auto es = std::vector(size);\n for (size_t i = 0; i < size ; i++)\n {\n es[i] = instance.*member + i;\n }\n return std::move(es);\n };\n }\n\n template \n inline constexpr auto default_setter_wrap(literal_array class_type::*member)\n { \/\/ match set any []\n return [member](class_type &instance, const std::vector &value) {\n if (value.size() >= size)\n {\n auto s = std::string(\"Array too large, maximum size : \") + std::to_string(size) + \" your size: \" + std::to_string(value.size());\n throw std::runtime_error(s);\n }\n for (int i = 0; i < value.size(); i++)\n {\n (instance.*member)[i] = value.at(i);\n }\n };\n }\n\n \/\/ specialization for any *[]\n template \n inline constexpr auto default_getter_wrap(literal_array class_type::*member)\n { \/\/ match get (any *)[]\n return [member](class_type &instance) {\n std::vector arr;\n for (auto &v : instance.*member)\n {\n arr.push_back(v);\n }\n return arr;\n };\n }\n\n \/\/ specialization for char[]\n template \n inline constexpr auto default_getter_wrap(string_literal class_type::*member)\n { \/\/ match get char []\n return [member](class_type &instance) {\n return get_string{}(instance.*member);\n };\n }\n\n template \n inline constexpr auto default_setter_wrap(string_literal class_type::*member)\n { \/\/ match set char []\n return [member](class_type &instance, const std::string_view &value) {\n return set_string{}(instance.*member, value.data());\n };\n }\n\n template \n struct getter_wrap\n {\n using value_type = decltype(default_getter_wrap(MemberConstant::value));\n static constexpr value_type value = default_getter_wrap(MemberConstant::value);\n };\n\n\n template \n struct setter_wrap\n {\n using value_type = decltype(default_setter_wrap(MemberConstant::value));\n static constexpr value_type value = default_setter_wrap(MemberConstant::value);\n };\n}\n#define AUTOCXXPY_DEF_PROPERTY(cls, name, member) \\\n def_property(name, autocxxpy::getter_wrap>::value,\\\n autocxxpy::setter_wrap>::value)\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2019 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {\n std::string partialPath;\n char pathPtrInt[2] = {encodedPartialPath[0], '\\0'};\n int partialPathInt = strtol(pathPtrInt, NULL, 10);\n if(partialPathInt == 0 || partialPathInt == 2){\n partialPath = encodedPartialPath.substr(2);\n }else{\n partialPath = encodedPartialPath.substr(1);\n }\n if(partialPath == path.substr(pathPtr, partialPath.size())){\n return partialPath.size();\n }else{\n return -1;\n }\n}\nbool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {\n try{\n dev::RLP currentNode;\n const int len = parentNodes.itemCount();\n dev::RLP nodeKey = root; \n int pathPtr = 0;\n\n \tconst std::string pathString = dev::toHex(path);\n \n int nibbles;\n char pathPtrInt[2];\n for (int i = 0 ; i < len ; i++) {\n currentNode = parentNodes[i];\n if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){\n return false;\n } \n\n if(pathPtr > (int)pathString.size()){\n return false;\n }\n\n switch(currentNode.itemCount()){\n case 17:\/\/branch node\n if(pathPtr == (int)pathString.size()){\n if(currentNode[16].payload().contentsEqual(value.data().toVector())){\n \n return true;\n }else{\n return false;\n }\n }\n \n pathPtrInt[0] = pathString[pathPtr];\n pathPtrInt[1] = '\\0';\n\n nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; \/\/must == sha3(rlp.encode(currentNode[path[pathptr]]))\n pathPtr += 1;\n break;\n case 2:\n nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);\n\n if(nibbles <= -1)\n return false;\n pathPtr += nibbles;\n \n if(pathPtr == (int)pathString.size()) { \/\/leaf node\n if(currentNode[1].payload().contentsEqual(value.data().toVector())){\n \n return true;\n } else {\n return false;\n }\n } else {\/\/extension node\n nodeKey = currentNode[1];\n }\n break;\n default:\n return false;\n }\n }\n }\n catch(...){\n return false;\n }\n return false;\n}\n\n\/**\n * Parse eth input string expected to contain smart contract method call data. If the method call is not what we\n * expected, or the length of the expected string is not what we expect then return false.\n *\n * @param vchInputExpectedMethodHash The expected method hash\n * @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits\n * @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits\n * @param vchInputData The input to parse\n * @param outputAmount The amount burned\n * @param nAsset The asset burned\n * @param witnessAddress The destination witness address for the minting\n * @return true if everything is valid\n *\/\nbool parseEthMethodInputData(const std::vector& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) {\n \/\/ total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash\n if(vchInputData.size() < 164 || vchInputData.size() > 196) {\n return false; \n }\n \/\/ method hash is 4 bytes\n std::vector::const_iterator firstMethod = vchInputData.begin();\n std::vector::const_iterator lastMethod = firstMethod + 4;\n const std::vector vchMethodHash(firstMethod,lastMethod);\n \/\/ if the method hash doesn't match the expected method hash then return false\n if(vchMethodHash != vchInputExpectedMethodHash) {\n return false;\n }\n\n std::vector vchAmount(lastMethod,lastMethod + 32);\n \/\/ reverse endian\n std::reverse(vchAmount.begin(), vchAmount.end());\n arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));\n \/\/ local precision can range between 0 and 8 decimal places, so it should fit within a CAmount\n \/\/ we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred\n if(nLocalPrecision > nERC20Precision){\n outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision);\n \/\/ ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision\n } else if(nLocalPrecision < nERC20Precision){\n outputAmountArith \/= pow(10, nERC20Precision-nLocalPrecision);\n }\n outputAmount = outputAmountArith.GetLow64();\n \n \/\/ convert the vch into a uint32_t (nAsset)\n \/\/ should be in position 68 walking backwards\n nAsset = static_cast(vchInputData[67]);\n nAsset |= static_cast(vchInputData[66]) << 8;\n nAsset |= static_cast(vchInputData[65]) << 16;\n nAsset |= static_cast(vchInputData[64]) << 24;\n \n \/\/ skip data field marker (32 bytes) + 31 bytes offset to the varint _byte\n const unsigned char &dataLength = vchInputData[131];\n \/\/ bech32 addresses to 46 bytes (sys1 vs bc1), min length is 9 for min witness address https:\/\/en.bitcoin.it\/wiki\/BIP_0173\n if(dataLength > 46 || dataLength < 9) {\n return false;\n }\n\n \/\/ witness address information starting at position 132 till the end\n witnessAddress = DecodeDestination(std::to_string(vchInputData.begin()+132, vchInputData.begin()+132 + dataLength));\n return true;\n}fix witness address\/\/ Copyright (c) 2019 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {\n std::string partialPath;\n char pathPtrInt[2] = {encodedPartialPath[0], '\\0'};\n int partialPathInt = strtol(pathPtrInt, NULL, 10);\n if(partialPathInt == 0 || partialPathInt == 2){\n partialPath = encodedPartialPath.substr(2);\n }else{\n partialPath = encodedPartialPath.substr(1);\n }\n if(partialPath == path.substr(pathPtr, partialPath.size())){\n return partialPath.size();\n }else{\n return -1;\n }\n}\nbool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {\n try{\n dev::RLP currentNode;\n const int len = parentNodes.itemCount();\n dev::RLP nodeKey = root; \n int pathPtr = 0;\n\n \tconst std::string pathString = dev::toHex(path);\n \n int nibbles;\n char pathPtrInt[2];\n for (int i = 0 ; i < len ; i++) {\n currentNode = parentNodes[i];\n if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){\n return false;\n } \n\n if(pathPtr > (int)pathString.size()){\n return false;\n }\n\n switch(currentNode.itemCount()){\n case 17:\/\/branch node\n if(pathPtr == (int)pathString.size()){\n if(currentNode[16].payload().contentsEqual(value.data().toVector())){\n \n return true;\n }else{\n return false;\n }\n }\n \n pathPtrInt[0] = pathString[pathPtr];\n pathPtrInt[1] = '\\0';\n\n nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; \/\/must == sha3(rlp.encode(currentNode[path[pathptr]]))\n pathPtr += 1;\n break;\n case 2:\n nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);\n\n if(nibbles <= -1)\n return false;\n pathPtr += nibbles;\n \n if(pathPtr == (int)pathString.size()) { \/\/leaf node\n if(currentNode[1].payload().contentsEqual(value.data().toVector())){\n \n return true;\n } else {\n return false;\n }\n } else {\/\/extension node\n nodeKey = currentNode[1];\n }\n break;\n default:\n return false;\n }\n }\n }\n catch(...){\n return false;\n }\n return false;\n}\n\n\/**\n * Parse eth input string expected to contain smart contract method call data. If the method call is not what we\n * expected, or the length of the expected string is not what we expect then return false.\n *\n * @param vchInputExpectedMethodHash The expected method hash\n * @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits\n * @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits\n * @param vchInputData The input to parse\n * @param outputAmount The amount burned\n * @param nAsset The asset burned\n * @param witnessAddress The destination witness address for the minting\n * @return true if everything is valid\n *\/\nbool parseEthMethodInputData(const std::vector& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) {\n \/\/ total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash\n if(vchInputData.size() < 164 || vchInputData.size() > 196) {\n return false; \n }\n \/\/ method hash is 4 bytes\n std::vector::const_iterator firstMethod = vchInputData.begin();\n std::vector::const_iterator lastMethod = firstMethod + 4;\n const std::vector vchMethodHash(firstMethod,lastMethod);\n \/\/ if the method hash doesn't match the expected method hash then return false\n if(vchMethodHash != vchInputExpectedMethodHash) {\n return false;\n }\n\n std::vector vchAmount(lastMethod,lastMethod + 32);\n \/\/ reverse endian\n std::reverse(vchAmount.begin(), vchAmount.end());\n arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));\n \/\/ local precision can range between 0 and 8 decimal places, so it should fit within a CAmount\n \/\/ we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred\n if(nLocalPrecision > nERC20Precision){\n outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision);\n \/\/ ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision\n } else if(nLocalPrecision < nERC20Precision){\n outputAmountArith \/= pow(10, nERC20Precision-nLocalPrecision);\n }\n outputAmount = outputAmountArith.GetLow64();\n \n \/\/ convert the vch into a uint32_t (nAsset)\n \/\/ should be in position 68 walking backwards\n nAsset = static_cast(vchInputData[67]);\n nAsset |= static_cast(vchInputData[66]) << 8;\n nAsset |= static_cast(vchInputData[65]) << 16;\n nAsset |= static_cast(vchInputData[64]) << 24;\n \n \/\/ skip data field marker (32 bytes) + 31 bytes offset to the varint _byte\n const unsigned char &dataLength = vchInputData[131];\n \/\/ bech32 addresses to 46 bytes (sys1 vs bc1), min length is 9 for min witness address https:\/\/en.bitcoin.it\/wiki\/BIP_0173\n if(dataLength > 46 || dataLength < 9) {\n return false;\n }\n\n \/\/ witness address information starting at position 132 till the end\n witnessAddress = DecodeDestination(std::to_string(HexStr(vchInputData.begin()+132, vchInputData.begin()+132 + dataLength)));\n return true;\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"yaml-cpp\/yaml.h\"\n#include \n\nstd::string pcd_file;\nstd::string config_file;\n\nnamespace YAML {\ntemplate<>\nstruct convert {\n static bool decode(const YAML::Node& node, Eigen::Vector3f& rhs) {\n if(!node.IsSequence() || node.size() != 3) {\n return false;\n }\n\n rhs[0] = node[0].as();\n rhs[1] = node[1].as();\n rhs[2] = node[2].as();\n return true;\n }\n};\n}\n\n#define EXPECT_VECTOR_ANGLE_LE(val1, val2, max_angle)\t\t\t\\\n do {\t\t\t\t\t\t\t\t\t\\\n Eigen::Vector3f val1_norm = val1.normalized();\t\t\t\\\n Eigen::Vector3f val2_norm = val2.normalized();\t\t\t\\\n if(val1_norm != val2_norm) {\t\t\t\t\t\\\n double angle = acos(val1_norm.dot(val2_norm));\t\t\t\\\n EXPECT_LE(fabs(angle), max_angle)\t\t\t\t\t\\\n\t<< \"Expected angle between \"\t\t\t\t\t\\\n\t<< \"[\" << val1[0] << \", \" << val1[1] << \", \" << val1[2] << \"]\"\t\\\n\t<< \" and [\" << val2[0] << \", \" << val2[1] << \", \" << val2[2] << \"]\" \\\n\t<< \" <= \" << max_angle << \", but was \" << angle;\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n } while(0)\n\n#define EXPECT_VECTOR_NEAR(val1, val2, abs_error)\t\t\t\\\n do {\t\t\t\t\t\t\t\t\t\\\n double error = (val1 - val2).norm();\t\t\t\t\\\n EXPECT_LE(error, abs_error)\t\t\t\t\t\t\\\n << \"Expected error between \"\t\t\t\t\t\\\n << \"[\" << val1[0] << \", \" << val1[1] << \", \" << val1[2] << \"]\"\t\\\n << \" and [\" << val2[0] << \", \" << val2[1] << \", \" << val2[2] << \"]\" \\\n << \" <= \" << abs_error << \", but was \" << error;\t\t\t\\\n } while(0)\n\nstruct StairDetectorTestData {\n StairDetectorTestData(std::string pcd_file, std::string config_file) : pcd_file(pcd_file), config_file(config_file) {}\n std::string pcd_file;\n std::string config_file;\n};\nvoid PrintTo(const StairDetectorTestData& data, ::std::ostream* os) {\n *os << \"PCD File: \" << data.pcd_file << \", Config File: \" << data.config_file;\n}\n\nclass StairDetectorTest : public ::testing::TestWithParam {};\n\n\nTEST_P(StairDetectorTest, detectStairs) {\n pcl::PointCloud::Ptr cloud(new pcl::PointCloud);\n pcl::io::loadPCDFile(GetParam().pcd_file, *cloud);\n\n YAML::Node config = YAML::LoadFile(GetParam().config_file);\n YAML::Node sensor_config = config[\"sensor\"];\n YAML::Node stairs_config = config[\"stairs\"];\n\n Eigen::Vector3f vertical_estimate = sensor_config[\"vertical\"].as();\n\n walrus_stair_detector::WalrusStairDetector detector;\n std::vector stairs;\n detector.detect(cloud, vertical_estimate, &stairs);\n\n ASSERT_EQ(stairs_config.size(), stairs.size());\n\n for(int i = 0; i < stairs.size(); ++i) {\n YAML::Node stair_config = stairs_config[i];\n walrus_stair_detector::StairModel& stair = stairs[i];\n EXPECT_NEAR(stair_config[\"rise\"].as(), stair.rise, 0.1);\n EXPECT_NEAR(stair_config[\"run\"].as(), stair.run, 0.1);\n\n EXPECT_VECTOR_ANGLE_LE(stair_config[\"direction\"].as(), stair.direction, 0.06);\n\n Eigen::Vector3f expected_origin = stair_config[\"origin\"].as();\n\n double expected_x = expected_origin.dot(stair.horizontal);\n double expected_y = expected_origin.dot(stair.vertical);\n double expected_z = expected_origin.dot(stair.direction);\n\n double actual_x = stair.origin.dot(stair.horizontal);\n double actual_y = stair.origin.dot(stair.vertical);\n double actual_z = stair.origin.dot(stair.direction);\n\n \/\/ Expect the horizontal component to be less accurate\n EXPECT_NEAR(expected_x, actual_x, 0.14);\n\n double max_origin_center_error = 0.05;\n Eigen::Vector3f expected_origin_center(0, expected_y, expected_z);\n Eigen::Vector3f origin_center(0, actual_y, actual_z);\n if(stair_config[\"can_miss_first_stair\"].IsDefined() && stair_config[\"can_miss_first_stair\"].as()){\n Eigen::Vector3f upper_origin_center(0, actual_y - stair.rise, actual_z - stair.run);\n if((expected_origin_center - upper_origin_center).norm() < max_origin_center_error)\n\tEXPECT_VECTOR_NEAR(expected_origin_center, upper_origin_center, max_origin_center_error);\n else\n\tEXPECT_VECTOR_NEAR(expected_origin_center, origin_center, max_origin_center_error);\n }\n else {\n EXPECT_VECTOR_NEAR(expected_origin_center, origin_center, max_origin_center_error);\n }\n\n EXPECT_GE(stair_config[\"width\"].as(), stair.width);\n EXPECT_LE(stair_config[\"width\"].as()-0.18, stair.width);\n\n if(stair_config[\"num_stairs\"].IsScalar()) {\n EXPECT_EQ(stair_config[\"num_stairs\"].as(), stair.num_stairs);\n }\n else {\n EXPECT_LE(stair_config[\"num_stairs\"][0].as(), stair.num_stairs);\n EXPECT_GE(stair_config[\"num_stairs\"][1].as(), stair.num_stairs);\n }\n }\n}\n\nstd::string find_package(const std::string& package, const std::string& path) {\n std::stringstream command;\n command << \"catkin_find \" << package << \" \" << path;\n\n char buf[1000];\n FILE *fp = popen(command.str().c_str(), \"r\");\n if (fp == NULL) {\n return \"\";\n }\n\n std::string result;\n while (fgets(buf, sizeof(buf), fp) != NULL) {\n result = buf;\n break;\n }\n\n if(result.size() > 0 && result[result.size()-1] == '\\n')\n result = result.substr(0, result.size()-1);\n\n pclose(fp);\n return result;\n}\n\nstd::vector GenerateStairDetectorParameterList() {\n std::vector data;\n std::string testdata_root_string = find_package(\"walrus_testdata\", \"kinectv2\/stairs\");\n\n if(testdata_root_string.size() > 0) {\n boost::filesystem::path testdata_root (testdata_root_string);\n std::cout << \"Searching for test data in: \" << testdata_root << std::endl;\n if(!boost::filesystem::is_directory(testdata_root))\n throw new std::runtime_error(\"Test data path is not a directory\");\n\n boost::filesystem::directory_iterator end;\n for(boost::filesystem::directory_iterator itr(testdata_root); itr != end; ++itr) {\n boost::filesystem::path test_collection = itr->path();\n std::cout << \"\\tFound test collection: \" << test_collection.filename() << std::endl;\n\n boost::filesystem::path test_collection_description = test_collection;\n test_collection_description\/=\"description.yaml\";\n if(boost::filesystem::exists(test_collection_description)){\n\tfor(boost::filesystem::directory_iterator itr2(test_collection); itr2 != end; ++itr2) {\n\t if(itr2->path().extension() == \".pcd\") {\n\t std::cout << \"\\t\\tFound test: \" << itr2->path().filename() << std::endl;\n\t data.push_back(StairDetectorTestData(itr2->path().native(), test_collection_description.native()));\n\t }\n\t}\n }\n else\n\tstd::cout << \"Did not find test description: \" << test_collection_description << std::endl;\n }\n\n }\n else\n throw new std::runtime_error(\"Could not find test data folder in walrus_testdata\");\n return data;\n}\nINSTANTIATE_TEST_CASE_P(\n\t\t\tStairTestData,\n\t\t\tStairDetectorTest,\n\t\t\ttesting::ValuesIn(GenerateStairDetectorParameterList()));\n\nint main(int argc, char** argv)\n{\n testing::InitGoogleTest(&argc, argv);\n ros::init(argc, argv, \"stair_detector_test\");\n\n return RUN_ALL_TESTS();\n}\nMade stair detector test nolonger a ROS node#include \n#include \n#include \n#include \n#include \"yaml-cpp\/yaml.h\"\n#include \n\nstd::string pcd_file;\nstd::string config_file;\n\nnamespace YAML {\ntemplate<>\nstruct convert {\n static bool decode(const YAML::Node& node, Eigen::Vector3f& rhs) {\n if(!node.IsSequence() || node.size() != 3) {\n return false;\n }\n\n rhs[0] = node[0].as();\n rhs[1] = node[1].as();\n rhs[2] = node[2].as();\n return true;\n }\n};\n}\n\n#define EXPECT_VECTOR_ANGLE_LE(val1, val2, max_angle)\t\t\t\\\n do {\t\t\t\t\t\t\t\t\t\\\n Eigen::Vector3f val1_norm = val1.normalized();\t\t\t\\\n Eigen::Vector3f val2_norm = val2.normalized();\t\t\t\\\n if(val1_norm != val2_norm) {\t\t\t\t\t\\\n double angle = acos(val1_norm.dot(val2_norm));\t\t\t\\\n EXPECT_LE(fabs(angle), max_angle)\t\t\t\t\t\\\n\t<< \"Expected angle between \"\t\t\t\t\t\\\n\t<< \"[\" << val1[0] << \", \" << val1[1] << \", \" << val1[2] << \"]\"\t\\\n\t<< \" and [\" << val2[0] << \", \" << val2[1] << \", \" << val2[2] << \"]\" \\\n\t<< \" <= \" << max_angle << \", but was \" << angle;\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n } while(0)\n\n#define EXPECT_VECTOR_NEAR(val1, val2, abs_error)\t\t\t\\\n do {\t\t\t\t\t\t\t\t\t\\\n double error = (val1 - val2).norm();\t\t\t\t\\\n EXPECT_LE(error, abs_error)\t\t\t\t\t\t\\\n << \"Expected error between \"\t\t\t\t\t\\\n << \"[\" << val1[0] << \", \" << val1[1] << \", \" << val1[2] << \"]\"\t\\\n << \" and [\" << val2[0] << \", \" << val2[1] << \", \" << val2[2] << \"]\" \\\n << \" <= \" << abs_error << \", but was \" << error;\t\t\t\\\n } while(0)\n\nstruct StairDetectorTestData {\n StairDetectorTestData(std::string pcd_file, std::string config_file) : pcd_file(pcd_file), config_file(config_file) {}\n std::string pcd_file;\n std::string config_file;\n};\nvoid PrintTo(const StairDetectorTestData& data, ::std::ostream* os) {\n *os << \"PCD File: \" << data.pcd_file << \", Config File: \" << data.config_file;\n}\n\nclass StairDetectorTest : public ::testing::TestWithParam {};\n\n\nTEST_P(StairDetectorTest, detectStairs) {\n pcl::PointCloud::Ptr cloud(new pcl::PointCloud);\n pcl::io::loadPCDFile(GetParam().pcd_file, *cloud);\n\n YAML::Node config = YAML::LoadFile(GetParam().config_file);\n YAML::Node sensor_config = config[\"sensor\"];\n YAML::Node stairs_config = config[\"stairs\"];\n\n Eigen::Vector3f vertical_estimate = sensor_config[\"vertical\"].as();\n\n walrus_stair_detector::WalrusStairDetector detector;\n std::vector stairs;\n detector.detect(cloud, vertical_estimate, &stairs);\n\n ASSERT_EQ(stairs_config.size(), stairs.size());\n\n for(int i = 0; i < stairs.size(); ++i) {\n YAML::Node stair_config = stairs_config[i];\n walrus_stair_detector::StairModel& stair = stairs[i];\n EXPECT_NEAR(stair_config[\"rise\"].as(), stair.rise, 0.1);\n EXPECT_NEAR(stair_config[\"run\"].as(), stair.run, 0.1);\n\n EXPECT_VECTOR_ANGLE_LE(stair_config[\"direction\"].as(), stair.direction, 0.06);\n\n Eigen::Vector3f expected_origin = stair_config[\"origin\"].as();\n\n double expected_x = expected_origin.dot(stair.horizontal);\n double expected_y = expected_origin.dot(stair.vertical);\n double expected_z = expected_origin.dot(stair.direction);\n\n double actual_x = stair.origin.dot(stair.horizontal);\n double actual_y = stair.origin.dot(stair.vertical);\n double actual_z = stair.origin.dot(stair.direction);\n\n \/\/ Expect the horizontal component to be less accurate\n EXPECT_NEAR(expected_x, actual_x, 0.14);\n\n double max_origin_center_error = 0.05;\n Eigen::Vector3f expected_origin_center(0, expected_y, expected_z);\n Eigen::Vector3f origin_center(0, actual_y, actual_z);\n if(stair_config[\"can_miss_first_stair\"].IsDefined() && stair_config[\"can_miss_first_stair\"].as()){\n Eigen::Vector3f upper_origin_center(0, actual_y - stair.rise, actual_z - stair.run);\n if((expected_origin_center - upper_origin_center).norm() < max_origin_center_error)\n\tEXPECT_VECTOR_NEAR(expected_origin_center, upper_origin_center, max_origin_center_error);\n else\n\tEXPECT_VECTOR_NEAR(expected_origin_center, origin_center, max_origin_center_error);\n }\n else {\n EXPECT_VECTOR_NEAR(expected_origin_center, origin_center, max_origin_center_error);\n }\n\n EXPECT_GE(stair_config[\"width\"].as(), stair.width);\n EXPECT_LE(stair_config[\"width\"].as()-0.18, stair.width);\n\n if(stair_config[\"num_stairs\"].IsScalar()) {\n EXPECT_EQ(stair_config[\"num_stairs\"].as(), stair.num_stairs);\n }\n else {\n EXPECT_LE(stair_config[\"num_stairs\"][0].as(), stair.num_stairs);\n EXPECT_GE(stair_config[\"num_stairs\"][1].as(), stair.num_stairs);\n }\n }\n}\n\nstd::string find_package(const std::string& package, const std::string& path) {\n std::stringstream command;\n command << \"catkin_find \" << package << \" \" << path;\n\n char buf[1000];\n FILE *fp = popen(command.str().c_str(), \"r\");\n if (fp == NULL) {\n return \"\";\n }\n\n std::string result;\n while (fgets(buf, sizeof(buf), fp) != NULL) {\n result = buf;\n break;\n }\n\n if(result.size() > 0 && result[result.size()-1] == '\\n')\n result = result.substr(0, result.size()-1);\n\n pclose(fp);\n return result;\n}\n\nstd::vector GenerateStairDetectorParameterList() {\n std::vector data;\n std::string testdata_root_string = find_package(\"walrus_testdata\", \"kinectv2\/stairs\");\n\n if(testdata_root_string.size() > 0) {\n boost::filesystem::path testdata_root (testdata_root_string);\n std::cout << \"Searching for test data in: \" << testdata_root << std::endl;\n if(!boost::filesystem::is_directory(testdata_root))\n throw new std::runtime_error(\"Test data path is not a directory\");\n\n boost::filesystem::directory_iterator end;\n for(boost::filesystem::directory_iterator itr(testdata_root); itr != end; ++itr) {\n boost::filesystem::path test_collection = itr->path();\n std::cout << \"\\tFound test collection: \" << test_collection.filename() << std::endl;\n\n boost::filesystem::path test_collection_description = test_collection;\n test_collection_description\/=\"description.yaml\";\n if(boost::filesystem::exists(test_collection_description)){\n\tfor(boost::filesystem::directory_iterator itr2(test_collection); itr2 != end; ++itr2) {\n\t if(itr2->path().extension() == \".pcd\") {\n\t std::cout << \"\\t\\tFound test: \" << itr2->path().filename() << std::endl;\n\t data.push_back(StairDetectorTestData(itr2->path().native(), test_collection_description.native()));\n\t }\n\t}\n }\n else\n\tstd::cout << \"Did not find test description: \" << test_collection_description << std::endl;\n }\n\n }\n else\n throw new std::runtime_error(\"Could not find test data folder in walrus_testdata\");\n return data;\n}\nINSTANTIATE_TEST_CASE_P(\n\t\t\tStairTestData,\n\t\t\tStairDetectorTest,\n\t\t\ttesting::ValuesIn(GenerateStairDetectorParameterList()));\n\nint main(int argc, char** argv)\n{\n testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \"Subsystems\/Chassis.h\"\n#include \"Commands\/DefaultDrive.h\"\n\nChassis* Chassis::m_pInstance = NULL;\n\nChassis* Chassis::GetInstance()\n{\n\tif(!m_pInstance) m_pInstance = new Chassis;\n\treturn m_pInstance;\n}\n\nChassis::Chassis() : PIDSubsystem(\"Chassis\", 0.05, 0.01, 0.15)\n{\n\tm_leftMotorFront = new CANTalon(CAN_LEFTMOTORFRONT);\n\tm_leftMotorRear = new CANTalon(CAN_LEFTMOTORREAR);\n\tm_rightMotorFront = new CANTalon(CAN_RIGHTMOTORFRONT);\n\tm_rightMotorRear = new CANTalon(CAN_RIGHTMOTORREAR);\n\tm_leftMotorFront->SetSensorDirection(false);\n\tm_rightMotorFront->SetSensorDirection(true);\n\tm_leftMotorFront->ConfigEncoderCodesPerRev(RATIO_DRIVECODESPERREV);\n\tm_rightMotorFront->ConfigEncoderCodesPerRev(RATIO_DRIVECODESPERREV);\n\n\tm_drive = new RobotDrive(m_leftMotorFront, m_leftMotorRear, m_rightMotorFront, m_rightMotorRear);\n\tm_drive->SetSafetyEnabled(false);\n\tm_shifter = new Solenoid(CAN_PNMMODULE, PNM_GEARSHIFTER);\n\tm_bShiftedLow = false;\n\n\ttry{\n\t\t\/\/Connect to navX Gyro on MXP port.\n\t\tm_navX = new AHRS(SPI::Port::kMXP);\n\t\tm_bNavXPresent = true;\n\t} catch (std::exception ex){\n\t\t\/\/If connection fails log the error and fall back to encoder based angle handling.\n\t\tstd::string str_error = \"Error instantiating navX from MXP: \";\n\t\tstr_error += ex.what();\n\t\tDriverStation::ReportError(str_error.c_str());\n\t\tm_bNavXPresent = false;\n\t}\n\n\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Left Front TalonSRX\", m_leftMotorFront);\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Left Rear TalonSRX\", m_leftMotorRear);\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Right Front TalonSRX\", m_rightMotorFront);\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Right Rear TalonSRX\", m_rightMotorRear);\n\n\tLiveWindow::GetInstance()->AddSensor(\"Chassis\", \"NavX\", m_navX);\n\n\n\tm_onPID = false;\n\tm_onGyro = false;\n\tmoveSpeed = 0;\n\tprevAbsBias = 0;\n}\n\nvoid Chassis::InitDefaultCommand()\n{\n\t\/\/ Set the default command for a subsystem here.\n\tSetDefaultCommand(new DefaultDrive());\n}\n\n\/\/Arcade Drives with the values of move as the forward value, and turn as the turning value\nvoid Chassis::Drive(double moveL, double moveR, bool quad)\n{\n\tm_drive->TankDrive(moveL, moveR, quad);\n}\n\nvoid Chassis::DriveArcade(double move, double turn, bool squaredInputs)\n{\n\n\tm_drive->ArcadeDrive(move, turn, squaredInputs);\n}\n\nvoid Chassis::Shift(bool shiftDown)\n{\n\tm_shifter->Set(shiftDown);\n\tm_bShiftedLow = shiftDown;\n}\n\ndouble Chassis::GetSpeedL()\n{\n\treturn m_leftMotorFront->GetSpeed() * InchesPerRev \/ 50.0;\n}\n\ndouble Chassis::GetSpeedR()\n{\n\treturn m_rightMotorFront->GetSpeed() * InchesPerRev \/ 50.0;\n}\n\ndouble Chassis::GetSpeed()\n{\n\treturn ( GetSpeedL() + GetSpeedR() ) \/ 2.0;\n}\n\ndouble Chassis::GetDistanceL()\n{\n\treturn m_leftMotorFront->GetPosition() * InchesPerRev;\n}\n\ndouble Chassis::GetDistanceR()\n{\n\treturn m_rightMotorFront->GetPosition() * InchesPerRev;\n}\n\ndouble Chassis::GetDistance()\n{\n\treturn ( GetDistanceL() + GetDistanceR() ) \/ 2.0;\n}\n\ndouble Chassis::GetAngle(bool forceGyro)\n{\n\tif((m_onGyro || forceGyro) && m_bNavXPresent)\n\t\/\/if(m_bNavXPresent)\t\t\t\t\t\t\t\t\t\/\/Always gyro unless not present\n\t{\n\t\t\/\/Angle use wants a faster, more accurate, but drifting angle, for quick use.\n\t\treturn -m_navX->GetAngle();\n\t}\n\telse {\n\t\t\/\/Means that angle use wants a driftless angle measure that lasts.\n\t\treturn ( GetDistanceR() - GetDistanceL() ) * 180 \/ (Preferences::GetInstance()->GetDouble(\"ChassisWidth\",28.55) * M_PI);\n\t\t\/*\n\t\t * Angle is 180 degrees times encoder difference over Pi * the distance between the wheels\n\t\t *\tMade from geometry and relation between angle fraction and arc fraction with semicircles.\n\t\t *\/\n\t}\n}\n\ndouble Chassis::ReturnPIDInput()\n{\n\treturn GetAngle();\n}\n\nvoid Chassis::UsePIDOutput(double bias)\n{\n\t\/\/ Chassis ramp rate is the limit on the voltage change per cycle to prevent skidding.\n\tconst double speedLimit = prevAbsBias + Preferences::GetInstance()->GetDouble(\"ChassisRampRate\", 0.25);\n\tif(bias > speedLimit) bias = speedLimit;\n\tif(bias < -speedLimit) bias = -speedLimit;\n\tdouble speed_L = moveSpeed-bias;\n\tdouble speed_R = moveSpeed+bias;\n\tm_drive->TankDrive(speed_L, speed_R, false);\n\tprevAbsBias = fabs(bias);\n}\n\nvoid Chassis::ReleaseAngle()\n{\n\tGetPIDController()->Disable();\n\tm_onPID=false;\n\tm_onGyro=false;\t\t\/\/Gyro needs to be explicitly enabled for each PID turn\n\tprevAbsBias=0;\n}\n\nvoid Chassis::ResetEncoders()\n{\n\tm_leftMotorFront->SetPosition(0);\n\tm_rightMotorFront->SetPosition(0);\n}\n\nvoid Chassis::HoldAngle(double angle, bool gyro)\n{\n\tif(!m_onPID) m_onGyro = gyro;\t\t\/\/Prevent changing angle mode when already in a turn\n\tSetPIDValues();\n\tGetPIDController()->SetSetpoint(GetAngle() + angle);\n\tGetPIDController()->Enable();\n\tm_onPID = true;\n}\n\nvoid Chassis::SetPIDValues()\n{\n\tif(m_bShiftedLow){\n\t\tGetPIDController()->SetPID(\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisHighP\",0.075),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisHighI\",0.01),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisHighD\",0.09)\n\t\t);\n\t}else{\n\t\tGetPIDController()->SetPID(\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisLowP\", 0.085),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisLowI\", 0.02),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisLowD\", 0.125)\n\t\t);\n\t}\n}\nMade Gyro always be used for angles unless it fails to initialize.#include \"Subsystems\/Chassis.h\"\n#include \"Commands\/DefaultDrive.h\"\n\nChassis* Chassis::m_pInstance = NULL;\n\nChassis* Chassis::GetInstance()\n{\n\tif(!m_pInstance) m_pInstance = new Chassis;\n\treturn m_pInstance;\n}\n\nChassis::Chassis() : PIDSubsystem(\"Chassis\", 0.05, 0.01, 0.15)\n{\n\tm_leftMotorFront = new CANTalon(CAN_LEFTMOTORFRONT);\n\tm_leftMotorRear = new CANTalon(CAN_LEFTMOTORREAR);\n\tm_rightMotorFront = new CANTalon(CAN_RIGHTMOTORFRONT);\n\tm_rightMotorRear = new CANTalon(CAN_RIGHTMOTORREAR);\n\tm_leftMotorFront->SetSensorDirection(false);\n\tm_rightMotorFront->SetSensorDirection(true);\n\tm_leftMotorFront->ConfigEncoderCodesPerRev(RATIO_DRIVECODESPERREV);\n\tm_rightMotorFront->ConfigEncoderCodesPerRev(RATIO_DRIVECODESPERREV);\n\n\tm_drive = new RobotDrive(m_leftMotorFront, m_leftMotorRear, m_rightMotorFront, m_rightMotorRear);\n\tm_drive->SetSafetyEnabled(false);\n\tm_shifter = new Solenoid(CAN_PNMMODULE, PNM_GEARSHIFTER);\n\tm_bShiftedLow = false;\n\n\ttry{\n\t\t\/\/Connect to navX Gyro on MXP port.\n\t\tm_navX = new AHRS(SPI::Port::kMXP);\n\t\tm_bNavXPresent = true;\n\t} catch (std::exception ex){\n\t\t\/\/If connection fails log the error and fall back to encoder based angle handling.\n\t\tstd::string str_error = \"Error instantiating navX from MXP: \";\n\t\tstr_error += ex.what();\n\t\tDriverStation::ReportError(str_error.c_str());\n\t\tm_bNavXPresent = false;\n\t}\n\n\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Left Front TalonSRX\", m_leftMotorFront);\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Left Rear TalonSRX\", m_leftMotorRear);\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Right Front TalonSRX\", m_rightMotorFront);\n\tLiveWindow::GetInstance()->AddActuator(\"Chassis\", \"Right Rear TalonSRX\", m_rightMotorRear);\n\n\tLiveWindow::GetInstance()->AddSensor(\"Chassis\", \"NavX\", m_navX);\n\n\n\tm_onPID = false;\n\tm_onGyro = false;\n\tmoveSpeed = 0;\n\tprevAbsBias = 0;\n}\n\nvoid Chassis::InitDefaultCommand()\n{\n\t\/\/ Set the default command for a subsystem here.\n\tSetDefaultCommand(new DefaultDrive());\n}\n\n\/\/Arcade Drives with the values of move as the forward value, and turn as the turning value\nvoid Chassis::Drive(double moveL, double moveR, bool quad)\n{\n\tm_drive->TankDrive(moveL, moveR, quad);\n}\n\nvoid Chassis::DriveArcade(double move, double turn, bool squaredInputs)\n{\n\n\tm_drive->ArcadeDrive(move, turn, squaredInputs);\n}\n\nvoid Chassis::Shift(bool shiftDown)\n{\n\tm_shifter->Set(shiftDown);\n\tm_bShiftedLow = shiftDown;\n}\n\ndouble Chassis::GetSpeedL()\n{\n\treturn m_leftMotorFront->GetSpeed() * InchesPerRev \/ 50.0;\n}\n\ndouble Chassis::GetSpeedR()\n{\n\treturn m_rightMotorFront->GetSpeed() * InchesPerRev \/ 50.0;\n}\n\ndouble Chassis::GetSpeed()\n{\n\treturn ( GetSpeedL() + GetSpeedR() ) \/ 2.0;\n}\n\ndouble Chassis::GetDistanceL()\n{\n\treturn m_leftMotorFront->GetPosition() * InchesPerRev;\n}\n\ndouble Chassis::GetDistanceR()\n{\n\treturn m_rightMotorFront->GetPosition() * InchesPerRev;\n}\n\ndouble Chassis::GetDistance()\n{\n\treturn ( GetDistanceL() + GetDistanceR() ) \/ 2.0;\n}\n\ndouble Chassis::GetAngle(bool forceGyro)\n{\n\t\/\/if((m_onGyro || forceGyro) && m_bNavXPresent)\n\tif(m_bNavXPresent)\t\t\t\t\t\t\t\t\t\/\/Always gyro unless not present\n\t{\n\t\t\/\/Angle use wants a faster, more accurate, but drifting angle, for quick use.\n\t\treturn -m_navX->GetAngle();\n\t}\n\telse {\n\t\t\/\/Means that angle use wants a driftless angle measure that lasts.\n\t\treturn ( GetDistanceR() - GetDistanceL() ) * 180 \/ (Preferences::GetInstance()->GetDouble(\"ChassisWidth\",28.55) * M_PI);\n\t\t\/*\n\t\t * Angle is 180 degrees times encoder difference over Pi * the distance between the wheels\n\t\t *\tMade from geometry and relation between angle fraction and arc fraction with semicircles.\n\t\t *\/\n\t}\n}\n\ndouble Chassis::ReturnPIDInput()\n{\n\treturn GetAngle();\n}\n\nvoid Chassis::UsePIDOutput(double bias)\n{\n\t\/\/ Chassis ramp rate is the limit on the voltage change per cycle to prevent skidding.\n\tconst double speedLimit = prevAbsBias + Preferences::GetInstance()->GetDouble(\"ChassisRampRate\", 0.25);\n\tif(bias > speedLimit) bias = speedLimit;\n\tif(bias < -speedLimit) bias = -speedLimit;\n\tdouble speed_L = moveSpeed-bias;\n\tdouble speed_R = moveSpeed+bias;\n\tm_drive->TankDrive(speed_L, speed_R, false);\n\tprevAbsBias = fabs(bias);\n}\n\nvoid Chassis::ReleaseAngle()\n{\n\tGetPIDController()->Disable();\n\tm_onPID=false;\n\tm_onGyro=false;\t\t\/\/Gyro needs to be explicitly enabled for each PID turn\n\tprevAbsBias=0;\n}\n\nvoid Chassis::ResetEncoders()\n{\n\tm_leftMotorFront->SetPosition(0);\n\tm_rightMotorFront->SetPosition(0);\n}\n\nvoid Chassis::HoldAngle(double angle, bool gyro)\n{\n\tif(!m_onPID) m_onGyro = gyro;\t\t\/\/Prevent changing angle mode when already in a turn\n\tSetPIDValues();\n\tGetPIDController()->SetSetpoint(GetAngle() + angle);\n\tGetPIDController()->Enable();\n\tm_onPID = true;\n}\n\nvoid Chassis::SetPIDValues()\n{\n\tif(m_bShiftedLow){\n\t\tGetPIDController()->SetPID(\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisHighP\",0.075),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisHighI\",0.01),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisHighD\",0.09)\n\t\t);\n\t}else{\n\t\tGetPIDController()->SetPID(\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisLowP\", 0.085),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisLowI\", 0.02),\n\t\t\t\tPreferences::GetInstance()->GetDouble(\"ChassisLowD\", 0.125)\n\t\t);\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * AliEmcalAnalysisFactory.cxx\n *\n * Created on: Feb 23, 2016\n * Author: markus\n *\/\n\n#include \"AliAODTrack.h\"\n#include \"AliESDtrackCuts.h\"\n#include \"AliEmcalTrackSelection.h\"\n#include \"AliEmcalTrackSelectionESD.h\"\n#include \"AliEmcalTrackSelectionAOD.h\"\n#include \"AliEmcalTriggerOfflineSelection.h\"\n#include \"AliEMCalTriggerExtraCuts.h\"\n\n#include \"AliEmcalAnalysisFactory.h\"\n\nClassImp(EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory)\n\nnamespace EMCalTriggerPtAnalysis {\n\nAliEmcalTrackSelection *AliEmcalAnalysisFactory::TrackCutsFactory(TString cut, Bool_t aod){\n AliEmcalTrackSelection *result = NULL;\n if(!aod){\n AliESDtrackCuts *esdcuts = NULL;\n if(cut == \"standard\"){\n AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(true, 1);\n esdcuts->DefineHistograms(kRed);\n esdcuts->SetName(\"Standard Track cuts\");\n esdcuts->SetMinNCrossedRowsTPC(120);\n esdcuts->SetMaxDCAToVertexXYPtDep(\"0.0182+0.0350\/pt^1.01\");\n } else if(cut == \"hybrid\"){\n esdcuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE);\n esdcuts->SetName(\"Global Hybrid tracks, loose DCA\");\n esdcuts->SetMaxDCAToVertexXY(2.4);\n esdcuts->SetMaxDCAToVertexZ(3.2);\n esdcuts->SetDCAToVertex2D(kTRUE);\n esdcuts->SetMaxChi2TPCConstrainedGlobal(36);\n esdcuts->SetMaxFractionSharedTPCClusters(0.4);\n }\n result = new AliEmcalTrackSelectionESD;\n result->AddTrackCuts(esdcuts);\n } else {\n AliEmcalTrackSelectionAOD *aodsel = new AliEmcalTrackSelectionAOD;\n result = aodsel;\n if(cut == \"standard\"){\n aodsel->AddFilterBit(AliAODTrack::kTrkGlobal);\n AliEMCalTriggerExtraCuts *extracuts = new AliEMCalTriggerExtraCuts;\n extracuts->SetMinTPCCrossedRows(120);\n aodsel->AddTrackCuts(extracuts);\n } else if(cut == \"hybrid\"){\n aodsel->AddFilterBit(256);\n aodsel->AddFilterBit(512);\n }\n }\n\n return result;\n}\n\nAliEmcalTriggerOfflineSelection *AliEmcalAnalysisFactory::TriggerSelectionFactory(Double_t el0, Double_t eg1, Double_t eg2, Double_t ej1, Double_t ej2){\n AliEmcalTriggerOfflineSelection *result = new AliEmcalTriggerOfflineSelection;\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEL0, el0);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEG1, eg1);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEG2, eg1);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEJ1, ej1);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEJ2, ej2);\n return result;\n}\n\n} \/* namespace EMCalTriggerPtAnalysis *\/\nFix missing assignment in the track selection factory\/*\n * AliEmcalAnalysisFactory.cxx\n *\n * Created on: Feb 23, 2016\n * Author: markus\n *\/\n\n#include \"AliAODTrack.h\"\n#include \"AliESDtrackCuts.h\"\n#include \"AliEmcalTrackSelection.h\"\n#include \"AliEmcalTrackSelectionESD.h\"\n#include \"AliEmcalTrackSelectionAOD.h\"\n#include \"AliEmcalTriggerOfflineSelection.h\"\n#include \"AliEMCalTriggerExtraCuts.h\"\n\n#include \"AliEmcalAnalysisFactory.h\"\n\nClassImp(EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory)\n\nnamespace EMCalTriggerPtAnalysis {\n\nAliEmcalTrackSelection *AliEmcalAnalysisFactory::TrackCutsFactory(TString cut, Bool_t aod){\n AliEmcalTrackSelection *result = NULL;\n if(!aod){\n AliESDtrackCuts *esdcuts = NULL;\n if(cut == \"standard\"){\n esdcuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(true, 1);\n esdcuts->DefineHistograms(kRed);\n esdcuts->SetName(\"Standard Track cuts\");\n esdcuts->SetMinNCrossedRowsTPC(120);\n esdcuts->SetMaxDCAToVertexXYPtDep(\"0.0182+0.0350\/pt^1.01\");\n } else if(cut == \"hybrid\"){\n esdcuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE);\n esdcuts->SetName(\"Global Hybrid tracks, loose DCA\");\n esdcuts->SetMaxDCAToVertexXY(2.4);\n esdcuts->SetMaxDCAToVertexZ(3.2);\n esdcuts->SetDCAToVertex2D(kTRUE);\n esdcuts->SetMaxChi2TPCConstrainedGlobal(36);\n esdcuts->SetMaxFractionSharedTPCClusters(0.4);\n }\n result = new AliEmcalTrackSelectionESD;\n result->AddTrackCuts(esdcuts);\n } else {\n AliEmcalTrackSelectionAOD *aodsel = new AliEmcalTrackSelectionAOD;\n result = aodsel;\n if(cut == \"standard\"){\n aodsel->AddFilterBit(AliAODTrack::kTrkGlobal);\n AliEMCalTriggerExtraCuts *extracuts = new AliEMCalTriggerExtraCuts;\n extracuts->SetMinTPCCrossedRows(120);\n aodsel->AddTrackCuts(extracuts);\n } else if(cut == \"hybrid\"){\n aodsel->AddFilterBit(256);\n aodsel->AddFilterBit(512);\n }\n }\n\n return result;\n}\n\nAliEmcalTriggerOfflineSelection *AliEmcalAnalysisFactory::TriggerSelectionFactory(Double_t el0, Double_t eg1, Double_t eg2, Double_t ej1, Double_t ej2){\n AliEmcalTriggerOfflineSelection *result = new AliEmcalTriggerOfflineSelection;\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEL0, el0);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEG1, eg1);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEG2, eg1);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEJ1, ej1);\n result->SetOfflineEnergyThreshold(AliEmcalTriggerOfflineSelection::kTrgEJ2, ej2);\n return result;\n}\n\n} \/* namespace EMCalTriggerPtAnalysis *\/\n<|endoftext|>"} {"text":"\/**\n * \\file\n * \\brief ThreadList class header\n *\n * \\author Copyright (C) 2014-2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLIST_HPP_\n#define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLIST_HPP_\n\n#include \"distortos\/internal\/scheduler\/ThreadListNode.hpp\"\n\n#include \"estd\/SortedIntrusiveList.hpp\"\n\nnamespace distortos\n{\n\nnamespace internal\n{\n\nclass ThreadControlBlock;\n\n\/\/\/ functor which gives descending effective priority order of elements on the list\nstruct ThreadDescendingEffectivePriority\n{\n\t\/**\n\t * \\brief ThreadDescendingEffectivePriority's constructor\n\t *\/\n\n\tconstexpr ThreadDescendingEffectivePriority()\n\t{\n\n\t}\n\n\t\/**\n\t * \\brief ThreadDescendingEffectivePriority's function call operator\n\t *\n\t * \\param [in] left is the object on the left-hand side of comparison\n\t * \\param [in] right is the object on the right-hand side of comparison\n\t *\n\t * \\return true if left's effective priority is less than right's effective priority\n\t *\/\n\n\tbool operator()(const ThreadListNode& left, const ThreadListNode& right) const\n\t{\n\t\treturn left.getEffectivePriority() < right.getEffectivePriority();\n\t}\n};\n\n\/\/\/ sorted intrusive list of threads (thread control blocks)\nclass ThreadList : public estd::SortedIntrusiveList\n{\n\n};\n\n}\t\/\/ namespace internal\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLIST_HPP_\nAdd constructor to ThreadList\/**\n * \\file\n * \\brief ThreadList class header\n *\n * \\author Copyright (C) 2014-2018 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLIST_HPP_\n#define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLIST_HPP_\n\n#include \"distortos\/internal\/scheduler\/ThreadListNode.hpp\"\n\n#include \"estd\/SortedIntrusiveList.hpp\"\n\nnamespace distortos\n{\n\nnamespace internal\n{\n\nclass ThreadControlBlock;\n\n\/\/\/ functor which gives descending effective priority order of elements on the list\nstruct ThreadDescendingEffectivePriority\n{\n\t\/**\n\t * \\brief ThreadDescendingEffectivePriority's constructor\n\t *\/\n\n\tconstexpr ThreadDescendingEffectivePriority()\n\t{\n\n\t}\n\n\t\/**\n\t * \\brief ThreadDescendingEffectivePriority's function call operator\n\t *\n\t * \\param [in] left is the object on the left-hand side of comparison\n\t * \\param [in] right is the object on the right-hand side of comparison\n\t *\n\t * \\return true if left's effective priority is less than right's effective priority\n\t *\/\n\n\tbool operator()(const ThreadListNode& left, const ThreadListNode& right) const\n\t{\n\t\treturn left.getEffectivePriority() < right.getEffectivePriority();\n\t}\n};\n\n\/\/\/ sorted intrusive list of threads (thread control blocks)\nclass ThreadList : public estd::SortedIntrusiveList\n{\npublic:\n\n\t\/**\n\t * \\brief ThreadList's constructor\n\t *\/\n\n\tconstexpr ThreadList() :\n\t\t\tSortedIntrusiveList{}\n\t{\n\n\t}\n};\n\n}\t\/\/ namespace internal\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLIST_HPP_\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2003, Magnus Jonsson\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCATE_RESOURCES_IMPL_HPP_INCLUDED\n#define TORRENT_ALLOCATE_RESOURCES_IMPL_HPP_INCLUDED\n\n#include \n#include \n\n#include \n\n#include \"libtorrent\/resource_request.hpp\"\n#include \"libtorrent\/peer_id.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/size_type.hpp\"\n\nnamespace libtorrent\n{\n\n\tint saturated_add(int a, int b);\n\n\tnamespace aux\n\t{\n\t\t\/\/ give num_resources to r,\n\t\t\/\/ return how how many were actually accepted.\n\t\tinline int give(resource_request& r, int num_resources)\n\t\t{\n\t\t\tassert(num_resources >= 0);\n\t\t\tassert(r.given <= r.max);\n\t\t\t\n\t\t\tint accepted = std::min(num_resources, r.max - r.given);\n\t\t\tassert(accepted >= 0);\n\n\t\t\tr.given += accepted;\n\t\t\tassert(r.given <= r.max);\n\n\t\t\treturn accepted;\n\t\t}\n\n#ifndef NDEBUG\n\n\t\ttemplate\n\t\tclass allocate_resources_contract_check\n\t\t{\n\t\t\tint m_resources;\n\t\t\tIt m_start;\n\t\t\tIt m_end;\n\t\t\tresource_request T::* m_res;\n\n\t\tpublic:\n\t\t\tallocate_resources_contract_check(\n\t\t\t\tint resources\n\t\t\t\t, It start\n\t\t\t\t, It end\n\t\t\t\t, resource_request T::* res)\n\t\t\t\t: m_resources(resources)\n\t\t\t\t, m_start(start)\n\t\t\t\t, m_end(end)\n\t\t\t\t, m_res(res)\n\t\t\t{\n\t\t\t\tassert(m_resources >= 0);\n\t\t\t\tfor (It i = m_start, end(m_end); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tassert(((*i).*m_res).max >= 0);\n\t\t\t\t\tassert(((*i).*m_res).given >= 0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t~allocate_resources_contract_check()\n\t\t\t{\n\t\t\t\tint sum_given = 0;\n\t\t\t\tint sum_max = 0;\n\t\t\t\tint sum_min = 0;\n\t\t\t\tfor (It i = m_start, end(m_end); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tassert(((*i).*m_res).max >= 0);\n\t\t\t\t\tassert(((*i).*m_res).min >= 0);\n\t\t\t\t\tassert(((*i).*m_res).max >= ((*i).*m_res).min);\n\t\t\t\t\tassert(((*i).*m_res).given >= 0);\n\t\t\t\t\tassert(((*i).*m_res).given <= ((*i).*m_res).max);\n\n\t\t\t\t\tsum_given = saturated_add(sum_given, ((*i).*m_res).given);\n\t\t\t\t\tsum_max = saturated_add(sum_max, ((*i).*m_res).max);\n\t\t\t\t\tsum_min = saturated_add(sum_min, ((*i).*m_res).min);\n\t\t\t\t}\n\t\t\t\tassert(sum_given == std::min(std::max(m_resources, sum_min), sum_max));\n\t\t\t}\n\t\t};\n\n#endif\n\n\t\ttemplate\n\t\tvoid allocate_resources_impl(\n\t\t\tint resources\n\t\t\t, It start\n\t\t\t, It end\n\t\t\t, resource_request T::* res)\n\t\t{\n\t\t\tassert(resources >= 0);\n\t#ifndef NDEBUG\n\t\t\tallocate_resources_contract_check contract_check(\n\t\t\t\tresources\n\t\t\t\t, start\n\t\t\t\t, end\n\t\t\t\t, res);\n\t#endif\n\n\t\t\tif (resources == resource_request::inf)\n\t\t\t{\n\t\t\t\t\/\/ No competition for resources.\n\t\t\t\t\/\/ Just give everyone what they want.\n\t\t\t\tfor (It i = start; i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\t((*i).*res).given = ((*i).*res).max;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Resources are scarce\n\n\t\t\tint sum_max = 0;\n\t\t\tint sum_min = 0;\n\t\t\tfor (It i = start; i != end; ++i)\n\t\t\t{\n\t\t\t\tsum_max = saturated_add(sum_max, ((*i).*res).max);\n\t\t\t\tassert(((*i).*res).min < resource_request::inf);\n\t\t\t\tassert(((*i).*res).min >= 0);\n\t\t\t\tassert(((*i).*res).min <= ((*i).*res).max);\n\t\t\t\tsum_min += ((*i).*res).min;\n\t\t\t\t((*i).*res).given = ((*i).*res).min;\n\t\t\t}\n\n\t\t\tif (resources == 0 || sum_max == 0)\n\t\t\t\treturn;\n\n\t\t\tresources = std::max(resources, sum_min);\n\t\t\tint resources_to_distribute = std::min(resources, sum_max) - sum_min;\n\t\t\tassert(resources_to_distribute >= 0);\n#ifndef NDEBUG\n\t\t\tint prev_resources_to_distribute = resources_to_distribute;\n#endif\n\t\t\twhile (resources_to_distribute > 0)\n\t\t\t{\n\t\t\t\tsize_type total_used = 0;\n\t\t\t\tsize_type max_used = 0;\n\t\t\t\tfor (It i = start; i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tresource_request& r = (*i).*res;\n\t\t\t\t\tif(r.given == r.max) continue;\n\n\t\t\t\t\tassert(r.given < r.max);\n\n\t\t\t\t\tmax_used = std::max(max_used, (size_type)r.used + 1);\n\t\t\t\t\ttotal_used += (size_type)r.used + 1;\n\t\t\t\t}\n\n\t\t\t\tsize_type kNumer = resources_to_distribute;\n\t\t\t\tsize_type kDenom = total_used;\n\t\t\t\tassert(kNumer >= 0);\n\t\t\t\tassert(kDenom >= 0);\n\t\t\t\tassert(kNumer <= std::numeric_limits::max());\n\t\t\t\tassert(total_used < std::numeric_limits::max());\n\n\t\t\t\tif (kNumer * max_used <= kDenom)\n\t\t\t\t{\n\t\t\t\t\tkNumer = 1;\n\t\t\t\t\tkDenom = max_used;\n\t\t\t\t\tassert(kDenom >= 0);\n\t\t\t\t\tassert(kDenom <= std::numeric_limits::max());\n\t\t\t\t}\n\n\t\t\t\tfor (It i = start; i != end && resources_to_distribute > 0; ++i)\n\t\t\t\t{\n\t\t\t\t\tresource_request& r = (*i).*res;\n\t\t\t\t\tif (r.given == r.max) continue;\n\n\t\t\t\t\tassert(r.given < r.max);\n\n\t\t\t\t\tsize_type used = (size_type)r.used + 1;\n\t\t\t\t\tif (used < 1) used = 1;\n\t\t\t\t\tsize_type to_give = used * kNumer \/ kDenom;\n\t\t\t\t\tif (to_give > resources_to_distribute)\n\t\t\t\t\t\tto_give = resources_to_distribute;\n\t\t\t\t\tassert(to_give >= 0);\n\t\t\t\t\tassert(to_give <= resources_to_distribute);\n\t\t\t\t\tresources_to_distribute -= give(r, (int)to_give);\n\t\t\t\t\tassert(resources_to_distribute >= 0);\n\t\t\t\t}\n\n\t\t\t\tassert(resources_to_distribute >= 0);\n\t\t\t\tassert(resources_to_distribute < prev_resources_to_distribute);\n#ifndef NDEBUG\n\t\t\t\tprev_resources_to_distribute = resources_to_distribute;\n#endif\n\t\t\t}\n\t\t}\n\n\t} \/\/ namespace libtorrent::aux\n}\n\n\n#endif\nadded msvc workarounds\/*\n\nCopyright (c) 2003, Magnus Jonsson\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCATE_RESOURCES_IMPL_HPP_INCLUDED\n#define TORRENT_ALLOCATE_RESOURCES_IMPL_HPP_INCLUDED\n\n#include \n#include \n\n#include \n\n#include \"libtorrent\/resource_request.hpp\"\n#include \"libtorrent\/peer_id.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/size_type.hpp\"\n\n#ifdef min\n#undef min\n#endif\n\n#ifdef max\n#undef max\n#endif\n\nnamespace libtorrent\n{\n\n\tint saturated_add(int a, int b);\n\n\tnamespace aux\n\t{\n\t\t\/\/ give num_resources to r,\n\t\t\/\/ return how how many were actually accepted.\n\t\tinline int give(resource_request& r, int num_resources)\n\t\t{\n\t\t\tassert(num_resources >= 0);\n\t\t\tassert(r.given <= r.max);\n\t\t\t\n\t\t\tint accepted = (std::min)(num_resources, r.max - r.given);\n\t\t\tassert(accepted >= 0);\n\n\t\t\tr.given += accepted;\n\t\t\tassert(r.given <= r.max);\n\n\t\t\treturn accepted;\n\t\t}\n\n#ifndef NDEBUG\n\n\t\ttemplate\n\t\tclass allocate_resources_contract_check\n\t\t{\n\t\t\tint m_resources;\n\t\t\tIt m_start;\n\t\t\tIt m_end;\n\t\t\tresource_request T::* m_res;\n\n\t\tpublic:\n\t\t\tallocate_resources_contract_check(\n\t\t\t\tint resources\n\t\t\t\t, It start\n\t\t\t\t, It end\n\t\t\t\t, resource_request T::* res)\n\t\t\t\t: m_resources(resources)\n\t\t\t\t, m_start(start)\n\t\t\t\t, m_end(end)\n\t\t\t\t, m_res(res)\n\t\t\t{\n\t\t\t\tassert(m_resources >= 0);\n\t\t\t\tfor (It i = m_start, end(m_end); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tassert(((*i).*m_res).max >= 0);\n\t\t\t\t\tassert(((*i).*m_res).given >= 0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t~allocate_resources_contract_check()\n\t\t\t{\n\t\t\t\tint sum_given = 0;\n\t\t\t\tint sum_max = 0;\n\t\t\t\tint sum_min = 0;\n\t\t\t\tfor (It i = m_start, end(m_end); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tassert(((*i).*m_res).max >= 0);\n\t\t\t\t\tassert(((*i).*m_res).min >= 0);\n\t\t\t\t\tassert(((*i).*m_res).max >= ((*i).*m_res).min);\n\t\t\t\t\tassert(((*i).*m_res).given >= 0);\n\t\t\t\t\tassert(((*i).*m_res).given <= ((*i).*m_res).max);\n\n\t\t\t\t\tsum_given = saturated_add(sum_given, ((*i).*m_res).given);\n\t\t\t\t\tsum_max = saturated_add(sum_max, ((*i).*m_res).max);\n\t\t\t\t\tsum_min = saturated_add(sum_min, ((*i).*m_res).min);\n\t\t\t\t}\n\t\t\t\tassert(sum_given == (std::min)(std::max(m_resources, sum_min), sum_max));\n\t\t\t}\n\t\t};\n\n#endif\n\n\t\ttemplate\n\t\tvoid allocate_resources_impl(\n\t\t\tint resources\n\t\t\t, It start\n\t\t\t, It end\n\t\t\t, resource_request T::* res)\n\t\t{\n\t\t\tassert(resources >= 0);\n\t#ifndef NDEBUG\n\t\t\tallocate_resources_contract_check contract_check(\n\t\t\t\tresources\n\t\t\t\t, start\n\t\t\t\t, end\n\t\t\t\t, res);\n\t#endif\n\n\t\t\tif (resources == resource_request::inf)\n\t\t\t{\n\t\t\t\t\/\/ No competition for resources.\n\t\t\t\t\/\/ Just give everyone what they want.\n\t\t\t\tfor (It i = start; i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\t((*i).*res).given = ((*i).*res).max;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Resources are scarce\n\n\t\t\tint sum_max = 0;\n\t\t\tint sum_min = 0;\n\t\t\tfor (It i = start; i != end; ++i)\n\t\t\t{\n\t\t\t\tsum_max = saturated_add(sum_max, ((*i).*res).max);\n\t\t\t\tassert(((*i).*res).min < resource_request::inf);\n\t\t\t\tassert(((*i).*res).min >= 0);\n\t\t\t\tassert(((*i).*res).min <= ((*i).*res).max);\n\t\t\t\tsum_min += ((*i).*res).min;\n\t\t\t\t((*i).*res).given = ((*i).*res).min;\n\t\t\t}\n\n\t\t\tif (resources == 0 || sum_max == 0)\n\t\t\t\treturn;\n\n\t\t\tresources = (std::max)(resources, sum_min);\n\t\t\tint resources_to_distribute = (std::min)(resources, sum_max) - sum_min;\n\t\t\tassert(resources_to_distribute >= 0);\n#ifndef NDEBUG\n\t\t\tint prev_resources_to_distribute = resources_to_distribute;\n#endif\n\t\t\twhile (resources_to_distribute > 0)\n\t\t\t{\n\t\t\t\tsize_type total_used = 0;\n\t\t\t\tsize_type max_used = 0;\n\t\t\t\tfor (It i = start; i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tresource_request& r = (*i).*res;\n\t\t\t\t\tif(r.given == r.max) continue;\n\n\t\t\t\t\tassert(r.given < r.max);\n\n\t\t\t\t\tmax_used = (std::max)(max_used, (size_type)r.used + 1);\n\t\t\t\t\ttotal_used += (size_type)r.used + 1;\n\t\t\t\t}\n\n\t\t\t\tsize_type kNumer = resources_to_distribute;\n\t\t\t\tsize_type kDenom = total_used;\n\t\t\t\tassert(kNumer >= 0);\n\t\t\t\tassert(kDenom >= 0);\n\t\t\t\tassert(kNumer <= (std::numeric_limits::max)());\n\t\t\t\tassert(total_used < (std::numeric_limits::max)());\n\n\t\t\t\tif (kNumer * max_used <= kDenom)\n\t\t\t\t{\n\t\t\t\t\tkNumer = 1;\n\t\t\t\t\tkDenom = max_used;\n\t\t\t\t\tassert(kDenom >= 0);\n\t\t\t\t\tassert(kDenom <= (std::numeric_limits::max)());\n\t\t\t\t}\n\n\t\t\t\tfor (It i = start; i != end && resources_to_distribute > 0; ++i)\n\t\t\t\t{\n\t\t\t\t\tresource_request& r = (*i).*res;\n\t\t\t\t\tif (r.given == r.max) continue;\n\n\t\t\t\t\tassert(r.given < r.max);\n\n\t\t\t\t\tsize_type used = (size_type)r.used + 1;\n\t\t\t\t\tif (used < 1) used = 1;\n\t\t\t\t\tsize_type to_give = used * kNumer \/ kDenom;\n\t\t\t\t\tif (to_give > resources_to_distribute)\n\t\t\t\t\t\tto_give = resources_to_distribute;\n\t\t\t\t\tassert(to_give >= 0);\n\t\t\t\t\tassert(to_give <= resources_to_distribute);\n\t\t\t\t\tresources_to_distribute -= give(r, (int)to_give);\n\t\t\t\t\tassert(resources_to_distribute >= 0);\n\t\t\t\t}\n\n\t\t\t\tassert(resources_to_distribute >= 0);\n\t\t\t\tassert(resources_to_distribute < prev_resources_to_distribute);\n#ifndef NDEBUG\n\t\t\t\tprev_resources_to_distribute = resources_to_distribute;\n#endif\n\t\t\t}\n\t\t}\n\n\t} \/\/ namespace libtorrent::aux\n}\n\n\n#endif\n<|endoftext|>"} {"text":"\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš \n\n This file is part of Magnum.\n\n Magnum 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 Magnum 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*\/\n\n#include \"Atlas.h\"\n\n#include \"Math\/Geometry\/Rectangle.h\"\n\nnamespace Magnum { namespace TextureTools {\n\nstd::vector atlas(const Vector2i& atlasSize, const std::vector& sizes) {\n if(sizes.empty()) return {};\n\n \/* Size of largest texture *\/\n Vector2i maxSize;\n for(const Vector2i& size: sizes) {\n \/** @todo max() for vector types *\/\n if(size.x() > maxSize.x()) maxSize.x() = size.x();\n if(size.y() > maxSize.y()) maxSize.y() = size.y();\n }\n\n std::vector atlas;\n\n \/* Columns and rows *\/\n Vector2i gridSize = atlasSize\/maxSize;\n if(std::size_t(gridSize.product()) < sizes.size()) {\n Error() << \"TextureTools::Atlas::create(): requested atlas size\"\n << atlasSize << \"is too small to fit\" << sizes.size()\n << maxSize << \"textures. Generated atlas will be empty.\";\n return atlas;\n }\n\n \/** @todo actual magic implementation, not this joke *\/\n\n atlas.reserve(sizes.size());\n for(std::size_t i = 0; i != sizes.size(); ++i)\n atlas.push_back(Rectanglei::fromSize(Vector2i(i%gridSize.x(), i\/gridSize.x())*maxSize, sizes[i]));\n\n return atlas;\n}\n\n}}\nTextureTools: use Math::max() instead of doing it by hand.\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš \n\n This file is part of Magnum.\n\n Magnum 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 Magnum 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*\/\n\n#include \"Atlas.h\"\n\n#include \"Math\/Functions.h\"\n#include \"Math\/Geometry\/Rectangle.h\"\n\nnamespace Magnum { namespace TextureTools {\n\nstd::vector atlas(const Vector2i& atlasSize, const std::vector& sizes) {\n if(sizes.empty()) return {};\n\n \/* Size of largest texture *\/\n Vector2i maxSize;\n for(const Vector2i& size: sizes)\n maxSize = Math::max(maxSize, size);\n\n std::vector atlas;\n\n \/* Columns and rows *\/\n Vector2i gridSize = atlasSize\/maxSize;\n if(std::size_t(gridSize.product()) < sizes.size()) {\n Error() << \"TextureTools::Atlas::create(): requested atlas size\"\n << atlasSize << \"is too small to fit\" << sizes.size()\n << maxSize << \"textures. Generated atlas will be empty.\";\n return atlas;\n }\n\n \/** @todo actual magic implementation, not this joke *\/\n\n atlas.reserve(sizes.size());\n for(std::size_t i = 0; i != sizes.size(); ++i)\n atlas.push_back(Rectanglei::fromSize(Vector2i(i%gridSize.x(), i\/gridSize.x())*maxSize, sizes[i]));\n\n return atlas;\n}\n\n}}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2013 Martin Klapetek \n Copyright (C) 2014 David Edmundson \n\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 as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"im-persons-data-source.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"KTp\/contact-factory.h\"\n#include \"KTp\/global-contact-manager.h\"\n#include \"KTp\/types.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace KPeople;\n\n\nclass KTpAllContacts : public AllContactsMonitor\n{\n Q_OBJECT\npublic:\n KTpAllContacts();\n ~KTpAllContacts();\n virtual KABC::Addressee::Map contacts();\n\nprivate Q_SLOTS:\n void loadCache();\n void onAccountManagerReady(Tp::PendingOperation *op);\n void onContactChanged();\n void onContactInvalidated();\n void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);\n\nprivate:\n QString createUri(const KTp::ContactPtr &contact) const;\n KABC::Addressee contactToAddressee(const Tp::ContactPtr &contact) const;\n QHash m_contacts;\n KABC::Addressee::Map m_contactVCards;\n};\n\nKTpAllContacts::KTpAllContacts()\n{\n Tp::registerTypes();\n\n QTimer::singleShot(0, this, SLOT(loadCache()));\n}\n\nKTpAllContacts::~KTpAllContacts()\n{\n}\n\nvoid KTpAllContacts::loadCache()\n{\n QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String(\"QSQLITE\"), QLatin1String(\"ktpCache\"));\n db.setDatabaseName(KGlobal::dirs()->locateLocal(\"data\", QLatin1String(\"ktp\/cache.db\")));\n db.open();\n\n QSqlQuery query(QLatin1String(\"SELECT accountId, contactId, alias, avatarFileName FROM contacts\"), db);\n\n query.exec();\n\n while (query.next()) {\n KABC::Addressee addressee;\n\n const QString accountId = query.value(0).toString();\n const QString contactId = query.value(1).toString();\n addressee.setFormattedName(query.value(2).toString());\n addressee.setPhoto(KABC::Picture(query.value(3).toString()));\n\n addressee.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"contactId\"), contactId);\n addressee.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"accountPath\"), accountId);\n addressee.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"presence\"), QLatin1String(\"offline\"));\n\n const QString uri = QLatin1String(\"ktp:\/\/\") + accountId + QLatin1Char('?') + contactId;\n\n m_contactVCards[uri] = addressee;\n Q_EMIT contactAdded(uri, addressee);\n }\n\n \/\/now start fetching the up-to-date information\n connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));\n\n emitInitialFetchComplete();\n}\n\n\nQString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const\n{\n \/\/ so real ID will look like\n \/\/ ktp:\/\/gabble\/jabber\/blah\/asdfjwer?foo@bar.com\n \/\/ ? is used as it is not a valid character in the dbus path that makes up the account UID\n return QLatin1String(\"ktp:\/\/\") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id();\n}\n\nvoid KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Failed to initialize AccountManager:\" << op->errorName();\n kWarning() << op->errorMessage();\n\n return;\n }\n\n kDebug() << \"Account manager ready\";\n\n connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),\n this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));\n\n onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());\n}\n\nvoid KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)\n{\n if (!m_contacts.isEmpty()) {\n Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) {\n const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);\n const QString uri = createUri(contact);\n m_contacts.remove(uri);\n m_contactVCards.remove(uri);\n Q_EMIT contactRemoved(uri);\n }\n }\n\n Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {\n KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);\n const QString uri = createUri(ktpContact);\n\n const KABC::Addressee vcard = contactToAddressee(contact);\n\n m_contacts.insert(uri, ktpContact);\n\n \/\/TODO OPTIMISATION if we already exist we shouldn't create a whole new KABC object, just update the existing one\n \/\/onContactChanged should be split into the relevant onAliasChanged etc.\n if (m_contactVCards.contains(uri)) {\n m_contactVCards[uri] = vcard;\n Q_EMIT contactChanged(uri, vcard);\n } else {\n m_contactVCards.insert(uri, vcard);\n Q_EMIT contactAdded(uri, vcard);\n }\n\n connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(invalidated()),\n this, SLOT(onContactInvalidated()));\n\n connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),\n this, SLOT(onContactChanged()));\n }\n}\n\nvoid KTpAllContacts::onContactChanged()\n{\n const KTp::ContactPtr contact(qobject_cast(sender()));\n m_contactVCards.insert(createUri(contact), contactToAddressee(contact));\n Q_EMIT contactChanged(createUri(contact), contactToAddressee(contact));\n}\n\nvoid KTpAllContacts::onContactInvalidated()\n{\n const KTp::ContactPtr contact(qobject_cast(sender()));\n const QString uri = createUri(contact);\n\n m_contacts.remove(uri);\n\n \/\/set to offline and emit changed\n KABC::Addressee &vcard = m_contactVCards[uri];\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"presence\"), QLatin1String(\"offline\"));\n Q_EMIT contactChanged(uri, vcard);\n}\n\nKABC::Addressee::Map KTpAllContacts::contacts()\n{\n return m_contactVCards;\n}\n\nKABC::Addressee KTpAllContacts::contactToAddressee(const Tp::ContactPtr &contact) const\n{\n KABC::Addressee vcard;\n Tp::AccountPtr account = KTp::contactManager()->accountForContact(contact);\n if (contact && account) {\n vcard.setFormattedName(contact->alias());\n vcard.setCategories(contact->groups());\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"contactId\"), contact->id());\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"accountPath\"), account->objectPath());\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"presence\"), contact->presence().status());\n if (!contact->avatarData().fileName.isEmpty()) {\n vcard.setPhoto(KABC::Picture(contact->avatarData().fileName));\n }\n }\n return vcard;\n}\n\nIMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)\n : BasePersonsDataSource(parent)\n{\n Q_UNUSED(args);\n}\n\nIMPersonsDataSource::~IMPersonsDataSource()\n{\n}\n\nQString IMPersonsDataSource::sourcePluginId() const\n{\n return QLatin1String(\"ktp\");\n}\n\nAllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()\n{\n return new KTpAllContacts();\n}\n\nK_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin(); )\nK_EXPORT_PLUGIN( IMPersonsDataSourceFactory(\"im_persons_data_source_plugin\") )\n\n\n#include \"im-persons-data-source.moc\"KPeople plugin: Implemented groups cache support.\/*\n Copyright (C) 2013 Martin Klapetek \n Copyright (C) 2014 David Edmundson \n\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 as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"im-persons-data-source.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"KTp\/contact-factory.h\"\n#include \"KTp\/global-contact-manager.h\"\n#include \"KTp\/types.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace KPeople;\n\n\nclass KTpAllContacts : public AllContactsMonitor\n{\n Q_OBJECT\npublic:\n KTpAllContacts();\n ~KTpAllContacts();\n virtual KABC::Addressee::Map contacts();\n\nprivate Q_SLOTS:\n void loadCache();\n void onAccountManagerReady(Tp::PendingOperation *op);\n void onContactChanged();\n void onContactInvalidated();\n void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);\n\nprivate:\n QString createUri(const KTp::ContactPtr &contact) const;\n KABC::Addressee contactToAddressee(const Tp::ContactPtr &contact) const;\n QHash m_contacts;\n KABC::Addressee::Map m_contactVCards;\n};\n\nKTpAllContacts::KTpAllContacts()\n{\n Tp::registerTypes();\n\n QTimer::singleShot(0, this, SLOT(loadCache()));\n}\n\nKTpAllContacts::~KTpAllContacts()\n{\n}\n\nvoid KTpAllContacts::loadCache()\n{\n QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String(\"QSQLITE\"), QLatin1String(\"ktpCache\"));\n db.setDatabaseName(KGlobal::dirs()->locateLocal(\"data\", QLatin1String(\"ktp\/cache.db\")));\n db.open();\n\n QSqlQuery query(db);\n query.exec(QLatin1String(\"SELECT groupName FROM groups ORDER BY groupId;\"));\n\n QStringList groupsList;\n while (query.next()) {\n groupsList.append(query.value(0).toString());\n }\n\n if (!groupsList.isEmpty()) {\n query.exec(QLatin1String(\"SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;\"));\n } else {\n query.exec(QLatin1String(\"SELECT accountId, contactId, alias, avatarFileName FROM contacts;\"));\n }\n\n while (query.next()) {\n KABC::Addressee addressee;\n\n const QString accountId = query.value(0).toString();\n const QString contactId = query.value(1).toString();\n addressee.setFormattedName(query.value(2).toString());\n addressee.setPhoto(KABC::Picture(query.value(3).toString()));\n\n if (!groupsList.isEmpty()) {\n QStringList contactGroups;\n\n Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(\",\"))) {\n bool convSuccess;\n int groupId = groupIdStr.toInt(&convSuccess);\n if ((!convSuccess) || (groupId >= groupsList.count()))\n continue;\n\n contactGroups.append(groupsList.at(groupId));\n }\n\n addressee.setCategories(contactGroups);\n }\n\n addressee.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"contactId\"), contactId);\n addressee.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"accountPath\"), accountId);\n addressee.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"presence\"), QLatin1String(\"offline\"));\n\n const QString uri = QLatin1String(\"ktp:\/\/\") + accountId + QLatin1Char('?') + contactId;\n\n m_contactVCards[uri] = addressee;\n Q_EMIT contactAdded(uri, addressee);\n }\n\n \/\/now start fetching the up-to-date information\n connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));\n\n emitInitialFetchComplete();\n}\n\nQString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const\n{\n \/\/ so real ID will look like\n \/\/ ktp:\/\/gabble\/jabber\/blah\/asdfjwer?foo@bar.com\n \/\/ ? is used as it is not a valid character in the dbus path that makes up the account UID\n return QLatin1String(\"ktp:\/\/\") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id();\n}\n\nvoid KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Failed to initialize AccountManager:\" << op->errorName();\n kWarning() << op->errorMessage();\n\n return;\n }\n\n kDebug() << \"Account manager ready\";\n\n connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),\n this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));\n\n onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());\n}\n\nvoid KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)\n{\n if (!m_contacts.isEmpty()) {\n Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) {\n const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);\n const QString uri = createUri(contact);\n m_contacts.remove(uri);\n m_contactVCards.remove(uri);\n Q_EMIT contactRemoved(uri);\n }\n }\n\n Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {\n KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);\n const QString uri = createUri(ktpContact);\n\n const KABC::Addressee vcard = contactToAddressee(contact);\n\n m_contacts.insert(uri, ktpContact);\n\n \/\/TODO OPTIMISATION if we already exist we shouldn't create a whole new KABC object, just update the existing one\n \/\/onContactChanged should be split into the relevant onAliasChanged etc.\n if (m_contactVCards.contains(uri)) {\n m_contactVCards[uri] = vcard;\n Q_EMIT contactChanged(uri, vcard);\n } else {\n m_contactVCards.insert(uri, vcard);\n Q_EMIT contactAdded(uri, vcard);\n }\n\n connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(invalidated()),\n this, SLOT(onContactInvalidated()));\n\n connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),\n this, SLOT(onContactChanged()));\n\n connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),\n this, SLOT(onContactChanged()));\n }\n}\n\nvoid KTpAllContacts::onContactChanged()\n{\n const KTp::ContactPtr contact(qobject_cast(sender()));\n m_contactVCards.insert(createUri(contact), contactToAddressee(contact));\n Q_EMIT contactChanged(createUri(contact), contactToAddressee(contact));\n}\n\nvoid KTpAllContacts::onContactInvalidated()\n{\n const KTp::ContactPtr contact(qobject_cast(sender()));\n const QString uri = createUri(contact);\n\n m_contacts.remove(uri);\n\n \/\/set to offline and emit changed\n KABC::Addressee &vcard = m_contactVCards[uri];\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"presence\"), QLatin1String(\"offline\"));\n Q_EMIT contactChanged(uri, vcard);\n}\n\nKABC::Addressee::Map KTpAllContacts::contacts()\n{\n return m_contactVCards;\n}\n\nKABC::Addressee KTpAllContacts::contactToAddressee(const Tp::ContactPtr &contact) const\n{\n KABC::Addressee vcard;\n Tp::AccountPtr account = KTp::contactManager()->accountForContact(contact);\n if (contact && account) {\n vcard.setFormattedName(contact->alias());\n vcard.setCategories(contact->groups());\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"contactId\"), contact->id());\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"accountPath\"), account->objectPath());\n vcard.insertCustom(QLatin1String(\"telepathy\"), QLatin1String(\"presence\"), contact->presence().status());\n if (!contact->avatarData().fileName.isEmpty()) {\n vcard.setPhoto(KABC::Picture(contact->avatarData().fileName));\n }\n }\n return vcard;\n}\n\nIMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)\n : BasePersonsDataSource(parent)\n{\n Q_UNUSED(args);\n}\n\nIMPersonsDataSource::~IMPersonsDataSource()\n{\n}\n\nQString IMPersonsDataSource::sourcePluginId() const\n{\n return QLatin1String(\"ktp\");\n}\n\nAllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()\n{\n return new KTpAllContacts();\n}\n\nK_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin(); )\nK_EXPORT_PLUGIN( IMPersonsDataSourceFactory(\"im_persons_data_source_plugin\") )\n\n\n#include \"im-persons-data-source.moc\"\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"cpu\/view.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"palette.h\"\n\n\nnamespace cpu {\n\nView::View(LockedObject* buffer)\n : factory_(this),\n graphics_2d_(NULL),\n pixel_buffer_(NULL),\n locked_buffer_(buffer),\n draw_loop_running_(false) {\n}\n\nView::~View() {\n delete graphics_2d_;\n delete pixel_buffer_;\n}\n\nbool View::DidChangeView(pp::Instance* instance,\n const pp::View& view) {\n pp::Size old_size = GetSize();\n pp::Size new_size = view.GetRect().size();\n if (old_size == new_size)\n return true;\n\n printf(\"Size: %d x %d\\n\", new_size.width(), new_size.height());\n\n delete graphics_2d_;\n graphics_2d_ = new pp::Graphics2D(instance, new_size,\n true); \/\/ is_always_opaque\n if (!instance->BindGraphics(*graphics_2d_)) {\n delete graphics_2d_;\n graphics_2d_ = NULL;\n return false;\n }\n\n \/\/ Create a new pixel buffer, the same size as the graphics context. We'll\n \/\/ write to this buffer directly, and copy regions of it to the graphics\n \/\/ context's backing store to draw to the screen.\n delete pixel_buffer_;\n pixel_buffer_ = new pp::ImageData(instance, PP_IMAGEDATAFORMAT_BGRA_PREMUL,\n new_size,\n true); \/\/ init_to_zero\n\n if (!draw_loop_running_) {\n DrawCallback(0); \/\/ Start the draw loop.\n draw_loop_running_ = true;\n }\n\n return true;\n}\n\npp::Size View::GetSize() const {\n return graphics_2d_ ? graphics_2d_->size() : pp::Size();\n}\n\nvoid View::DrawCallback(int32_t result) {\n if (!graphics_2d_) {\n draw_loop_running_ = false;\n return;\n }\n assert(pixel_buffer_);\n\n AlignedUint32* data = locked_buffer_->Lock();\n DrawBuffer(*data);\n locked_buffer_->Unlock();\n\n PaintRectToGraphics2D(pp::Rect(GetSize()));\n\n \/\/ Graphics2D::Flush writes all paints to the graphics context's backing\n \/\/ store. When it is finished, it calls the callback. By hooking our draw\n \/\/ function to the Flush callback, we will be able to draw as quickly as\n \/\/ possible.\n graphics_2d_->Flush(factory_.NewCallback(&View::DrawCallback));\n}\n\nvoid View::PaintRectToGraphics2D(const pp::Rect& rect) {\n const pp::Point top_left(0, 0);\n graphics_2d_->PaintImageData(*pixel_buffer_, top_left, rect);\n}\n\nvoid View::DrawBuffer(const AlignedUint32& a) {\n uint32_t* pixels = static_cast(pixel_buffer_->data());\n if (!pixels)\n return;\n\n double scale;\n int x_offset;\n int y_offset;\n GetScreenToSimScale(a.size(), &scale, &x_offset, &y_offset);\n\n int image_width = GetSize().width();\n int image_height = GetSize().height();\n int buffer_width = a.size().width();\n double buffer_x = 0;\n double buffer_y = 0;\n\n for (int y = y_offset; y < image_height - y_offset; ++y) {\n buffer_x = 0;\n for (int x = x_offset; x < image_width - x_offset; ++x) {\n uint32_t v = a[(int)buffer_y * buffer_width + (int)buffer_x];\n pixels[y * image_width + x] = v;\n buffer_x += scale;\n }\n buffer_y += scale;\n }\n}\n\n} \/\/ namespace cpu\nclear area around drawn image (bug on mac). It was just drawing garbage.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"cpu\/view.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"palette.h\"\n\n\nnamespace cpu {\n\nView::View(LockedObject* buffer)\n : factory_(this),\n graphics_2d_(NULL),\n pixel_buffer_(NULL),\n locked_buffer_(buffer),\n draw_loop_running_(false) {\n}\n\nView::~View() {\n delete graphics_2d_;\n delete pixel_buffer_;\n}\n\nbool View::DidChangeView(pp::Instance* instance,\n const pp::View& view) {\n pp::Size old_size = GetSize();\n pp::Size new_size = view.GetRect().size();\n if (old_size == new_size)\n return true;\n\n printf(\"Size: %d x %d\\n\", new_size.width(), new_size.height());\n\n delete graphics_2d_;\n graphics_2d_ = new pp::Graphics2D(instance, new_size,\n true); \/\/ is_always_opaque\n if (!instance->BindGraphics(*graphics_2d_)) {\n delete graphics_2d_;\n graphics_2d_ = NULL;\n return false;\n }\n\n \/\/ Create a new pixel buffer, the same size as the graphics context. We'll\n \/\/ write to this buffer directly, and copy regions of it to the graphics\n \/\/ context's backing store to draw to the screen.\n delete pixel_buffer_;\n pixel_buffer_ = new pp::ImageData(instance, PP_IMAGEDATAFORMAT_BGRA_PREMUL,\n new_size,\n true); \/\/ init_to_zero\n\n if (!draw_loop_running_) {\n DrawCallback(0); \/\/ Start the draw loop.\n draw_loop_running_ = true;\n }\n\n return true;\n}\n\npp::Size View::GetSize() const {\n return graphics_2d_ ? graphics_2d_->size() : pp::Size();\n}\n\nvoid View::DrawCallback(int32_t result) {\n if (!graphics_2d_) {\n draw_loop_running_ = false;\n return;\n }\n assert(pixel_buffer_);\n\n AlignedUint32* data = locked_buffer_->Lock();\n DrawBuffer(*data);\n locked_buffer_->Unlock();\n\n PaintRectToGraphics2D(pp::Rect(GetSize()));\n\n \/\/ Graphics2D::Flush writes all paints to the graphics context's backing\n \/\/ store. When it is finished, it calls the callback. By hooking our draw\n \/\/ function to the Flush callback, we will be able to draw as quickly as\n \/\/ possible.\n graphics_2d_->Flush(factory_.NewCallback(&View::DrawCallback));\n}\n\nvoid View::PaintRectToGraphics2D(const pp::Rect& rect) {\n const pp::Point top_left(0, 0);\n graphics_2d_->PaintImageData(*pixel_buffer_, top_left, rect);\n}\n\nvoid View::DrawBuffer(const AlignedUint32& a) {\n uint32_t* pixels = static_cast(pixel_buffer_->data());\n if (!pixels)\n return;\n\n double scale;\n int x_offset;\n int y_offset;\n GetScreenToSimScale(a.size(), &scale, &x_offset, &y_offset);\n\n int image_width = GetSize().width();\n int image_height = GetSize().height();\n int buffer_width = a.size().width();\n double buffer_x = 0;\n double buffer_y = 0;\n\n std::fill(pixels, pixels + image_width * image_height, 0xff000000);\n\n for (int y = y_offset; y < image_height - y_offset; ++y) {\n buffer_x = 0;\n for (int x = x_offset; x < image_width - x_offset; ++x) {\n uint32_t v = a[(int)buffer_y * buffer_width + (int)buffer_x];\n pixels[y * image_width + x] = v;\n buffer_x += scale;\n }\n buffer_y += scale;\n }\n}\n\n} \/\/ namespace cpu\n<|endoftext|>"} {"text":"\n#include \n#include \"opencv2\/opencv.hpp\"\n#include \n#include \n\n\/\/for the rasperry pi\n#ifndef INT64_C\n#define INT64_C(c) (c ## LL)\n#define UINT64_C(c) (c ## ULL)\n#endif\n\nextern \"C\" {\n\t#include \n\t#include \n\t#include \n}\n\n#include \n#include \n#include \n\n#ifdef __amd64__\n\t#ifndef RUNNINGONINTEL\n\t#define RUNNINGONINTEL\n\t#endif\n#else\n\t#ifndef RUNNINGONPI\n\t#define RUNNINGONPI\n\t#endif\n\t#include \n#endif\n\nusing namespace cv;\n\n#define SCREEN_HEIGHT 768\n#define SCREEN_WIDTH 1232\n\n\n\nint cameraWorker(void* data);\nvoid processEvents();\nvoid signalToQuit();\nvoid close();\n\nIplImage threadImage1;\nbool updatedImage1 = false;\n\nVideoCapture cap(0);\n\nMat frame;\nSDL_Renderer* renderer = NULL;\nSDL_Window* window = NULL;\n\nSDL_Rect videoRect;\nint cameraHeight;\nint cameraWidth;\n\nSDL_Thread* SDLCameraThread;\nSDL_Thread* SDLMusicThread;\n\nint quit;\n\n\/***********************************************************************\n\/*\t\t\t\t\t\t\tSDL functions \n\/***********************************************************************\/\n\/\/ Initializes SDL window \/ renderer for use\n\nbool init_SDL()\n{\n\tbool success = true;\n\t\n\tif (SDL_Init(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) < 0)\n\t{\n\t\tprintf( \"SDL could not initialize! SDL Error: %s\\n\", SDL_GetError() );\n\t\tsuccess = false;\n\t} else {\n\t\twindow = SDL_CreateWindow(\"Video Application\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);\n\t\tif (window == NULL)\n\t\t{\n\t\t\tprintf(\"error\");\n\t\t\tsuccess = false;\n\t\t} else {\n\t\t\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n\t\t\tif (renderer == NULL)\n\t\t\t{\n\t\t\t\tprintf(\"Renderer could not be created. SDL_Error: %s \\n\", SDL_GetError());\n\t\t\t\tsuccess = false;\n\t\t\t} else {\n\t\t\t\tSDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);\n\t\t\t}\n\t\t}\n\t}\n\treturn success;\n}\n\nbool init_CameraSettings()\n{\n\tbool success = true;\n\tvideoRect.x = 0;\n\tvideoRect.y = 0;\n\tvideoRect.w = 1280;\t\/\/640 not actually sure why we have this\n\tvideoRect.h = 720;\t\/\/480\n\n\tcameraWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);\n\tcameraHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);\n\n\tprintf(\"Camera Width%d, Camera Height %d \\n\",cameraWidth,cameraHeight);\n\treturn success;\n}\n\nint cameraWorker(void* data) \n{\n\twhile (!quit)\n\t{\n\t\tcap >> frame;\n\t\tthreadImage1 = frame;\n\t\tupdatedImage1 = true;\n\t}\n\treturn 0;\n}\n\n\n\/\/ Shows an individual frame of the supplied video\nint show_Camera(IplImage* img)\n{\t\t\n\tif(updatedImage1 == true)\n\t{\n\t\tSDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)img->imageData,\n\t\t\timg->width,\n\t\t\timg->height,\n\t\t\timg->depth * img->nChannels,\n\t\t\timg->widthStep,\n\t\t\t0xff0000, 0x00ff00, 0x0000ff, 0\n\t\t\t);\n\t\tupdatedImage1 = false;\n\n\t\tSDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);\n\t\tSDL_FreeSurface(surface);\n\t\tsurface = NULL;\n\t\tSDL_RendererFlip flip = SDL_FLIP_HORIZONTAL;\n\t\tSDL_RenderCopyEx(renderer, texture, NULL, &videoRect ,0, NULL, flip);\n\t\tSDL_DestroyTexture(texture);\n\t\treturn 1;\n\t}\n\t\treturn 0;\n\n}\n \nvoid processEvents()\n{\n\tSDL_Event event;\n \t\twhile (SDL_PollEvent(&event))\n \t\t{\n\t \t\tswitch(event.type)\n\t \t\t{\n\t \t\t\tcase SDL_QUIT:\n\t \t\t\t\tprintf(\"SDL_QUIT was called\\n\");\n\t \t\t\t\tsignalToQuit();\n\t \t\t\t\tclose();\n\t\t \t\t\tbreak;\n\n\t \t\t\tcase SDL_KEYDOWN:\n\t \t\t\t\tswitch(event.key.keysym.sym) \n\t \t\t\t\t{\n\t\t\t\t \t\tcase SDLK_ESCAPE: \n\t\t\t\t \t\t \tprintf(\"Esc was Pressed!\\n\");\n\t\t\t\t \t\t \tsignalToQuit();\n\t\t\t\t \t\t \tclose();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_LEFT:\n\t\t\t\t\t\t\tprintf(\"Left arrow was Pressed!\\n\");\n\t\t\t\t\t\t\tpreviousSong();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_RIGHT:\n\t\t\t\t\t\t\tprintf(\"Right arrow was Pressed!\\n\");\n\t\t\t\t\t\t\tnextSong();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_UP:\n\t\t\t\t\t\t\tchangeVolume(0.1);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_DOWN:\n\t\t\t\t\t\t\tchangeVolume(-0.1);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_SPACE:\n\t\t\t\t\t\t\tprintf(\"Space was pressed!\\n\");\n\t\t\t\t\t\t\tplayPause();\n\t\t\t \t}\n\t \t\t}\n \t\t}\n}\n\n\n\/* Signals all the threads to quit and then waits for the threads *\/\nvoid signalToQuit()\n{\n\tquit = true;\n\tsongQuit();\n}\n\n\/* Cleans up and should free everything used in the program*\/\nvoid close()\n{\n\tcloseSongPlayer();\n\tSDL_DestroyRenderer(renderer);\n\tSDL_DestroyWindow(window);\n\twindow = NULL;\n\trenderer = NULL;\n\tSDL_Quit();\n\texit(0);\n}\n\nint main(int argc, char* argv[])\n{\n\tint noSongs;\n\t \n \tif (!init_SDL()){\n \t\tfprintf(stderr, \"Could not initialize SDL!\\n\");\n \t\treturn -1;\n \t}\n \tif (!cap.isOpened()){\n \t\tfprintf(stderr, \"Failed to load file!\\n\");\n \t\treturn -1;\n \t}\n \tif (!init_CameraSettings()){\n \t\tprintf(\"failed to load settings\\n\");\n \t\treturn -1;\n \t}\n\t\t\n \tinitSongPlayer();\n \tnoSongs = loadSong((char *)currentSong().c_str());\n\n \tSDLCameraThread = SDL_CreateThread(cameraWorker, \"Backup Camera Thread\", NULL);\n \tif (!noSongs)\n \t SDLMusicThread = SDL_CreateThread(songThread, \"Music Playing Thread\", NULL);\n\n\tint screenUpdate = 0;\n\n \twhile (!quit)\n \t{\n \t\t\n\t\tscreenUpdate = show_Camera(&threadImage1);\n\t\tprocessEvents();\n\t\tif (screenUpdate == 1){\n\t\t\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);\n\t\t\tSDL_RenderPresent(renderer);\n\t\t\tSDL_RenderClear(renderer);\n\t\t}\n\t}\n\n\tSDL_WaitThread(SDLCameraThread, NULL);\n\tif (!noSongs)\n\t SDL_WaitThread(SDLMusicThread, NULL);\n\treturn 0;\n}\nChanged code to double buffer\n#include \n#include \"opencv2\/opencv.hpp\"\n#include \n#include \n\n\/\/for the rasperry pi\n#ifndef INT64_C\n#define INT64_C(c) (c ## LL)\n#define UINT64_C(c) (c ## ULL)\n#endif\n\nextern \"C\" {\n\t#include \n\t#include \n\t#include \n}\n\n#include \n#include \n#include \n\n#ifdef __amd64__\n\t#ifndef RUNNINGONINTEL\n\t#define RUNNINGONINTEL\n\t#endif\n#else\n\t#ifndef RUNNINGONPI\n\t#define RUNNINGONPI\n\t#endif\n\t#include \n#endif\n\nusing namespace cv;\n\n#define SCREEN_HEIGHT 768\n#define SCREEN_WIDTH 1232\n\n\n\nint cameraWorker(void* data);\nvoid processEvents();\nvoid signalToQuit();\nvoid close();\n\n\/\/attempting double buffer\nIplImage threadImage1;\nIplImage threadImage2;\nbool updatedImage = false;\nint bufferNumber = 1;\n\nVideoCapture cap(0);\n\nMat frame;\nSDL_Renderer* renderer = NULL;\nSDL_Window* window = NULL;\n\nSDL_Rect videoRect;\nint cameraHeight;\nint cameraWidth;\nint noSongs;\n\nSDL_Thread* SDLCameraThread;\nSDL_Thread* SDLMusicThread;\n\nint quit;\n\n\/***********************************************************************\n\/*\t\t\t\t\t\t\tSDL functions \n\/***********************************************************************\/\n\/\/ Initializes SDL window \/ renderer for use\n\nbool init_SDL()\n{\n\tbool success = true;\n\t\n\tif (SDL_Init(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) < 0)\n\t{\n\t\tprintf( \"SDL could not initialize! SDL Error: %s\\n\", SDL_GetError() );\n\t\tsuccess = false;\n\t} else {\n\t\twindow = SDL_CreateWindow(\"Video Application\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);\n\t\tif (window == NULL)\n\t\t{\n\t\t\tprintf(\"error\");\n\t\t\tsuccess = false;\n\t\t} else {\n\t\t\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n\t\t\tif (renderer == NULL)\n\t\t\t{\n\t\t\t\tprintf(\"Renderer could not be created. SDL_Error: %s \\n\", SDL_GetError());\n\t\t\t\tsuccess = false;\n\t\t\t} else {\n\t\t\t\tSDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);\n\t\t\t}\n\t\t}\n\t}\n\treturn success;\n}\n\nbool init_CameraSettings()\n{\n\tbool success = true;\n\tvideoRect.x = 0;\n\tvideoRect.y = 0;\n\tvideoRect.w = 1280;\t\/\/640 not actually sure why we have this\n\tvideoRect.h = 720;\t\/\/480\n\n\tcameraWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);\n\tcameraHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);\n\n\tprintf(\"Camera Width%d, Camera Height %d \\n\",cameraWidth,cameraHeight);\n\treturn success;\n}\n\nint cameraWorker(void* data) \n{\n\twhile (!quit)\n\t{\n\t\tcap >> frame;\n\t\tif(bufferNumber == 1){\n\t\t\tthreadImage2 = frame;\n\t\t\tbufferNumber = 2;\n\t\t} else {\n\t\t\tthreadImage1 = frame;\n\t\t\tbufferNumber = 1;\n\t\t}\n\t\tupdatedImage = true;\n\t}\n\treturn 0;\n}\n\n\n\/\/ Shows an individual frame of the supplied video\nint show_Camera()\n{\t\t\n\tIplImage* img = NULL;\n\tif(updatedImage == true)\n\t{\n\t\tupdatedImage = false;\n\t\tif(bufferNumber == 1){\n\t\t\t img = &threadImage1;\n\t\t} else {\n\t\t\t img = &threadImage2;\n\t\t}\n\t\tSDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)img->imageData,\n\t\t\timg->width,\n\t\t\timg->height,\n\t\t\timg->depth * img->nChannels,\n\t\t\timg->widthStep,\n\t\t\t0xff0000, 0x00ff00, 0x0000ff, 0\n\t\t\t);\n\t\t\n\n\t\tSDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);\n\t\tSDL_FreeSurface(surface);\n\t\tsurface = NULL;\n\t\tSDL_RendererFlip flip = SDL_FLIP_HORIZONTAL;\n\t\tSDL_RenderCopyEx(renderer, texture, NULL, &videoRect ,0, NULL, flip);\n\t\tSDL_DestroyTexture(texture);\n\t\treturn 1;\n\t}\n\t\treturn 0;\n\n}\n \nvoid processEvents()\n{\n\tSDL_Event event;\n \t\twhile (SDL_PollEvent(&event))\n \t\t{\n\t \t\tswitch(event.type)\n\t \t\t{\n\t \t\t\tcase SDL_QUIT:\n\t \t\t\t\tprintf(\"SDL_QUIT was called\\n\");\n\t \t\t\t\tsignalToQuit();\n\t \t\t\t\tclose();\n\t\t \t\t\tbreak;\n\n\t \t\t\tcase SDL_KEYDOWN:\n\t \t\t\t\tswitch(event.key.keysym.sym) \n\t \t\t\t\t{\n\t\t\t\t \t\tcase SDLK_ESCAPE: \n\t\t\t\t \t\t \tprintf(\"Esc was Pressed!\\n\");\n\t\t\t\t \t\t \tsignalToQuit();\n\t\t\t\t \t\t \tclose();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_LEFT:\n\t\t\t\t\t\t\tprintf(\"Left arrow was Pressed!\\n\");\n\t\t\t\t\t\t\tpreviousSong();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_RIGHT:\n\t\t\t\t\t\t\tprintf(\"Right arrow was Pressed!\\n\");\n\t\t\t\t\t\t\tnextSong();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_UP:\n\t\t\t\t\t\t\tchangeVolume(0.1);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_DOWN:\n\t\t\t\t\t\t\tchangeVolume(-0.1);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase SDLK_SPACE:\n\t\t\t\t\t\t\tprintf(\"Space was pressed!\\n\");\n\t\t\t\t\t\t\tplayPause();\n\t\t\t \t}\n\t \t\t}\n \t\t}\n}\n\n\n\/* Signals all the threads to quit and then waits for the threads *\/\nvoid signalToQuit()\n{\n\tquit = true;\n\tsongQuit();\n}\n\n\/* Cleans up and should free everything used in the program*\/\nvoid close()\n{\n\tcloseSongPlayer();\n\tSDL_DestroyRenderer(renderer);\n\tSDL_DestroyWindow(window);\n\twindow = NULL;\n\trenderer = NULL;\n\tSDL_Quit();\n\texit(0);\n}\n\nint main(int argc, char* argv[])\n{\n\t\n\t \n \tif (!init_SDL()){\n \t\tfprintf(stderr, \"Could not initialize SDL!\\n\");\n \t\treturn -1;\n \t}\n \tif (!cap.isOpened()){\n \t\tfprintf(stderr, \"Failed to load file!\\n\");\n \t\treturn -1;\n \t}\n \tif (!init_CameraSettings()){\n \t\tprintf(\"failed to load settings\\n\");\n \t\treturn -1;\n \t}\n\t\t\n \tinitSongPlayer();\n \tnoSongs = loadSong((char *)currentSong().c_str());\n\n \tSDLCameraThread = SDL_CreateThread(cameraWorker, \"Backup Camera Thread\", NULL);\n \tif (!noSongs)\n \t SDLMusicThread = SDL_CreateThread(songThread, \"Music Playing Thread\", NULL);\n\n\tint screenUpdate = 0;\n\n \twhile (!quit)\n \t{\n \t\t\n\t\tscreenUpdate = show_Camera();\n\t\tprocessEvents();\n\t\tif (screenUpdate == 1){\n\t\t\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);\n\t\t\tSDL_RenderPresent(renderer);\n\t\t\tSDL_RenderClear(renderer);\n\t\t}\n\t}\n\n\tSDL_WaitThread(SDLCameraThread, NULL);\n\tif (!noSongs)\n\t SDL_WaitThread(SDLMusicThread, NULL);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014 Kyle Isom \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n\/\/ This is a test of instructions from http:\/\/skilldrick.github.io\/easy6502\/index.html.\n\/\/ As this library isn't an assembler, it won't assemble the files; I'm\n\/\/ to check some of the expected behaviours from the emulator.\n\n#include \n#include \nusing namespace std;\n\n#include \"cpu.h\"\n\n\nvoid\ttest1(void);\nvoid\ttest2(void);\nvoid\ttest3(void);\nvoid\ttest4(void);\nvoid\ttest5(void);\nvoid\ttest6(void);\n\n\nstatic void\ndump_program(const unsigned char *program, size_t len)\n{\n\tsize_t\ti = 0;\n\tint\tl = 0;\n\tfor (i = 0; i < len; ++i) {\n\t\tif (l == 0)\n\t\t\tstd::cerr << std::setw(8) << std::hex << i << \"| \";\n\t\tstd::cerr << std::hex << std::setw(2) << std::setfill('0')\n\t\t\t << (unsigned short)(program[i] & 0xff);\n\t\tstd::cerr << \" \";\n\t\tl++;\n\t\tif (l == 8) {\n\t\t\tstd::cerr << \" \";\n\t\t} else if (l == 16) {\n\t\t\tstd::cerr << std::endl;\n\t\t\tl = 0;\n\t\t}\n\t}\n\tstd::cerr << std::endl;\n}\n\n\nstatic void\nrun(const unsigned char *program, size_t size, bool trace)\n{\n\tCPU\tcpu(0x400);\n\tstd::cerr << \"\\nPROGRAM:\\n\";\n\tdump_program(program, size);\n\tstd::cerr << std::endl;\n\n\tcpu.load(program, 0x300, size);\n\tcpu.start_pc(0x300);\n\n\tcpu.run(trace);\n\tcpu.dump_memory();\n\tcpu.dump_registers();\n}\n\n\nvoid\ntest1()\n{\n\tstd::cerr << \"\\nStarting test 1\\n\";\n\tstd::cerr << \"\\t(First compiled program)\\n\";\n\n\t\/\/ test1, compiled as opcodes\n\tunsigned char\tprogram[] = {0xA9, 0x01, 0x8D, 0x01, 0x00};\n\trun(program, 5, false);\n}\n\n\nvoid\ntest2()\n{\n\tstd::cerr << \"\\nStarting test 2\\n\";\n\tstd::cerr << \"\\t(First full compiled easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa9, 0x01, 0x8d, 0x00, 0x02, 0xa9, 0x05, 0x8d,\n\t\t0x01, 0x02, 0xa9, 0x08, 0x8d, 0x02, 0x02, 0x00\n\t};\n\trun(program, 15, false);\n}\n\n\nvoid\ntest3()\n{\n\tstd::cerr << \"\\nStarting test 3\\n\";\n\tstd::cerr << \"\\t(Second full compiled easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa9, 0xc0, 0xaa, 0xe8, 0x69, 0xc4, 0x00\n\t};\n\n\trun(program, 7, false);\n}\n\n\nvoid\ntest4()\n{\n\tstd::cerr << \"\\nStarting test 4\\n\";\n\tstd::cerr << \"\\t(Third full compiled easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa9, 0x80, 0x85, 0x01, 0x65, 0x01 \n\t};\n\n\trun(program, 6, false);\n}\n\n\nvoid\ntest5()\n{\n\tstd::cerr << \"\\nStarting test 5\\n\";\n\tstd::cerr << \"\\t(First branching easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa2, 0x08, 0xca, 0x8e, 0x00, 0x02, 0xe0, 0x03,\n\t\t0xd0, 0xf8, 0x8e, 0x01, 0x02, 0x00\n\t};\n\trun(program, 14, false);\n}\n\n\nvoid\ntest6()\n{\n\tstd::cerr << \"\\nStarting test 6\\n\";\n\tstd::cerr << \"\\t(Indexed indirect addressing)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa2, 0x01, 0xa9, 0x05, 0x85, 0x01, 0xa9, 0x03,\n\t\t0x85, 0x02, 0xa0, 0x0a, 0x8c, 0x05, 0x03, 0xa1,\n\t\t0x00\n\t};\n\trun(program, 17, false);\n}\n\n\nint\nmain(void)\n{\n\ttest1();\n\ttest2();\n\ttest3();\n\ttest4();\n\ttest5();\n\ttest6();\n}\nAdd indirect indexed addressing example\/*\n * Copyright (c) 2014 Kyle Isom \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n\/\/ This is a test of instructions from http:\/\/skilldrick.github.io\/easy6502\/index.html.\n\/\/ As this library isn't an assembler, it won't assemble the files; I'm\n\/\/ to check some of the expected behaviours from the emulator.\n\n#include \n#include \nusing namespace std;\n\n#include \"cpu.h\"\n\n\nvoid\ttest1(void);\nvoid\ttest2(void);\nvoid\ttest3(void);\nvoid\ttest4(void);\nvoid\ttest5(void);\nvoid\ttest6(void);\nvoid\ttest7(void);\n\n\nstatic void\ndump_program(const unsigned char *program, size_t len)\n{\n\tsize_t\ti = 0;\n\tint\tl = 0;\n\tfor (i = 0; i < len; ++i) {\n\t\tif (l == 0)\n\t\t\tstd::cerr << std::setw(8) << std::hex << i << \"| \";\n\t\tstd::cerr << std::hex << std::setw(2) << std::setfill('0')\n\t\t\t << (unsigned short)(program[i] & 0xff);\n\t\tstd::cerr << \" \";\n\t\tl++;\n\t\tif (l == 8) {\n\t\t\tstd::cerr << \" \";\n\t\t} else if (l == 16) {\n\t\t\tstd::cerr << std::endl;\n\t\t\tl = 0;\n\t\t}\n\t}\n\tstd::cerr << std::endl;\n}\n\n\nstatic void\nrun(const unsigned char *program, size_t size, bool trace)\n{\n\tCPU\tcpu(0x400);\n\tstd::cerr << \"\\nPROGRAM:\\n\";\n\tdump_program(program, size);\n\tstd::cerr << std::endl;\n\n\tcpu.load(program, 0x300, size);\n\tcpu.start_pc(0x300);\n\n\tcpu.run(trace);\n\tcpu.dump_memory();\n\tcpu.dump_registers();\n}\n\n\nvoid\ntest1()\n{\n\tstd::cerr << \"\\nStarting test 1\\n\";\n\tstd::cerr << \"\\t(First compiled program)\\n\";\n\n\t\/\/ test1, compiled as opcodes\n\tunsigned char\tprogram[] = {0xA9, 0x01, 0x8D, 0x01, 0x00};\n\trun(program, 5, false);\n}\n\n\nvoid\ntest2()\n{\n\tstd::cerr << \"\\nStarting test 2\\n\";\n\tstd::cerr << \"\\t(First full compiled easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa9, 0x01, 0x8d, 0x00, 0x02, 0xa9, 0x05, 0x8d,\n\t\t0x01, 0x02, 0xa9, 0x08, 0x8d, 0x02, 0x02, 0x00\n\t};\n\trun(program, 15, false);\n}\n\n\nvoid\ntest3()\n{\n\tstd::cerr << \"\\nStarting test 3\\n\";\n\tstd::cerr << \"\\t(Second full compiled easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa9, 0xc0, 0xaa, 0xe8, 0x69, 0xc4, 0x00\n\t};\n\n\trun(program, 7, false);\n}\n\n\nvoid\ntest4()\n{\n\tstd::cerr << \"\\nStarting test 4\\n\";\n\tstd::cerr << \"\\t(Third full compiled easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa9, 0x80, 0x85, 0x01, 0x65, 0x01 \n\t};\n\n\trun(program, 6, false);\n}\n\n\nvoid\ntest5()\n{\n\tstd::cerr << \"\\nStarting test 5\\n\";\n\tstd::cerr << \"\\t(First branching easy6502 program)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa2, 0x08, 0xca, 0x8e, 0x00, 0x02, 0xe0, 0x03,\n\t\t0xd0, 0xf8, 0x8e, 0x01, 0x02, 0x00\n\t};\n\trun(program, 14, false);\n}\n\n\nvoid\ntest6()\n{\n\tstd::cerr << \"\\nStarting test 6\\n\";\n\tstd::cerr << \"\\t(Indexed indirect addressing)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa2, 0x01, 0xa9, 0x05, 0x85, 0x01, 0xa9, 0x03,\n\t\t0x85, 0x02, 0xa0, 0x0a, 0x8c, 0x05, 0x03, 0xa1,\n\t\t0x00\n\t};\n\trun(program, 17, false);\n}\n\n\nvoid\ntest7()\n{\n\tstd::cerr << \"\\nStarting test 7\\n\";\n\tstd::cerr << \"\\t(Indirect indexed addressing)\\n\";\n\n\tunsigned char\tprogram[] = {\n\t\t0xa0, 0x01, 0xa9, 0x03, 0x85, 0x01, 0xa9, 0x01,\n\t\t0x85, 0x02, 0xa2, 0x0a, 0x8e, 0x04, 0x01, 0xb1,\n\t\t0x01, 0x00\n\t};\n\trun(program, 18, false);\n}\n\n\nint\nmain(void)\n{\n\ttest1();\n\ttest2();\n\ttest3();\n\ttest4();\n\ttest5();\n\ttest6();\n\ttest7();\n}\n<|endoftext|>"} {"text":"\/\/\/ random\n\/\/ Random implements a pseudo random number generator (PRNG).\n\/\/ The PRNG is a nonlinear additive feedback random number generator using 256 bytes of state\n\/\/ information and a period of up to 2^69.\n\/\/ @module random\n#include \"Random.h\"\n#include \n\nint luaopen_poco_random(lua_State* L)\n{\n LuaPoco::RandomUserdata::registerRandom(L);\n return LuaPoco::loadConstructor(L, LuaPoco::RandomUserdata::Random);\n}\n\nnamespace LuaPoco\n{\n\nconst char* POCO_RANDOM_METATABLE_NAME = \"Poco.Random.metatable\";\n\nRandomUserdata::RandomUserdata(int stateSize)\n : mRandom(stateSize)\n{\n}\n\nRandomUserdata::~RandomUserdata()\n{\n}\n\n\/\/ register metatable for this class\nbool RandomUserdata::registerRandom(lua_State* L)\n{\n struct CFunctions methods[] = \n {\n { \"__gc\", metamethod__gc },\n { \"__tostring\", metamethod__tostring },\n { \"next\", next },\n { \"nextNumber\", nextNumber },\n { \"nextByte\", nextByte },\n { \"nextBool\", nextBool },\n { NULL, NULL}\n };\n \n setupUserdataMetatable(L, POCO_RANDOM_METATABLE_NAME, methods);\n return true;\n}\n\n\/\/\/ Constructs a new random userdata.\n\/\/ @tparam[opt] number stateSize (default: 256) state buffer size: 8, 16, 32, 64, 128, or 256.\n\/\/ @tparam[opt] number seed seed for prng, if unspecified an internal RandomNumberStream is used.\n\/\/ @return userdata or nil. (error)\n\/\/ @return error message.\n\/\/ @function new\nint RandomUserdata::Random(lua_State* L)\n{\n int rv = 0;\n int firstArg = lua_istable(L, 1) ? 2 : 1;\n \n lua_Integer stateSize = 256;\n lua_Integer seed = lua_isinteger(L, firstArg + 1) ? lua_tointeger(L, firstArg + 1) : 0;\n \n if (lua_isinteger(L, firstArg)) { stateSize = lua_tointeger(L, firstArg); }\n if (stateSize != 256 && stateSize != 128 && stateSize != 64 && stateSize != 32 &&\n stateSize != 16 && stateSize != 8)\n {\n lua_pushnil(L); lua_pushfstring(L, \"invalid stateSize: %d\", stateSize);\n return 2;\n }\n \n try\n {\n RandomUserdata* rud = new(lua_newuserdata(L, sizeof *rud))\n RandomUserdata(stateSize);\n setupPocoUserdata(L, rud, POCO_RANDOM_METATABLE_NAME);\n\n if (seed) { rud->mRandom.seed(seed); }\n else { rud->mRandom.seed(); }\n \n rv = 1;\n }\n catch (const Poco::Exception& e)\n {\n rv = pushPocoException(L, e);\n }\n catch (...)\n {\n rv = pushUnknownException(L);\n }\n \n return rv;\n}\n\n\/\/ metamethod infrastructure\nint RandomUserdata::metamethod__tostring(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_pushfstring(L, \"Poco.Random (%p)\", static_cast(rud));\n \n return 1;\n}\n\nint RandomUserdata::metamethod__gc(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n rud->~RandomUserdata();\n\n return 0;\n}\n\/\/\/ \n\/\/ @type random\n\n\/\/\/ Returns the next 31-bit pseudo random number. (modulo n, if supplied)\n\/\/ @tparam[opt] integer n modulo value.\n\/\/ @function next\nint RandomUserdata::next(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_Integer rval = 0;\n \n if (lua_isinteger(L, 2))\n { rval = static_cast(rud->mRandom.next(lua_tointeger(L, 2))); }\n else { rval = rud->mRandom.next(); }\n \n lua_pushinteger(L, rval);\n return 1;\n}\n\n\/\/\/ Returns the next pseudo random number between 0.0 and 1.0 as a double.\n\/\/ @function nextNumber\nint RandomUserdata::nextNumber(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_pushnumber(L, static_cast(rud->mRandom.nextDouble()));\n return 1;\n}\n\n\/\/\/ Returns the next pseudo random byte.\n\/\/ @function nextByte\nint RandomUserdata::nextByte(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n unsigned char rval = static_cast(rud->mRandom.nextChar());\n lua_pushinteger(L, static_cast(rval));\n return 1;\n}\n\n\/\/\/ Returns the next pseudo random boolean value.\n\/\/ @function nextBool\nint RandomUserdata::nextBool(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_pushboolean(L, static_cast(rud->mRandom.nextBool()));\n return 1;\n}\n\n} \/\/ LuaPoco\n\nchange to lua_isnumber for argument checks on constructor for 5.1\/5.2 compat\/\/\/ random\n\/\/ Random implements a pseudo random number generator (PRNG).\n\/\/ The PRNG is a nonlinear additive feedback random number generator using 256 bytes of state\n\/\/ information and a period of up to 2^69.\n\/\/ @module random\n#include \"Random.h\"\n#include \n\nint luaopen_poco_random(lua_State* L)\n{\n LuaPoco::RandomUserdata::registerRandom(L);\n return LuaPoco::loadConstructor(L, LuaPoco::RandomUserdata::Random);\n}\n\nnamespace LuaPoco\n{\n\nconst char* POCO_RANDOM_METATABLE_NAME = \"Poco.Random.metatable\";\n\nRandomUserdata::RandomUserdata(int stateSize)\n : mRandom(stateSize)\n{\n}\n\nRandomUserdata::~RandomUserdata()\n{\n}\n\n\/\/ register metatable for this class\nbool RandomUserdata::registerRandom(lua_State* L)\n{\n struct CFunctions methods[] = \n {\n { \"__gc\", metamethod__gc },\n { \"__tostring\", metamethod__tostring },\n { \"next\", next },\n { \"nextNumber\", nextNumber },\n { \"nextByte\", nextByte },\n { \"nextBool\", nextBool },\n { NULL, NULL}\n };\n \n setupUserdataMetatable(L, POCO_RANDOM_METATABLE_NAME, methods);\n return true;\n}\n\n\/\/\/ Constructs a new random userdata.\n\/\/ @tparam[opt] number stateSize (default: 256) state buffer size: 8, 16, 32, 64, 128, or 256.\n\/\/ @tparam[opt] number seed seed for prng, if unspecified an internal RandomNumberStream is used.\n\/\/ @return userdata or nil. (error)\n\/\/ @return error message.\n\/\/ @function new\nint RandomUserdata::Random(lua_State* L)\n{\n int rv = 0;\n int firstArg = lua_istable(L, 1) ? 2 : 1;\n \n lua_Integer stateSize = 256;\n lua_Integer seed = lua_isinteger(L, firstArg + 1) ? lua_tointeger(L, firstArg + 1) : 0;\n \n if (lua_isnumber(L, firstArg)) { stateSize = lua_tointeger(L, firstArg); }\n if (stateSize != 256 && stateSize != 128 && stateSize != 64 && stateSize != 32 &&\n stateSize != 16 && stateSize != 8)\n {\n lua_pushnil(L); lua_pushfstring(L, \"invalid stateSize: %d\", stateSize);\n return 2;\n }\n \n try\n {\n RandomUserdata* rud = new(lua_newuserdata(L, sizeof *rud))\n RandomUserdata(stateSize);\n setupPocoUserdata(L, rud, POCO_RANDOM_METATABLE_NAME);\n\n if (seed) { rud->mRandom.seed(seed); }\n else { rud->mRandom.seed(); }\n \n rv = 1;\n }\n catch (const Poco::Exception& e)\n {\n rv = pushPocoException(L, e);\n }\n catch (...)\n {\n rv = pushUnknownException(L);\n }\n \n return rv;\n}\n\n\/\/ metamethod infrastructure\nint RandomUserdata::metamethod__tostring(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_pushfstring(L, \"Poco.Random (%p)\", static_cast(rud));\n \n return 1;\n}\n\nint RandomUserdata::metamethod__gc(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n rud->~RandomUserdata();\n\n return 0;\n}\n\/\/\/ \n\/\/ @type random\n\n\/\/\/ Returns the next 31-bit pseudo random number. (modulo n, if supplied)\n\/\/ @tparam[opt] integer n modulo value.\n\/\/ @function next\nint RandomUserdata::next(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_Integer rval = 0;\n \n if (lua_isnumber(L, 2))\n { rval = static_cast(rud->mRandom.next(lua_tointeger(L, 2))); }\n else { rval = rud->mRandom.next(); }\n \n lua_pushinteger(L, rval);\n return 1;\n}\n\n\/\/\/ Returns the next pseudo random number between 0.0 and 1.0 as a double.\n\/\/ @function nextNumber\nint RandomUserdata::nextNumber(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_pushnumber(L, static_cast(rud->mRandom.nextDouble()));\n return 1;\n}\n\n\/\/\/ Returns the next pseudo random byte.\n\/\/ @function nextByte\nint RandomUserdata::nextByte(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n unsigned char rval = static_cast(rud->mRandom.nextChar());\n lua_pushinteger(L, static_cast(rval));\n return 1;\n}\n\n\/\/\/ Returns the next pseudo random boolean value.\n\/\/ @function nextBool\nint RandomUserdata::nextBool(lua_State* L)\n{\n RandomUserdata* rud = checkPrivateUserdata(L, 1);\n lua_pushboolean(L, static_cast(rud->mRandom.nextBool()));\n return 1;\n}\n\n} \/\/ LuaPoco\n\n<|endoftext|>"} {"text":"\/\/===--- AccessSummaryAnalysis.cpp - SIL Access Summary Analysis ----------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-access-summary-analysis\"\n#include \"swift\/SIL\/SILArgument.h\"\n#include \"swift\/SILOptimizer\/Analysis\/AccessSummaryAnalysis.h\"\n#include \"swift\/SILOptimizer\/Analysis\/FunctionOrder.h\"\n#include \"swift\/SILOptimizer\/PassManager\/PassManager.h\"\n\nusing namespace swift;\n\nvoid AccessSummaryAnalysis::processFunction(FunctionInfo *info,\n FunctionOrder &order) {\n \/\/ Does the summary need to be recomputed?\n if (order.prepareForVisiting(info))\n return;\n\n \/\/ Compute function summary on a per-argument basis.\n unsigned index = 0;\n for (SILArgument *arg : info->getFunction()->getArguments()) {\n FunctionSummary &functionSummary = info->getSummary();\n ArgumentSummary &argSummary =\n functionSummary.getAccessForArgument(index);\n index++;\n\n auto *functionArg = cast(arg);\n \/\/ Only summarize @inout_aliasable arguments.\n SILArgumentConvention convention =\n functionArg->getArgumentConvention().Value;\n if (convention != SILArgumentConvention::Indirect_InoutAliasable)\n continue;\n\n processArgument(info, functionArg, argSummary, order);\n }\n}\n\n\/\/\/ Track uses of the arguments, recording in the summary any accesses\n\/\/\/ started by a begin_access and any flows of the arguments to other\n\/\/\/ functions.\nvoid AccessSummaryAnalysis::processArgument(FunctionInfo *info,\n SILFunctionArgument *argument,\n ArgumentSummary &summary,\n FunctionOrder &order) {\n unsigned argumentIndex = argument->getIndex();\n\n \/\/ Use a worklist to track argument uses to be processed.\n llvm::SmallVector worklist;\n\n \/\/ Start by adding the immediate uses of the argument to the worklist.\n worklist.append(argument->use_begin(), argument->use_end());\n\n \/\/ Iterate to follow uses of the arguments.\n while (!worklist.empty()) {\n Operand *operand = worklist.pop_back_val();\n SILInstruction *user = operand->getUser();\n\n switch (user->getKind()) {\n case ValueKind::BeginAccessInst: {\n auto *BAI = cast(user);\n summary.mergeWith(BAI->getAccessKind(), BAI->getLoc());\n \/\/ We don't add the users of the begin_access to the worklist because\n \/\/ even if these users eventually begin an access to the address\n \/\/ or a projection from it, that access can't begin more exclusive\n \/\/ access than this access -- otherwise it will be diagnosed\n \/\/ elsewhere.\n break;\n }\n case ValueKind::EndUnpairedAccessInst:\n \/\/ Don't diagnose unpaired access statically.\n assert(cast(user)->getEnforcement() ==\n SILAccessEnforcement::Dynamic);\n break;\n case ValueKind::StructElementAddrInst:\n case ValueKind::TupleElementAddrInst:\n \/\/ Eventually we'll summarize individual struct elements separately.\n \/\/ For now an access to a part of the struct is treated as an access\n \/\/ to the whole struct.\n worklist.append(user->use_begin(), user->use_end());\n break;\n case ValueKind::DebugValueAddrInst:\n case ValueKind::AddressToPointerInst:\n \/\/ Ignore these uses, they don't affect formal accesses.\n break;\n case ValueKind::PartialApplyInst:\n processPartialApply(info, argumentIndex, cast(user),\n operand, order);\n break;\n case ValueKind::ApplyInst:\n processFullApply(info, argumentIndex, cast(user), operand,\n order);\n break;\n case ValueKind::TryApplyInst:\n processFullApply(info, argumentIndex, cast(user), operand,\n order);\n break;\n case ValueKind::CopyAddrInst:\n case ValueKind::ExistentialMetatypeInst:\n case ValueKind::ValueMetatypeInst:\n case ValueKind::LoadInst:\n case ValueKind::LoadBorrowInst:\n case ValueKind::EndBorrowInst:\n case ValueKind::OpenExistentialAddrInst:\n case ValueKind::ProjectBlockStorageInst:\n \/\/ These likely represent scenarios in which we're not generating\n \/\/ begin access markers. Ignore these for now. But we really should\n \/\/ add SIL verification to ensure all loads and stores have associated\n \/\/ access markers.\n break;\n default:\n \/\/ TODO: These requirements should be checked for in the SIL verifier.\n \/\/ This is an assertion rather than llvm_unreachable() because\n \/\/ it is likely the whitelist above for scenarios in which we'ren\n \/\/ not generating access markers is not comprehensive.\n assert(false && \"Unrecognized argument use\");\n break;\n }\n }\n}\n\n#ifndef NDEBUG\n\/\/\/ Sanity check to make sure that a noescape partial apply is\n\/\/\/ only ultimately used by an apply, a try_apply or as an argument (but not\n\/\/\/ the called function) in a partial_apply.\n\/\/\/ TODO: This really should be checked in the SILVerifier.\nstatic bool hasExpectedUsesOfNoEscapePartialApply(Operand *partialApplyUse) {\n SILInstruction *user = partialApplyUse->getUser();\n\n \/\/ It is fine to call the partial apply\n switch (user->getKind()) {\n case ValueKind::ApplyInst:\n case ValueKind::TryApplyInst:\n return true;\n\n case ValueKind::ConvertFunctionInst:\n return llvm::all_of(user->getUses(),\n hasExpectedUsesOfNoEscapePartialApply);\n\n case ValueKind::PartialApplyInst:\n return partialApplyUse->get() != cast(user)->getCallee();\n\n case ValueKind::StoreInst:\n case ValueKind::DestroyValueInst:\n \/\/ @block_storage is passed by storing it to the stack. We know this is\n \/\/ still nonescaping simply because our original argument convention is\n \/\/ @inout_aliasable. In this SIL, both store and destroy_value are users\n \/\/ of %closure:\n \/\/\n \/\/ %closure = partial_apply %f1(%arg)\n \/\/ : $@convention(thin) (@inout_aliasable T) -> ()\n \/\/ %storage = alloc_stack $@block_storage @callee_owned () -> ()\n \/\/ %block_addr = project_block_storage %storage\n \/\/ : $*@block_storage @callee_owned () -> ()\n \/\/ store %closure to [init] %block_addr : $*@callee_owned () -> ()\n \/\/ %block = init_block_storage_header %storage\n \/\/ : $*@block_storage @callee_owned () -> (),\n \/\/ invoke %f2 : $@convention(c)\n \/\/ (@inout_aliasable @block_storage @callee_owned () -> ()) -> (),\n \/\/ type $@convention(block) () -> ()\n \/\/ %copy = copy_block %block : $@convention(block) () -> ()\n \/\/ destroy_value %storage : $@callee_owned () -> ()\n return true;\n default:\n return false;\n }\n}\n#endif\n\nvoid AccessSummaryAnalysis::processPartialApply(FunctionInfo *callerInfo,\n unsigned callerArgumentIndex,\n PartialApplyInst *apply,\n Operand *applyArgumentOperand,\n FunctionOrder &order) {\n SILFunction *calleeFunction = apply->getCalleeFunction();\n assert(calleeFunction && !calleeFunction->empty() &&\n \"Missing definition of noescape closure?\");\n\n \/\/ Make sure the partial_apply is not calling the result of another\n \/\/ partial_apply.\n assert(isa(apply->getCallee()) &&\n \"Noescape partial apply of non-functionref?\");\n\n assert(llvm::all_of(apply->getUses(),\n hasExpectedUsesOfNoEscapePartialApply) &&\n \"noescape partial_apply has unexpected use!\");\n\n \/\/ The argument index in the called function.\n ApplySite site(apply);\n unsigned calleeArgumentIndex = site.getCalleeArgIndex(*applyArgumentOperand);\n\n processCall(callerInfo, callerArgumentIndex, calleeFunction,\n calleeArgumentIndex, order);\n}\n\nvoid AccessSummaryAnalysis::processFullApply(FunctionInfo *callerInfo,\n unsigned callerArgumentIndex,\n FullApplySite apply,\n Operand *argumentOperand,\n FunctionOrder &order) {\n unsigned operandNumber = argumentOperand->getOperandNumber();\n assert(operandNumber > 0 && \"Summarizing apply for non-argument?\");\n\n unsigned calleeArgumentIndex = operandNumber - 1;\n SILFunction *callee = apply.getCalleeFunction();\n \/\/ We can't apply a summary for function whose body we can't see.\n \/\/ Since user-provided closures are always in the same module as their callee\n \/\/ This likely indicates a missing begin_access before an open-coded\n \/\/ call.\n if (!callee || callee->empty())\n return;\n\n processCall(callerInfo, callerArgumentIndex, callee, calleeArgumentIndex,\n order);\n}\n\nvoid AccessSummaryAnalysis::processCall(FunctionInfo *callerInfo,\n unsigned callerArgumentIndex,\n SILFunction *callee,\n unsigned argumentIndex,\n FunctionOrder &order) {\n \/\/ Record the flow of an argument from the caller to the callee so that\n \/\/ the interprocedural analysis can iterate to a fixpoint.\n FunctionInfo *calleeInfo = getFunctionInfo(callee);\n ArgumentFlow flow = {callerArgumentIndex, argumentIndex, calleeInfo};\n callerInfo->recordFlow(flow);\n if (!calleeInfo->isVisited()) {\n processFunction(calleeInfo, order);\n order.tryToSchedule(calleeInfo);\n }\n\n propagateFromCalleeToCaller(callerInfo, flow);\n}\n\nbool AccessSummaryAnalysis::ArgumentSummary::mergeWith(SILAccessKind otherKind,\n SILLocation otherLoc) {\n \/\/ In the lattice, a modification-like accesses subsume a read access or no\n \/\/ access.\n if (!Kind.hasValue() ||\n (*Kind == SILAccessKind::Read && otherKind != SILAccessKind::Read)) {\n Kind = otherKind;\n AccessLoc = otherLoc;\n return true;\n }\n\n return false;\n}\n\nbool AccessSummaryAnalysis::ArgumentSummary::mergeWith(\n const ArgumentSummary &other) {\n if (other.Kind.hasValue())\n return mergeWith(*other.Kind, other.AccessLoc);\n return false;\n}\n\nvoid AccessSummaryAnalysis::recompute(FunctionInfo *initial) {\n allocNewUpdateID();\n\n FunctionOrder order(getCurrentUpdateID());\n\n \/\/ Summarize the function and its callees.\n processFunction(initial, order);\n\n \/\/ Build the bottom-up order.\n order.tryToSchedule(initial);\n order.finishScheduling();\n\n \/\/ Iterate the interprocedural analysis to a fixed point.\n bool needAnotherIteration;\n do {\n needAnotherIteration = false;\n for (FunctionInfo *calleeInfo : order) {\n for (const auto &callerEntry : calleeInfo->getCallers()) {\n assert(callerEntry.isValid());\n if (!order.wasRecomputedWithCurrentUpdateID(calleeInfo))\n continue;\n\n FunctionInfo *callerInfo = callerEntry.Caller;\n\n \/\/ Propagate from callee to caller.\n for (const auto &argumentFlow : callerInfo->getArgumentFlows()) {\n if (argumentFlow.CalleeFunctionInfo != calleeInfo)\n continue;\n\n bool changed = propagateFromCalleeToCaller(callerInfo, argumentFlow);\n if (changed && !callerInfo->isScheduledAfter(calleeInfo)) {\n needAnotherIteration = true;\n }\n }\n }\n }\n } while (needAnotherIteration);\n}\n\nStringRef AccessSummaryAnalysis::ArgumentSummary::getDescription() const {\n if (Optional kind = getAccessKind()) {\n return getSILAccessKindName(*kind);\n }\n\n return \"none\";\n}\n\nbool AccessSummaryAnalysis::propagateFromCalleeToCaller(\n FunctionInfo *callerInfo, ArgumentFlow flow) {\n \/\/ For a given flow from a caller's argument to a callee's argument,\n \/\/ propagate the argument summary information to the caller.\n\n FunctionInfo *calleeInfo = flow.CalleeFunctionInfo;\n const auto &calleeArgument =\n calleeInfo->getSummary().getAccessForArgument(flow.CalleeArgumentIndex);\n auto &callerArgument =\n callerInfo->getSummary().getAccessForArgument(flow.CallerArgumentIndex);\n\n bool changed = callerArgument.mergeWith(calleeArgument);\n return changed;\n}\n\nAccessSummaryAnalysis::FunctionInfo *\nAccessSummaryAnalysis::getFunctionInfo(SILFunction *F) {\n FunctionInfo *&FInfo = FunctionInfos[F];\n if (!FInfo) {\n FInfo = new (Allocator.Allocate()) FunctionInfo(F);\n }\n return FInfo;\n}\n\nconst AccessSummaryAnalysis::FunctionSummary &\nAccessSummaryAnalysis::getOrCreateSummary(SILFunction *fn) {\n FunctionInfo *info = getFunctionInfo(fn);\n if (!info->isValid())\n recompute(info);\n\n return info->getSummary();\n}\n\nvoid AccessSummaryAnalysis::AccessSummaryAnalysis::invalidate() {\n FunctionInfos.clear();\n Allocator.DestroyAll();\n delete SubPathTrie;\n SubPathTrie = new IndexTrieNode();\n}\n\nvoid AccessSummaryAnalysis::invalidate(SILFunction *F, InvalidationKind K) {\n FunctionInfos.erase(F);\n}\n\nSILAnalysis *swift::createAccessSummaryAnalysis(SILModule *M) {\n return new AccessSummaryAnalysis();\n}\n\nraw_ostream &swift::\noperator<<(raw_ostream &os,\n const AccessSummaryAnalysis::FunctionSummary &summary) {\n unsigned argCount = summary.getArgumentCount();\n os << \"(\";\n\n if (argCount > 0) {\n os << summary.getAccessForArgument(0).getDescription();\n for (unsigned i = 1; i < argCount; i++) {\n os << \", \" << summary.getAccessForArgument(i).getDescription();\n }\n }\n\n os << \")\";\n return os;\n}\nDisable an unnecessary assert in AccessSummaryAnalysis.\/\/===--- AccessSummaryAnalysis.cpp - SIL Access Summary Analysis ----------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-access-summary-analysis\"\n#include \"swift\/SIL\/SILArgument.h\"\n#include \"swift\/SILOptimizer\/Analysis\/AccessSummaryAnalysis.h\"\n#include \"swift\/SILOptimizer\/Analysis\/FunctionOrder.h\"\n#include \"swift\/SILOptimizer\/PassManager\/PassManager.h\"\n\nusing namespace swift;\n\nvoid AccessSummaryAnalysis::processFunction(FunctionInfo *info,\n FunctionOrder &order) {\n \/\/ Does the summary need to be recomputed?\n if (order.prepareForVisiting(info))\n return;\n\n \/\/ Compute function summary on a per-argument basis.\n unsigned index = 0;\n for (SILArgument *arg : info->getFunction()->getArguments()) {\n FunctionSummary &functionSummary = info->getSummary();\n ArgumentSummary &argSummary =\n functionSummary.getAccessForArgument(index);\n index++;\n\n auto *functionArg = cast(arg);\n \/\/ Only summarize @inout_aliasable arguments.\n SILArgumentConvention convention =\n functionArg->getArgumentConvention().Value;\n if (convention != SILArgumentConvention::Indirect_InoutAliasable)\n continue;\n\n processArgument(info, functionArg, argSummary, order);\n }\n}\n\n\/\/\/ Track uses of the arguments, recording in the summary any accesses\n\/\/\/ started by a begin_access and any flows of the arguments to other\n\/\/\/ functions.\nvoid AccessSummaryAnalysis::processArgument(FunctionInfo *info,\n SILFunctionArgument *argument,\n ArgumentSummary &summary,\n FunctionOrder &order) {\n unsigned argumentIndex = argument->getIndex();\n\n \/\/ Use a worklist to track argument uses to be processed.\n llvm::SmallVector worklist;\n\n \/\/ Start by adding the immediate uses of the argument to the worklist.\n worklist.append(argument->use_begin(), argument->use_end());\n\n \/\/ Iterate to follow uses of the arguments.\n while (!worklist.empty()) {\n Operand *operand = worklist.pop_back_val();\n SILInstruction *user = operand->getUser();\n\n switch (user->getKind()) {\n case ValueKind::BeginAccessInst: {\n auto *BAI = cast(user);\n summary.mergeWith(BAI->getAccessKind(), BAI->getLoc());\n \/\/ We don't add the users of the begin_access to the worklist because\n \/\/ even if these users eventually begin an access to the address\n \/\/ or a projection from it, that access can't begin more exclusive\n \/\/ access than this access -- otherwise it will be diagnosed\n \/\/ elsewhere.\n break;\n }\n case ValueKind::EndUnpairedAccessInst:\n \/\/ Don't diagnose unpaired access statically.\n assert(cast(user)->getEnforcement() ==\n SILAccessEnforcement::Dynamic);\n break;\n case ValueKind::StructElementAddrInst:\n case ValueKind::TupleElementAddrInst:\n \/\/ Eventually we'll summarize individual struct elements separately.\n \/\/ For now an access to a part of the struct is treated as an access\n \/\/ to the whole struct.\n worklist.append(user->use_begin(), user->use_end());\n break;\n case ValueKind::DebugValueAddrInst:\n case ValueKind::AddressToPointerInst:\n \/\/ Ignore these uses, they don't affect formal accesses.\n break;\n case ValueKind::PartialApplyInst:\n processPartialApply(info, argumentIndex, cast(user),\n operand, order);\n break;\n case ValueKind::ApplyInst:\n processFullApply(info, argumentIndex, cast(user), operand,\n order);\n break;\n case ValueKind::TryApplyInst:\n processFullApply(info, argumentIndex, cast(user), operand,\n order);\n break;\n default:\n \/\/ FIXME: These likely represent scenarios in which we're not generating\n \/\/ begin access markers. Ignore these for now. But we really should\n \/\/ add SIL verification to ensure all loads and stores have associated\n \/\/ access markers. Once SIL verification is implemented, enable the\n \/\/ following assert to verify that the whitelist above is comprehensive,\n \/\/ which guarnatees that exclusivity enforcement is complete.\n \/\/ assert(false && \"Unrecognized argument use\");\n break;\n }\n }\n}\n\n#ifndef NDEBUG\n\/\/\/ Sanity check to make sure that a noescape partial apply is\n\/\/\/ only ultimately used by an apply, a try_apply or as an argument (but not\n\/\/\/ the called function) in a partial_apply.\n\/\/\/\n\/\/\/ FIXME: This needs to be checked in the SILVerifier.\nstatic bool hasExpectedUsesOfNoEscapePartialApply(Operand *partialApplyUse) {\n SILInstruction *user = partialApplyUse->getUser();\n\n \/\/ It is fine to call the partial apply\n switch (user->getKind()) {\n case ValueKind::ApplyInst:\n case ValueKind::TryApplyInst:\n return true;\n\n case ValueKind::ConvertFunctionInst:\n return llvm::all_of(user->getUses(),\n hasExpectedUsesOfNoEscapePartialApply);\n\n case ValueKind::PartialApplyInst:\n return partialApplyUse->get() != cast(user)->getCallee();\n\n case ValueKind::StoreInst:\n case ValueKind::DestroyValueInst:\n \/\/ @block_storage is passed by storing it to the stack. We know this is\n \/\/ still nonescaping simply because our original argument convention is\n \/\/ @inout_aliasable. In this SIL, both store and destroy_value are users\n \/\/ of %closure:\n \/\/\n \/\/ %closure = partial_apply %f1(%arg)\n \/\/ : $@convention(thin) (@inout_aliasable T) -> ()\n \/\/ %storage = alloc_stack $@block_storage @callee_owned () -> ()\n \/\/ %block_addr = project_block_storage %storage\n \/\/ : $*@block_storage @callee_owned () -> ()\n \/\/ store %closure to [init] %block_addr : $*@callee_owned () -> ()\n \/\/ %block = init_block_storage_header %storage\n \/\/ : $*@block_storage @callee_owned () -> (),\n \/\/ invoke %f2 : $@convention(c)\n \/\/ (@inout_aliasable @block_storage @callee_owned () -> ()) -> (),\n \/\/ type $@convention(block) () -> ()\n \/\/ %copy = copy_block %block : $@convention(block) () -> ()\n \/\/ destroy_value %storage : $@callee_owned () -> ()\n return true;\n default:\n return false;\n }\n}\n#endif\n\nvoid AccessSummaryAnalysis::processPartialApply(FunctionInfo *callerInfo,\n unsigned callerArgumentIndex,\n PartialApplyInst *apply,\n Operand *applyArgumentOperand,\n FunctionOrder &order) {\n SILFunction *calleeFunction = apply->getCalleeFunction();\n assert(calleeFunction && !calleeFunction->empty() &&\n \"Missing definition of noescape closure?\");\n\n \/\/ Make sure the partial_apply is not calling the result of another\n \/\/ partial_apply.\n assert(isa(apply->getCallee()) &&\n \"Noescape partial apply of non-functionref?\");\n\n assert(llvm::all_of(apply->getUses(),\n hasExpectedUsesOfNoEscapePartialApply) &&\n \"noescape partial_apply has unexpected use!\");\n\n \/\/ The argument index in the called function.\n ApplySite site(apply);\n unsigned calleeArgumentIndex = site.getCalleeArgIndex(*applyArgumentOperand);\n\n processCall(callerInfo, callerArgumentIndex, calleeFunction,\n calleeArgumentIndex, order);\n}\n\nvoid AccessSummaryAnalysis::processFullApply(FunctionInfo *callerInfo,\n unsigned callerArgumentIndex,\n FullApplySite apply,\n Operand *argumentOperand,\n FunctionOrder &order) {\n unsigned operandNumber = argumentOperand->getOperandNumber();\n assert(operandNumber > 0 && \"Summarizing apply for non-argument?\");\n\n unsigned calleeArgumentIndex = operandNumber - 1;\n SILFunction *callee = apply.getCalleeFunction();\n \/\/ We can't apply a summary for function whose body we can't see.\n \/\/ Since user-provided closures are always in the same module as their callee\n \/\/ This likely indicates a missing begin_access before an open-coded\n \/\/ call.\n if (!callee || callee->empty())\n return;\n\n processCall(callerInfo, callerArgumentIndex, callee, calleeArgumentIndex,\n order);\n}\n\nvoid AccessSummaryAnalysis::processCall(FunctionInfo *callerInfo,\n unsigned callerArgumentIndex,\n SILFunction *callee,\n unsigned argumentIndex,\n FunctionOrder &order) {\n \/\/ Record the flow of an argument from the caller to the callee so that\n \/\/ the interprocedural analysis can iterate to a fixpoint.\n FunctionInfo *calleeInfo = getFunctionInfo(callee);\n ArgumentFlow flow = {callerArgumentIndex, argumentIndex, calleeInfo};\n callerInfo->recordFlow(flow);\n if (!calleeInfo->isVisited()) {\n processFunction(calleeInfo, order);\n order.tryToSchedule(calleeInfo);\n }\n\n propagateFromCalleeToCaller(callerInfo, flow);\n}\n\nbool AccessSummaryAnalysis::ArgumentSummary::mergeWith(SILAccessKind otherKind,\n SILLocation otherLoc) {\n \/\/ In the lattice, a modification-like accesses subsume a read access or no\n \/\/ access.\n if (!Kind.hasValue() ||\n (*Kind == SILAccessKind::Read && otherKind != SILAccessKind::Read)) {\n Kind = otherKind;\n AccessLoc = otherLoc;\n return true;\n }\n\n return false;\n}\n\nbool AccessSummaryAnalysis::ArgumentSummary::mergeWith(\n const ArgumentSummary &other) {\n if (other.Kind.hasValue())\n return mergeWith(*other.Kind, other.AccessLoc);\n return false;\n}\n\nvoid AccessSummaryAnalysis::recompute(FunctionInfo *initial) {\n allocNewUpdateID();\n\n FunctionOrder order(getCurrentUpdateID());\n\n \/\/ Summarize the function and its callees.\n processFunction(initial, order);\n\n \/\/ Build the bottom-up order.\n order.tryToSchedule(initial);\n order.finishScheduling();\n\n \/\/ Iterate the interprocedural analysis to a fixed point.\n bool needAnotherIteration;\n do {\n needAnotherIteration = false;\n for (FunctionInfo *calleeInfo : order) {\n for (const auto &callerEntry : calleeInfo->getCallers()) {\n assert(callerEntry.isValid());\n if (!order.wasRecomputedWithCurrentUpdateID(calleeInfo))\n continue;\n\n FunctionInfo *callerInfo = callerEntry.Caller;\n\n \/\/ Propagate from callee to caller.\n for (const auto &argumentFlow : callerInfo->getArgumentFlows()) {\n if (argumentFlow.CalleeFunctionInfo != calleeInfo)\n continue;\n\n bool changed = propagateFromCalleeToCaller(callerInfo, argumentFlow);\n if (changed && !callerInfo->isScheduledAfter(calleeInfo)) {\n needAnotherIteration = true;\n }\n }\n }\n }\n } while (needAnotherIteration);\n}\n\nStringRef AccessSummaryAnalysis::ArgumentSummary::getDescription() const {\n if (Optional kind = getAccessKind()) {\n return getSILAccessKindName(*kind);\n }\n\n return \"none\";\n}\n\nbool AccessSummaryAnalysis::propagateFromCalleeToCaller(\n FunctionInfo *callerInfo, ArgumentFlow flow) {\n \/\/ For a given flow from a caller's argument to a callee's argument,\n \/\/ propagate the argument summary information to the caller.\n\n FunctionInfo *calleeInfo = flow.CalleeFunctionInfo;\n const auto &calleeArgument =\n calleeInfo->getSummary().getAccessForArgument(flow.CalleeArgumentIndex);\n auto &callerArgument =\n callerInfo->getSummary().getAccessForArgument(flow.CallerArgumentIndex);\n\n bool changed = callerArgument.mergeWith(calleeArgument);\n return changed;\n}\n\nAccessSummaryAnalysis::FunctionInfo *\nAccessSummaryAnalysis::getFunctionInfo(SILFunction *F) {\n FunctionInfo *&FInfo = FunctionInfos[F];\n if (!FInfo) {\n FInfo = new (Allocator.Allocate()) FunctionInfo(F);\n }\n return FInfo;\n}\n\nconst AccessSummaryAnalysis::FunctionSummary &\nAccessSummaryAnalysis::getOrCreateSummary(SILFunction *fn) {\n FunctionInfo *info = getFunctionInfo(fn);\n if (!info->isValid())\n recompute(info);\n\n return info->getSummary();\n}\n\nvoid AccessSummaryAnalysis::AccessSummaryAnalysis::invalidate() {\n FunctionInfos.clear();\n Allocator.DestroyAll();\n delete SubPathTrie;\n SubPathTrie = new IndexTrieNode();\n}\n\nvoid AccessSummaryAnalysis::invalidate(SILFunction *F, InvalidationKind K) {\n FunctionInfos.erase(F);\n}\n\nSILAnalysis *swift::createAccessSummaryAnalysis(SILModule *M) {\n return new AccessSummaryAnalysis();\n}\n\nraw_ostream &swift::\noperator<<(raw_ostream &os,\n const AccessSummaryAnalysis::FunctionSummary &summary) {\n unsigned argCount = summary.getArgumentCount();\n os << \"(\";\n\n if (argCount > 0) {\n os << summary.getAccessForArgument(0).getDescription();\n for (unsigned i = 1; i < argCount; i++) {\n os << \", \" << summary.getAccessForArgument(i).getDescription();\n }\n }\n\n os << \")\";\n return os;\n}\n<|endoftext|>"} {"text":"\/** ==========================================================================\n* 2013 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes\n* with no warranties. This code is yours to share, use and modify with no\n* strings attached and no restrictions or obligations.\n *\n * For more information see g3log\/LICENSE or refer refer to http:\/\/unlicense.org\n* ============================================================================*\/\n\n#pragma once\n\n#include \"g3log\/logmessage.hpp\"\n\nnamespace g3 {\n namespace internal {\n\n struct SinkWrapper {\n virtual ~SinkWrapper() { }\n virtual void send(LogMessageMover msg) = 0;\n };\n }\n}\n\ncompiles on arm\/** ==========================================================================\n* 2013 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes\n* with no warranties. This code is yours to share, use and modify with no\n* strings attached and no restrictions or obligations.\n *\n * For more information see g3log\/LICENSE or refer refer to http:\/\/unlicense.org\n* ============================================================================*\/\n\n#pragma once\n\n#include \"g3log\/logmessage.hpp\"\n\nnamespace g3 {\n namespace internal {\n\n struct SinkWrapper {\n virtual ~SinkWrapper() { }\n virtual void send(LogMessageMover msg) { }\n };\n }\n}\n\n<|endoftext|>"} {"text":"\n\/**********************************************************************************\n * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *\n * Package: TMVA *\n * Classes: PDEFoamDistr *\n * Web : http:\/\/tmva.sourceforge.net *\n * *\n * Description: *\n * The TFDSITR class provides an interface between the Binary search tree *\n * and the PDEFoam object. In order to build-up the foam one needs to *\n * calculate the density of events at a given point (sampling during *\n * Foam build-up). The function PDEFoamDistr::Density() does this job. It *\n * uses a binary search tree, filled with training events, in order to *\n * provide this density. *\n * *\n * Authors (alphabetical): *\n * Tancredi Carli - CERN, Switzerland *\n * Dominik Dannheim - CERN, Switzerland *\n * S. Jadach - Institute of Nuclear Physics, Cracow, Poland *\n * Alexander Voigt - CERN, Switzerland *\n * Peter Speckmayer - CERN, Switzerland *\n * *\n * Copyright (c) 2008: *\n * CERN, Switzerland *\n * MPI-K Heidelberg, Germany *\n * *\n * Redistribution and use in source and binary forms, with or without *\n * modification, are permitted according to the terms listed in LICENSE *\n * (http:\/\/tmva.sourceforge.net\/LICENSE) *\n **********************************************************************************\/\n\n#ifndef ROOT_TMath\n#include \"TMath.h\"\n#endif\n\n#ifndef ROOT_TMVA_PDEFoamDistr\n#include \"TMVA\/PDEFoamDistr.h\"\n#endif\n\nClassImp(TMVA::PDEFoamDistr)\n\n\/\/_____________________________________________________________________\nTMVA::PDEFoamDistr::PDEFoamDistr() \n : TObject(),\n fDim(-1),\n fXmin(0),\n fXmax(0),\n fVolFrac(-1.),\n fBst(NULL),\n fDensityCalc(kEVENT_DENSITY), \/\/ default: fill event density to BinarySearchTree\n fSignalClass(1),\n fBackgroundClass(0),\n fLogger( new MsgLogger(\"PDEFoamDistr\"))\n{}\n\n\/\/_____________________________________________________________________\nTMVA::PDEFoamDistr::~PDEFoamDistr() \n{\n if (fBst) delete fBst;\n if (fXmin) delete [] fXmin; fXmin=0;\n if (fXmax) delete [] fXmax; fXmax=0;\n delete fLogger;\n}\n\n\/\/_____________________________________________________________________\nTMVA::PDEFoamDistr::PDEFoamDistr(const PDEFoamDistr &distr)\n : TObject(),\n fDim (distr.fDim),\n fXmin (distr.fXmin),\n fXmax (distr.fXmax),\n fVolFrac (distr.fVolFrac),\n fBst (distr.fBst),\n fDensityCalc (kEVENT_DENSITY), \/\/ default: fill event density to BinarySearchTree\n fSignalClass (distr.fSignalClass),\n fBackgroundClass (distr.fBackgroundClass),\n fLogger( new MsgLogger(\"PDEFoamDistr\"))\n{\n \/\/ Copy constructor\n Log() << kFATAL << \"COPY CONSTRUCTOR NOT IMPLEMENTED\" << Endl;\n}\n\n\/\/_____________________________________________________________________\nvoid TMVA::PDEFoamDistr::Initialize( Int_t ndim )\n{\n \/\/ Initialisation procedure of internal foam density.\n \/\/ Set dimension to 'ndim' and create BinarySearchTree.\n\n SetDim(ndim); \/\/ set dimension of BST\n\n if (fBst) delete fBst;\n fBst = new TMVA::BinarySearchTree();\n\n if (!fBst){\n Log() << kFATAL << \" \"\n << \"ERROR: an not create binary tree !\" << Endl;\n }\n\n fBst->SetPeriode(fDim);\n}\n\n\/\/_____________________________________________________________________\nvoid TMVA::PDEFoamDistr::SetDim(Int_t idim)\n{\n \/\/ set dimension of distribution\n\n fDim = idim;\n if (fXmin) delete [] fXmin;\n if (fXmax) delete [] fXmax;\n fXmin = new Float_t[fDim];\n fXmax = new Float_t[fDim];\n return;\n}\n\n\/\/_____________________________________________________________________\nvoid TMVA::PDEFoamDistr::FillBinarySearchTree( const Event* ev, EFoamType ft, Bool_t NoNegWeights )\n{\n \/\/ This method creates an TMVA::Event and inserts it into the\n \/\/ binary search tree.\n \/\/\n \/\/ If 'NoNegWeights' is true, an event with negative weight will\n \/\/ not be filled into the foam. (Default value: false)\n\n if((NoNegWeights && ev->GetWeight()<=0) || ev->GetOriginalWeight()==0)\n return;\n\n TMVA::Event *event = new TMVA::Event(*ev);\n \n \/\/ set event class and normalization\n if (ft==kSeparate || ft==kDiscr){\n event->SetClass(ev->GetClass()==fSignalClass ? fSignalClass : fBackgroundClass);\n } else if (ft==kMultiTarget){\n \/\/ since in multi target regression targets are handled like\n \/\/ variables, remove targets and add them to the event variabels\n std::vector targets = ev->GetTargets();\n for (UInt_t i = 0; i < targets.size(); i++)\n event->SetVal(i+ev->GetValues().size(), targets.at(i));\n event->GetTargets().clear();\n event->SetClass(fSignalClass);\n }\n fBst->Insert(event);\n}\n\n\/\/_____________________________________________________________________\nDouble_t TMVA::PDEFoamDistr::Density( Double_t *Xarg, Double_t &event_density )\n{\n \/\/ This function is needed during the foam buildup.\n \/\/ It return a certain density depending on the selected classification\n \/\/ or regression options:\n \/\/\n \/\/ In case of separated foams (classification) or multi target regression:\n \/\/ - returns event density within volume (specified by VolFrac)\n \/\/ In case of unified foams: (classification)\n \/\/ - returns discriminator (N_sig)\/(N_sig + N_bg) divided by volume\n \/\/ (specified by VolFrac)\n \/\/ In case of mono target regression:\n \/\/ - returns average target value within volume divided by volume\n \/\/ (specified by VolFrac)\n\n if (!fBst)\n Log() << kFATAL << \" Binary tree not found!\"<< Endl;\n\n \/\/ make the variable Xarg transform, since Foam only knows about x=[0,1]\n \/\/ transformation [0, 1] --> [xmin, xmax]\n for (Int_t idim=0; idim lb(fDim);\n std::vector ub(fDim);\n\n \/\/ probevolume relative to hypercube with edge length 1:\n static const Double_t probevolume_inv = TMath::Power((fVolFrac\/2), fDim);\n\n \/\/ set upper and lower bound for search volume\n for (Int_t idim = 0; idim < fDim; idim++) {\n Double_t volsize=(fXmax[idim] - fXmin[idim]) \/ fVolFrac;\n lb[idim] = Xarg[idim] - volsize;\n ub[idim] = Xarg[idim] + volsize;\n }\n\n TMVA::Volume volume(&lb, &ub); \/\/ volume to search in\n std::vector nodes; \/\/ BST nodes found\n\n \/\/ do range searching\n fBst->SearchVolume(&volume, &nodes);\n\n \/\/ normalized density: (number of counted events) \/ volume \/ (total\n \/\/ number of events) should be ~1 on average\n const Double_t count = (Double_t) (nodes.size()); \/\/ number of events found\n\n \/\/ store density based on total number of events\n event_density = count * probevolume_inv;\n\n Double_t weighted_count = 0.; \/\/ number of events found (sum of weights!)\n for (UInt_t j=0; jGetWeight();\n\n if (FillDiscriminator()){ \/\/ calc number of signal events in nodes\n Double_t N_sig = 0; \/\/ number of target events found\n \/\/ now sum over all nodes->IsSignal;\n for (Int_t j=0; jIsSignal()?1.:0.) * (nodes.at(j))->GetWeight();\n }\n return (N_sig\/(weighted_count+0.1))*probevolume_inv; \/\/ return: (N_sig\/N_total) \/ (cell_volume)\n }\n else if (FillTarget0()){ \/\/ calc sum of weighted target values\n Double_t N_tar = 0; \/\/ number of target events found\n \/\/ now sum over all nodes->GetTarget(0);\n for (Int_t j=0; jGetTargets()).at(0) * ((nodes.at(j))->GetWeight());\n }\n return (N_tar\/(weighted_count+0.1))*probevolume_inv; \/\/ return: (N_tar\/N_total) \/ (cell_volume)\n }\n\n return ((weighted_count+0.1)*probevolume_inv); \/\/ return: N_total(weighted) \/ cell_volume\n}\nfix clang warning (operands of ? are integers of different signs).\n\/**********************************************************************************\n * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *\n * Package: TMVA *\n * Classes: PDEFoamDistr *\n * Web : http:\/\/tmva.sourceforge.net *\n * *\n * Description: *\n * The TFDSITR class provides an interface between the Binary search tree *\n * and the PDEFoam object. In order to build-up the foam one needs to *\n * calculate the density of events at a given point (sampling during *\n * Foam build-up). The function PDEFoamDistr::Density() does this job. It *\n * uses a binary search tree, filled with training events, in order to *\n * provide this density. *\n * *\n * Authors (alphabetical): *\n * Tancredi Carli - CERN, Switzerland *\n * Dominik Dannheim - CERN, Switzerland *\n * S. Jadach - Institute of Nuclear Physics, Cracow, Poland *\n * Alexander Voigt - CERN, Switzerland *\n * Peter Speckmayer - CERN, Switzerland *\n * *\n * Copyright (c) 2008: *\n * CERN, Switzerland *\n * MPI-K Heidelberg, Germany *\n * *\n * Redistribution and use in source and binary forms, with or without *\n * modification, are permitted according to the terms listed in LICENSE *\n * (http:\/\/tmva.sourceforge.net\/LICENSE) *\n **********************************************************************************\/\n\n#ifndef ROOT_TMath\n#include \"TMath.h\"\n#endif\n\n#ifndef ROOT_TMVA_PDEFoamDistr\n#include \"TMVA\/PDEFoamDistr.h\"\n#endif\n\nClassImp(TMVA::PDEFoamDistr)\n\n\/\/_____________________________________________________________________\nTMVA::PDEFoamDistr::PDEFoamDistr() \n : TObject(),\n fDim(-1),\n fXmin(0),\n fXmax(0),\n fVolFrac(-1.),\n fBst(NULL),\n fDensityCalc(kEVENT_DENSITY), \/\/ default: fill event density to BinarySearchTree\n fSignalClass(1),\n fBackgroundClass(0),\n fLogger( new MsgLogger(\"PDEFoamDistr\"))\n{}\n\n\/\/_____________________________________________________________________\nTMVA::PDEFoamDistr::~PDEFoamDistr() \n{\n if (fBst) delete fBst;\n if (fXmin) delete [] fXmin; fXmin=0;\n if (fXmax) delete [] fXmax; fXmax=0;\n delete fLogger;\n}\n\n\/\/_____________________________________________________________________\nTMVA::PDEFoamDistr::PDEFoamDistr(const PDEFoamDistr &distr)\n : TObject(),\n fDim (distr.fDim),\n fXmin (distr.fXmin),\n fXmax (distr.fXmax),\n fVolFrac (distr.fVolFrac),\n fBst (distr.fBst),\n fDensityCalc (kEVENT_DENSITY), \/\/ default: fill event density to BinarySearchTree\n fSignalClass (distr.fSignalClass),\n fBackgroundClass (distr.fBackgroundClass),\n fLogger( new MsgLogger(\"PDEFoamDistr\"))\n{\n \/\/ Copy constructor\n Log() << kFATAL << \"COPY CONSTRUCTOR NOT IMPLEMENTED\" << Endl;\n}\n\n\/\/_____________________________________________________________________\nvoid TMVA::PDEFoamDistr::Initialize( Int_t ndim )\n{\n \/\/ Initialisation procedure of internal foam density.\n \/\/ Set dimension to 'ndim' and create BinarySearchTree.\n\n SetDim(ndim); \/\/ set dimension of BST\n\n if (fBst) delete fBst;\n fBst = new TMVA::BinarySearchTree();\n\n if (!fBst){\n Log() << kFATAL << \" \"\n << \"ERROR: an not create binary tree !\" << Endl;\n }\n\n fBst->SetPeriode(fDim);\n}\n\n\/\/_____________________________________________________________________\nvoid TMVA::PDEFoamDistr::SetDim(Int_t idim)\n{\n \/\/ set dimension of distribution\n\n fDim = idim;\n if (fXmin) delete [] fXmin;\n if (fXmax) delete [] fXmax;\n fXmin = new Float_t[fDim];\n fXmax = new Float_t[fDim];\n return;\n}\n\n\/\/_____________________________________________________________________\nvoid TMVA::PDEFoamDistr::FillBinarySearchTree( const Event* ev, EFoamType ft, Bool_t NoNegWeights )\n{\n \/\/ This method creates an TMVA::Event and inserts it into the\n \/\/ binary search tree.\n \/\/\n \/\/ If 'NoNegWeights' is true, an event with negative weight will\n \/\/ not be filled into the foam. (Default value: false)\n\n if((NoNegWeights && ev->GetWeight()<=0) || ev->GetOriginalWeight()==0)\n return;\n\n TMVA::Event *event = new TMVA::Event(*ev);\n \n \/\/ set event class and normalization\n if (ft==kSeparate || ft==kDiscr){\n event->SetClass(ev->GetClass()==fSignalClass ? fSignalClass : (UInt_t)fBackgroundClass);\n } else if (ft==kMultiTarget){\n \/\/ since in multi target regression targets are handled like\n \/\/ variables, remove targets and add them to the event variabels\n std::vector targets = ev->GetTargets();\n for (UInt_t i = 0; i < targets.size(); i++)\n event->SetVal(i+ev->GetValues().size(), targets.at(i));\n event->GetTargets().clear();\n event->SetClass(fSignalClass);\n }\n fBst->Insert(event);\n}\n\n\/\/_____________________________________________________________________\nDouble_t TMVA::PDEFoamDistr::Density( Double_t *Xarg, Double_t &event_density )\n{\n \/\/ This function is needed during the foam buildup.\n \/\/ It return a certain density depending on the selected classification\n \/\/ or regression options:\n \/\/\n \/\/ In case of separated foams (classification) or multi target regression:\n \/\/ - returns event density within volume (specified by VolFrac)\n \/\/ In case of unified foams: (classification)\n \/\/ - returns discriminator (N_sig)\/(N_sig + N_bg) divided by volume\n \/\/ (specified by VolFrac)\n \/\/ In case of mono target regression:\n \/\/ - returns average target value within volume divided by volume\n \/\/ (specified by VolFrac)\n\n if (!fBst)\n Log() << kFATAL << \" Binary tree not found!\"<< Endl;\n\n \/\/ make the variable Xarg transform, since Foam only knows about x=[0,1]\n \/\/ transformation [0, 1] --> [xmin, xmax]\n for (Int_t idim=0; idim lb(fDim);\n std::vector ub(fDim);\n\n \/\/ probevolume relative to hypercube with edge length 1:\n static const Double_t probevolume_inv = TMath::Power((fVolFrac\/2), fDim);\n\n \/\/ set upper and lower bound for search volume\n for (Int_t idim = 0; idim < fDim; idim++) {\n Double_t volsize=(fXmax[idim] - fXmin[idim]) \/ fVolFrac;\n lb[idim] = Xarg[idim] - volsize;\n ub[idim] = Xarg[idim] + volsize;\n }\n\n TMVA::Volume volume(&lb, &ub); \/\/ volume to search in\n std::vector nodes; \/\/ BST nodes found\n\n \/\/ do range searching\n fBst->SearchVolume(&volume, &nodes);\n\n \/\/ normalized density: (number of counted events) \/ volume \/ (total\n \/\/ number of events) should be ~1 on average\n const Double_t count = (Double_t) (nodes.size()); \/\/ number of events found\n\n \/\/ store density based on total number of events\n event_density = count * probevolume_inv;\n\n Double_t weighted_count = 0.; \/\/ number of events found (sum of weights!)\n for (UInt_t j=0; jGetWeight();\n\n if (FillDiscriminator()){ \/\/ calc number of signal events in nodes\n Double_t N_sig = 0; \/\/ number of target events found\n \/\/ now sum over all nodes->IsSignal;\n for (Int_t j=0; jIsSignal()?1.:0.) * (nodes.at(j))->GetWeight();\n }\n return (N_sig\/(weighted_count+0.1))*probevolume_inv; \/\/ return: (N_sig\/N_total) \/ (cell_volume)\n }\n else if (FillTarget0()){ \/\/ calc sum of weighted target values\n Double_t N_tar = 0; \/\/ number of target events found\n \/\/ now sum over all nodes->GetTarget(0);\n for (Int_t j=0; jGetTargets()).at(0) * ((nodes.at(j))->GetWeight());\n }\n return (N_tar\/(weighted_count+0.1))*probevolume_inv; \/\/ return: (N_tar\/N_total) \/ (cell_volume)\n }\n\n return ((weighted_count+0.1)*probevolume_inv); \/\/ return: N_total(weighted) \/ cell_volume\n}\n<|endoftext|>"} {"text":"#include \"gamelib\/core\/Game.hpp\"\n#include \n#include \n#include \"gamelib\/core\/GameState.hpp\"\n#include \"gamelib\/utils\/log.hpp\"\n#include \"gamelib\/core\/event\/EventManager.hpp\"\n#include \"gamelib\/events\/SFMLEvent.hpp\"\n#include \"gamelib\/core\/input\/InputSystem.hpp\"\n#include \"imgui-SFML.h\"\n#include \"imgui.h\"\n\nnamespace gamelib\n{\n Game::Game() :\n bgcolor(sf::Color::Black),\n closebutton(true),\n escclose(true),\n unfocusPause(true),\n _frametime(0),\n _rendertime(0),\n _updatetime(0),\n _size(640, 480),\n _maxfps(60),\n _title(\"Unnamed Game\"),\n _repeatkeys(false),\n _vsync(true),\n _initialized(false)\n {\n#define WIN_PROP_SET_LAMBDA(varname, winfunc) \\\n +[](const decltype(varname)* val, Game* self) { \\\n self->varname = *val; \\\n if (self->_window.isOpen()) \\\n self->_window.winfunc(*val); \\\n }\n\n auto setSize = +[](const math::Vec2i* val, Game* self) {\n self->resize(sf::Vector2u(val->x, val->y));\n };\n\n _props.registerProperty(\"bgcolor\", bgcolor);\n _props.registerProperty(\"closebutton\", closebutton);\n _props.registerProperty(\"escclose\", escclose);\n _props.registerProperty(\"unfocusPause\", unfocusPause);\n _props.registerProperty(\"size\", _size, setSize, this);\n _props.registerProperty(\"maxfps\", _maxfps, WIN_PROP_SET_LAMBDA(_maxfps, setFramerateLimit), this, 0, INT_MAX);\n _props.registerProperty(\"vsync\", _vsync, WIN_PROP_SET_LAMBDA(_vsync, setVerticalSyncEnabled), this);\n _props.registerProperty(\"title\", _title, WIN_PROP_SET_LAMBDA(_title, setTitle), this);\n _props.registerProperty(\"repeatkeys\", _repeatkeys, WIN_PROP_SET_LAMBDA(_repeatkeys, setKeyRepeatEnabled), this);\n }\n\n Game::~Game()\n {\n destroy();\n }\n\n\n bool Game::init()\n {\n LOG(\"Initializing game...\");\n _window.create(sf::VideoMode(_size.x, _size.y), _title, sf::Style::Close);\n _window.setFramerateLimit(_maxfps);\n _window.setVerticalSyncEnabled(_vsync);\n _window.setKeyRepeatEnabled(_repeatkeys);\n\n ImGui::SFML::Init(_window);\n\n \/\/ ImGui::StyleColorsClassic();\n ImGui::GetStyle().WindowBorderSize = 0;\n ImGui::GetStyle().WindowRounding = 0;\n ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_DockingEnable;\n ImGui::GetIO().ConfigDockingWithShift = false;\n ImGui::GetIO().ConfigWindowsResizeFromEdges = true;\n\n _initialized = true;\n\n return true;\n }\n\n auto Game::isInitialized() const -> bool\n {\n return _initialized;\n }\n\n void Game::run()\n {\n if (!isInitialized())\n {\n LOG_ERROR(\"Game is not initialized\");\n return;\n }\n\n sf::Clock clock, detailclock;\n sf::Event ev;\n\n while (_window.isOpen())\n {\n clock.restart();\n detailclock.restart();\n\n auto inputsys = getSubsystem();\n if (inputsys)\n inputsys->beginFrame();\n\n while (_window.pollEvent(ev))\n {\n if (inputsys)\n inputsys->process(ev);\n\n ImGui::SFML::ProcessEvent(ev);\n\n \/\/ TODO: clear keyboard\n\n auto evmgr = getSubsystem();\n if (evmgr)\n evmgr->triggerEvent(SFMLEvent::create(ev));\n\n if (closebutton && ev.type == sf::Event::Closed)\n {\n close();\n return;\n }\n }\n\n if (_window.hasFocus() || !unfocusPause)\n {\n ImGui::SFML::Update(_window, sf::seconds(_frametime));\n\n bool frozen = false;\n for (auto it = _states.rbegin(), end = _states.rend(); it != end; ++it)\n {\n auto state = (*it).get();\n if (state->flags & gamestate_paused)\n continue;\n\n if (!frozen || state->flags & gamestate_forceupdate)\n state->update(_frametime);\n\n if (state->flags & gamestate_freeze)\n frozen = true;\n }\n\n if (escclose && inputsys && inputsys->isKeyPressed(sf::Keyboard::Escape))\n {\n close();\n return;\n }\n }\n\n _updatetime = detailclock.getElapsedTime().asMilliseconds() \/ 1000.f;\n detailclock.restart();\n\n _window.resetGLStates(); \/\/ without this things start randomly disappearing\n _window.clear(bgcolor);\n\n if (_vsync)\n detailclock.restart();\n\n for (auto& i : _states)\n i->render(_window);\n\n ImGui::SFML::Render(_window);\n\n \/\/ TODO: implement own fps capping.\n \/\/ SFML caps inside window.display(), so it's impossible to get the exact render time\n if (!_vsync)\n _rendertime = detailclock.getElapsedTime().asMilliseconds() \/ 1000.0f;\n\n _window.display();\n\n if (_vsync)\n _rendertime = detailclock.getElapsedTime().asMilliseconds() \/ 1000.0f;\n\n \/\/ Get elapsed time\n _frametime = clock.getElapsedTime().asMilliseconds() \/ 1000.0f;\n }\n }\n\n void Game::close()\n {\n if (_window.isOpen())\n {\n _window.close();\n LOG_DEBUG(\"Game window closed\");\n }\n }\n\n void Game::destroy()\n {\n if (!isInitialized())\n return;\n\n close();\n\n if (!_states.empty())\n {\n LOG_DEBUG(\"Closing game states...\");\n for (auto& i : _states)\n i->quit();\n _states.clear();\n }\n\n ImGui::SFML::Shutdown();\n _initialized = false;\n }\n\n\n bool Game::loadFromJson(const Json::Value& node)\n {\n return _props.loadFromJson(node);\n }\n\n void Game::writeToJson(Json::Value& node) const\n {\n _props.writeToJson(node);\n }\n\n\n void Game::pushState(std::unique_ptr state)\n {\n if (!state->init(this))\n {\n LOG_ERROR(\"Failed to initialize game state\");\n return;\n }\n _states.push_back(std::move(state));\n LOG_DEBUG(\"Game state added\");\n }\n\n void Game::popState()\n {\n _states.back()->quit();\n _states.pop_back();\n }\n\n GameState* Game::pullState() const\n {\n return _states.back().get();\n }\n\n float Game::getFrametime() const\n {\n return _frametime;\n }\n\n float Game::getRealFrametime() const\n {\n return _rendertime + _updatetime;\n }\n\n float Game::getRenderTime() const\n {\n return _rendertime;\n }\n\n float Game::getUpdateTime() const\n {\n return _updatetime;\n }\n\n sf::RenderWindow& Game::getWindow()\n {\n return _window;\n }\n\n const PropertyContainer& Game::getProperties() const\n {\n return _props;\n }\n\n void Game::resize(const sf::Vector2u& size)\n {\n if (size.x <= 0 || size.y <= 0)\n {\n LOG_ERROR(\"Invalid window size: \", size.x, \"x\", size.y);\n return;\n }\n\n _size.fill(size.x, size.y);\n\n if (_window.isOpen())\n {\n auto diff = size - _window.getSize();\n auto pos = _window.getPosition();\n pos.x -= diff.x \/ 2;\n pos.y -= diff.y \/ 2;\n\n _window.setSize(size);\n _window.setPosition(pos);\n _window.setView(sf::View(sf::FloatRect(0, 0, size.x, size.y)));\n }\n\n \/\/ Don't create a new window, as it could lead to problems\n \/\/ if (size != _window.getSize())\n \/\/ {\n \/\/ _window.close();\n \/\/ _window.create(sf::VideoMode(size.x, size.y), game_title, sf::Style::Close);\n \/\/ }\n }\n}\n\nMake game window resizable#include \"gamelib\/core\/Game.hpp\"\n#include \n#include \n#include \"gamelib\/core\/GameState.hpp\"\n#include \"gamelib\/utils\/log.hpp\"\n#include \"gamelib\/core\/event\/EventManager.hpp\"\n#include \"gamelib\/events\/SFMLEvent.hpp\"\n#include \"gamelib\/core\/input\/InputSystem.hpp\"\n#include \"imgui-SFML.h\"\n#include \"imgui.h\"\n\nnamespace gamelib\n{\n Game::Game() :\n bgcolor(sf::Color::Black),\n closebutton(true),\n escclose(true),\n unfocusPause(true),\n _frametime(0),\n _rendertime(0),\n _updatetime(0),\n _size(640, 480),\n _maxfps(60),\n _title(\"Unnamed Game\"),\n _repeatkeys(false),\n _vsync(true),\n _initialized(false)\n {\n#define WIN_PROP_SET_LAMBDA(varname, winfunc) \\\n +[](const decltype(varname)* val, Game* self) { \\\n self->varname = *val; \\\n if (self->_window.isOpen()) \\\n self->_window.winfunc(*val); \\\n }\n\n auto setSize = +[](const math::Vec2i* val, Game* self) {\n self->resize(sf::Vector2u(val->x, val->y));\n };\n\n _props.registerProperty(\"bgcolor\", bgcolor);\n _props.registerProperty(\"closebutton\", closebutton);\n _props.registerProperty(\"escclose\", escclose);\n _props.registerProperty(\"unfocusPause\", unfocusPause);\n _props.registerProperty(\"size\", _size, setSize, this);\n _props.registerProperty(\"maxfps\", _maxfps, WIN_PROP_SET_LAMBDA(_maxfps, setFramerateLimit), this, 0, INT_MAX);\n _props.registerProperty(\"vsync\", _vsync, WIN_PROP_SET_LAMBDA(_vsync, setVerticalSyncEnabled), this);\n _props.registerProperty(\"title\", _title, WIN_PROP_SET_LAMBDA(_title, setTitle), this);\n _props.registerProperty(\"repeatkeys\", _repeatkeys, WIN_PROP_SET_LAMBDA(_repeatkeys, setKeyRepeatEnabled), this);\n }\n\n Game::~Game()\n {\n destroy();\n }\n\n\n bool Game::init()\n {\n LOG(\"Initializing game...\");\n _window.create(sf::VideoMode(_size.x, _size.y), _title);\n _window.setFramerateLimit(_maxfps);\n _window.setVerticalSyncEnabled(_vsync);\n _window.setKeyRepeatEnabled(_repeatkeys);\n\n ImGui::SFML::Init(_window);\n\n \/\/ ImGui::StyleColorsClassic();\n ImGui::GetStyle().WindowBorderSize = 0;\n ImGui::GetStyle().WindowRounding = 0;\n ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_DockingEnable;\n ImGui::GetIO().ConfigDockingWithShift = false;\n ImGui::GetIO().ConfigWindowsResizeFromEdges = true;\n\n _initialized = true;\n\n return true;\n }\n\n auto Game::isInitialized() const -> bool\n {\n return _initialized;\n }\n\n void Game::run()\n {\n if (!isInitialized())\n {\n LOG_ERROR(\"Game is not initialized\");\n return;\n }\n\n sf::Clock clock, detailclock;\n sf::Event ev;\n\n while (_window.isOpen())\n {\n clock.restart();\n detailclock.restart();\n\n auto inputsys = getSubsystem();\n if (inputsys)\n inputsys->beginFrame();\n\n while (_window.pollEvent(ev))\n {\n if (inputsys)\n inputsys->process(ev);\n\n ImGui::SFML::ProcessEvent(ev);\n\n \/\/ TODO: clear keyboard\n\n auto evmgr = getSubsystem();\n if (evmgr)\n evmgr->triggerEvent(SFMLEvent::create(ev));\n\n if (closebutton && ev.type == sf::Event::Closed)\n {\n close();\n return;\n }\n }\n\n if (_window.hasFocus() || !unfocusPause)\n {\n ImGui::SFML::Update(_window, sf::seconds(_frametime));\n\n bool frozen = false;\n for (auto it = _states.rbegin(), end = _states.rend(); it != end; ++it)\n {\n auto state = (*it).get();\n if (state->flags & gamestate_paused)\n continue;\n\n if (!frozen || state->flags & gamestate_forceupdate)\n state->update(_frametime);\n\n if (state->flags & gamestate_freeze)\n frozen = true;\n }\n\n if (escclose && inputsys && inputsys->isKeyPressed(sf::Keyboard::Escape))\n {\n close();\n return;\n }\n }\n\n _updatetime = detailclock.getElapsedTime().asMilliseconds() \/ 1000.f;\n detailclock.restart();\n\n _window.resetGLStates(); \/\/ without this things start randomly disappearing\n _window.clear(bgcolor);\n\n if (_vsync)\n detailclock.restart();\n\n for (auto& i : _states)\n i->render(_window);\n\n ImGui::SFML::Render(_window);\n\n \/\/ TODO: implement own fps capping.\n \/\/ SFML caps inside window.display(), so it's impossible to get the exact render time\n if (!_vsync)\n _rendertime = detailclock.getElapsedTime().asMilliseconds() \/ 1000.0f;\n\n _window.display();\n\n if (_vsync)\n _rendertime = detailclock.getElapsedTime().asMilliseconds() \/ 1000.0f;\n\n \/\/ Get elapsed time\n _frametime = clock.getElapsedTime().asMilliseconds() \/ 1000.0f;\n }\n }\n\n void Game::close()\n {\n if (_window.isOpen())\n {\n _window.close();\n LOG_DEBUG(\"Game window closed\");\n }\n }\n\n void Game::destroy()\n {\n if (!isInitialized())\n return;\n\n close();\n\n if (!_states.empty())\n {\n LOG_DEBUG(\"Closing game states...\");\n for (auto& i : _states)\n i->quit();\n _states.clear();\n }\n\n ImGui::SFML::Shutdown();\n _initialized = false;\n }\n\n\n bool Game::loadFromJson(const Json::Value& node)\n {\n return _props.loadFromJson(node);\n }\n\n void Game::writeToJson(Json::Value& node) const\n {\n _props.writeToJson(node);\n }\n\n\n void Game::pushState(std::unique_ptr state)\n {\n if (!state->init(this))\n {\n LOG_ERROR(\"Failed to initialize game state\");\n return;\n }\n _states.push_back(std::move(state));\n LOG_DEBUG(\"Game state added\");\n }\n\n void Game::popState()\n {\n _states.back()->quit();\n _states.pop_back();\n }\n\n GameState* Game::pullState() const\n {\n return _states.back().get();\n }\n\n float Game::getFrametime() const\n {\n return _frametime;\n }\n\n float Game::getRealFrametime() const\n {\n return _rendertime + _updatetime;\n }\n\n float Game::getRenderTime() const\n {\n return _rendertime;\n }\n\n float Game::getUpdateTime() const\n {\n return _updatetime;\n }\n\n sf::RenderWindow& Game::getWindow()\n {\n return _window;\n }\n\n const PropertyContainer& Game::getProperties() const\n {\n return _props;\n }\n\n void Game::resize(const sf::Vector2u& size)\n {\n if (size.x <= 0 || size.y <= 0)\n {\n LOG_ERROR(\"Invalid window size: \", size.x, \"x\", size.y);\n return;\n }\n\n _size.fill(size.x, size.y);\n\n if (_window.isOpen())\n {\n auto diff = size - _window.getSize();\n auto pos = _window.getPosition();\n pos.x -= diff.x \/ 2;\n pos.y -= diff.y \/ 2;\n\n _window.setSize(size);\n _window.setPosition(pos);\n _window.setView(sf::View(sf::FloatRect(0, 0, size.x, size.y)));\n }\n\n \/\/ Don't create a new window, as it could lead to problems\n \/\/ if (size != _window.getSize())\n \/\/ {\n \/\/ _window.close();\n \/\/ _window.create(sf::VideoMode(size.x, size.y), game_title, sf::Style::Close);\n \/\/ }\n }\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n\nOpenGLProgram::OpenGLProgram() :\n mnId( 0 ),\n mnEnabledAttribs( 0 ),\n mnPositionAttrib( SAL_MAX_UINT32 ),\n mnTexCoordAttrib( SAL_MAX_UINT32 ),\n mnAlphaCoordAttrib( SAL_MAX_UINT32 ),\n mbBlending( false )\n{\n}\n\nOpenGLProgram::~OpenGLProgram()\n{\n maUniformLocations.clear();\n if( mnId != 0 )\n glDeleteProgram( mnId );\n}\n\nbool OpenGLProgram::Load( const OUString& rVertexShader, const OUString& rFragmentShader )\n{\n mnId = OpenGLHelper::LoadShaders( rVertexShader, rFragmentShader );\n return ( mnId != 0 );\n}\n\nbool OpenGLProgram::Use()\n{\n if( !mnId )\n return false;\n\n glUseProgram( mnId );\n return true;\n}\n\nbool OpenGLProgram::Clean()\n{\n \/\/ unbind all textures\n if( !maTextures.empty() )\n {\n int nIndex( maTextures.size() - 1 );\n TextureList::reverse_iterator it( maTextures.rbegin() );\n while( it != maTextures.rend() )\n {\n glActiveTexture( GL_TEXTURE0 + nIndex-- );\n it->Unbind();\n it++;\n }\n maTextures.clear();\n }\n\n \/\/ disable any enabled vertex attrib array\n if( mnEnabledAttribs )\n {\n for( int i = 0; i < 32; i++ )\n {\n if( mnEnabledAttribs & ( 1 << i ) )\n glDisableVertexAttribArray( i );\n }\n mnEnabledAttribs = 0;\n }\n\n \/\/ disable blending if enabled\n if( mbBlending )\n {\n mbBlending = false;\n glDisable( GL_BLEND );\n }\n\n CHECK_GL_ERROR();\n return true;\n}\n\nvoid OpenGLProgram::SetVertexAttrib( GLuint& rAttrib, const OString& rName, const GLvoid* pData )\n{\n if( rAttrib == SAL_MAX_UINT32 )\n rAttrib = glGetAttribLocation( mnId, (char*) rName.getStr() );\n if( (mnEnabledAttribs & ( 1 << rAttrib )) == 0 )\n {\n glEnableVertexAttribArray( rAttrib );\n mnEnabledAttribs |= ( 1 << rAttrib );\n }\n glVertexAttribPointer( rAttrib, 2, GL_FLOAT, GL_FALSE, 0, pData );\n}\n\nvoid OpenGLProgram::SetVertices( const GLvoid* pData )\n{\n SetVertexAttrib( mnPositionAttrib, \"position\", pData );\n}\n\nvoid OpenGLProgram::SetTextureCoord( const GLvoid* pData )\n{\n SetVertexAttrib( mnTexCoordAttrib, \"tex_coord_in\", pData );\n}\n\nvoid OpenGLProgram::SetAlphaCoord( const GLvoid* pData )\n{\n SetVertexAttrib( mnAlphaCoordAttrib, \"alpha_coord_in\", pData );\n}\n\nGLuint OpenGLProgram::GetUniformLocation( const OString& rName )\n{\n boost::unordered_map::iterator it;\n\n it = maUniformLocations.find( rName );\n if( it == maUniformLocations.end() )\n {\n GLuint nLocation = glGetUniformLocation( mnId, (char*) rName.getStr() );\n maUniformLocations[rName] = nLocation;\n return nLocation;\n }\n\n return it->second;\n}\n\nvoid OpenGLProgram::SetUniform1f( const OString& rName, GLfloat v1 )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform1f( nUniform, v1 );\n}\n\nvoid OpenGLProgram::SetUniform2f( const OString& rName, GLfloat v1, GLfloat v2 )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform2f( nUniform, v1, v2 );\n}\n\nvoid OpenGLProgram::SetUniform1fv( const OString& rName, GLsizei nCount, GLfloat* aValues )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform1fv( nUniform, nCount, aValues );\n}\n\nvoid OpenGLProgram::SetUniform2fv( const OString& rName, GLsizei nCount, GLfloat* aValues )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform2fv( nUniform, nCount, aValues );\n}\n\nvoid OpenGLProgram::SetColor( const OString& rName, SalColor nColor, sal_uInt8 nTransparency )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) SALCOLOR_RED( nColor )) \/ 255,\n ((float) SALCOLOR_GREEN( nColor )) \/ 255,\n ((float) SALCOLOR_BLUE( nColor )) \/ 255,\n (100 - nTransparency) * (1.0 \/ 100) );\n\n if( nTransparency > 0 )\n SetBlendMode( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid OpenGLProgram::SetColorf( const OString& rName, SalColor nColor, double fTransparency )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) SALCOLOR_RED( nColor )) \/ 255,\n ((float) SALCOLOR_GREEN( nColor )) \/ 255,\n ((float) SALCOLOR_BLUE( nColor )) \/ 255,\n (1.0f - fTransparency) );\n\n if( fTransparency > 0.0 )\n SetBlendMode( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid OpenGLProgram::SetColor( const OString& rName, const Color& rColor )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) rColor.GetRed()) \/ 255,\n ((float) rColor.GetGreen()) \/ 255,\n ((float) rColor.GetBlue()) \/ 255,\n 1.0f - ((float) rColor.GetTransparency()) \/ 255 );\n\n if( rColor.GetTransparency() > 0 )\n SetBlendMode( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid OpenGLProgram::SetColorWithIntensity( const OString& rName, const Color& rColor, long nFactor )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) rColor.GetRed()) * nFactor \/ 25500.0,\n ((float) rColor.GetGreen()) * nFactor \/ 25500.0,\n ((float) rColor.GetBlue()) * nFactor \/ 25500.0,\n 1.0f );\n}\n\nvoid OpenGLProgram::SetTexture( const OString& rName, OpenGLTexture& rTexture )\n{\n GLuint nUniform = GetUniformLocation( rName );\n int nIndex = maTextures.size();\n\n glUniform1i( nUniform, nIndex );\n glActiveTexture( GL_TEXTURE0 + nIndex );\n rTexture.Bind();\n maTextures.push_back( rTexture );\n}\n\nvoid OpenGLProgram::SetTransform(\n const OString& rName,\n const OpenGLTexture& rTexture,\n const basegfx::B2DPoint& rNull,\n const basegfx::B2DPoint& rX,\n const basegfx::B2DPoint& rY )\n{\n GLuint nUniform = GetUniformLocation( rName );\n const basegfx::B2DVector aXRel = rX - rNull;\n const basegfx::B2DVector aYRel = rY - rNull;\n const float aValues[] = {\n (float) aXRel.getX()\/rTexture.GetWidth(), (float) aXRel.getY()\/rTexture.GetWidth(), 0, 0,\n (float) aYRel.getX()\/rTexture.GetHeight(), (float) aYRel.getY()\/rTexture.GetHeight(), 0, 0,\n 0, 0, 1, 0,\n (float) rNull.getX(), (float) rNull.getY(), 0, 1 };\n glm::mat4 mMatrix = glm::make_mat4( aValues );\n glUniformMatrix4fv( nUniform, 1, GL_FALSE, glm::value_ptr( mMatrix ) );\n}\n\nvoid OpenGLProgram::SetBlendMode( GLenum nSFactor, GLenum nDFactor )\n{\n glEnable( GL_BLEND );\n glBlendFunc( nSFactor, nDFactor );\n mbBlending = true;\n}\n\nbool OpenGLProgram::DrawTexture( OpenGLTexture& rTexture )\n{\n GLfloat aPosition[8] = { -1, -1, -1, 1, 1, 1, 1, -1 };\n GLfloat aTexCoord[8];\n\n if( !rTexture )\n return false;\n\n rTexture.GetWholeCoord( aTexCoord );\n SetVertices( aPosition );\n SetTextureCoord( aTexCoord );\n glDrawArrays( GL_TRIANGLE_FAN, 0, 4 );\n CHECK_GL_ERROR();\n\n return true;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ncoverity#1256664 Division or modulo by float zero\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n\nOpenGLProgram::OpenGLProgram() :\n mnId( 0 ),\n mnEnabledAttribs( 0 ),\n mnPositionAttrib( SAL_MAX_UINT32 ),\n mnTexCoordAttrib( SAL_MAX_UINT32 ),\n mnAlphaCoordAttrib( SAL_MAX_UINT32 ),\n mbBlending( false )\n{\n}\n\nOpenGLProgram::~OpenGLProgram()\n{\n maUniformLocations.clear();\n if( mnId != 0 )\n glDeleteProgram( mnId );\n}\n\nbool OpenGLProgram::Load( const OUString& rVertexShader, const OUString& rFragmentShader )\n{\n mnId = OpenGLHelper::LoadShaders( rVertexShader, rFragmentShader );\n return ( mnId != 0 );\n}\n\nbool OpenGLProgram::Use()\n{\n if( !mnId )\n return false;\n\n glUseProgram( mnId );\n return true;\n}\n\nbool OpenGLProgram::Clean()\n{\n \/\/ unbind all textures\n if( !maTextures.empty() )\n {\n int nIndex( maTextures.size() - 1 );\n TextureList::reverse_iterator it( maTextures.rbegin() );\n while( it != maTextures.rend() )\n {\n glActiveTexture( GL_TEXTURE0 + nIndex-- );\n it->Unbind();\n it++;\n }\n maTextures.clear();\n }\n\n \/\/ disable any enabled vertex attrib array\n if( mnEnabledAttribs )\n {\n for( int i = 0; i < 32; i++ )\n {\n if( mnEnabledAttribs & ( 1 << i ) )\n glDisableVertexAttribArray( i );\n }\n mnEnabledAttribs = 0;\n }\n\n \/\/ disable blending if enabled\n if( mbBlending )\n {\n mbBlending = false;\n glDisable( GL_BLEND );\n }\n\n CHECK_GL_ERROR();\n return true;\n}\n\nvoid OpenGLProgram::SetVertexAttrib( GLuint& rAttrib, const OString& rName, const GLvoid* pData )\n{\n if( rAttrib == SAL_MAX_UINT32 )\n rAttrib = glGetAttribLocation( mnId, (char*) rName.getStr() );\n if( (mnEnabledAttribs & ( 1 << rAttrib )) == 0 )\n {\n glEnableVertexAttribArray( rAttrib );\n mnEnabledAttribs |= ( 1 << rAttrib );\n }\n glVertexAttribPointer( rAttrib, 2, GL_FLOAT, GL_FALSE, 0, pData );\n}\n\nvoid OpenGLProgram::SetVertices( const GLvoid* pData )\n{\n SetVertexAttrib( mnPositionAttrib, \"position\", pData );\n}\n\nvoid OpenGLProgram::SetTextureCoord( const GLvoid* pData )\n{\n SetVertexAttrib( mnTexCoordAttrib, \"tex_coord_in\", pData );\n}\n\nvoid OpenGLProgram::SetAlphaCoord( const GLvoid* pData )\n{\n SetVertexAttrib( mnAlphaCoordAttrib, \"alpha_coord_in\", pData );\n}\n\nGLuint OpenGLProgram::GetUniformLocation( const OString& rName )\n{\n boost::unordered_map::iterator it;\n\n it = maUniformLocations.find( rName );\n if( it == maUniformLocations.end() )\n {\n GLuint nLocation = glGetUniformLocation( mnId, (char*) rName.getStr() );\n maUniformLocations[rName] = nLocation;\n return nLocation;\n }\n\n return it->second;\n}\n\nvoid OpenGLProgram::SetUniform1f( const OString& rName, GLfloat v1 )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform1f( nUniform, v1 );\n}\n\nvoid OpenGLProgram::SetUniform2f( const OString& rName, GLfloat v1, GLfloat v2 )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform2f( nUniform, v1, v2 );\n}\n\nvoid OpenGLProgram::SetUniform1fv( const OString& rName, GLsizei nCount, GLfloat* aValues )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform1fv( nUniform, nCount, aValues );\n}\n\nvoid OpenGLProgram::SetUniform2fv( const OString& rName, GLsizei nCount, GLfloat* aValues )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform2fv( nUniform, nCount, aValues );\n}\n\nvoid OpenGLProgram::SetColor( const OString& rName, SalColor nColor, sal_uInt8 nTransparency )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) SALCOLOR_RED( nColor )) \/ 255,\n ((float) SALCOLOR_GREEN( nColor )) \/ 255,\n ((float) SALCOLOR_BLUE( nColor )) \/ 255,\n (100 - nTransparency) * (1.0 \/ 100) );\n\n if( nTransparency > 0 )\n SetBlendMode( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid OpenGLProgram::SetColorf( const OString& rName, SalColor nColor, double fTransparency )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) SALCOLOR_RED( nColor )) \/ 255,\n ((float) SALCOLOR_GREEN( nColor )) \/ 255,\n ((float) SALCOLOR_BLUE( nColor )) \/ 255,\n (1.0f - fTransparency) );\n\n if( fTransparency > 0.0 )\n SetBlendMode( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid OpenGLProgram::SetColor( const OString& rName, const Color& rColor )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) rColor.GetRed()) \/ 255,\n ((float) rColor.GetGreen()) \/ 255,\n ((float) rColor.GetBlue()) \/ 255,\n 1.0f - ((float) rColor.GetTransparency()) \/ 255 );\n\n if( rColor.GetTransparency() > 0 )\n SetBlendMode( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n}\n\nvoid OpenGLProgram::SetColorWithIntensity( const OString& rName, const Color& rColor, long nFactor )\n{\n GLuint nUniform = GetUniformLocation( rName );\n glUniform4f( nUniform,\n ((float) rColor.GetRed()) * nFactor \/ 25500.0,\n ((float) rColor.GetGreen()) * nFactor \/ 25500.0,\n ((float) rColor.GetBlue()) * nFactor \/ 25500.0,\n 1.0f );\n}\n\nvoid OpenGLProgram::SetTexture( const OString& rName, OpenGLTexture& rTexture )\n{\n GLuint nUniform = GetUniformLocation( rName );\n int nIndex = maTextures.size();\n\n glUniform1i( nUniform, nIndex );\n glActiveTexture( GL_TEXTURE0 + nIndex );\n rTexture.Bind();\n maTextures.push_back( rTexture );\n}\n\nvoid OpenGLProgram::SetTransform(\n const OString& rName,\n const OpenGLTexture& rTexture,\n const basegfx::B2DPoint& rNull,\n const basegfx::B2DPoint& rX,\n const basegfx::B2DPoint& rY )\n{\n auto nTexWidth = rTexture.GetWidth();\n auto nTexHeight = rTexture.GetHeight();\n if (nTexWidth == 0 || nTexHeight == 0)\n return;\n\n GLuint nUniform = GetUniformLocation( rName );\n const basegfx::B2DVector aXRel = rX - rNull;\n const basegfx::B2DVector aYRel = rY - rNull;\n const float aValues[] = {\n (float) aXRel.getX()\/nTexWidth, (float) aXRel.getY()\/nTexWidth, 0, 0,\n (float) aYRel.getX()\/nTexHeight, (float) aYRel.getY()\/nTexHeight, 0, 0,\n 0, 0, 1, 0,\n (float) rNull.getX(), (float) rNull.getY(), 0, 1 };\n glm::mat4 mMatrix = glm::make_mat4( aValues );\n glUniformMatrix4fv( nUniform, 1, GL_FALSE, glm::value_ptr( mMatrix ) );\n}\n\nvoid OpenGLProgram::SetBlendMode( GLenum nSFactor, GLenum nDFactor )\n{\n glEnable( GL_BLEND );\n glBlendFunc( nSFactor, nDFactor );\n mbBlending = true;\n}\n\nbool OpenGLProgram::DrawTexture( OpenGLTexture& rTexture )\n{\n GLfloat aPosition[8] = { -1, -1, -1, 1, 1, 1, 1, -1 };\n GLfloat aTexCoord[8];\n\n if( !rTexture )\n return false;\n\n rTexture.GetWholeCoord( aTexCoord );\n SetVertices( aPosition );\n SetTextureCoord( aTexCoord );\n glDrawArrays( GL_TRIANGLE_FAN, 0, 4 );\n CHECK_GL_ERROR();\n\n return true;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\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 \"ble\/Gap.h\"\n\nnamespace {\n\nble_error_t convert_address_type(\n Gap::PeerAddressType_t input_type,\n const BLEProtocol::AddressBytes_t address,\n BLEProtocol::AddressType_t& output_type\n) {\n typedef Gap::RandomAddressType_t RandomAddressType_t;\n typedef Gap::PeerAddressType_t PeerAddressType_t;\n typedef BLEProtocol::AddressType LegacyAddressType_t;\n\n \/\/ best effort; peerAddrTypeIn should not be used when privacy is on.\n switch(input_type.value()) {\n case PeerAddressType_t::PUBLIC:\n case PeerAddressType_t::PUBLIC_IDENTITY:\n output_type = LegacyAddressType_t::PUBLIC;\n break;\n case PeerAddressType_t::RANDOM: {\n RandomAddressType_t random_address_type(RandomAddressType_t::STATIC);\n ble_error_t err = Gap::getRandomAddressType(address, &random_address_type);\n if (err) {\n return err;\n }\n switch (random_address_type.value()) {\n case RandomAddressType_t::STATIC:\n output_type = LegacyAddressType_t::RANDOM_STATIC;\n break;\n case RandomAddressType_t::NON_RESOLVABLE_PRIVATE:\n output_type = LegacyAddressType_t::RANDOM_PRIVATE_NON_RESOLVABLE;\n break;\n case RandomAddressType_t::RESOLVABLE_PRIVATE:\n output_type = LegacyAddressType_t::RANDOM_PRIVATE_RESOLVABLE;\n break;\n }\n break;\n }\n case PeerAddressType_t::RANDOM_STATIC_IDENTITY:\n output_type = LegacyAddressType_t::RANDOM_STATIC;\n break;\n }\n\n return BLE_ERROR_NONE;\n}\n\nGap::PeerAddressType_t convert_legacy_address_type(\n BLEProtocol::AddressType_t legacy_address\n) {\n if (legacy_address == BLEProtocol::AddressType::PUBLIC) {\n return Gap::PeerAddressType_t::PUBLIC;\n } else {\n return Gap::PeerAddressType_t::RANDOM;\n }\n}\n\n}\n\nconst Gap::PeripheralPrivacyConfiguration_t Gap::default_peripheral_privacy_configuration = {\n \/* use_non_resolvable_random_address *\/ false,\n \/* resolution_strategy *\/ PeripheralPrivacyConfiguration_t::PERFORM_PAIRING_PROCEDURE\n};\n\nconst Gap::CentralPrivacyConfiguration_t Gap::default_central_privacy_configuration = {\n \/* use_non_resolvable_random_address *\/ false,\n \/* resolution_strategy *\/ CentralPrivacyConfiguration_t::DO_NOT_RESOLVE\n};\n\nvoid Gap::processConnectionEvent(\n Handle_t handle,\n Role_t role,\n PeerAddressType_t peerAddrType,\n const BLEProtocol::AddressBytes_t peerAddr,\n BLEProtocol::AddressType_t ownAddrType,\n const BLEProtocol::AddressBytes_t ownAddr,\n const ConnectionParams_t *connectionParams,\n const uint8_t *peerResolvableAddr,\n const uint8_t *localResolvableAddr\n) {\n \/* Update Gap state *\/\n state.advertising = 0;\n state.connected = 1;\n ++connectionCount;\n\n ConnectionCallbackParams_t callbackParams(\n handle,\n role,\n peerAddrType,\n peerAddr,\n ownAddrType,\n ownAddr,\n connectionParams,\n peerResolvableAddr,\n localResolvableAddr\n );\n\n connectionCallChain.call(&callbackParams);\n}\n\nvoid Gap::processAdvertisementReport(\n const BLEProtocol::AddressBytes_t peerAddr,\n int8_t rssi,\n bool isScanResponse,\n GapAdvertisingParams::AdvertisingType_t type,\n uint8_t advertisingDataLen,\n const uint8_t *advertisingData,\n PeerAddressType_t addressType\n) {\n AdvertisementCallbackParams_t params;\n\n memcpy(params.peerAddr, peerAddr, ADDR_LEN);\n params.rssi = rssi;\n params.isScanResponse = isScanResponse;\n params.type = type;\n params.advertisingDataLen = advertisingDataLen;\n params.advertisingData = advertisingData;\n params.peerAddrType = addressType;\n\n convert_address_type(\n addressType,\n peerAddr,\n params.addressType\n );\n\n onAdvertisementReport.call(¶ms);\n}\n\n\n#if defined(__GNUC__) && !defined(__CC_ARM)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#elif defined(__CC_ARM)\n#pragma push\n#pragma diag_suppress 1361\n#endif\n\nGap::AdvertisementCallbackParams_t::AdvertisementCallbackParams_t() :\n peerAddr(),\n rssi(),\n isScanResponse(),\n type(),\n advertisingDataLen(0),\n advertisingData(NULL),\n addressType(),\n peerAddrType(PeerAddressType_t::PUBLIC)\n{\n}\n\nble_error_t Gap::getRandomAddressType(\n const BLEProtocol::AddressBytes_t address,\n RandomAddressType_t* type\n) {\n \/\/ see section Device address in Bluetooth Link Layer specification\n \/\/ (Vol 6 - Part B)\n switch (address[5] >> 6) {\n case 0x03:\n *type = RandomAddressType_t::STATIC;\n return BLE_ERROR_NONE;\n case 0x00:\n *type = RandomAddressType_t::NON_RESOLVABLE_PRIVATE;\n return BLE_ERROR_NONE;\n case 0x02:\n *type = RandomAddressType_t::RESOLVABLE_PRIVATE;\n return BLE_ERROR_NONE;\n default:\n return BLE_ERROR_INVALID_PARAM;\n }\n}\n\nGap::ConnectionCallbackParams_t::ConnectionCallbackParams_t(\n Handle_t handleIn,\n Role_t roleIn,\n BLEProtocol::AddressType_t peerAddrTypeIn,\n const uint8_t *peerAddrIn,\n BLEProtocol::AddressType_t ownAddrTypeIn,\n const uint8_t *ownAddrIn,\n const ConnectionParams_t *connectionParamsIn,\n const uint8_t *peerResolvableAddrIn,\n const uint8_t *localResolvableAddrIn\n) : handle(handleIn),\n role(roleIn),\n peerAddrType(peerAddrTypeIn),\n peerAddr(),\n ownAddrType(ownAddrTypeIn),\n ownAddr(),\n connectionParams(connectionParamsIn),\n peerResolvableAddr(),\n localResolvableAddr(),\n peerAddressType(convert_legacy_address_type(peerAddrTypeIn))\n{\n constructor_helper(\n peerAddrIn,\n ownAddrIn,\n peerResolvableAddrIn,\n localResolvableAddrIn\n );\n}\n\nGap::ConnectionCallbackParams_t::ConnectionCallbackParams_t(\n Handle_t handleIn,\n Role_t roleIn,\n PeerAddressType_t peerAddrTypeIn,\n const uint8_t *peerAddrIn,\n BLEProtocol::AddressType_t ownAddrTypeIn,\n const uint8_t *ownAddrIn,\n const ConnectionParams_t *connectionParamsIn,\n const uint8_t *peerResolvableAddrIn,\n const uint8_t *localResolvableAddrIn\n) : handle(handleIn),\n role(roleIn),\n peerAddrType(),\n peerAddr(),\n ownAddrType(ownAddrTypeIn),\n ownAddr(),\n connectionParams(connectionParamsIn),\n peerResolvableAddr(),\n localResolvableAddr(),\n peerAddressType(peerAddrTypeIn)\n{\n constructor_helper(\n peerAddrIn,\n ownAddrIn,\n peerResolvableAddrIn,\n localResolvableAddrIn\n );\n\n convert_address_type(peerAddrTypeIn, peerAddrIn, peerAddrType);\n}\n\nvoid Gap::ConnectionCallbackParams_t::constructor_helper(\n const uint8_t *peerAddrIn,\n const uint8_t *ownAddrIn,\n const uint8_t *peerResolvableAddrIn,\n const uint8_t *localResolvableAddrIn\n) {\n memcpy(peerAddr, peerAddrIn, ADDR_LEN);\n\n if (ownAddrIn) {\n memcpy(ownAddr, ownAddrIn, ADDR_LEN);\n } else {\n memset(ownAddr, 0, ADDR_LEN);\n }\n\n if (peerResolvableAddrIn) {\n memcpy(peerResolvableAddr, peerResolvableAddrIn, ADDR_LEN);\n } else {\n memset(ownAddr, 0, ADDR_LEN);\n }\n\n if (localResolvableAddrIn) {\n memcpy(localResolvableAddr, localResolvableAddrIn, ADDR_LEN);\n } else {\n memset(ownAddr, 0, ADDR_LEN);\n }\n}\n\nble_error_t Gap::connect(\n const BLEProtocol::AddressBytes_t peerAddr,\n DeprecatedAddressType_t peerAddrType,\n const ConnectionParams_t *connectionParams,\n const GapScanningParams *scanParams\n) {\n return connect(\n peerAddr,\n (BLEProtocol::AddressType_t) peerAddrType,\n connectionParams,\n scanParams\n );\n}\n\nvoid Gap::processConnectionEvent(\n Handle_t handle,\n Role_t role,\n BLEProtocol::AddressType_t peerAddrType,\n const BLEProtocol::AddressBytes_t peerAddr,\n BLEProtocol::AddressType_t ownAddrType,\n const BLEProtocol::AddressBytes_t ownAddr,\n const ConnectionParams_t *connectionParams,\n const uint8_t *peerResolvableAddr,\n const uint8_t *localResolvableAddr\n) {\n \/* Update Gap state *\/\n state.advertising = 0;\n state.connected = 1;\n ++connectionCount;\n\n ConnectionCallbackParams_t callbackParams(\n handle,\n role,\n peerAddrType,\n peerAddr,\n ownAddrType,\n ownAddr,\n connectionParams,\n peerResolvableAddr,\n localResolvableAddr\n );\n\n connectionCallChain.call(&callbackParams);\n}\n\nvoid Gap::processAdvertisementReport(\n const BLEProtocol::AddressBytes_t peerAddr,\n int8_t rssi,\n bool isScanResponse,\n GapAdvertisingParams::AdvertisingType_t type,\n uint8_t advertisingDataLen,\n const uint8_t *advertisingData,\n BLEProtocol::AddressType_t addressType\n) {\n AdvertisementCallbackParams_t params;\n memcpy(params.peerAddr, peerAddr, ADDR_LEN);\n params.rssi = rssi;\n params.isScanResponse = isScanResponse;\n params.type = type;\n params.advertisingDataLen = advertisingDataLen;\n params.advertisingData = advertisingData;\n params.addressType = addressType;\n\n params.peerAddrType = convert_legacy_address_type(addressType);\n onAdvertisementReport.call(¶ms);\n}\n\n#if defined(__GNUC__) && !defined(__CC_ARM)\n#pragma GCC diagnostic pop\n#elif defined(__CC_ARM)\n#pragma pop\n#endif\nBLE: Fix resolvable private address identification.\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\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 \"ble\/Gap.h\"\n\nnamespace {\n\nble_error_t convert_address_type(\n Gap::PeerAddressType_t input_type,\n const BLEProtocol::AddressBytes_t address,\n BLEProtocol::AddressType_t& output_type\n) {\n typedef Gap::RandomAddressType_t RandomAddressType_t;\n typedef Gap::PeerAddressType_t PeerAddressType_t;\n typedef BLEProtocol::AddressType LegacyAddressType_t;\n\n \/\/ best effort; peerAddrTypeIn should not be used when privacy is on.\n switch(input_type.value()) {\n case PeerAddressType_t::PUBLIC:\n case PeerAddressType_t::PUBLIC_IDENTITY:\n output_type = LegacyAddressType_t::PUBLIC;\n break;\n case PeerAddressType_t::RANDOM: {\n RandomAddressType_t random_address_type(RandomAddressType_t::STATIC);\n ble_error_t err = Gap::getRandomAddressType(address, &random_address_type);\n if (err) {\n return err;\n }\n switch (random_address_type.value()) {\n case RandomAddressType_t::STATIC:\n output_type = LegacyAddressType_t::RANDOM_STATIC;\n break;\n case RandomAddressType_t::NON_RESOLVABLE_PRIVATE:\n output_type = LegacyAddressType_t::RANDOM_PRIVATE_NON_RESOLVABLE;\n break;\n case RandomAddressType_t::RESOLVABLE_PRIVATE:\n output_type = LegacyAddressType_t::RANDOM_PRIVATE_RESOLVABLE;\n break;\n }\n break;\n }\n case PeerAddressType_t::RANDOM_STATIC_IDENTITY:\n output_type = LegacyAddressType_t::RANDOM_STATIC;\n break;\n }\n\n return BLE_ERROR_NONE;\n}\n\nGap::PeerAddressType_t convert_legacy_address_type(\n BLEProtocol::AddressType_t legacy_address\n) {\n if (legacy_address == BLEProtocol::AddressType::PUBLIC) {\n return Gap::PeerAddressType_t::PUBLIC;\n } else {\n return Gap::PeerAddressType_t::RANDOM;\n }\n}\n\n}\n\nconst Gap::PeripheralPrivacyConfiguration_t Gap::default_peripheral_privacy_configuration = {\n \/* use_non_resolvable_random_address *\/ false,\n \/* resolution_strategy *\/ PeripheralPrivacyConfiguration_t::PERFORM_PAIRING_PROCEDURE\n};\n\nconst Gap::CentralPrivacyConfiguration_t Gap::default_central_privacy_configuration = {\n \/* use_non_resolvable_random_address *\/ false,\n \/* resolution_strategy *\/ CentralPrivacyConfiguration_t::DO_NOT_RESOLVE\n};\n\nvoid Gap::processConnectionEvent(\n Handle_t handle,\n Role_t role,\n PeerAddressType_t peerAddrType,\n const BLEProtocol::AddressBytes_t peerAddr,\n BLEProtocol::AddressType_t ownAddrType,\n const BLEProtocol::AddressBytes_t ownAddr,\n const ConnectionParams_t *connectionParams,\n const uint8_t *peerResolvableAddr,\n const uint8_t *localResolvableAddr\n) {\n \/* Update Gap state *\/\n state.advertising = 0;\n state.connected = 1;\n ++connectionCount;\n\n ConnectionCallbackParams_t callbackParams(\n handle,\n role,\n peerAddrType,\n peerAddr,\n ownAddrType,\n ownAddr,\n connectionParams,\n peerResolvableAddr,\n localResolvableAddr\n );\n\n connectionCallChain.call(&callbackParams);\n}\n\nvoid Gap::processAdvertisementReport(\n const BLEProtocol::AddressBytes_t peerAddr,\n int8_t rssi,\n bool isScanResponse,\n GapAdvertisingParams::AdvertisingType_t type,\n uint8_t advertisingDataLen,\n const uint8_t *advertisingData,\n PeerAddressType_t addressType\n) {\n AdvertisementCallbackParams_t params;\n\n memcpy(params.peerAddr, peerAddr, ADDR_LEN);\n params.rssi = rssi;\n params.isScanResponse = isScanResponse;\n params.type = type;\n params.advertisingDataLen = advertisingDataLen;\n params.advertisingData = advertisingData;\n params.peerAddrType = addressType;\n\n convert_address_type(\n addressType,\n peerAddr,\n params.addressType\n );\n\n onAdvertisementReport.call(¶ms);\n}\n\n\n#if defined(__GNUC__) && !defined(__CC_ARM)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#elif defined(__CC_ARM)\n#pragma push\n#pragma diag_suppress 1361\n#endif\n\nGap::AdvertisementCallbackParams_t::AdvertisementCallbackParams_t() :\n peerAddr(),\n rssi(),\n isScanResponse(),\n type(),\n advertisingDataLen(0),\n advertisingData(NULL),\n addressType(),\n peerAddrType(PeerAddressType_t::PUBLIC)\n{\n}\n\nble_error_t Gap::getRandomAddressType(\n const BLEProtocol::AddressBytes_t address,\n RandomAddressType_t* type\n) {\n \/\/ see section Device address in Bluetooth Link Layer specification\n \/\/ (Vol 6 - Part B)\n switch (address[5] >> 6) {\n case 0x03:\n *type = RandomAddressType_t::STATIC;\n return BLE_ERROR_NONE;\n case 0x00:\n *type = RandomAddressType_t::NON_RESOLVABLE_PRIVATE;\n return BLE_ERROR_NONE;\n case 0x01:\n *type = RandomAddressType_t::RESOLVABLE_PRIVATE;\n return BLE_ERROR_NONE;\n default:\n return BLE_ERROR_INVALID_PARAM;\n }\n}\n\nGap::ConnectionCallbackParams_t::ConnectionCallbackParams_t(\n Handle_t handleIn,\n Role_t roleIn,\n BLEProtocol::AddressType_t peerAddrTypeIn,\n const uint8_t *peerAddrIn,\n BLEProtocol::AddressType_t ownAddrTypeIn,\n const uint8_t *ownAddrIn,\n const ConnectionParams_t *connectionParamsIn,\n const uint8_t *peerResolvableAddrIn,\n const uint8_t *localResolvableAddrIn\n) : handle(handleIn),\n role(roleIn),\n peerAddrType(peerAddrTypeIn),\n peerAddr(),\n ownAddrType(ownAddrTypeIn),\n ownAddr(),\n connectionParams(connectionParamsIn),\n peerResolvableAddr(),\n localResolvableAddr(),\n peerAddressType(convert_legacy_address_type(peerAddrTypeIn))\n{\n constructor_helper(\n peerAddrIn,\n ownAddrIn,\n peerResolvableAddrIn,\n localResolvableAddrIn\n );\n}\n\nGap::ConnectionCallbackParams_t::ConnectionCallbackParams_t(\n Handle_t handleIn,\n Role_t roleIn,\n PeerAddressType_t peerAddrTypeIn,\n const uint8_t *peerAddrIn,\n BLEProtocol::AddressType_t ownAddrTypeIn,\n const uint8_t *ownAddrIn,\n const ConnectionParams_t *connectionParamsIn,\n const uint8_t *peerResolvableAddrIn,\n const uint8_t *localResolvableAddrIn\n) : handle(handleIn),\n role(roleIn),\n peerAddrType(),\n peerAddr(),\n ownAddrType(ownAddrTypeIn),\n ownAddr(),\n connectionParams(connectionParamsIn),\n peerResolvableAddr(),\n localResolvableAddr(),\n peerAddressType(peerAddrTypeIn)\n{\n constructor_helper(\n peerAddrIn,\n ownAddrIn,\n peerResolvableAddrIn,\n localResolvableAddrIn\n );\n\n convert_address_type(peerAddrTypeIn, peerAddrIn, peerAddrType);\n}\n\nvoid Gap::ConnectionCallbackParams_t::constructor_helper(\n const uint8_t *peerAddrIn,\n const uint8_t *ownAddrIn,\n const uint8_t *peerResolvableAddrIn,\n const uint8_t *localResolvableAddrIn\n) {\n memcpy(peerAddr, peerAddrIn, ADDR_LEN);\n\n if (ownAddrIn) {\n memcpy(ownAddr, ownAddrIn, ADDR_LEN);\n } else {\n memset(ownAddr, 0, ADDR_LEN);\n }\n\n if (peerResolvableAddrIn) {\n memcpy(peerResolvableAddr, peerResolvableAddrIn, ADDR_LEN);\n } else {\n memset(ownAddr, 0, ADDR_LEN);\n }\n\n if (localResolvableAddrIn) {\n memcpy(localResolvableAddr, localResolvableAddrIn, ADDR_LEN);\n } else {\n memset(ownAddr, 0, ADDR_LEN);\n }\n}\n\nble_error_t Gap::connect(\n const BLEProtocol::AddressBytes_t peerAddr,\n DeprecatedAddressType_t peerAddrType,\n const ConnectionParams_t *connectionParams,\n const GapScanningParams *scanParams\n) {\n return connect(\n peerAddr,\n (BLEProtocol::AddressType_t) peerAddrType,\n connectionParams,\n scanParams\n );\n}\n\nvoid Gap::processConnectionEvent(\n Handle_t handle,\n Role_t role,\n BLEProtocol::AddressType_t peerAddrType,\n const BLEProtocol::AddressBytes_t peerAddr,\n BLEProtocol::AddressType_t ownAddrType,\n const BLEProtocol::AddressBytes_t ownAddr,\n const ConnectionParams_t *connectionParams,\n const uint8_t *peerResolvableAddr,\n const uint8_t *localResolvableAddr\n) {\n \/* Update Gap state *\/\n state.advertising = 0;\n state.connected = 1;\n ++connectionCount;\n\n ConnectionCallbackParams_t callbackParams(\n handle,\n role,\n peerAddrType,\n peerAddr,\n ownAddrType,\n ownAddr,\n connectionParams,\n peerResolvableAddr,\n localResolvableAddr\n );\n\n connectionCallChain.call(&callbackParams);\n}\n\nvoid Gap::processAdvertisementReport(\n const BLEProtocol::AddressBytes_t peerAddr,\n int8_t rssi,\n bool isScanResponse,\n GapAdvertisingParams::AdvertisingType_t type,\n uint8_t advertisingDataLen,\n const uint8_t *advertisingData,\n BLEProtocol::AddressType_t addressType\n) {\n AdvertisementCallbackParams_t params;\n memcpy(params.peerAddr, peerAddr, ADDR_LEN);\n params.rssi = rssi;\n params.isScanResponse = isScanResponse;\n params.type = type;\n params.advertisingDataLen = advertisingDataLen;\n params.advertisingData = advertisingData;\n params.addressType = addressType;\n\n params.peerAddrType = convert_legacy_address_type(addressType);\n onAdvertisementReport.call(¶ms);\n}\n\n#if defined(__GNUC__) && !defined(__CC_ARM)\n#pragma GCC diagnostic pop\n#elif defined(__CC_ARM)\n#pragma pop\n#endif\n<|endoftext|>"} {"text":"Control: fix return status for mpc controller submodule<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2015 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\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 as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\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, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"libmesh\/libmesh_config.h\"\n#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS\n\n\n\/\/ Local includes cont'd\n#include \"libmesh\/face_inf_quad4.h\"\n#include \"libmesh\/fe_interface.h\"\n#include \"libmesh\/fe_type.h\"\n#include \"libmesh\/side.h\"\n#include \"libmesh\/edge_edge2.h\"\n#include \"libmesh\/edge_inf_edge2.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ InfQuad4 class static member initializations\nconst unsigned int InfQuad4::side_nodes_map[3][2] =\n {\n {0, 1}, \/\/ Side 0\n {1, 3}, \/\/ Side 1\n {0, 2} \/\/ Side 2\n };\n\n\n\n#ifdef LIBMESH_ENABLE_AMR\n\nconst float InfQuad4::_embedding_matrix[2][4][4] =\n {\n \/\/ embedding matrix for child 0\n {\n \/\/ 0 1 2 3rd parent node\n {1.0, 0.0, 0.0, 0.0}, \/\/ 0th child node\n {0.5, 0.5, 0.0, 0.0}, \/\/ 1\n {0.0, 0.0, 1.0, 0.0}, \/\/ 2\n {0.0, 0.0, 0.5, 0.5} \/\/ 3\n },\n\n \/\/ embedding matrix for child 1\n {\n \/\/ 0 1 2 3\n {0.5, 0.5, 0.0, 0.0}, \/\/ 0\n {0.0, 1.0, 0.0, 0.0}, \/\/ 1\n {0.0, 0.0, 0.5, 0.5}, \/\/ 2\n {0.0, 0.0, 0.0, 1.0} \/\/ 3\n }\n };\n\n#endif\n\n\n\/\/ ------------------------------------------------------------\n\/\/ InfQuad4 class member functions\n\nbool InfQuad4::is_vertex(const unsigned int i) const\n{\n if (i < 2)\n return true;\n return false;\n}\n\nbool InfQuad4::is_edge(const unsigned int i) const\n{\n if (i < 2)\n return false;\n return true;\n}\n\nbool InfQuad4::is_face(const unsigned int) const\n{\n return false;\n}\n\nbool InfQuad4::is_node_on_side(const unsigned int n,\n const unsigned int s) const\n{\n libmesh_assert_less (s, n_sides());\n for (unsigned int i = 0; i != 2; ++i)\n if (side_nodes_map[s][i] == n)\n return true;\n return false;\n}\n\nbool InfQuad4::contains_point (const Point& p, Real tol) const\n{\n \/*\n * make use of the fact that infinite elements do not\n * live inside the envelope. Use a fast scheme to\n * check whether point \\p p is inside or outside\n * our relevant part of the envelope. Note that\n * this is not exclusive: the point may be outside\n * the envelope, but contained in another infinite element.\n * Therefore, if the distance is greater, do fall back\n * to the scheme of using FEInterface::inverse_map().\n *\/\n const Point my_origin (this->origin());\n\n \/*\n * determine the minimal distance of the base from the origin\n * use size_sq() instead of size(), it is slightly faster\n *\/\n const Real min_distance_sq = std::min((Point(this->point(0)-my_origin)).size_sq(),\n (Point(this->point(1)-my_origin)).size_sq());\n\n \/*\n * work with 1% allowable deviation. Can still fall\n * back to the InfFE::inverse_map()\n *\/\n const Real conservative_p_dist_sq = 1.01 * (Point(p-my_origin).size_sq());\n\n if (conservative_p_dist_sq < min_distance_sq)\n {\n \/*\n * the physical point is definitely not contained\n * in the element, return false.\n *\/\n return false;\n }\n else\n {\n \/*\n * cannot say anything, fall back to the FEInterface::inverse_map()\n *\n * Declare a basic FEType. Will use default in the base,\n * and something else (not important) in radial direction.\n *\/\n FEType fe_type(default_order());\n\n const Point mapped_point = FEInterface::inverse_map(dim(),\n fe_type,\n this,\n p,\n tol,\n false);\n\n return FEInterface::on_reference_element(mapped_point, this->type(), tol);\n }\n}\n\n\n\n\nUniquePtr InfQuad4::build_side (const unsigned int i,\n bool proxy) const\n{\n \/\/ libmesh_assert_less (i, this->n_sides());\n\n if (proxy)\n {\n switch (i)\n {\n \/\/ base\n case 0:\n return UniquePtr(new Side(this,i));\n\n \/\/ ifem edges\n case 1:\n case 2:\n return UniquePtr(new Side(this,i));\n\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n }\n\n else\n {\n \/\/ Create NULL pointer to be initialized, returned later.\n Elem* edge = NULL;\n\n switch (i)\n {\n case 0:\n {\n edge = new Edge2;\n edge->set_node(0) = this->get_node(0);\n edge->set_node(1) = this->get_node(1);\n break;\n }\n\n case 1:\n {\n \/\/ adjacent to another infinite element\n edge = new InfEdge2;\n edge->set_node(0) = this->get_node(1);\n edge->set_node(1) = this->get_node(3);\n break;\n }\n\n case 2:\n {\n \/\/ adjacent to another infinite element\n edge = new InfEdge2;\n edge->set_node(0) = this->get_node(0);\n edge->set_node(1) = this->get_node(2);\n break;\n }\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n\n edge->subdomain_id() = this->subdomain_id();\n return UniquePtr(edge);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return UniquePtr();\n}\n\n\nvoid InfQuad4::connectivity(const unsigned int libmesh_dbg_var(sf),\n const IOPackage iop,\n std::vector& conn) const\n{\n libmesh_assert_less (sf, this->n_sub_elem());\n libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);\n\n conn.resize(4);\n\n switch (iop)\n {\n case TECPLOT:\n {\n conn[0] = this->node(0)+1;\n conn[1] = this->node(1)+1;\n conn[2] = this->node(3)+1;\n conn[3] = this->node(2)+1;\n return;\n }\n case VTK:\n {\n conn[0] = this->node(0);\n conn[1] = this->node(1);\n conn[2] = this->node(3);\n conn[3] = this->node(2);\n }\n default:\n libmesh_error_msg(\"Unsupported IO package \" << iop);\n }\n}\n\n} \/\/ namespace libMesh\n\n\n#endif \/\/ ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS\nRefactor InfQuad4::build_side()\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2015 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\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 as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\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, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"libmesh\/libmesh_config.h\"\n#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS\n\n\n\/\/ Local includes cont'd\n#include \"libmesh\/face_inf_quad4.h\"\n#include \"libmesh\/fe_interface.h\"\n#include \"libmesh\/fe_type.h\"\n#include \"libmesh\/side.h\"\n#include \"libmesh\/edge_edge2.h\"\n#include \"libmesh\/edge_inf_edge2.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ InfQuad4 class static member initializations\nconst unsigned int InfQuad4::side_nodes_map[3][2] =\n {\n {0, 1}, \/\/ Side 0\n {1, 3}, \/\/ Side 1\n {0, 2} \/\/ Side 2\n };\n\n\n\n#ifdef LIBMESH_ENABLE_AMR\n\nconst float InfQuad4::_embedding_matrix[2][4][4] =\n {\n \/\/ embedding matrix for child 0\n {\n \/\/ 0 1 2 3rd parent node\n {1.0, 0.0, 0.0, 0.0}, \/\/ 0th child node\n {0.5, 0.5, 0.0, 0.0}, \/\/ 1\n {0.0, 0.0, 1.0, 0.0}, \/\/ 2\n {0.0, 0.0, 0.5, 0.5} \/\/ 3\n },\n\n \/\/ embedding matrix for child 1\n {\n \/\/ 0 1 2 3\n {0.5, 0.5, 0.0, 0.0}, \/\/ 0\n {0.0, 1.0, 0.0, 0.0}, \/\/ 1\n {0.0, 0.0, 0.5, 0.5}, \/\/ 2\n {0.0, 0.0, 0.0, 1.0} \/\/ 3\n }\n };\n\n#endif\n\n\n\/\/ ------------------------------------------------------------\n\/\/ InfQuad4 class member functions\n\nbool InfQuad4::is_vertex(const unsigned int i) const\n{\n if (i < 2)\n return true;\n return false;\n}\n\nbool InfQuad4::is_edge(const unsigned int i) const\n{\n if (i < 2)\n return false;\n return true;\n}\n\nbool InfQuad4::is_face(const unsigned int) const\n{\n return false;\n}\n\nbool InfQuad4::is_node_on_side(const unsigned int n,\n const unsigned int s) const\n{\n libmesh_assert_less (s, n_sides());\n for (unsigned int i = 0; i != 2; ++i)\n if (side_nodes_map[s][i] == n)\n return true;\n return false;\n}\n\nbool InfQuad4::contains_point (const Point& p, Real tol) const\n{\n \/*\n * make use of the fact that infinite elements do not\n * live inside the envelope. Use a fast scheme to\n * check whether point \\p p is inside or outside\n * our relevant part of the envelope. Note that\n * this is not exclusive: the point may be outside\n * the envelope, but contained in another infinite element.\n * Therefore, if the distance is greater, do fall back\n * to the scheme of using FEInterface::inverse_map().\n *\/\n const Point my_origin (this->origin());\n\n \/*\n * determine the minimal distance of the base from the origin\n * use size_sq() instead of size(), it is slightly faster\n *\/\n const Real min_distance_sq = std::min((Point(this->point(0)-my_origin)).size_sq(),\n (Point(this->point(1)-my_origin)).size_sq());\n\n \/*\n * work with 1% allowable deviation. Can still fall\n * back to the InfFE::inverse_map()\n *\/\n const Real conservative_p_dist_sq = 1.01 * (Point(p-my_origin).size_sq());\n\n if (conservative_p_dist_sq < min_distance_sq)\n {\n \/*\n * the physical point is definitely not contained\n * in the element, return false.\n *\/\n return false;\n }\n else\n {\n \/*\n * cannot say anything, fall back to the FEInterface::inverse_map()\n *\n * Declare a basic FEType. Will use default in the base,\n * and something else (not important) in radial direction.\n *\/\n FEType fe_type(default_order());\n\n const Point mapped_point = FEInterface::inverse_map(dim(),\n fe_type,\n this,\n p,\n tol,\n false);\n\n return FEInterface::on_reference_element(mapped_point, this->type(), tol);\n }\n}\n\n\n\n\nUniquePtr InfQuad4::build_side (const unsigned int i,\n bool proxy) const\n{\n \/\/ libmesh_assert_less (i, this->n_sides());\n\n if (proxy)\n {\n switch (i)\n {\n \/\/ base\n case 0:\n return UniquePtr(new Side(this,i));\n\n \/\/ ifem edges\n case 1:\n case 2:\n return UniquePtr(new Side(this,i));\n\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n }\n\n else\n {\n \/\/ Create NULL pointer to be initialized, returned later.\n Elem* edge = NULL;\n\n switch (i)\n {\n case 0:\n {\n edge = new Edge2;\n break;\n }\n\n \/\/ adjacent to another infinite element\n case 1:\n case 2:\n {\n edge = new InfEdge2;\n break;\n }\n\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n\n edge->subdomain_id() = this->subdomain_id();\n\n \/\/ Set the nodes\n for (unsigned n=0; nn_nodes(); ++n)\n edge->set_node(n) = this->get_node(InfQuad4::side_nodes_map[i][n]);\n\n return UniquePtr(edge);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return UniquePtr();\n}\n\n\nvoid InfQuad4::connectivity(const unsigned int libmesh_dbg_var(sf),\n const IOPackage iop,\n std::vector& conn) const\n{\n libmesh_assert_less (sf, this->n_sub_elem());\n libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);\n\n conn.resize(4);\n\n switch (iop)\n {\n case TECPLOT:\n {\n conn[0] = this->node(0)+1;\n conn[1] = this->node(1)+1;\n conn[2] = this->node(3)+1;\n conn[3] = this->node(2)+1;\n return;\n }\n case VTK:\n {\n conn[0] = this->node(0);\n conn[1] = this->node(1);\n conn[2] = this->node(3);\n conn[3] = this->node(2);\n }\n default:\n libmesh_error_msg(\"Unsupported IO package \" << iop);\n }\n}\n\n} \/\/ namespace libMesh\n\n\n#endif \/\/ ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n SDL Rectangle Primitive\n\n Copyright (c) 2013 Jeffrey Carpenter\n All rights reserved.\n\n******************************************************************************\/\n#include \"SDL_Rectangle.hpp\"\n\nnom::Rectangle::Rectangle ( void )\n{\n this->coords = nom::Coords ( 0, 0, 0, 0 );\n this->color = nom::Color ( 0, 0, 0 );\n}\n\nnom::Rectangle::~Rectangle ( void )\n{\n \/\/ ...\n}\n\n\/\/ Constructor variant for creating a rectangle from an existing type\n\/\/ This is a \"shallow\" copy assignment\nnom::Rectangle::Rectangle ( const nom::Rectangle& rect )\n{\n this->coords = rect.coords;\n this->color = rect.color;\n}\n\nnom::Rectangle::Rectangle ( const nom::Coords& coords, const nom::Color& color )\n{\n this->coords = coords;\n this->color = color;\n}\n\nvoid nom::Rectangle::Update ( void )\n{\n \/\/ Stub\n}\n\nvoid nom::Rectangle::Draw ( void* video_buffer ) const\n{\n SDL_Rect rectangle = getSDL_Rect ( this->coords );\n unsigned int rectangle_color = 0;\n SDL_Surface *buffer = static_cast ( video_buffer );\n\n rectangle_color = getColorAsInt ( buffer->format, this->color );\n\n if ( SDL_FillRect ( buffer, &rectangle, rectangle_color ) != 0 )\n {\nNOMLIB_LOG_ERR ( SDL_GetError() );\n return;\n }\n\n \/\/ Destruct as soon as we are done to free memory\n \/\/ that could otherwise be held too long before\n \/\/ cleaned up, resulting in slow, but steady climb\n \/\/ in memory usage\n Rectangle::~Rectangle();\n}\nAdd fix for Linux GCC compile\/******************************************************************************\n\n SDL Rectangle Primitive\n\n Copyright (c) 2013 Jeffrey Carpenter\n All rights reserved.\n\n******************************************************************************\/\n#include \"SDL_Rectangle.hpp\"\n\nnom::Rectangle::Rectangle ( void )\n{\n this->coords = nom::Coords ( 0, 0, 0, 0 );\n this->color = nom::Color ( 0, 0, 0 );\n}\n\nnom::Rectangle::~Rectangle ( void )\n{\n \/\/ ...\n}\n\n\/\/ Constructor variant for creating a rectangle from an existing type\n\/\/ This is a \"shallow\" copy assignment\nnom::Rectangle::Rectangle ( const nom::Rectangle& rect )\n{\n this->coords = rect.coords;\n this->color = rect.color;\n}\n\nnom::Rectangle::Rectangle ( const nom::Coords& coords, const nom::Color& color )\n{\n this->coords = coords;\n this->color = color;\n}\n\nvoid nom::Rectangle::Update ( void )\n{\n \/\/ Stub\n}\n\nvoid nom::Rectangle::Draw ( void* video_buffer ) const\n{\n SDL_Rect rectangle = getSDL_Rect ( this->coords );\n unsigned int rectangle_color = 0;\n SDL_Surface *buffer = static_cast ( video_buffer );\n\n rectangle_color = getColorAsInt ( buffer->format, this->color );\n\n if ( SDL_FillRect ( buffer, &rectangle, rectangle_color ) != 0 )\n {\nNOMLIB_LOG_ERR ( SDL_GetError() );\n return;\n }\n\n \/\/ Destruct as soon as we are done to free memory\n \/\/ that could otherwise be held too long before\n \/\/ cleaned up, resulting in slow, but steady climb\n \/\/ in memory usage\n#ifndef NOMLIB_SYSTEM_LINUX\n Rectangle::~Rectangle();\n#endif\n}\n<|endoftext|>"} {"text":"#include \"x_client_thumbnail_gl.hpp\"\n\n#include \n#include \n\nx_client_thumbnail::x_client_thumbnail(x_connection & c,\n const rectangle & rect,\n const xcb_window_t & window,\n std::shared_ptr xclient)\n : _c(c)\n{\n if (window == XCB_NONE && xclient == NULL) {\n throw std::invalid_argument(\n \"x_client_thumbnail requires either window or xclient parameter\");\n } else if (xclient == NULL) {\n _x_client = x_client_ptr(new x_client(_c, window));\n } else {\n _x_client = xclient;\n }\n\n update_rectangle(rect);\n\n _c.register_handler(_c.damage_event_id(), this);\n _c.register_handler(XCB_CONFIGURE_NOTIFY, this);\n\n _damage = xcb_generate_id(_c());\n\n configure_parent_pixmap();\n\n _thumbnail_window = xcb_generate_id(_c());\n xcb_colormap_t colormap = xcb_generate_id(_c());\n\n GLint gl_vi_attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };\n XVisualInfo * vi =\n glXChooseVisual(_c.dpy(), DefaultScreen(_c.dpy()), gl_vi_attr);\n\n xcb_create_colormap(_c(), XCB_COLORMAP_ALLOC_NONE, colormap,\n _c.root_window(), vi->visualid);\n\n uint32_t valuemask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_COLORMAP;\n uint32_t valuelist[] = { 1, colormap, 0 };\n xcb_create_window(_c(), XCB_COPY_FROM_PARENT, _thumbnail_window,\n _c.root_window(), 0, 0,\n _x_client->rect().width(), _x_client->rect().height(),\n 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, vi->visualid,\n valuemask, valuelist);\n\n xcb_free_colormap(_c(), colormap);\n\n configure_gl(vi);\n init_gl_shader();\n delete vi;\n\n update();\n}\n\nx_client_thumbnail::~x_client_thumbnail(void)\n{\n _c.deregister_handler(_c.damage_event_id(), this);\n _c.deregister_handler(XCB_CONFIGURE_NOTIFY, this);\n release_gl();\n xcb_free_pixmap(_c(), _parent_pixmap);\n xcb_destroy_window(_c(), _thumbnail_window);\n}\n\nvoid\nx_client_thumbnail::show(void)\n{\n xcb_damage_create(_c(), _damage, _x_client->window(),\n XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY);\n configure_thumbnail_window();\n update();\n}\n\nvoid\nx_client_thumbnail::hide(void)\n{\n xcb_damage_destroy(_c(), _damage);\n xcb_unmap_window(_c(), _thumbnail_window);\n}\n\nvoid\nx_client_thumbnail::select(void)\n{\n _c.request_change_current_desktop(_x_client->net_wm_desktop());\n _c.request_change_active_window(_x_client->window());\n}\n\nvoid\nx_client_thumbnail::update(void)\n{\n update(0, 0, _rectangle.width(), _rectangle.height());\n}\n\nvoid\nx_client_thumbnail::update(int x, int y, unsigned int width, unsigned int height)\n{\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n\n glViewport(0, 0, _rectangle.width(), _rectangle.height());\n glClearColor(0.0, 0.0, 0.0, 1.0);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glBegin(GL_QUADS);\n glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, 1.0, 0.0);\n glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, 1.0, 0.0);\n glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, -1.0, 0.0);\n glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, -1.0, 0.0);\n glEnd();\n\n glXSwapBuffers(_c.dpy(), _thumbnail_window);\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n}\n\nvoid\nx_client_thumbnail::highlight(bool want_highlight)\n{\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n if (want_highlight) {\n _c.glUseProgram(0);\n } else {\n _c.glUseProgram(_programs[\"grayscale_shader\"]);\n }\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n\n update();\n}\n\nbool\nx_client_thumbnail::handle(xcb_generic_event_t * ge)\n{\n bool result = false;\n if (_c.damage_event_id() == (ge->response_type & ~0x80)) {\n xcb_damage_notify_event_t * e = (xcb_damage_notify_event_t *)ge;\n xcb_damage_subtract(_c(), e->damage, XCB_NONE, XCB_NONE);\n update(e->area.x * _scale, e->area.y * _scale,\n e->area.width * _scale, e->area.height * _scale);\n result = true;\n\n } else if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) {\n xcb_configure_notify_event_t * e = (xcb_configure_notify_event_t *)ge;\n if (e->window == _c.root_window()) {\n configure_parent_pixmap();\n release_gl();\n configure_gl();\n update();\n }\n result = true;\n }\n\n return result;\n}\n\nvoid\nx_client_thumbnail::update_rectangle(const rectangle & rect)\n{\n _scale = std::min((double)rect.width() \/ _x_client->rect().width(),\n (double)rect.height() \/ _x_client->rect().height());\n _scale = std::min(1.0, _scale);\n\n _rectangle.x() = rect.x();\n _rectangle.y() = rect.y();\n _rectangle.width() = _x_client->rect().width() * _scale;\n _rectangle.height() = _x_client->rect().height() * _scale;\n}\n\nvoid\nx_client_thumbnail::configure_thumbnail_window(void)\n{\n uint32_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y\n | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT\n | XCB_CONFIG_WINDOW_STACK_MODE;\n\n uint32_t values[] = { (uint32_t)_rectangle.x(),\n (uint32_t)_rectangle.y(),\n (uint32_t)_rectangle.width(),\n (uint32_t)_rectangle.height(),\n XCB_STACK_MODE_ABOVE };\n\n xcb_configure_window(_c(), _thumbnail_window, mask, values);\n xcb_map_window(_c(), _thumbnail_window);\n}\n\nvoid\nx_client_thumbnail::configure_parent_pixmap(void)\n{\n xcb_free_pixmap(_c(), _parent_pixmap);\n _parent_pixmap = xcb_generate_id(_c());\n xcb_composite_name_window_pixmap(_c(), _x_client->window(), _parent_pixmap);\n}\n\nvoid\nx_client_thumbnail::configure_gl(XVisualInfo * vi)\n{\n const int pixmap_config[] = {\n GLX_BIND_TO_TEXTURE_RGBA_EXT, True,\n GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,\n GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,\n GLX_DOUBLEBUFFER, False,\n GLX_Y_INVERTED_EXT,\n None\n };\n\n const int pixmap_attr[] = {\n GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,\n GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGB_EXT,\n None\n };\n\n auto create_ctx = [this, &vi]()\n {\n _gl_ctx = glXCreateContext(_c.dpy(), vi, NULL, GL_TRUE);\n };\n\n if (vi == NULL) {\n GLint gl_vi_attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };\n vi = glXChooseVisual(_c.dpy(), DefaultScreen(_c.dpy()), gl_vi_attr);\n create_ctx();\n delete vi;\n } else {\n create_ctx();\n }\n\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n\n int config = 0;\n GLXFBConfig * _gl_configs =\n glXChooseFBConfig(_c.dpy(), 0, pixmap_config, &config);\n _thumbnail_gl_pixmap =\n glXCreatePixmap(_c.dpy(), _gl_configs[0], _parent_pixmap, pixmap_attr);\n delete _gl_configs;\n\n GLuint _thumbnail_gl_texture_id;\n glEnable(GL_TEXTURE_2D);\n glGenTextures(1, &_thumbnail_gl_texture_id);\n glBindTexture(GL_TEXTURE_2D, _thumbnail_gl_texture_id);\n _c.glXBindTexImageEXT(_c.dpy(), _thumbnail_gl_pixmap, GLX_FRONT_EXT, NULL);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n}\n\nvoid\nx_client_thumbnail::init_gl_shader(void)\n{\n std::string shader_name = \"grayscale_shader\";\n std::ifstream file(\".\/grayscale.frag\");\n std::string shader_source_str((std::istreambuf_iterator(file)),\n std::istreambuf_iterator());\n file.close();\n\n const GLchar * shader_source[] = { shader_source_str.c_str() };\n const GLint shader_source_len[] = { (GLint)(shader_source_str.length()) };\n\n GLsizei log_length = 0, max_len = 1024;\n GLchar log_buffer[max_len];\n\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n\n GLuint shader = _c.glCreateShader(GL_FRAGMENT_SHADER);\n _c.glShaderSource(shader, 1, shader_source, shader_source_len);\n _c.glCompileShader(shader);\n\n _c.glGetShaderInfoLog(shader, max_len, &log_length, log_buffer);\n if (log_length > 0) {\n std::cerr << \"Shader compilation failed:\" << std::endl\n << log_buffer << std::endl;\n }\n\n _programs[shader_name] = _c.glCreateProgram();\n _c.glAttachShader(_programs[shader_name], shader);\n _c.glLinkProgram(_programs[shader_name]);\n _c.glUseProgram(_programs[shader_name]);\n\n _c.glGetProgramInfoLog(_programs[shader_name],\n max_len, &log_length, log_buffer);\n if (log_length > 0) {\n std::cerr << \"Program creation failed:\" << std::endl\n << log_buffer << std::endl;\n }\n\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n}\n\nvoid\nx_client_thumbnail::release_gl(void)\n{\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n _c.glXReleaseTexImageEXT(_c.dpy(), _thumbnail_gl_pixmap, GLX_FRONT_EXT);\n glXDestroyContext(_c.dpy(), _gl_ctx);\n glXMakeCurrent(_c.dpy(), None, NULL);\n}\n\nbool operator==(const x_client_thumbnail & thumbnail, const xcb_window_t & window)\n{\n return *(thumbnail._x_client) == window;\n}\n\nbool operator==(const xcb_window_t & window, const x_client_thumbnail & thumbnail)\n{\n return thumbnail == window;\n}\nInitialize gl shaders after gl context got purged#include \"x_client_thumbnail_gl.hpp\"\n\n#include \n#include \n\nx_client_thumbnail::x_client_thumbnail(x_connection & c,\n const rectangle & rect,\n const xcb_window_t & window,\n std::shared_ptr xclient)\n : _c(c)\n{\n if (window == XCB_NONE && xclient == NULL) {\n throw std::invalid_argument(\n \"x_client_thumbnail requires either window or xclient parameter\");\n } else if (xclient == NULL) {\n _x_client = x_client_ptr(new x_client(_c, window));\n } else {\n _x_client = xclient;\n }\n\n update_rectangle(rect);\n\n _c.register_handler(_c.damage_event_id(), this);\n _c.register_handler(XCB_CONFIGURE_NOTIFY, this);\n\n _damage = xcb_generate_id(_c());\n\n configure_parent_pixmap();\n\n _thumbnail_window = xcb_generate_id(_c());\n xcb_colormap_t colormap = xcb_generate_id(_c());\n\n GLint gl_vi_attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };\n XVisualInfo * vi =\n glXChooseVisual(_c.dpy(), DefaultScreen(_c.dpy()), gl_vi_attr);\n\n xcb_create_colormap(_c(), XCB_COLORMAP_ALLOC_NONE, colormap,\n _c.root_window(), vi->visualid);\n\n uint32_t valuemask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_COLORMAP;\n uint32_t valuelist[] = { 1, colormap, 0 };\n xcb_create_window(_c(), XCB_COPY_FROM_PARENT, _thumbnail_window,\n _c.root_window(), 0, 0,\n _x_client->rect().width(), _x_client->rect().height(),\n 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, vi->visualid,\n valuemask, valuelist);\n\n xcb_free_colormap(_c(), colormap);\n\n configure_gl(vi);\n init_gl_shader();\n delete vi;\n\n update();\n}\n\nx_client_thumbnail::~x_client_thumbnail(void)\n{\n _c.deregister_handler(_c.damage_event_id(), this);\n _c.deregister_handler(XCB_CONFIGURE_NOTIFY, this);\n release_gl();\n xcb_free_pixmap(_c(), _parent_pixmap);\n xcb_destroy_window(_c(), _thumbnail_window);\n}\n\nvoid\nx_client_thumbnail::show(void)\n{\n xcb_damage_create(_c(), _damage, _x_client->window(),\n XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY);\n configure_thumbnail_window();\n update();\n}\n\nvoid\nx_client_thumbnail::hide(void)\n{\n xcb_damage_destroy(_c(), _damage);\n xcb_unmap_window(_c(), _thumbnail_window);\n}\n\nvoid\nx_client_thumbnail::select(void)\n{\n _c.request_change_current_desktop(_x_client->net_wm_desktop());\n _c.request_change_active_window(_x_client->window());\n}\n\nvoid\nx_client_thumbnail::update(void)\n{\n update(0, 0, _rectangle.width(), _rectangle.height());\n}\n\nvoid\nx_client_thumbnail::update(int x, int y, unsigned int width, unsigned int height)\n{\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n\n glViewport(0, 0, _rectangle.width(), _rectangle.height());\n glClearColor(0.0, 0.0, 0.0, 1.0);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glBegin(GL_QUADS);\n glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, 1.0, 0.0);\n glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, 1.0, 0.0);\n glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, -1.0, 0.0);\n glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, -1.0, 0.0);\n glEnd();\n\n glXSwapBuffers(_c.dpy(), _thumbnail_window);\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n}\n\nvoid\nx_client_thumbnail::highlight(bool want_highlight)\n{\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n if (want_highlight) {\n _c.glUseProgram(0);\n } else {\n _c.glUseProgram(_programs[\"grayscale_shader\"]);\n }\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n\n update();\n}\n\nbool\nx_client_thumbnail::handle(xcb_generic_event_t * ge)\n{\n bool result = false;\n if (_c.damage_event_id() == (ge->response_type & ~0x80)) {\n xcb_damage_notify_event_t * e = (xcb_damage_notify_event_t *)ge;\n xcb_damage_subtract(_c(), e->damage, XCB_NONE, XCB_NONE);\n update(e->area.x * _scale, e->area.y * _scale,\n e->area.width * _scale, e->area.height * _scale);\n result = true;\n\n } else if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) {\n xcb_configure_notify_event_t * e = (xcb_configure_notify_event_t *)ge;\n if (e->window == _c.root_window()) {\n configure_parent_pixmap();\n release_gl();\n configure_gl();\n init_gl_shader();\n update();\n }\n result = true;\n }\n\n return result;\n}\n\nvoid\nx_client_thumbnail::update_rectangle(const rectangle & rect)\n{\n _scale = std::min((double)rect.width() \/ _x_client->rect().width(),\n (double)rect.height() \/ _x_client->rect().height());\n _scale = std::min(1.0, _scale);\n\n _rectangle.x() = rect.x();\n _rectangle.y() = rect.y();\n _rectangle.width() = _x_client->rect().width() * _scale;\n _rectangle.height() = _x_client->rect().height() * _scale;\n}\n\nvoid\nx_client_thumbnail::configure_thumbnail_window(void)\n{\n uint32_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y\n | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT\n | XCB_CONFIG_WINDOW_STACK_MODE;\n\n uint32_t values[] = { (uint32_t)_rectangle.x(),\n (uint32_t)_rectangle.y(),\n (uint32_t)_rectangle.width(),\n (uint32_t)_rectangle.height(),\n XCB_STACK_MODE_ABOVE };\n\n xcb_configure_window(_c(), _thumbnail_window, mask, values);\n xcb_map_window(_c(), _thumbnail_window);\n}\n\nvoid\nx_client_thumbnail::configure_parent_pixmap(void)\n{\n xcb_free_pixmap(_c(), _parent_pixmap);\n _parent_pixmap = xcb_generate_id(_c());\n xcb_composite_name_window_pixmap(_c(), _x_client->window(), _parent_pixmap);\n}\n\nvoid\nx_client_thumbnail::configure_gl(XVisualInfo * vi)\n{\n const int pixmap_config[] = {\n GLX_BIND_TO_TEXTURE_RGBA_EXT, True,\n GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,\n GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,\n GLX_DOUBLEBUFFER, False,\n GLX_Y_INVERTED_EXT,\n None\n };\n\n const int pixmap_attr[] = {\n GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,\n GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGB_EXT,\n None\n };\n\n auto create_ctx = [this, &vi]()\n {\n _gl_ctx = glXCreateContext(_c.dpy(), vi, NULL, GL_TRUE);\n };\n\n if (vi == NULL) {\n GLint gl_vi_attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };\n vi = glXChooseVisual(_c.dpy(), DefaultScreen(_c.dpy()), gl_vi_attr);\n create_ctx();\n delete vi;\n } else {\n create_ctx();\n }\n\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n\n int config = 0;\n GLXFBConfig * _gl_configs =\n glXChooseFBConfig(_c.dpy(), 0, pixmap_config, &config);\n _thumbnail_gl_pixmap =\n glXCreatePixmap(_c.dpy(), _gl_configs[0], _parent_pixmap, pixmap_attr);\n delete _gl_configs;\n\n GLuint _thumbnail_gl_texture_id;\n glEnable(GL_TEXTURE_2D);\n glGenTextures(1, &_thumbnail_gl_texture_id);\n glBindTexture(GL_TEXTURE_2D, _thumbnail_gl_texture_id);\n _c.glXBindTexImageEXT(_c.dpy(), _thumbnail_gl_pixmap, GLX_FRONT_EXT, NULL);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n}\n\nvoid\nx_client_thumbnail::init_gl_shader(void)\n{\n std::string shader_name = \"grayscale_shader\";\n std::ifstream file(\".\/grayscale.frag\");\n std::string shader_source_str((std::istreambuf_iterator(file)),\n std::istreambuf_iterator());\n file.close();\n\n const GLchar * shader_source[] = { shader_source_str.c_str() };\n const GLint shader_source_len[] = { (GLint)(shader_source_str.length()) };\n\n GLsizei log_length = 0, max_len = 1024;\n GLchar log_buffer[max_len];\n\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n\n GLuint shader = _c.glCreateShader(GL_FRAGMENT_SHADER);\n _c.glShaderSource(shader, 1, shader_source, shader_source_len);\n _c.glCompileShader(shader);\n\n _c.glGetShaderInfoLog(shader, max_len, &log_length, log_buffer);\n if (log_length > 0) {\n std::cerr << \"Shader compilation failed:\" << std::endl\n << log_buffer << std::endl;\n }\n\n _programs[shader_name] = _c.glCreateProgram();\n _c.glAttachShader(_programs[shader_name], shader);\n _c.glLinkProgram(_programs[shader_name]);\n _c.glUseProgram(_programs[shader_name]);\n\n _c.glGetProgramInfoLog(_programs[shader_name],\n max_len, &log_length, log_buffer);\n if (log_length > 0) {\n std::cerr << \"Program creation failed:\" << std::endl\n << log_buffer << std::endl;\n }\n\n glXMakeCurrent(_c.dpy(), XCB_NONE, NULL);\n}\n\nvoid\nx_client_thumbnail::release_gl(void)\n{\n glXMakeCurrent(_c.dpy(), _thumbnail_window, _gl_ctx);\n _c.glXReleaseTexImageEXT(_c.dpy(), _thumbnail_gl_pixmap, GLX_FRONT_EXT);\n glXDestroyContext(_c.dpy(), _gl_ctx);\n glXMakeCurrent(_c.dpy(), None, NULL);\n}\n\nbool operator==(const x_client_thumbnail & thumbnail, const xcb_window_t & window)\n{\n return *(thumbnail._x_client) == window;\n}\n\nbool operator==(const xcb_window_t & window, const x_client_thumbnail & thumbnail)\n{\n return thumbnail == window;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: accessiblestatesethelper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: sab $ $Date: 2002-02-20 12:45:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \"unotools\/accessiblestatesethelper.hxx\"\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#include \n\n\/\/ defines how many states the bitfield can contain\n#define BITFIELDSIZE 30\n\nusing namespace ::utl;\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::drafts::com::sun::star::accessibility;\n\nclass AccessibleStateSetHelperImpl\n{\npublic:\n AccessibleStateSetHelperImpl();\n AccessibleStateSetHelperImpl(const AccessibleStateSetHelperImpl& rImpl);\n ~AccessibleStateSetHelperImpl();\n\n sal_Bool IsEmpty ()\n throw (uno::RuntimeException);\n sal_Bool Contains (sal_Int16 aState)\n throw (uno::RuntimeException);\n void AddState(sal_Int16 aState)\n throw (uno::RuntimeException);\n void RemoveState(sal_Int16 aState)\n throw (uno::RuntimeException);\n void Compare(const AccessibleStateSetHelperImpl* pComparativeValue,\n AccessibleStateSetHelperImpl* pOldStates,\n AccessibleStateSetHelperImpl* pNewStates)\n throw (uno::RuntimeException);\n\nprivate:\n std::bitset maStates; \/\/Bitfield\n};\n\nAccessibleStateSetHelperImpl::AccessibleStateSetHelperImpl()\n{\n}\n\nAccessibleStateSetHelperImpl::AccessibleStateSetHelperImpl(const AccessibleStateSetHelperImpl& rImpl)\n : maStates(rImpl.maStates)\n{\n}\n\nAccessibleStateSetHelperImpl::~AccessibleStateSetHelperImpl()\n{\n}\n\nsal_Bool AccessibleStateSetHelperImpl::IsEmpty ()\n throw (uno::RuntimeException)\n{\n return maStates.none();\n}\n\nsal_Bool AccessibleStateSetHelperImpl::Contains (sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n DBG_ASSERT(aState >= BITFIELDSIZE, \"the statesset is to small\")\n return maStates.test(aState);\n}\n\nvoid AccessibleStateSetHelperImpl::AddState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n DBG_ASSERT(aState >= BITFIELDSIZE, \"the statesset is to small\")\n maStates.set(aState);\n}\n\nvoid AccessibleStateSetHelperImpl::RemoveState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n DBG_ASSERT(aState >= BITFIELDSIZE, \"the statesset is to small\")\n maStates.set(aState, 0);\n}\n\nvoid AccessibleStateSetHelperImpl::Compare(\n const AccessibleStateSetHelperImpl* pComparativeValue,\n AccessibleStateSetHelperImpl* pOldStates,\n AccessibleStateSetHelperImpl* pNewStates)\n throw (uno::RuntimeException)\n{\n if (pComparativeValue && pOldStates && pNewStates)\n {\n std::bitset aTempBitSet(maStates);\n aTempBitSet ^= pComparativeValue->maStates;\n pOldStates->maStates = aTempBitSet;\n pOldStates->maStates &= maStates;\n pNewStates->maStates = aTempBitSet;\n pNewStates->maStates &= pComparativeValue->maStates;\n }\n}\n\n\n\/\/===== internal ============================================================\n\nAccessibleStateSetHelper::AccessibleStateSetHelper ()\n : mpHelperImpl(NULL)\n{\n mpHelperImpl = new AccessibleStateSetHelperImpl();\n}\n\nAccessibleStateSetHelper::AccessibleStateSetHelper (const AccessibleStateSetHelper& rHelper)\n : mpHelperImpl(NULL)\n{\n if (rHelper.mpHelperImpl)\n mpHelperImpl = new AccessibleStateSetHelperImpl(*rHelper.mpHelperImpl);\n else\n mpHelperImpl = new AccessibleStateSetHelperImpl();\n}\n\nAccessibleStateSetHelper::~AccessibleStateSetHelper(void)\n{\n delete mpHelperImpl;\n}\n\n\/\/===== XAccessibleStateSet ==============================================\n\n \/** Checks whether the current state set is empty.\n\n @return\n Returns if there is no state in this state set and\n if there is at least one state set in it.\n *\/\nsal_Bool SAL_CALL AccessibleStateSetHelper::isEmpty ()\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n return mpHelperImpl->IsEmpty();\n}\n\n \/** Checks if the given state is a member of the state set of this\n object.\n\n @param aState\n The state for which to check membership. This has to be one of\n the constants of AccessibleStateType<\/type>.\n\n @return\n Returns if the given state is a memeber of this object's\n state set and otherwise.\n *\/\nsal_Bool SAL_CALL AccessibleStateSetHelper::contains (sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n return mpHelperImpl->Contains(aState);\n}\n\n \/** Checks if all of the given states are in this object's state\n set.\n\n @param aStateSet\n This sequence of states is interpreted as set and every of its\n members, duplicates are ignored, is checked for membership in\n this object's state set. Each state has to be one of the\n constants of AccessibleStateType<\/type>.\n\n @return\n Returns if all states of the given state set are members\n of this object's state set. is returned if at least\n one of the states in the given state is not a member of this\n object's state set.\n *\/\nsal_Bool SAL_CALL AccessibleStateSetHelper::containsAll\n (const uno::Sequence& rStateSet)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n sal_Int32 nCount(rStateSet.getLength());\n const sal_Int16* pStates = rStateSet.getConstArray();\n sal_Int32 i = 0;\n sal_Bool bFound(sal_True);\n while (i < nCount)\n {\n bFound = mpHelperImpl->Contains(pStates[i]);\n i++;\n }\n return bFound;\n}\n\nvoid AccessibleStateSetHelper::AddState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n mpHelperImpl->AddState(aState);\n}\n\nvoid AccessibleStateSetHelper::RemoveState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n mpHelperImpl->RemoveState(aState);\n}\n\nvoid AccessibleStateSetHelper::Compare(\n const AccessibleStateSetHelper& rComparativeValue,\n AccessibleStateSetHelper& rOldStates,\n AccessibleStateSetHelper& rNewStates)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n mpHelperImpl->Compare(rComparativeValue.mpHelperImpl,\n rOldStates.mpHelperImpl, rNewStates.mpHelperImpl);\n}\n\n\/\/===== XTypeProvider =======================================================\n\nuno::Sequence< ::com::sun::star::uno::Type>\n AccessibleStateSetHelper::getTypes (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n const ::com::sun::star::uno::Type aTypeList[] = {\n ::getCppuType((const uno::Reference<\n XAccessibleStateSet>*)0),\n ::getCppuType((const uno::Reference<\n lang::XTypeProvider>*)0)\n };\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>\n aTypeSequence (aTypeList, 2);\n return aTypeSequence;\n}\n\nuno::Sequence SAL_CALL\n AccessibleStateSetHelper::getImplementationId (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n static uno::Sequence aId;\n if (aId.getLength() == 0)\n {\n ::vos::OGuard aGuard (maMutex);\n aId.realloc (16);\n rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);\n }\n return aId;\n}\n#95584#; correct the assertion condition\/*************************************************************************\n *\n * $RCSfile: accessiblestatesethelper.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: sab $ $Date: 2002-02-21 12:43:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \"unotools\/accessiblestatesethelper.hxx\"\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#include \n\n\/\/ defines how many states the bitfield can contain\n#define BITFIELDSIZE 30\n\nusing namespace ::utl;\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::drafts::com::sun::star::accessibility;\n\nclass AccessibleStateSetHelperImpl\n{\npublic:\n AccessibleStateSetHelperImpl();\n AccessibleStateSetHelperImpl(const AccessibleStateSetHelperImpl& rImpl);\n ~AccessibleStateSetHelperImpl();\n\n sal_Bool IsEmpty ()\n throw (uno::RuntimeException);\n sal_Bool Contains (sal_Int16 aState)\n throw (uno::RuntimeException);\n void AddState(sal_Int16 aState)\n throw (uno::RuntimeException);\n void RemoveState(sal_Int16 aState)\n throw (uno::RuntimeException);\n void Compare(const AccessibleStateSetHelperImpl* pComparativeValue,\n AccessibleStateSetHelperImpl* pOldStates,\n AccessibleStateSetHelperImpl* pNewStates)\n throw (uno::RuntimeException);\n\nprivate:\n std::bitset maStates; \/\/Bitfield\n};\n\nAccessibleStateSetHelperImpl::AccessibleStateSetHelperImpl()\n{\n}\n\nAccessibleStateSetHelperImpl::AccessibleStateSetHelperImpl(const AccessibleStateSetHelperImpl& rImpl)\n : maStates(rImpl.maStates)\n{\n}\n\nAccessibleStateSetHelperImpl::~AccessibleStateSetHelperImpl()\n{\n}\n\nsal_Bool AccessibleStateSetHelperImpl::IsEmpty ()\n throw (uno::RuntimeException)\n{\n return maStates.none();\n}\n\nsal_Bool AccessibleStateSetHelperImpl::Contains (sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n DBG_ASSERT(aState < BITFIELDSIZE, \"the statesset is to small\")\n return maStates.test(aState);\n}\n\nvoid AccessibleStateSetHelperImpl::AddState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n DBG_ASSERT(aState < BITFIELDSIZE, \"the statesset is to small\")\n maStates.set(aState);\n}\n\nvoid AccessibleStateSetHelperImpl::RemoveState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n DBG_ASSERT(aState < BITFIELDSIZE, \"the statesset is to small\")\n maStates.set(aState, 0);\n}\n\nvoid AccessibleStateSetHelperImpl::Compare(\n const AccessibleStateSetHelperImpl* pComparativeValue,\n AccessibleStateSetHelperImpl* pOldStates,\n AccessibleStateSetHelperImpl* pNewStates)\n throw (uno::RuntimeException)\n{\n if (pComparativeValue && pOldStates && pNewStates)\n {\n std::bitset aTempBitSet(maStates);\n aTempBitSet ^= pComparativeValue->maStates;\n pOldStates->maStates = aTempBitSet;\n pOldStates->maStates &= maStates;\n pNewStates->maStates = aTempBitSet;\n pNewStates->maStates &= pComparativeValue->maStates;\n }\n}\n\n\n\/\/===== internal ============================================================\n\nAccessibleStateSetHelper::AccessibleStateSetHelper ()\n : mpHelperImpl(NULL)\n{\n mpHelperImpl = new AccessibleStateSetHelperImpl();\n}\n\nAccessibleStateSetHelper::AccessibleStateSetHelper (const AccessibleStateSetHelper& rHelper)\n : mpHelperImpl(NULL)\n{\n if (rHelper.mpHelperImpl)\n mpHelperImpl = new AccessibleStateSetHelperImpl(*rHelper.mpHelperImpl);\n else\n mpHelperImpl = new AccessibleStateSetHelperImpl();\n}\n\nAccessibleStateSetHelper::~AccessibleStateSetHelper(void)\n{\n delete mpHelperImpl;\n}\n\n\/\/===== XAccessibleStateSet ==============================================\n\n \/** Checks whether the current state set is empty.\n\n @return\n Returns if there is no state in this state set and\n if there is at least one state set in it.\n *\/\nsal_Bool SAL_CALL AccessibleStateSetHelper::isEmpty ()\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n return mpHelperImpl->IsEmpty();\n}\n\n \/** Checks if the given state is a member of the state set of this\n object.\n\n @param aState\n The state for which to check membership. This has to be one of\n the constants of AccessibleStateType<\/type>.\n\n @return\n Returns if the given state is a memeber of this object's\n state set and otherwise.\n *\/\nsal_Bool SAL_CALL AccessibleStateSetHelper::contains (sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n return mpHelperImpl->Contains(aState);\n}\n\n \/** Checks if all of the given states are in this object's state\n set.\n\n @param aStateSet\n This sequence of states is interpreted as set and every of its\n members, duplicates are ignored, is checked for membership in\n this object's state set. Each state has to be one of the\n constants of AccessibleStateType<\/type>.\n\n @return\n Returns if all states of the given state set are members\n of this object's state set. is returned if at least\n one of the states in the given state is not a member of this\n object's state set.\n *\/\nsal_Bool SAL_CALL AccessibleStateSetHelper::containsAll\n (const uno::Sequence& rStateSet)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n sal_Int32 nCount(rStateSet.getLength());\n const sal_Int16* pStates = rStateSet.getConstArray();\n sal_Int32 i = 0;\n sal_Bool bFound(sal_True);\n while (i < nCount)\n {\n bFound = mpHelperImpl->Contains(pStates[i]);\n i++;\n }\n return bFound;\n}\n\nvoid AccessibleStateSetHelper::AddState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n mpHelperImpl->AddState(aState);\n}\n\nvoid AccessibleStateSetHelper::RemoveState(sal_Int16 aState)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n mpHelperImpl->RemoveState(aState);\n}\n\nvoid AccessibleStateSetHelper::Compare(\n const AccessibleStateSetHelper& rComparativeValue,\n AccessibleStateSetHelper& rOldStates,\n AccessibleStateSetHelper& rNewStates)\n throw (uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n mpHelperImpl->Compare(rComparativeValue.mpHelperImpl,\n rOldStates.mpHelperImpl, rNewStates.mpHelperImpl);\n}\n\n\/\/===== XTypeProvider =======================================================\n\nuno::Sequence< ::com::sun::star::uno::Type>\n AccessibleStateSetHelper::getTypes (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n const ::com::sun::star::uno::Type aTypeList[] = {\n ::getCppuType((const uno::Reference<\n XAccessibleStateSet>*)0),\n ::getCppuType((const uno::Reference<\n lang::XTypeProvider>*)0)\n };\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>\n aTypeSequence (aTypeList, 2);\n return aTypeSequence;\n}\n\nuno::Sequence SAL_CALL\n AccessibleStateSetHelper::getImplementationId (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n ::vos::OGuard aGuard (maMutex);\n static uno::Sequence aId;\n if (aId.getLength() == 0)\n {\n ::vos::OGuard aGuard (maMutex);\n aId.realloc (16);\n rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);\n }\n return aId;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The SwiftShader Authors. All Rights Reserved.\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#ifndef VK_IMAGE_VIEW_HPP_\n#define VK_IMAGE_VIEW_HPP_\n\n#include \"VkDebug.hpp\"\n#include \"VkFormat.h\"\n#include \"VkObject.hpp\"\n#include \"VkImage.hpp\"\n\nnamespace vk\n{\n\nclass ImageView : public Object\n{\npublic:\n\tImageView(const VkImageViewCreateInfo* pCreateInfo, void* mem);\n\t~ImageView() = delete;\n\tvoid destroy(const VkAllocationCallbacks* pAllocator);\n\n\tstatic size_t ComputeRequiredAllocationSize(const VkImageViewCreateInfo* pCreateInfo);\n\n\tvoid clear(const VkClearValue& clearValues, VkImageAspectFlags aspectMask, const VkRect2D& renderArea);\n\tvoid clear(const VkClearValue& clearValue, VkImageAspectFlags aspectMask, const VkClearRect& renderArea);\n\tvoid resolve(ImageView* resolveAttachment);\n\n\tVkImageViewType getType() const { return viewType; }\n\tFormat getFormat() const { return format; }\n\tint getSampleCount() const { return image->getSampleCountFlagBits(); }\n\tint rowPitchBytes(VkImageAspectFlagBits aspect, uint32_t mipLevel) const { return image->rowPitchBytes(aspect, subresourceRange.baseMipLevel + mipLevel); }\n\tint slicePitchBytes(VkImageAspectFlagBits aspect, uint32_t mipLevel) const { return image->slicePitchBytes(aspect, subresourceRange.baseMipLevel + mipLevel); }\n\tint layerPitchBytes(VkImageAspectFlagBits aspect) const { return static_cast(image->getLayerSize(aspect)); }\n\tVkExtent3D getMipLevelExtent(uint32_t mipLevel) const { return image->getMipLevelExtent(subresourceRange.baseMipLevel + mipLevel); }\n\n\tvoid *getOffsetPointer(const VkOffset3D& offset, VkImageAspectFlagBits aspect, uint32_t mipLevel) const;\n\tbool hasDepthAspect() const { return (subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0; }\n\tbool hasStencilAspect() const { return (subresourceRange.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) != 0; }\n\n\tconst VkComponentMapping &getComponentMapping() const { return components; }\n\tconst VkImageSubresourceRange &getSubresourceRange() const { return subresourceRange; }\n\tconst size_t getImageSizeInBytes() const { return image->getMemoryRequirements().size; }\n\nprivate:\n\tbool imageTypesMatch(VkImageType imageType) const;\n\n\tImage *const image = nullptr;\n\tconst VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D;\n\tconst Format format;\n\tconst VkComponentMapping components = {};\n\tconst VkImageSubresourceRange subresourceRange = {};\n};\n\nstatic inline ImageView* Cast(VkImageView object)\n{\n\treturn reinterpret_cast(object);\n}\n\n} \/\/ namespace vk\n\n#endif \/\/ VK_IMAGE_VIEW_HPP_\nRemove useless const on ImageView::getImageSizeInBytes return value\/\/ Copyright 2018 The SwiftShader Authors. All Rights Reserved.\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#ifndef VK_IMAGE_VIEW_HPP_\n#define VK_IMAGE_VIEW_HPP_\n\n#include \"VkDebug.hpp\"\n#include \"VkFormat.h\"\n#include \"VkObject.hpp\"\n#include \"VkImage.hpp\"\n\nnamespace vk\n{\n\nclass ImageView : public Object\n{\npublic:\n\tImageView(const VkImageViewCreateInfo* pCreateInfo, void* mem);\n\t~ImageView() = delete;\n\tvoid destroy(const VkAllocationCallbacks* pAllocator);\n\n\tstatic size_t ComputeRequiredAllocationSize(const VkImageViewCreateInfo* pCreateInfo);\n\n\tvoid clear(const VkClearValue& clearValues, VkImageAspectFlags aspectMask, const VkRect2D& renderArea);\n\tvoid clear(const VkClearValue& clearValue, VkImageAspectFlags aspectMask, const VkClearRect& renderArea);\n\tvoid resolve(ImageView* resolveAttachment);\n\n\tVkImageViewType getType() const { return viewType; }\n\tFormat getFormat() const { return format; }\n\tint getSampleCount() const { return image->getSampleCountFlagBits(); }\n\tint rowPitchBytes(VkImageAspectFlagBits aspect, uint32_t mipLevel) const { return image->rowPitchBytes(aspect, subresourceRange.baseMipLevel + mipLevel); }\n\tint slicePitchBytes(VkImageAspectFlagBits aspect, uint32_t mipLevel) const { return image->slicePitchBytes(aspect, subresourceRange.baseMipLevel + mipLevel); }\n\tint layerPitchBytes(VkImageAspectFlagBits aspect) const { return static_cast(image->getLayerSize(aspect)); }\n\tVkExtent3D getMipLevelExtent(uint32_t mipLevel) const { return image->getMipLevelExtent(subresourceRange.baseMipLevel + mipLevel); }\n\n\tvoid *getOffsetPointer(const VkOffset3D& offset, VkImageAspectFlagBits aspect, uint32_t mipLevel) const;\n\tbool hasDepthAspect() const { return (subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0; }\n\tbool hasStencilAspect() const { return (subresourceRange.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) != 0; }\n\n\tconst VkComponentMapping &getComponentMapping() const { return components; }\n\tconst VkImageSubresourceRange &getSubresourceRange() const { return subresourceRange; }\n\tsize_t getImageSizeInBytes() const { return image->getMemoryRequirements().size; }\n\nprivate:\n\tbool imageTypesMatch(VkImageType imageType) const;\n\n\tImage *const image = nullptr;\n\tconst VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D;\n\tconst Format format;\n\tconst VkComponentMapping components = {};\n\tconst VkImageSubresourceRange subresourceRange = {};\n};\n\nstatic inline ImageView* Cast(VkImageView object)\n{\n\treturn reinterpret_cast(object);\n}\n\n} \/\/ namespace vk\n\n#endif \/\/ VK_IMAGE_VIEW_HPP_\n<|endoftext|>"} {"text":"#include \"xchainer\/python\/device.h\"\n\n#include \n#include \n\n#include \"xchainer\/backend.h\"\n#include \"xchainer\/context.h\"\n#include \"xchainer\/device.h\"\n\n#include \"xchainer\/python\/common.h\"\n\nnamespace xchainer {\n\nnamespace py = pybind11; \/\/ standard convention\n\nclass PyDeviceScope {\npublic:\n explicit PyDeviceScope(Device& target) : target_(target) {}\n void Enter() { scope_ = std::make_unique(target_); }\n void Exit(py::args args) {\n (void)args; \/\/ unused\n scope_.reset();\n }\n\nprivate:\n \/\/ TODO(beam2d): better to replace it by \"optional\"...\n std::unique_ptr scope_;\n Device& target_;\n};\n\nvoid InitXchainerDevice(pybind11::module& m) {\n py::class_(m, \"Device\")\n .def(\"__repr__\", &Device::name)\n .def(\"synchronize\", &Device::Synchronize)\n .def_property_readonly(\"name\", &Device::name)\n .def_property_readonly(\"backend\", &Device::backend, py::return_value_policy::reference)\n .def_property_readonly(\"context\", &Device::context, py::return_value_policy::reference)\n .def_property_readonly(\"index\", &Device::index);\n\n m.def(\"get_default_device\", []() -> Device& { return GetDefaultDevice(); }, py::return_value_policy::reference);\n m.def(\"set_default_device\", [](Device& device) { SetDefaultDevice(&device); });\n\n py::class_(m, \"DeviceScope\").def(\"__enter__\", &PyDeviceScope::Enter).def(\"__exit__\", &PyDeviceScope::Exit);\n m.def(\"device_scope\", [](Device& device) { return PyDeviceScope(device); });\n}\n\n} \/\/ namespace xchainer\nAllow setting default device by str in Python#include \"xchainer\/python\/device.h\"\n\n#include \n#include \n#include \n\n#include \"xchainer\/backend.h\"\n#include \"xchainer\/context.h\"\n#include \"xchainer\/device.h\"\n\n#include \"xchainer\/python\/common.h\"\n\nnamespace xchainer {\n\nnamespace py = pybind11; \/\/ standard convention\n\nclass PyDeviceScope {\npublic:\n explicit PyDeviceScope(Device& target) : target_(target) {}\n void Enter() { scope_ = std::make_unique(target_); }\n void Exit(py::args args) {\n (void)args; \/\/ unused\n scope_.reset();\n }\n\nprivate:\n \/\/ TODO(beam2d): better to replace it by \"optional\"...\n std::unique_ptr scope_;\n Device& target_;\n};\n\nvoid InitXchainerDevice(pybind11::module& m) {\n py::class_(m, \"Device\")\n .def(\"__repr__\", &Device::name)\n .def(\"synchronize\", &Device::Synchronize)\n .def_property_readonly(\"name\", &Device::name)\n .def_property_readonly(\"backend\", &Device::backend, py::return_value_policy::reference)\n .def_property_readonly(\"context\", &Device::context, py::return_value_policy::reference)\n .def_property_readonly(\"index\", &Device::index);\n\n m.def(\"get_default_device\", []() -> Device& { return GetDefaultDevice(); }, py::return_value_policy::reference);\n m.def(\"set_default_device\", [](Device& device) { SetDefaultDevice(&device); });\n m.def(\"set_default_device\", [](const std::string& device_id) { SetDefaultDevice(&GetDefaultContext().GetDevice(device_id)); });\n\n py::class_(m, \"DeviceScope\").def(\"__enter__\", &PyDeviceScope::Enter).def(\"__exit__\", &PyDeviceScope::Exit);\n m.def(\"device_scope\", [](Device& device) { return PyDeviceScope(device); });\n}\n\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"\/\/**************************************************************************************************\n\/\/\n\/\/ OSSIM Open Source Geospatial Data Processing Library\n\/\/ See top level LICENSE.txt file for license information\n\/\/\n\/\/**************************************************************************************************\n\n#include \"ossimPotraceUtil.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst char* ossimPotraceUtil::DESCRIPTION =\n \"Computes vector representation of input raster image.\";\n\nstatic const string MODE_KW = \"mode\";\n\n\nossimPotraceUtil::ossimPotraceUtil()\n: m_mode (LINESTRING)\n{\n}\n\nossimPotraceUtil::~ossimPotraceUtil()\n{\n}\n\nvoid ossimPotraceUtil::setUsage(ossimArgumentParser& ap)\n{\n \/\/ Add global usage options.\n ossimUtility::setUsage(ap);\n\n \/\/ Set the general usage:\n ossimApplicationUsage* au = ap.getApplicationUsage();\n ossimString usageString = ap.getApplicationName();\n usageString += \" [options] []\";\n au->setCommandLineUsage(usageString);\n\n \/\/ Set the command line options:\n au->addCommandLineOption(\"--mode polygon|linestring\",\n \"Specifies whether to represent foreground-background boundary as polygons or line-strings\"\n \". Polygons are closed regions surrounding either null or non-null pixels. Most viewers \"\n \"will represent polygons as solid blobs. Line-strings only outline the boundary but do not\"\n \" maintain sense of \\\"insideness\\\"\");\n}\n\nbool ossimPotraceUtil::initialize(ossimArgumentParser& ap)\n{\n string ts1;\n ossimArgumentParser::ossimParameter sp1(ts1);\n\n if (!ossimUtility::initialize(ap))\n return false;\n\n if ( ap.read(\"--mode\", sp1))\n m_kwl.addPair(MODE_KW, ts1);\n\n \/\/ Remaining argument is input and output file names:\n if (ap.argc() > 1)\n {\n m_kwl.add(ossimKeywordNames::IMAGE_FILE_KW, ap.argv()[1]);\n if (ap.argc() > 2)\n m_kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, ap.argv()[2]);\n }\n else\n {\n setUsage(ap);\n ap.reportError(\"Missing input raster filename.\");\n ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE));\n return false;\n }\n\n initialize(m_kwl);\n return true;\n}\n\nvoid ossimPotraceUtil::initialize(const ossimKeywordlist& kwl)\n{\n ossimString value;\n ostringstream xmsg;\n\n \/\/ Don't copy KWL if member KWL passed in:\n if (&kwl != &m_kwl)\n {\n \/\/ Start with clean options keyword list.\n m_kwl.clear();\n m_kwl.addList( kwl, true );\n }\n\n value = m_kwl.findKey(MODE_KW);\n if (value.contains(\"polygon\"))\n m_mode = POLYGON;\n else if (value.contains(\"linestring\"))\n m_mode = LINESTRING;\n else\n {\n xmsg <<\"ossimPotraceUtil:\"<<__LINE__<<\" Unallowed mode requested: <\"<.\"\n <open(m_inputRasterFname, 1, 0);\n if (!m_inputHandler.valid())\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Could not open input file <\"<\"\n < geom = m_inputHandler->getImageGeometry();\n if (!geom.valid())\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Encountered null image geometry!\"<turdsize = 10;\n potraceParam->alphamax = 0;\n potrace_state_t* potraceOutput = potrace_trace(potraceParam, potraceBitmap);\n if (!potraceOutput)\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Null pointer returned from potrace_trace!\"<plist;\n potrace_path_t* path = potracePaths;\n ossimDpt imgPt;\n ossimGpt gndPt;\n while (path)\n {\n int numSegments = path->curve.n;\n for (int i=0; icurve.tag[i] = POTRACE_CORNER))\n continue;\n\n imgPt.x = path->curve.c[i][v].x;\n imgPt.y = path->curve.c[i][v].y;\n geom->localToWorld(imgPt, gndPt);\n path->curve.c[i][v].x = gndPt.lon;\n path->curve.c[i][v].y = gndPt.lat;\n }\n }\n path = path->next;\n }\n\n \/\/ Write to output vector file:\n if (!writeGeoJSON(potracePaths))\n return false;\n\n \/\/ Release memory:\n potrace_state_free(potraceOutput);\n \/\/free(potraceBitmap->map);\n delete potraceBitmap;\n free(potraceParam);\n\n return true;\n}\n\nvoid ossimPotraceUtil::getKwlTemplate(ossimKeywordlist& kwl)\n{\n kwl.add(MODE_KW.c_str(), \"polygom|linestring\");\n kwl.add(ossimKeywordNames::IMAGE_FILE_KW, \"\");\n kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, \"\");\n}\n\npotrace_bitmap_t* ossimPotraceUtil::convertToBitmap()\n{\n potrace_bitmap_t* potraceBitmap = new potrace_bitmap_t;\n\n \/\/ Determine output bitmap size to even word boundary:\n ossimIrect rect = m_inputHandler->getImageRectangle();\n potraceBitmap->w = rect.width();\n potraceBitmap->h = rect.height();\n int pixelsPerWord = 8 * sizeof(int*);\n potraceBitmap->dy = (int) ceil((double)rect.width()\/pixelsPerWord);\n\n \/\/ Allocate the bitmap memory:\n unsigned long bufLength = potraceBitmap->dy*potraceBitmap->h;\n potraceBitmap->map = new potrace_word[bufLength];\n\n \/\/ Prepare to sequence over all input image tiles and fill the bitmap image:\n ossimRefPtr sequencer =\n new ossimImageSourceSequencer(m_inputHandler.get());\n ossimRefPtr tile = sequencer->getNextTile();\n double null_pix = tile->getNullPix(0);\n unsigned long offset=0;\n\n \/\/ Loop to fill bitmap buffer:\n while (tile.valid())\n {\n ossimIpt pt (tile->getOrigin());\n ossimIpt lastPt (pt.x + tile->getWidth() - 1, pt.y + tile->getHeight() - 1);\n\n \/\/ Nested loops over all pixels in input tile:\n for (; pt.y <= lastPt.y; ++pt.y)\n {\n offset = tile->getOrigin().x\/pixelsPerWord + pt.y*potraceBitmap->dy;\n for (pt.x = tile->getOrigin().x; pt.x <= lastPt.x; )\n {\n \/\/ Loop to pack a word buffer with pixel on (non-null) or off bit in proper positions:\n unsigned long wordBuf = 0;\n for (int bitpos=pixelsPerWord-1; bitpos>=0; --bitpos)\n {\n unsigned long pixel = (tile->getPix(pt) != null_pix) ? 1 : 0;\n wordBuf |= pixel << bitpos;\n ++pt.x;\n if (pt.x > lastPt.x)\n break;\n }\n potraceBitmap->map[offset++] = wordBuf;\n }\n }\n\n tile = sequencer->getNextTile();\n }\n\n return potraceBitmap;\n}\n\nbool ossimPotraceUtil::writeGeoJSON(potrace_path_t* vectorList)\n{\n FILE* outFile = fopen(m_outputVectorFname.chars(), \"w\");\n if (!outFile)\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Could not open output file <\"< for writing.\"<made param optional\/\/**************************************************************************************************\n\/\/\n\/\/ OSSIM Open Source Geospatial Data Processing Library\n\/\/ See top level LICENSE.txt file for license information\n\/\/\n\/\/**************************************************************************************************\n\n#include \"ossimPotraceUtil.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst char* ossimPotraceUtil::DESCRIPTION =\n \"Computes vector representation of input raster image.\";\n\nstatic const string MODE_KW = \"mode\";\n\n\nossimPotraceUtil::ossimPotraceUtil()\n: m_mode (LINESTRING)\n{\n}\n\nossimPotraceUtil::~ossimPotraceUtil()\n{\n}\n\nvoid ossimPotraceUtil::setUsage(ossimArgumentParser& ap)\n{\n \/\/ Add global usage options.\n ossimUtility::setUsage(ap);\n\n \/\/ Set the general usage:\n ossimApplicationUsage* au = ap.getApplicationUsage();\n ossimString usageString = ap.getApplicationName();\n usageString += \" [options] []\";\n au->setCommandLineUsage(usageString);\n\n \/\/ Set the command line options:\n au->addCommandLineOption(\"--mode polygon|linestring\",\n \"Specifies whether to represent foreground-background boundary as polygons or line-strings\"\n \". Polygons are closed regions surrounding either null or non-null pixels. Most viewers \"\n \"will represent polygons as solid blobs. Line-strings only outline the boundary but do not\"\n \" maintain sense of \\\"insideness\\\"\");\n}\n\nbool ossimPotraceUtil::initialize(ossimArgumentParser& ap)\n{\n string ts1;\n ossimArgumentParser::ossimParameter sp1(ts1);\n\n if (!ossimUtility::initialize(ap))\n return false;\n\n if ( ap.read(\"--mode\", sp1))\n m_kwl.addPair(MODE_KW, ts1);\n\n \/\/ Remaining argument is input and output file names:\n if (ap.argc() > 1)\n {\n m_kwl.add(ossimKeywordNames::IMAGE_FILE_KW, ap.argv()[1]);\n if (ap.argc() > 2)\n m_kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, ap.argv()[2]);\n }\n else\n {\n setUsage(ap);\n ap.reportError(\"Missing input raster filename.\");\n ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE));\n return false;\n }\n\n initialize(m_kwl);\n return true;\n}\n\nvoid ossimPotraceUtil::initialize(const ossimKeywordlist& kwl)\n{\n ossimString value;\n ostringstream xmsg;\n\n \/\/ Don't copy KWL if member KWL passed in:\n if (&kwl != &m_kwl)\n {\n \/\/ Start with clean options keyword list.\n m_kwl.clear();\n m_kwl.addList( kwl, true );\n }\n\n value = m_kwl.findKey(MODE_KW);\n if (value.contains(\"polygon\"))\n m_mode = POLYGON;\n else if (value.contains(\"linestring\"))\n m_mode = LINESTRING;\n else if (!value.empty())\n {\n xmsg <<\"ossimPotraceUtil:\"<<__LINE__<<\" Unallowed mode requested: <\"<.\"\n <open(m_inputRasterFname, 1, 0);\n if (!m_inputHandler.valid())\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Could not open input file <\"<\"\n < geom = m_inputHandler->getImageGeometry();\n if (!geom.valid())\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Encountered null image geometry!\"<turdsize = 10;\n potraceParam->alphamax = 0;\n potrace_state_t* potraceOutput = potrace_trace(potraceParam, potraceBitmap);\n if (!potraceOutput)\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Null pointer returned from potrace_trace!\"<plist;\n potrace_path_t* path = potracePaths;\n ossimDpt imgPt;\n ossimGpt gndPt;\n while (path)\n {\n int numSegments = path->curve.n;\n for (int i=0; icurve.tag[i] = POTRACE_CORNER))\n continue;\n\n imgPt.x = path->curve.c[i][v].x;\n imgPt.y = path->curve.c[i][v].y;\n geom->localToWorld(imgPt, gndPt);\n path->curve.c[i][v].x = gndPt.lon;\n path->curve.c[i][v].y = gndPt.lat;\n }\n }\n path = path->next;\n }\n\n \/\/ Write to output vector file:\n if (!writeGeoJSON(potracePaths))\n return false;\n\n \/\/ Release memory:\n potrace_state_free(potraceOutput);\n \/\/free(potraceBitmap->map);\n delete potraceBitmap;\n free(potraceParam);\n\n return true;\n}\n\nvoid ossimPotraceUtil::getKwlTemplate(ossimKeywordlist& kwl)\n{\n kwl.add(MODE_KW.c_str(), \"polygom|linestring\");\n kwl.add(ossimKeywordNames::IMAGE_FILE_KW, \"\");\n kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, \"\");\n}\n\npotrace_bitmap_t* ossimPotraceUtil::convertToBitmap()\n{\n potrace_bitmap_t* potraceBitmap = new potrace_bitmap_t;\n\n \/\/ Determine output bitmap size to even word boundary:\n ossimIrect rect = m_inputHandler->getImageRectangle();\n potraceBitmap->w = rect.width();\n potraceBitmap->h = rect.height();\n int pixelsPerWord = 8 * sizeof(int*);\n potraceBitmap->dy = (int) ceil((double)rect.width()\/pixelsPerWord);\n\n \/\/ Allocate the bitmap memory:\n unsigned long bufLength = potraceBitmap->dy*potraceBitmap->h;\n potraceBitmap->map = new potrace_word[bufLength];\n\n \/\/ Prepare to sequence over all input image tiles and fill the bitmap image:\n ossimRefPtr sequencer =\n new ossimImageSourceSequencer(m_inputHandler.get());\n ossimRefPtr tile = sequencer->getNextTile();\n double null_pix = tile->getNullPix(0);\n unsigned long offset=0;\n\n \/\/ Loop to fill bitmap buffer:\n while (tile.valid())\n {\n ossimIpt pt (tile->getOrigin());\n ossimIpt lastPt (pt.x + tile->getWidth() - 1, pt.y + tile->getHeight() - 1);\n\n \/\/ Nested loops over all pixels in input tile:\n for (; pt.y <= lastPt.y; ++pt.y)\n {\n offset = tile->getOrigin().x\/pixelsPerWord + pt.y*potraceBitmap->dy;\n for (pt.x = tile->getOrigin().x; pt.x <= lastPt.x; )\n {\n \/\/ Loop to pack a word buffer with pixel on (non-null) or off bit in proper positions:\n unsigned long wordBuf = 0;\n for (int bitpos=pixelsPerWord-1; bitpos>=0; --bitpos)\n {\n unsigned long pixel = (tile->getPix(pt) != null_pix) ? 1 : 0;\n wordBuf |= pixel << bitpos;\n ++pt.x;\n if (pt.x > lastPt.x)\n break;\n }\n potraceBitmap->map[offset++] = wordBuf;\n }\n }\n\n tile = sequencer->getNextTile();\n }\n\n return potraceBitmap;\n}\n\nbool ossimPotraceUtil::writeGeoJSON(potrace_path_t* vectorList)\n{\n FILE* outFile = fopen(m_outputVectorFname.chars(), \"w\");\n if (!outFile)\n {\n cout <<\"ossimPotraceUtil:\"<<__LINE__<<\" Could not open output file <\"< for writing.\"<"} {"text":"\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * Licensed under the MIT license (see LICENSE).\n *\/\n#include \n#include \n#include \"barchart.h\"\n#include \"domain.h\"\n\n\/**\n * todo:\n * - stacked\n * - labels inside\/outside\n * - calculate domain\n *\/\nnamespace fnordmetric {\n\nBarChart::BarChart() :\n orientation_(O_HORIZONTAL),\n stacked_(false) {}\n\nvoid BarChart::draw(ChartRenderTarget* target) {\n prepareData();\n\n \/* draw the bars *\/\n switch (orientation_) {\n case O_VERTICAL:\n drawVerticalBars(target);\n break;\n case O_HORIZONTAL:\n drawHorizontalBars(target);\n break;\n }\n\n target->finishChart();\n}\n\nvoid BarChart::prepareData() {\n \/* setup our value domain *\/\n y_domain = Domain(0, 40, false);\n\n for (const auto& series : getSeries()) {\n \/\/ FIXPAUL this could be O(N) but is O(N*2)\n for (const auto& datum : series->getData()) {\n const auto& x_val = datum[0];\n const auto& y_val = datum[1];\n\n BarData* bar_data = nullptr;\n for (auto& candidate : data_) {\n if (candidate.x == x_val) {\n bar_data = &candidate;\n }\n }\n\n if (bar_data == nullptr) {\n data_.emplace_back();\n bar_data = &data_.back();\n bar_data->x = x_val;\n }\n\n bar_data->ys.push_back(scaleValue(&y_val, &y_domain));\n }\n }\n}\n\nstd::pair BarChart::scaleValue(\n const query::SValue* value,\n const Domain* domain) const {\n switch (value->getType()) {\n case query::SValue::T_INTEGER:\n return std::pair(\n domain->scale(0.0f),\n domain->scale(value->getInteger()));\n case query::SValue::T_FLOAT:\n return std::pair(\n domain->scale(0.0f),\n domain->scale(value->getFloat()));\n default:\n assert(0); \/\/ FIXPAUL\n }\n}\n\nvoid BarChart::drawVerticalBars(ChartRenderTarget* target) {\n target->beginChart(width_, height_, \"chart bar vertical\");\n Drawable::draw(target);\n\n \/* calculate bar width and padding *\/\n auto bar_width = (inner_width_ \/ data_.size()) * (1.0f - kBarPadding);\n auto bar_padding = (inner_width_ \/ data_.size()) * (kBarPadding * 0.5f);\n bar_width -= bar_padding \/ data_.size() * 2;\n\n \/* draw the bars *\/\n std::vector x_ticks = {0.0f};\n std::vector> x_labels;\n auto draw_x = padding_left_ + bar_padding;\n auto draw_width = bar_width;\n for (const auto& bar : data_) {\n draw_x += bar_padding;\n\n \/* single series *\/\n if (getSeries().size() == 1) {\n auto& y_val = bar.ys[0];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_);\n auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_;\n target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(0));\n }\n\n \/* multi series stacked *\/\n else if (stacked_) {\n }\n\n \/* multi series unstacked *\/\n else {\n auto num_series = getSeries().size();\n auto draw_x_multi = draw_x;\n auto draw_width_multi = draw_width \/ num_series;\n for (int i = 0; i < bar.ys.size(); i++) {\n auto& y_val = bar.ys[i];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_);\n auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_;\n target->drawRect(\n draw_x_multi,\n draw_y,\n draw_width_multi * (1.0f - kBarPadding * 0.5f),\n draw_height,\n colorName(i));\n draw_x_multi += (draw_width_multi * (1.0f + kBarPadding * 0.5f));\n }\n }\n\n x_labels.push_back(std::make_pair((\n draw_x - padding_left_ + bar_width * 0.5f) \/ inner_width_,\n format::svalueToHuman(bar.x)));\n draw_x += bar_width + bar_padding;\n x_ticks.push_back((draw_x - padding_left_) \/ inner_width_);\n }\n x_ticks.back() = 1.0f;\n\n if (show_axis_[LEFT]) {\n drawLeftAxis(target, &y_domain);\n }\n\n if (show_axis_[RIGHT]) {\n drawRightAxis(target, &y_domain);\n }\n\n if (show_axis_[BOTTOM]) {\n drawBottomAxis(target, x_ticks, x_labels);\n }\n\n if (show_axis_[TOP]) {\n drawTopAxis(target, &y_domain);\n }\n}\n\nvoid BarChart::drawHorizontalBars(ChartRenderTarget* target) {\n target->beginChart(width_, height_, \"chart bar horizontal\");\n Drawable::draw(target);\n\n \/* calculate bar width and padding *\/\n auto bar_height = (inner_height_ \/ data_.size()) * (1.0f - kBarPadding);\n auto bar_padding = (inner_height_ \/ data_.size()) * (kBarPadding * 0.5f);\n bar_height -= bar_padding \/ data_.size() * 2;\n\n \/* draw the bars *\/\n std::vector y_ticks = {0.0f};\n std::vector> y_labels;\n auto draw_y = padding_top_ + bar_padding;\n auto draw_height = bar_height;\n for (const auto& bar : data_) {\n draw_y += bar_padding;\n\n \/* single series *\/\n if (getSeries().size() == 1) {\n auto& y_val = bar.ys[0];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_x = padding_left_ + y_min * inner_width_;\n auto draw_width = (y_max - y_min) * inner_width_;\n target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(0));\n }\n\n \/* multi series stacked *\/\n else if (stacked_) {\n }\n\n \/* multi series unstacked *\/\n else {\n auto num_series = getSeries().size();\n auto draw_y_multi = draw_y;\n auto draw_height_multi = draw_height \/ num_series;\n for (int i = 0; i < bar.ys.size(); i++) {\n auto& y_val = bar.ys[i];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_x = padding_left_ + y_min * inner_width_;\n auto draw_width = (y_max - y_min) * inner_width_;\n target->drawRect(\n draw_x,\n draw_y_multi,\n draw_width,\n draw_height_multi * (1.0f - kBarPadding * 0.5f),\n colorName(i));\n draw_y_multi += (draw_height_multi * (1.0f + kBarPadding * 0.5f));\n }\n }\n\n y_labels.push_back(std::make_pair((\n draw_y - padding_top_ + bar_height * 0.5f) \/ inner_height_,\n format::svalueToHuman(bar.x)));\n draw_y += bar_height + bar_padding;\n y_ticks.push_back((draw_y - padding_top_) \/ inner_height_);\n }\n y_ticks.back() = 1.0f;\n\n if (show_axis_[LEFT]) {\n drawLeftAxis(target, y_ticks, y_labels);\n }\n\n if (show_axis_[RIGHT]) {\n drawRightAxis(target, y_ticks, y_labels);\n }\n\n if (show_axis_[BOTTOM]) {\n drawBottomAxis(target, &y_domain);\n }\n\n if (show_axis_[TOP]) {\n drawTopAxis(target, &y_domain);\n }\n}\n\n}\nstacked bar charts :)\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * Licensed under the MIT license (see LICENSE).\n *\/\n#include \n#include \n#include \"barchart.h\"\n#include \"domain.h\"\n\n\/**\n * todo:\n * - labels inside\/outside\n * - calculate domain\n *\/\nnamespace fnordmetric {\n\nBarChart::BarChart() :\n orientation_(O_VERTICAL),\n stacked_(false) {}\n\nvoid BarChart::draw(ChartRenderTarget* target) {\n prepareData();\n\n \/* draw the bars *\/\n switch (orientation_) {\n case O_VERTICAL:\n drawVerticalBars(target);\n break;\n case O_HORIZONTAL:\n drawHorizontalBars(target);\n break;\n }\n\n target->finishChart();\n}\n\nvoid BarChart::prepareData() {\n \/* setup our value domain *\/\n y_domain = Domain(0, 40, false);\n\n for (const auto& series : getSeries()) {\n \/\/ FIXPAUL this could be O(N) but is O(N*2)\n for (const auto& datum : series->getData()) {\n const auto& x_val = datum[0];\n const auto& y_val = datum[1];\n\n BarData* bar_data = nullptr;\n for (auto& candidate : data_) {\n if (candidate.x == x_val) {\n bar_data = &candidate;\n }\n }\n\n if (bar_data == nullptr) {\n data_.emplace_back();\n bar_data = &data_.back();\n bar_data->x = x_val;\n }\n\n bar_data->ys.push_back(scaleValue(&y_val, &y_domain));\n }\n }\n}\n\nstd::pair BarChart::scaleValue(\n const query::SValue* value,\n const Domain* domain) const {\n switch (value->getType()) {\n case query::SValue::T_INTEGER:\n return std::pair(\n domain->scale(0.0f),\n domain->scale(value->getInteger()));\n case query::SValue::T_FLOAT:\n return std::pair(\n domain->scale(0.0f),\n domain->scale(value->getFloat()));\n default:\n assert(0); \/\/ FIXPAUL\n }\n}\n\nvoid BarChart::drawVerticalBars(ChartRenderTarget* target) {\n target->beginChart(width_, height_, \"chart bar vertical\");\n Drawable::draw(target);\n\n \/* calculate bar width and padding *\/\n auto bar_width = (inner_width_ \/ data_.size()) * (1.0f - kBarPadding);\n auto bar_padding = (inner_width_ \/ data_.size()) * (kBarPadding * 0.5f);\n bar_width -= bar_padding \/ data_.size() * 2;\n\n \/* draw the bars *\/\n std::vector x_ticks = {0.0f};\n std::vector> x_labels;\n auto draw_x = padding_left_ + bar_padding;\n auto draw_width = bar_width;\n for (const auto& bar : data_) {\n draw_x += bar_padding;\n\n \/* single series *\/\n if (getSeries().size() == 1) {\n auto& y_val = bar.ys[0];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_);\n auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_;\n target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(0));\n }\n\n \/* multi series stacked *\/\n else if (stacked_) {\n double y_min = 0.0f;\n double y_max = 0.0f;\n for (int i = 0; i < bar.ys.size(); i++) {\n auto& y_val = bar.ys[i];\n y_max += y_val.second - y_val.first;\n auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_);\n auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_;\n target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(i));\n y_min += y_val.second - y_val.first;\n }\n }\n\n \/* multi series unstacked *\/\n else {\n auto num_series = getSeries().size();\n auto draw_x_multi = draw_x;\n auto draw_width_multi = draw_width \/ num_series;\n for (int i = 0; i < bar.ys.size(); i++) {\n auto& y_val = bar.ys[i];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_);\n auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_;\n target->drawRect(\n draw_x_multi,\n draw_y,\n draw_width_multi * (1.0f - kBarPadding * 0.5f),\n draw_height,\n colorName(i));\n draw_x_multi += (draw_width_multi * (1.0f + kBarPadding * 0.5f));\n }\n }\n\n x_labels.push_back(std::make_pair((\n draw_x - padding_left_ + bar_width * 0.5f) \/ inner_width_,\n format::svalueToHuman(bar.x)));\n draw_x += bar_width + bar_padding;\n x_ticks.push_back((draw_x - padding_left_) \/ inner_width_);\n }\n x_ticks.back() = 1.0f;\n\n if (show_axis_[LEFT]) {\n drawLeftAxis(target, &y_domain);\n }\n\n if (show_axis_[RIGHT]) {\n drawRightAxis(target, &y_domain);\n }\n\n if (show_axis_[BOTTOM]) {\n drawBottomAxis(target, x_ticks, x_labels);\n }\n\n if (show_axis_[TOP]) {\n drawTopAxis(target, &y_domain);\n }\n}\n\nvoid BarChart::drawHorizontalBars(ChartRenderTarget* target) {\n target->beginChart(width_, height_, \"chart bar horizontal\");\n Drawable::draw(target);\n\n \/* calculate bar width and padding *\/\n auto bar_height = (inner_height_ \/ data_.size()) * (1.0f - kBarPadding);\n auto bar_padding = (inner_height_ \/ data_.size()) * (kBarPadding * 0.5f);\n bar_height -= bar_padding \/ data_.size() * 2;\n\n \/* draw the bars *\/\n std::vector y_ticks = {0.0f};\n std::vector> y_labels;\n auto draw_y = padding_top_ + bar_padding;\n auto draw_height = bar_height;\n for (const auto& bar : data_) {\n draw_y += bar_padding;\n\n \/* single series *\/\n if (getSeries().size() == 1) {\n auto& y_val = bar.ys[0];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_x = padding_left_ + y_min * inner_width_;\n auto draw_width = (y_max - y_min) * inner_width_;\n target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(0));\n }\n\n \/* multi series stacked *\/\n else if (stacked_) {\n double y_min = 0.0f;\n double y_max = 0.0f;\n for (int i = 0; i < bar.ys.size(); i++) {\n auto& y_val = bar.ys[i];\n y_max += y_val.second - y_val.first;\n auto draw_x = padding_left_ + y_min * inner_width_;\n auto draw_width = (y_max - y_min) * inner_width_;\n target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(i));\n y_min += y_val.second - y_val.first;\n }\n }\n\n \/* multi series unstacked *\/\n else {\n auto num_series = getSeries().size();\n auto draw_y_multi = draw_y;\n auto draw_height_multi = draw_height \/ num_series;\n for (int i = 0; i < bar.ys.size(); i++) {\n auto& y_val = bar.ys[i];\n auto y_min = y_val.first;\n auto y_max = y_val.second;\n auto draw_x = padding_left_ + y_min * inner_width_;\n auto draw_width = (y_max - y_min) * inner_width_;\n target->drawRect(\n draw_x,\n draw_y_multi,\n draw_width,\n draw_height_multi * (1.0f - kBarPadding * 0.5f),\n colorName(i));\n draw_y_multi += (draw_height_multi * (1.0f + kBarPadding * 0.5f));\n }\n }\n\n y_labels.push_back(std::make_pair((\n draw_y - padding_top_ + bar_height * 0.5f) \/ inner_height_,\n format::svalueToHuman(bar.x)));\n draw_y += bar_height + bar_padding;\n y_ticks.push_back((draw_y - padding_top_) \/ inner_height_);\n }\n y_ticks.back() = 1.0f;\n\n if (show_axis_[LEFT]) {\n drawLeftAxis(target, y_ticks, y_labels);\n }\n\n if (show_axis_[RIGHT]) {\n drawRightAxis(target, y_ticks, y_labels);\n }\n\n if (show_axis_[BOTTOM]) {\n drawBottomAxis(target, &y_domain);\n }\n\n if (show_axis_[TOP]) {\n drawTopAxis(target, &y_domain);\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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\/**\n * @file\n * @brief Predicate --- Standard ValueList Implementation\n *\n * @author Christopher Alfeld \n *\/\n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\nnamespace {\n\nstatic const node_p c_false(new Null());\n\n}\n\nstring SetName::name() const\n{\n return \"setName\";\n}\n\nValue SetName::value_calculate(Value v, EvalContext context)\n{\n Value name = literal_value(children().front());\n ConstByteString name_bs = name.value_as_byte_string();\n\n return v.dup(v.memory_pool(), name_bs.const_data(), name_bs.length());\n}\n\nvoid SetName::calculate(EvalContext context)\n{\n map_calculate(children().back(), context);\n}\n\nbool SetName::validate(NodeReporter reporter) const\n{\n return\n Validate::n_children(reporter, 2) &&\n Validate::nth_child_is_string(reporter, 0) &&\n Validate::nth_child_is_not_null(reporter, 1)\n ;\n}\n\nstring Cat::name() const\n{\n return \"cat\";\n}\n\nbool Cat::transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n NodeReporter reporter\n)\n{\n node_p me = shared_from_this();\n bool result = false;\n\n \/\/ Remove null children.\n {\n node_list_t to_remove;\n BOOST_FOREACH(const node_p& child, children()) {\n if (child->is_literal() && ! literal_value(child)) {\n to_remove.push_back(child);\n }\n }\n BOOST_FOREACH(const node_p& child, to_remove) {\n merge_graph.remove(me, child);\n }\n\n result = true;\n }\n\n \/\/ Become child if only one child.\n if (children().size() == 1) {\n node_p replacement = children().front();\n merge_graph.replace(me, replacement);\n return true;\n }\n\n \/\/ Become false if no children.\n if (children().size() == 0) {\n node_p replacement = c_false;\n merge_graph.replace(me, replacement);\n return true;\n }\n\n return result;\n}\n\nvoid Cat::calculate(EvalContext context)\n{\n \/\/ @todo Change to be opportunistic. I.e., add values of first\n \/\/ child immediately. Once that child is finished, do same for next,\n \/\/ and so on.\n\n \/\/ Do nothing if any unfinished children.\n BOOST_FOREACH(const node_p& child, children()) {\n child->eval(context);\n if (! child->is_finished()) {\n return;\n }\n }\n\n \/\/ All children finished, concatenate values.\n BOOST_FOREACH(const node_p& child, children()) {\n BOOST_FOREACH(Value v, child->values()) {\n add_value(v);\n }\n }\n finish();\n}\n\nstring First::name() const\n{\n return \"first\";\n}\n\nvoid First::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n ValueList values = child->eval(context);\n if (! values.empty()) {\n add_value(values.front());\n finish();\n }\n else if (child->is_finished()) {\n finish();\n }\n}\n\nbool First::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nstruct Rest::data_t\n{\n boost::thread_specific_ptr location;\n};\n\nRest::Rest() :\n m_data(new data_t())\n{\n \/\/ nop\n}\n\nstring Rest::name() const\n{\n return \"rest\";\n}\n\nvoid Rest::reset()\n{\n if (m_data->location.get()) {\n *(m_data->location) = ValueList::const_iterator();\n }\n else {\n m_data->location.reset(new ValueList::const_iterator());\n }\n}\n\nvoid Rest::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n ValueList values = child->eval(context);\n ValueList::const_iterator& location = *(m_data->location.get());\n\n \/\/ Special case if no values yet.\n if (values.empty()) {\n if (child->is_finished()) {\n finish();\n }\n return;\n }\n\n if (location == ValueList::const_iterator()) {\n location = values.begin();\n }\n\n \/\/ At this point, location refers to element before next one\n \/\/ to push.\n ValueList::const_iterator next_location = location;\n ++next_location;\n const ValueList::const_iterator end = values.end();\n while (next_location != end) {\n add_value(*next_location);\n location = next_location;\n ++next_location;\n }\n\n if (child->is_finished()) {\n finish();\n }\n}\n\nbool Rest::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nstring Nth::name() const\n{\n return \"nth\";\n}\n\nvoid Nth::calculate(EvalContext context)\n{\n int64_t n = literal_value(children().front()).value_as_number();\n\n if (n <= 0) {\n finish();\n return;\n }\n\n const node_p& child = children().back();\n ValueList values = child->eval(context);\n\n if (values.size() < size_t(n)) {\n if (child->is_finished()) {\n finish();\n }\n return;\n }\n\n ValueList::const_iterator i = values.begin();\n advance(i, n - 1);\n\n add_value(*i);\n finish();\n}\n\nbool Nth::validate(NodeReporter reporter) const\n{\n return\n Validate::n_children(reporter, 2) &&\n Validate::nth_child_is_integer_above(reporter, 0, -1)\n ;\n}\n\nstring Scatter::name() const\n{\n return \"scatter\";\n}\n\nvoid Scatter::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n child->eval(context);\n\n if (! child->is_finished()) {\n return;\n }\n\n Value value = simple_value(child);\n if (value) {\n BOOST_FOREACH(Value v, value.value_as_list()) {\n add_value(v);\n }\n finish();\n }\n}\n\nbool Scatter::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nstring Gather::name() const\n{\n return \"gather\";\n}\n\nvoid Gather::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n child->eval(context);\n\n if (! child->is_finished()) {\n return;\n }\n\n List values =\n List::create(context.memory_pool());\n\n copy(\n child->values().begin(), child->values().end(),\n back_inserter(values)\n );\n\n add_value(Field::create_no_copy_list(\n context.memory_pool(),\n \"\", 0,\n values\n ));\n\n finish();\n}\n\nbool Gather::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nvoid load_valuelist(CallFactory& to)\n{\n to\n .add()\n .add()\n .add()\n .add()\n .add()\n .add()\n .add()\n ;\n}\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\npredicate\/standard_valuelist: Fix bug in cat transformations.\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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\/**\n * @file\n * @brief Predicate --- Standard ValueList Implementation\n *\n * @author Christopher Alfeld \n *\/\n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\nnamespace {\n\nstatic const node_p c_false(new Null());\n\n}\n\nstring SetName::name() const\n{\n return \"setName\";\n}\n\nValue SetName::value_calculate(Value v, EvalContext context)\n{\n Value name = literal_value(children().front());\n ConstByteString name_bs = name.value_as_byte_string();\n\n return v.dup(v.memory_pool(), name_bs.const_data(), name_bs.length());\n}\n\nvoid SetName::calculate(EvalContext context)\n{\n map_calculate(children().back(), context);\n}\n\nbool SetName::validate(NodeReporter reporter) const\n{\n return\n Validate::n_children(reporter, 2) &&\n Validate::nth_child_is_string(reporter, 0) &&\n Validate::nth_child_is_not_null(reporter, 1)\n ;\n}\n\nstring Cat::name() const\n{\n return \"cat\";\n}\n\nbool Cat::transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n NodeReporter reporter\n)\n{\n node_p me = shared_from_this();\n bool result = false;\n\n \/\/ Remove null children.\n {\n node_list_t to_remove;\n BOOST_FOREACH(const node_p& child, children()) {\n if (child->is_literal() && ! literal_value(child)) {\n to_remove.push_back(child);\n }\n }\n BOOST_FOREACH(const node_p& child, to_remove) {\n merge_graph.remove(me, child);\n }\n\n if (! to_remove.empty()) {\n result = true;\n }\n }\n\n \/\/ Become child if only one child.\n if (children().size() == 1) {\n node_p replacement = children().front();\n merge_graph.replace(me, replacement);\n return true;\n }\n\n \/\/ Become false if no children.\n if (children().size() == 0) {\n node_p replacement = c_false;\n merge_graph.replace(me, replacement);\n return true;\n }\n\n return result;\n}\n\nvoid Cat::calculate(EvalContext context)\n{\n \/\/ @todo Change to be opportunistic. I.e., add values of first\n \/\/ child immediately. Once that child is finished, do same for next,\n \/\/ and so on.\n\n \/\/ Do nothing if any unfinished children.\n BOOST_FOREACH(const node_p& child, children()) {\n child->eval(context);\n if (! child->is_finished()) {\n return;\n }\n }\n\n \/\/ All children finished, concatenate values.\n BOOST_FOREACH(const node_p& child, children()) {\n BOOST_FOREACH(Value v, child->values()) {\n add_value(v);\n }\n }\n finish();\n}\n\nstring First::name() const\n{\n return \"first\";\n}\n\nvoid First::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n ValueList values = child->eval(context);\n if (! values.empty()) {\n add_value(values.front());\n finish();\n }\n else if (child->is_finished()) {\n finish();\n }\n}\n\nbool First::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nstruct Rest::data_t\n{\n boost::thread_specific_ptr location;\n};\n\nRest::Rest() :\n m_data(new data_t())\n{\n \/\/ nop\n}\n\nstring Rest::name() const\n{\n return \"rest\";\n}\n\nvoid Rest::reset()\n{\n if (m_data->location.get()) {\n *(m_data->location) = ValueList::const_iterator();\n }\n else {\n m_data->location.reset(new ValueList::const_iterator());\n }\n}\n\nvoid Rest::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n ValueList values = child->eval(context);\n ValueList::const_iterator& location = *(m_data->location.get());\n\n \/\/ Special case if no values yet.\n if (values.empty()) {\n if (child->is_finished()) {\n finish();\n }\n return;\n }\n\n if (location == ValueList::const_iterator()) {\n location = values.begin();\n }\n\n \/\/ At this point, location refers to element before next one\n \/\/ to push.\n ValueList::const_iterator next_location = location;\n ++next_location;\n const ValueList::const_iterator end = values.end();\n while (next_location != end) {\n add_value(*next_location);\n location = next_location;\n ++next_location;\n }\n\n if (child->is_finished()) {\n finish();\n }\n}\n\nbool Rest::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nstring Nth::name() const\n{\n return \"nth\";\n}\n\nvoid Nth::calculate(EvalContext context)\n{\n int64_t n = literal_value(children().front()).value_as_number();\n\n if (n <= 0) {\n finish();\n return;\n }\n\n const node_p& child = children().back();\n ValueList values = child->eval(context);\n\n if (values.size() < size_t(n)) {\n if (child->is_finished()) {\n finish();\n }\n return;\n }\n\n ValueList::const_iterator i = values.begin();\n advance(i, n - 1);\n\n add_value(*i);\n finish();\n}\n\nbool Nth::validate(NodeReporter reporter) const\n{\n return\n Validate::n_children(reporter, 2) &&\n Validate::nth_child_is_integer_above(reporter, 0, -1)\n ;\n}\n\nstring Scatter::name() const\n{\n return \"scatter\";\n}\n\nvoid Scatter::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n child->eval(context);\n\n if (! child->is_finished()) {\n return;\n }\n\n Value value = simple_value(child);\n if (value) {\n BOOST_FOREACH(Value v, value.value_as_list()) {\n add_value(v);\n }\n finish();\n }\n}\n\nbool Scatter::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nstring Gather::name() const\n{\n return \"gather\";\n}\n\nvoid Gather::calculate(EvalContext context)\n{\n const node_p& child = children().front();\n child->eval(context);\n\n if (! child->is_finished()) {\n return;\n }\n\n List values =\n List::create(context.memory_pool());\n\n copy(\n child->values().begin(), child->values().end(),\n back_inserter(values)\n );\n\n add_value(Field::create_no_copy_list(\n context.memory_pool(),\n \"\", 0,\n values\n ));\n\n finish();\n}\n\nbool Gather::validate(NodeReporter reporter) const\n{\n return Validate::n_children(reporter, 1);\n}\n\nvoid load_valuelist(CallFactory& to)\n{\n to\n .add()\n .add()\n .add()\n .add()\n .add()\n .add()\n .add()\n ;\n}\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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\/**\n * @file\n * @brief Predicate --- Standard ValueList.\n *\n * @author Christopher Alfeld \n *\/\n\n#ifndef __PREDICATE__STANDARD_VALUELIST__\n#define __PREDICATE__STANDARD_VALUELIST__\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\n\/**\n * Construct a named value from a name (string) and value.\n **\/\nclass SetName :\n public MaplikeCall,\n public Validate::Call,\n public Validate::NChildren<2,\n Validate::NthChildIsString<0,\n Validate::NthChildIsNotNull<1\n > > >\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual Value value_calculate(Value v, EvalContext context);\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Concatenate values of children.\n **\/\nclass Cat :\n public Call\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * First value.\n **\/\nclass First :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * All but first value.\n **\/\nclass Rest :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! Constructor.\n Rest();\n\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void reset();\n virtual void calculate(EvalContext context);\n\nprivate:\n \/\/! Hidden complex implementation details.\n struct data_t;\n\n \/\/! Hidden complex implementation details.\n boost::scoped_ptr m_data;\n};\n\n\/**\n * Nth value.\n **\/\nclass Nth :\n public Validate::Call,\n public Validate::NChildren<2,\n Validate::NthChildIsInteger<0\n > >\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Expand simple list value.\n **\/\nclass Scatter :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Gathers values into simple list value.\n **\/\nclass Gather :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Load all standard valielist calls into a CallFactory.\n *\n * @param [in] to CallFactory to load into.\n **\/\nvoid load_valuelist(CallFactory& to);\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n\n#endif\npredicate\/standard_valuelist: Cleanup.\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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\/**\n * @file\n * @brief Predicate --- Standard ValueList.\n *\n * @author Christopher Alfeld \n *\/\n\n#ifndef __PREDICATE__STANDARD_VALUELIST__\n#define __PREDICATE__STANDARD_VALUELIST__\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\n\/**\n * Construct a named value from a name (string) and value.\n **\/\nclass SetName :\n public MaplikeCall,\n public Validate::Call,\n public Validate::NChildren<2,\n Validate::NthChildIsString<0,\n Validate::NthChildIsNotNull<1\n > > >\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual Value value_calculate(Value v, EvalContext context);\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Concatenate values of children.\n **\/\nclass Cat :\n public Call\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * First value.\n **\/\nclass First :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * All but first value.\n **\/\nclass Rest :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! Constructor.\n Rest();\n\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void reset();\n virtual void calculate(EvalContext context);\n\nprivate:\n \/\/! Hidden complex implementation details.\n struct data_t;\n\n \/\/! Hidden complex implementation details.\n boost::scoped_ptr m_data;\n};\n\n\/**\n * Nth value.\n **\/\nclass Nth :\n public Validate::Call,\n public Validate::NChildren<2,\n Validate::NthChildIsInteger<0\n > >\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Expand simple list value.\n **\/\nclass Scatter :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Gathers values into simple list value.\n **\/\nclass Gather :\n public Validate::Call,\n public Validate::NChildren<1>\n{\npublic:\n \/\/! See Call:name()\n virtual std::string name() const;\n\nprotected:\n virtual void calculate(EvalContext context);\n};\n\n\/**\n * Load all standard valuelists calls into a CallFactory.\n *\n * @param [in] to CallFactory to load into.\n **\/\nvoid load_valuelist(CallFactory& to);\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: EventThread.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: fs $ $Date: 2001-08-22 13:57:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FRM_EVENT_THREAD_HXX_\n#define _FRM_EVENT_THREAD_HXX_\n\n#include \n#include \n#include \n#include \n#include \n\n\n#ifndef _OSL_CONDITN_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_COMPONENT_HXX_\n#include \n#endif\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_GUARDING_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\nusing namespace comphelper;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n\/\/ ***************************************************************************************************\n\/\/ ***************************************************************************************************\n\ntypedef ::vos::OThread OComponentEventThread_TBASE;\nclass OComponentEventThread\n :public OComponentEventThread_TBASE\n ,public ::com::sun::star::lang::XEventListener\n ,public ::cppu::OWeakObject\n{\n DECLARE_STL_VECTOR(::com::sun::star::lang::EventObject*, ThreadEvents);\n DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAdapter> , ThreadObjects);\n DECLARE_STL_VECTOR(sal_Bool, ThreadBools);\n\n OCountedMutex m_aMutex;\n ::osl::Condition m_aCond; \/\/ Queue gefuellt?\n ThreadEvents m_aEvents; \/\/ Event-Queue\n ThreadObjects m_aControls; \/\/ Control fuer Submit\n ThreadBools m_aFlags; \/\/ Flags fuer Submit\/Reset\n\n ::cppu::OComponentHelper* m_pCompImpl; \/\/ Implementierung des Controls\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> m_xComp; \/\/ ::com::sun::star::lang::XComponent des Controls\n\nprotected:\n\n \/\/ XThread\n virtual void SAL_CALL run();\n\n virtual void SAL_CALL kill();\n virtual void SAL_CALL onTerminated();\n\n \/\/ Die folgende Methode wird gerufen um das Event unter Beruecksichtigung\n \/\/ seines Typs zu duplizieren.\n virtual ::com::sun::star::lang::EventObject* cloneEvent(const ::com::sun::star::lang::EventObject* _pEvt) const = 0;\n\n \/\/ Ein Event bearbeiten. Der Mutex ist dabei nicht gelockt, pCompImpl\n \/\/ bleibt aber in jedem Fall gueltig. Bei pEvt kann es sich auch um\n \/\/ einen abgeleiteten Typ handeln, naemlich den, den cloneEvent\n \/\/ zurueckgibt. rControl ist nur gesetzt, wenn beim addEvent ein\n \/\/ Control uebergeben wurde. Da das Control nur als WeakRef gehalten\n \/\/ wird kann es auch zwischenzeitlich verschwinden.\n virtual void processEvent( ::cppu::OComponentHelper* _pCompImpl,\n const ::com::sun::star::lang::EventObject* _pEvt,\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl>& _rControl,\n sal_Bool _bFlag) = 0;\n\npublic:\n\n \/\/ UNO Anbindung\n DECLARE_UNO3_DEFAULTS(OComponentEventThread, OWeakObject);\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException);\n\n OComponentEventThread(::cppu::OComponentHelper* pCompImpl);\n virtual ~OComponentEventThread();\n\n void addEvent( const ::com::sun::star::lang::EventObject* _pEvt, sal_Bool bFlag = sal_False );\n void addEvent( const ::com::sun::star::lang::EventObject* _pEvt, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl>& rControl,\n sal_Bool bFlag = sal_False );\n\n \/\/ ::com::sun::star::lang::XEventListener\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource );\n\n\/* resolve ambiguity : both OWeakObject and OObject have these memory operators *\/\n void * SAL_CALL operator new( size_t size ) throw() { return OThread::operator new(size); }\n void SAL_CALL operator delete( void * p ) throw() { OThread::operator delete(p); }\n\nprivate:\n void implStarted( );\n void implTerminated( );\n};\n\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n#endif \/\/ _FRM_EVENT_THREAD_HXX_\n\n#92075# exception specification\/*************************************************************************\n *\n * $RCSfile: EventThread.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2001-09-12 10:25:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FRM_EVENT_THREAD_HXX_\n#define _FRM_EVENT_THREAD_HXX_\n\n#include \n#include \n#include \n#include \n#include \n\n\n#ifndef _OSL_CONDITN_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_COMPONENT_HXX_\n#include \n#endif\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_GUARDING_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\nusing namespace comphelper;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n\/\/ ***************************************************************************************************\n\/\/ ***************************************************************************************************\n\ntypedef ::vos::OThread OComponentEventThread_TBASE;\nclass OComponentEventThread\n :public OComponentEventThread_TBASE\n ,public ::com::sun::star::lang::XEventListener\n ,public ::cppu::OWeakObject\n{\n DECLARE_STL_VECTOR(::com::sun::star::lang::EventObject*, ThreadEvents);\n DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAdapter> , ThreadObjects);\n DECLARE_STL_VECTOR(sal_Bool, ThreadBools);\n\n OCountedMutex m_aMutex;\n ::osl::Condition m_aCond; \/\/ Queue gefuellt?\n ThreadEvents m_aEvents; \/\/ Event-Queue\n ThreadObjects m_aControls; \/\/ Control fuer Submit\n ThreadBools m_aFlags; \/\/ Flags fuer Submit\/Reset\n\n ::cppu::OComponentHelper* m_pCompImpl; \/\/ Implementierung des Controls\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> m_xComp; \/\/ ::com::sun::star::lang::XComponent des Controls\n\nprotected:\n\n \/\/ XThread\n virtual void SAL_CALL run();\n\n virtual void SAL_CALL kill();\n virtual void SAL_CALL onTerminated();\n\n \/\/ Die folgende Methode wird gerufen um das Event unter Beruecksichtigung\n \/\/ seines Typs zu duplizieren.\n virtual ::com::sun::star::lang::EventObject* cloneEvent(const ::com::sun::star::lang::EventObject* _pEvt) const = 0;\n\n \/\/ Ein Event bearbeiten. Der Mutex ist dabei nicht gelockt, pCompImpl\n \/\/ bleibt aber in jedem Fall gueltig. Bei pEvt kann es sich auch um\n \/\/ einen abgeleiteten Typ handeln, naemlich den, den cloneEvent\n \/\/ zurueckgibt. rControl ist nur gesetzt, wenn beim addEvent ein\n \/\/ Control uebergeben wurde. Da das Control nur als WeakRef gehalten\n \/\/ wird kann es auch zwischenzeitlich verschwinden.\n virtual void processEvent( ::cppu::OComponentHelper* _pCompImpl,\n const ::com::sun::star::lang::EventObject* _pEvt,\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl>& _rControl,\n sal_Bool _bFlag) = 0;\n\npublic:\n\n \/\/ UNO Anbindung\n DECLARE_UNO3_DEFAULTS(OComponentEventThread, OWeakObject);\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException);\n\n OComponentEventThread(::cppu::OComponentHelper* pCompImpl);\n virtual ~OComponentEventThread();\n\n void addEvent( const ::com::sun::star::lang::EventObject* _pEvt, sal_Bool bFlag = sal_False );\n void addEvent( const ::com::sun::star::lang::EventObject* _pEvt, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl>& rControl,\n sal_Bool bFlag = sal_False );\n\n \/\/ ::com::sun::star::lang::XEventListener\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException);\n\n\/* resolve ambiguity : both OWeakObject and OObject have these memory operators *\/\n void * SAL_CALL operator new( size_t size ) throw() { return OThread::operator new(size); }\n void SAL_CALL operator delete( void * p ) throw() { OThread::operator delete(p); }\n\nprivate:\n void implStarted( );\n void implTerminated( );\n};\n\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n#endif \/\/ _FRM_EVENT_THREAD_HXX_\n\n<|endoftext|>"} {"text":"#include \"Flow.hpp\"\n#include \n#include \n\nnamespace Slic3r {\n\n\/* This constructor builds a Flow object from an extrusion width config setting\n and other context properties. *\/\nFlow\nFlow::new_from_config_width(FlowRole role, const ConfigOptionFloatOrPercent &width, float nozzle_diameter, float height, float bridge_flow_ratio) {\n \/\/ we need layer height unless it's a bridge\n if (height <= 0 && bridge_flow_ratio == 0) CONFESS(\"Invalid flow height supplied to new_from_config_width()\");\n \n float w;\n if (bridge_flow_ratio > 0) {\n \/\/ if bridge flow was requested, calculate bridge width\n height = w = Flow::_bridge_width(nozzle_diameter, bridge_flow_ratio);\n } else if (!width.percent && width.value == 0) {\n \/\/ if user left option to 0, calculate a sane default width\n w = Flow::_auto_width(role, nozzle_diameter, height);\n } else {\n \/\/ if user set a manual value, use it\n w = width.get_abs_value(height);\n }\n \n return Flow(w, height, nozzle_diameter, bridge_flow_ratio > 0);\n}\n\n\/* This constructor builds a Flow object from a given centerline spacing. *\/\nFlow\nFlow::new_from_spacing(float spacing, float nozzle_diameter, float height, bool bridge) {\n \/\/ we need layer height unless it's a bridge\n if (height <= 0 && !bridge) CONFESS(\"Invalid flow height supplied to new_from_spacing()\");\n\n float w = Flow::_width_from_spacing(spacing, nozzle_diameter, height, bridge);\n if (bridge) height = w;\n return Flow(w, height, nozzle_diameter, bridge);\n}\n\n\/* This method returns the centerline spacing between two adjacent extrusions \n having the same extrusion width (and other properties). *\/\nfloat\nFlow::spacing() const {\n if (this->bridge) {\n return this->width + BRIDGE_EXTRA_SPACING;\n }\n \n \/\/ rectangle with semicircles at the ends\n float min_flow_spacing = this->width - this->height * (1 - PI\/4.0);\n return this->width - OVERLAP_FACTOR * (this->width - min_flow_spacing);\n}\n\nvoid\nFlow::set_spacing(float spacing) {\n this->width = Flow::_width_from_spacing(spacing, this->nozzle_diameter, this->height, this->bridge);\n}\n\n\/* This method returns the centerline spacing between an extrusion using this\n flow and another one using another flow.\n this->spacing(other) shall return the same value as other.spacing(*this) *\/\nfloat\nFlow::spacing(const Flow &other) const {\n assert(this->height == other.height);\n assert(this->bridge == other.bridge);\n \n if (this->bridge) {\n return this->width\/2 + other.width\/2 + BRIDGE_EXTRA_SPACING;\n }\n \n return this->spacing()\/2 + other.spacing()\/2;\n}\n\n\/* This method returns extrusion volume per head move unit. *\/\ndouble\nFlow::mm3_per_mm() const {\n if (this->bridge) {\n return (this->width * this->width) * PI\/4.0;\n }\n \n \/\/ rectangle with semicircles at the ends\n return this->width * this->height + (this->height*this->height) \/ 4.0 * (PI-4.0);\n}\n\n\/* This static method returns bridge width for a given nozzle diameter. *\/\nfloat\nFlow::_bridge_width(float nozzle_diameter, float bridge_flow_ratio) {\n if (bridge_flow_ratio == 1) return nozzle_diameter; \/\/ optimization to avoid sqrt()\n return sqrt(bridge_flow_ratio * (nozzle_diameter*nozzle_diameter));\n}\n\n\/* This static method returns a sane extrusion width default. *\/\nfloat\nFlow::_auto_width(FlowRole role, float nozzle_diameter, float height) {\n \/\/ here we calculate a sane default by matching the flow speed (at the nozzle) and the feed rate\n \/\/ shape: rectangle with semicircles at the ends\n float width = ((nozzle_diameter*nozzle_diameter) * PI + (height*height) * (4.0 - PI)) \/ (4.0 * height);\n \n float min = nozzle_diameter * 1.05;\n float max = nozzle_diameter * 1.25; \/\/ cap width to 1.25x nozzle diameter\n if (role == frExternalPerimeter || role == frSupportMaterial || role == frSupportMaterialInterface) {\n min = max = nozzle_diameter*1.1;\n } else if (role != frInfill) {\n \/\/ limit width a bit for sparse infill to avoid unwanted overextrusion.\n max = nozzle_diameter * 1.4;\n }\n if (width > max) width = max;\n if (width < min) width = min;\n \n return width;\n}\n\n\/* This static method returns the extrusion width value corresponding to the supplied centerline spacing. *\/\nfloat\nFlow::_width_from_spacing(float spacing, float nozzle_diameter, float height, bool bridge) {\n if (bridge) {\n return spacing - BRIDGE_EXTRA_SPACING;\n }\n \n \/\/ rectangle with semicircles at the ends\n return spacing + OVERLAP_FACTOR * height * (1 - PI\/4.0);\n}\n\n\/\/\/ Calculate a new spacing to fill width with possibly integer number of lines,\n\/\/\/ the first and last line being centered at the interval ends.\n\/\/\/ This function possibly increases the spacing, never decreases, \n\/\/\/ and for a narrow width the increase in spacing may become severe,\n\/\/\/ therefore the adjustment is limited to 20% increase.\ntemplate \nT\nFlow::solid_spacing(const T total_width, const T spacing)\n{\n assert(total_width >= 0);\n assert(spacing > 0);\n const int number_of_intervals = floor(total_width \/ spacing);\n if (number_of_intervals == 0) return spacing;\n \n T spacing_new = (total_width \/ number_of_intervals);\n \n const double factor = (double)spacing_new \/ (double)spacing;\n assert(factor > 1. - 1e-5);\n \n \/\/ How much could the extrusion width be increased? By 20%.\n \/\/ Because of this limit, this method is not idempotent: each run\n \/\/ will increment spacing by 20%.\n const double factor_max = 1.2;\n if (factor > factor_max)\n spacing_new = floor((double)spacing * factor_max + 0.5);\n \n assert((spacing_new * number_of_intervals) <= total_width);\n \n return spacing_new;\n}\ntemplate coord_t Flow::solid_spacing(const coord_t total_width, const coord_t spacing);\ntemplate coordf_t Flow::solid_spacing(const coordf_t total_width, const coordf_t spacing);\n\n}\nCode cleanup: Ensure that a floats remain floats all the way through expressions.#include \"Flow.hpp\"\n#include \n#include \n\nnamespace Slic3r {\n\n\/* This constructor builds a Flow object from an extrusion width config setting\n and other context properties. *\/\nFlow\nFlow::new_from_config_width(FlowRole role, const ConfigOptionFloatOrPercent &width, float nozzle_diameter, float height, float bridge_flow_ratio) {\n \/\/ we need layer height unless it's a bridge\n if (height <= 0 && bridge_flow_ratio == 0) CONFESS(\"Invalid flow height supplied to new_from_config_width()\");\n \n float w;\n if (bridge_flow_ratio > 0) {\n \/\/ if bridge flow was requested, calculate bridge width\n height = w = Flow::_bridge_width(nozzle_diameter, bridge_flow_ratio);\n } else if (!width.percent && width.value == 0) {\n \/\/ if user left option to 0, calculate a sane default width\n w = Flow::_auto_width(role, nozzle_diameter, height);\n } else {\n \/\/ if user set a manual value, use it\n w = width.get_abs_value(height);\n }\n \n return Flow(w, height, nozzle_diameter, bridge_flow_ratio > 0);\n}\n\n\/* This constructor builds a Flow object from a given centerline spacing. *\/\nFlow\nFlow::new_from_spacing(float spacing, float nozzle_diameter, float height, bool bridge) {\n \/\/ we need layer height unless it's a bridge\n if (height <= 0 && !bridge) CONFESS(\"Invalid flow height supplied to new_from_spacing()\");\n\n float w = Flow::_width_from_spacing(spacing, nozzle_diameter, height, bridge);\n if (bridge) height = w;\n return Flow(w, height, nozzle_diameter, bridge);\n}\n\n\/* This method returns the centerline spacing between two adjacent extrusions \n having the same extrusion width (and other properties). *\/\nfloat\nFlow::spacing() const {\n if (this->bridge) {\n return this->width + BRIDGE_EXTRA_SPACING;\n }\n \n \/\/ rectangle with semicircles at the ends\n float min_flow_spacing = this->width - this->height * (1.0 - PI\/4.0);\n return this->width - OVERLAP_FACTOR * (this->width - min_flow_spacing);\n}\n\nvoid\nFlow::set_spacing(float spacing) {\n this->width = Flow::_width_from_spacing(spacing, this->nozzle_diameter, this->height, this->bridge);\n}\n\n\/* This method returns the centerline spacing between an extrusion using this\n flow and another one using another flow.\n this->spacing(other) shall return the same value as other.spacing(*this) *\/\nfloat\nFlow::spacing(const Flow &other) const {\n assert(this->height == other.height);\n assert(this->bridge == other.bridge);\n \n if (this->bridge) {\n return this->width\/2.0 + other.width\/2.0 + BRIDGE_EXTRA_SPACING;\n }\n \n return this->spacing()\/2.0 + other.spacing()\/2.0;\n}\n\n\/* This method returns extrusion volume per head move unit. *\/\ndouble\nFlow::mm3_per_mm() const {\n if (this->bridge) {\n return (this->width * this->width) * PI\/4.0;\n }\n \n \/\/ rectangle with semicircles at the ends\n return this->width * this->height + (this->height*this->height) \/ 4.0 * (PI-4.0);\n}\n\n\/* This static method returns bridge width for a given nozzle diameter. *\/\nfloat\nFlow::_bridge_width(float nozzle_diameter, float bridge_flow_ratio) {\n if (bridge_flow_ratio == 1) return nozzle_diameter; \/\/ optimization to avoid sqrt()\n return sqrt(bridge_flow_ratio * (nozzle_diameter*nozzle_diameter));\n}\n\n\/* This static method returns a sane extrusion width default. *\/\nfloat\nFlow::_auto_width(FlowRole role, float nozzle_diameter, float height) {\n \/\/ here we calculate a sane default by matching the flow speed (at the nozzle) and the feed rate\n \/\/ shape: rectangle with semicircles at the ends\n float width = ((nozzle_diameter*nozzle_diameter) * PI + (height*height) * (4.0 - PI)) \/ (4.0 * height);\n \n float min = nozzle_diameter * 1.05;\n float max = nozzle_diameter * 1.25; \/\/ cap width to 1.25x nozzle diameter\n if (role == frExternalPerimeter || role == frSupportMaterial || role == frSupportMaterialInterface) {\n min = max = nozzle_diameter*1.1;\n } else if (role != frInfill) {\n \/\/ limit width a bit for sparse infill to avoid unwanted overextrusion.\n max = nozzle_diameter * 1.4;\n }\n if (width > max) width = max;\n if (width < min) width = min;\n \n return width;\n}\n\n\/* This static method returns the extrusion width value corresponding to the supplied centerline spacing. *\/\nfloat\nFlow::_width_from_spacing(float spacing, float nozzle_diameter, float height, bool bridge) {\n if (bridge) {\n return spacing - BRIDGE_EXTRA_SPACING;\n }\n \n \/\/ rectangle with semicircles at the ends\n return spacing + OVERLAP_FACTOR * height * (1 - PI\/4.0);\n}\n\n\/\/\/ Calculate a new spacing to fill width with possibly integer number of lines,\n\/\/\/ the first and last line being centered at the interval ends.\n\/\/\/ This function possibly increases the spacing, never decreases, \n\/\/\/ and for a narrow width the increase in spacing may become severe,\n\/\/\/ therefore the adjustment is limited to 20% increase.\ntemplate \nT\nFlow::solid_spacing(const T total_width, const T spacing)\n{\n assert(total_width >= 0);\n assert(spacing > 0);\n const int number_of_intervals = floor(total_width \/ spacing);\n if (number_of_intervals == 0) return spacing;\n \n T spacing_new = (total_width \/ number_of_intervals);\n \n const double factor = (double)spacing_new \/ (double)spacing;\n assert(factor > 1. - 1e-5);\n \n \/\/ How much could the extrusion width be increased? By 20%.\n \/\/ Because of this limit, this method is not idempotent: each run\n \/\/ will increment spacing by 20%.\n const double factor_max = 1.2;\n if (factor > factor_max)\n spacing_new = floor((double)spacing * factor_max + 0.5);\n \n assert((spacing_new * number_of_intervals) <= total_width);\n \n return spacing_new;\n}\ntemplate coord_t Flow::solid_spacing(const coord_t total_width, const coord_t spacing);\ntemplate coordf_t Flow::solid_spacing(const coordf_t total_width, const coordf_t spacing);\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mtrace.h\"\n#include \"fstest.h\"\n#include \"libutil.h\"\n#include \"spinbarrier.hh\"\n\nextern char _end[];\n__thread sigjmp_buf pf_jmpbuf;\n__thread int pf_active;\n\nclass double_barrier {\n spin_barrier enter_;\n spin_barrier exit_;\n\npublic:\n double_barrier() : enter_(2), exit_(2) {}\n void sync() { enter(); exit(); }\n void enter() { enter_.join(); }\n void exit() { exit_.join(); }\n};\n\nstruct testproc {\n double_barrier setup;\n std::atomic setupf1;\n std::atomic setupf2;\n\n testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}\n void run() {\n setup.enter();\n setupf1();\n setupf2();\n setup.exit();\n }\n};\n\nstruct testfunc {\n double_barrier start;\n double_barrier stop;\n\n std::atomic func;\n std::atomic retval;\n\n testfunc(int (*f)(void)) : func(f) {}\n void run() {\n#ifndef XV6_USER\n errno = 0;\n#endif\n start.sync();\n retval = func();\n stop.sync();\n }\n};\n\nstatic void*\ntestfunc_thread(void* arg)\n{\n madvise(0, (size_t) _end, MADV_WILLNEED);\n testfunc* f = (testfunc*) arg;\n f->run();\n return nullptr;\n}\n\nstatic void\nrun_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)\n{\n assert(first_func == 0 || first_func == 1);\n if (do_pin)\n setaffinity(2);\n\n for (int i = 0; i < 2; i++)\n new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);\n for (int i = 0; i < 2; i++)\n new (&tf[i]) testfunc(t->func[i].call);\n\n t->setup_common();\n\n pid_t pids[2] = { 0, 0 };\n for (int p = 0; p < 2; p++) {\n int nfunc = 0;\n for (int f = 0; f < 2; f++)\n if (t->func[f].callproc == p)\n nfunc++;\n if (nfunc == 0)\n continue;\n\n fflush(stdout);\n if (do_pin) {\n for (int f = 0; f < 2; f++) {\n if (t->func[f].callproc == p) {\n setaffinity(f+2);\n break;\n }\n }\n }\n\n pids[p] = fork();\n assert(pids[p] >= 0);\n\n if (pids[p] == 0) {\n \/\/ Get all text and data structures\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n \/\/ Prime the VM system (this must be kept in sync with\n \/\/ fs_testgen.py)\n void *r = mmap((void*)0x12345600000, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap (fixed)\");\n munmap(r, 4 * 4096);\n\n r = mmap(0, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap (non-fixed)\");\n munmap(r, 4 * 4096);\n\n \/\/ Run setup\n tp[p].run();\n\n int ndone = 0;\n pthread_t tid[2];\n for (int f = 0; f < 2; f++) {\n if (t->func[f].callproc == p) {\n if (do_pin)\n setaffinity(f);\n ndone++;\n if (ndone == nfunc)\n testfunc_thread(&tf[f]);\n else\n pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);\n }\n }\n\n if (nfunc == 2)\n pthread_join(tid[0], nullptr);\n exit(0);\n }\n }\n\n for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();\n t->setup_final();\n\n for (int i = 0; i < 2; i++) tf[i].start.enter();\n\n char mtname[64];\n snprintf(mtname, sizeof(mtname), \"%s\", t->testname);\n mtenable_type(mtrace_record_ascope, mtname);\n\n for (int i = 0; i < 2; i++) {\n tf[first_func ^ i].start.exit();\n tf[first_func ^ i].stop.enter();\n }\n\n mtdisable(mtname);\n\n for (int i = 0; i < 2; i++) tf[i].stop.exit();\n\n for (int p = 0; p < 2; p++)\n if (pids[p])\n assert(waitpid(pids[p], nullptr, 0) >= 0);\n\n t->cleanup();\n}\n\nstatic void\npf_handler(int signo)\n{\n if (pf_active)\n siglongjmp(pf_jmpbuf, signo);\n \/\/ Let the error happen\n signal(signo, SIG_DFL);\n}\n\nstatic bool verbose = false;\nstatic bool check_commutativity = false;\nstatic bool run_threads = false;\nstatic bool check_results = false;\nstatic fstest *cur_test = nullptr;\n\nvoid\nexpect_result(const char *varname, long got, long expect)\n{\n if (!check_results) return;\n if (got == expect) return;\n auto name = cur_test->testname;\n#ifdef XV6_USER\n printf(\"%s: expected %s == %ld, got %ld\\n\",\n name, varname, expect, got);\n#else\n printf(\"%s: expected %s == %ld, got %ld (errno %s)\\n\",\n name, varname, expect, got, strerror(errno));\n#endif\n}\n\nvoid\nexpect_errno(int expect)\n{\n#ifndef XV6_USER\n if (!check_results) return;\n if (errno == expect) return;\n auto name = cur_test->testname;\n printf(\"%s: expected errno == %s, got %s\\n\",\n name, strerror(expect), strerror(errno));\n#endif\n}\n\nstatic void\nusage(const char* prog)\n{\n fprintf(stderr, \"Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\\n\", prog);\n}\n\nint\nmain(int ac, char** av)\n{\n uint32_t min = 0;\n uint32_t max;\n int nparts = -1;\n int thispart = -1;\n\n uint32_t ntests = 0;\n for (ntests = min; fstests[ntests].testname; ntests++)\n ;\n max = ntests - 1;\n\n for (;;) {\n int opt = getopt(ac, av, \"vctrp:n:\");\n if (opt == -1)\n break;\n\n switch (opt) {\n case 'v':\n verbose = true;\n break;\n\n case 'c':\n check_commutativity = true;\n break;\n\n case 't':\n run_threads = true;\n break;\n\n case 'r':\n run_threads = true;\n check_results = true;\n break;\n\n case 'n':\n nparts = atoi(optarg);\n break;\n\n case 'p':\n thispart = atoi(optarg);\n break;\n\n default:\n usage(av[0]);\n return -1;\n }\n }\n\n if (optind < ac) {\n char* dash = strchr(av[optind], '-');\n if (!dash) {\n min = max = atoi(av[optind]);\n } else {\n *dash = '\\0';\n if (av[optind])\n min = atoi(av[optind]);\n if (*(dash + 1))\n max = atoi(dash + 1);\n }\n } else if (nparts >= 0 || thispart >= 0) {\n if (nparts < 0 || thispart < 0) {\n usage(av[0]);\n return -1;\n }\n\n uint32_t partsize = (ntests + nparts - 1) \/nparts;\n min = partsize * thispart;\n max = partsize * (thispart + 1) - 1;\n }\n\n if (!check_commutativity && !run_threads) {\n fprintf(stderr, \"Must specify one of -c or -t\\n\");\n usage(av[0]);\n return -1;\n }\n\n printf(\"fstest:\");\n if (verbose)\n printf(\" verbose\");\n if (check_commutativity)\n printf(\" check\");\n if (run_threads)\n printf(\" threads\");\n if (check_results)\n printf(\" results\");\n if (min == 0 && max == ntests - 1)\n printf(\" all\");\n else if (min == max)\n printf(\" %d\", min);\n else\n printf(\" %d-%d\", min, max);\n printf(\"\\n\");\n\n testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tp != MAP_FAILED);\n assert(2*sizeof(*tp) <= 4096);\n\n testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tf != MAP_FAILED);\n assert(2*sizeof(*tf) <= 4096);\n\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n signal(SIGPIPE, SIG_IGN);\n signal(SIGBUS, pf_handler);\n signal(SIGSEGV, pf_handler);\n\n for (uint32_t t = min; t <= max && t < ntests; t++) {\n cur_test = &fstests[t];\n\n if (verbose)\n printf(\"%s (test %d) starting\\n\", fstests[t].testname, t);\n\n if (check_commutativity) {\n run_test(tp, tf, &fstests[t], 0, false);\n int ra0 = tf[0].retval;\n int ra1 = tf[1].retval;\n\n run_test(tp, tf, &fstests[t], 1, false);\n int rb0 = tf[0].retval;\n int rb1 = tf[1].retval;\n\n if (ra0 == rb0 && ra1 == rb1) {\n if (verbose)\n printf(\"%s: commutes: %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);\n } else {\n printf(\"%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,\n fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);\n }\n }\n\n if (run_threads) {\n run_test(tp, tf, &fstests[t], 0, true);\n }\n }\n\n printf(\"fstest: done\\n\");\n}\nfstest: Accept a test case name on the command line#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mtrace.h\"\n#include \"fstest.h\"\n#include \"libutil.h\"\n#include \"spinbarrier.hh\"\n\nextern char _end[];\n__thread sigjmp_buf pf_jmpbuf;\n__thread int pf_active;\n\nclass double_barrier {\n spin_barrier enter_;\n spin_barrier exit_;\n\npublic:\n double_barrier() : enter_(2), exit_(2) {}\n void sync() { enter(); exit(); }\n void enter() { enter_.join(); }\n void exit() { exit_.join(); }\n};\n\nstruct testproc {\n double_barrier setup;\n std::atomic setupf1;\n std::atomic setupf2;\n\n testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}\n void run() {\n setup.enter();\n setupf1();\n setupf2();\n setup.exit();\n }\n};\n\nstruct testfunc {\n double_barrier start;\n double_barrier stop;\n\n std::atomic func;\n std::atomic retval;\n\n testfunc(int (*f)(void)) : func(f) {}\n void run() {\n#ifndef XV6_USER\n errno = 0;\n#endif\n start.sync();\n retval = func();\n stop.sync();\n }\n};\n\nstatic void*\ntestfunc_thread(void* arg)\n{\n madvise(0, (size_t) _end, MADV_WILLNEED);\n testfunc* f = (testfunc*) arg;\n f->run();\n return nullptr;\n}\n\nstatic void\nrun_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)\n{\n assert(first_func == 0 || first_func == 1);\n if (do_pin)\n setaffinity(2);\n\n for (int i = 0; i < 2; i++)\n new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);\n for (int i = 0; i < 2; i++)\n new (&tf[i]) testfunc(t->func[i].call);\n\n t->setup_common();\n\n pid_t pids[2] = { 0, 0 };\n for (int p = 0; p < 2; p++) {\n int nfunc = 0;\n for (int f = 0; f < 2; f++)\n if (t->func[f].callproc == p)\n nfunc++;\n if (nfunc == 0)\n continue;\n\n fflush(stdout);\n if (do_pin) {\n for (int f = 0; f < 2; f++) {\n if (t->func[f].callproc == p) {\n setaffinity(f+2);\n break;\n }\n }\n }\n\n pids[p] = fork();\n assert(pids[p] >= 0);\n\n if (pids[p] == 0) {\n \/\/ Get all text and data structures\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n \/\/ Prime the VM system (this must be kept in sync with\n \/\/ fs_testgen.py)\n void *r = mmap((void*)0x12345600000, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap (fixed)\");\n munmap(r, 4 * 4096);\n\n r = mmap(0, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap (non-fixed)\");\n munmap(r, 4 * 4096);\n\n \/\/ Run setup\n tp[p].run();\n\n int ndone = 0;\n pthread_t tid[2];\n for (int f = 0; f < 2; f++) {\n if (t->func[f].callproc == p) {\n if (do_pin)\n setaffinity(f);\n ndone++;\n if (ndone == nfunc)\n testfunc_thread(&tf[f]);\n else\n pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);\n }\n }\n\n if (nfunc == 2)\n pthread_join(tid[0], nullptr);\n exit(0);\n }\n }\n\n for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();\n t->setup_final();\n\n for (int i = 0; i < 2; i++) tf[i].start.enter();\n\n char mtname[64];\n snprintf(mtname, sizeof(mtname), \"%s\", t->testname);\n mtenable_type(mtrace_record_ascope, mtname);\n\n for (int i = 0; i < 2; i++) {\n tf[first_func ^ i].start.exit();\n tf[first_func ^ i].stop.enter();\n }\n\n mtdisable(mtname);\n\n for (int i = 0; i < 2; i++) tf[i].stop.exit();\n\n for (int p = 0; p < 2; p++)\n if (pids[p])\n assert(waitpid(pids[p], nullptr, 0) >= 0);\n\n t->cleanup();\n}\n\nstatic void\npf_handler(int signo)\n{\n if (pf_active)\n siglongjmp(pf_jmpbuf, signo);\n \/\/ Let the error happen\n signal(signo, SIG_DFL);\n}\n\nstatic bool verbose = false;\nstatic bool check_commutativity = false;\nstatic bool run_threads = false;\nstatic bool check_results = false;\nstatic fstest *cur_test = nullptr;\n\nvoid\nexpect_result(const char *varname, long got, long expect)\n{\n if (!check_results) return;\n if (got == expect) return;\n auto name = cur_test->testname;\n#ifdef XV6_USER\n printf(\"%s: expected %s == %ld, got %ld\\n\",\n name, varname, expect, got);\n#else\n printf(\"%s: expected %s == %ld, got %ld (errno %s)\\n\",\n name, varname, expect, got, strerror(errno));\n#endif\n}\n\nvoid\nexpect_errno(int expect)\n{\n#ifndef XV6_USER\n if (!check_results) return;\n if (errno == expect) return;\n auto name = cur_test->testname;\n printf(\"%s: expected errno == %s, got %s\\n\",\n name, strerror(expect), strerror(errno));\n#endif\n}\n\nstatic void\nusage(const char* prog)\n{\n fprintf(stderr, \"Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\\n\", prog);\n}\n\nint\nmain(int ac, char** av)\n{\n uint32_t min = 0;\n uint32_t max;\n int nparts = -1;\n int thispart = -1;\n\n uint32_t ntests = 0;\n for (ntests = min; fstests[ntests].testname; ntests++)\n ;\n max = ntests - 1;\n\n for (;;) {\n int opt = getopt(ac, av, \"vctrp:n:\");\n if (opt == -1)\n break;\n\n switch (opt) {\n case 'v':\n verbose = true;\n break;\n\n case 'c':\n check_commutativity = true;\n break;\n\n case 't':\n run_threads = true;\n break;\n\n case 'r':\n run_threads = true;\n check_results = true;\n break;\n\n case 'n':\n nparts = atoi(optarg);\n break;\n\n case 'p':\n thispart = atoi(optarg);\n break;\n\n default:\n usage(av[0]);\n return -1;\n }\n }\n\n if (optind < ac) {\n bool found = false;\n for (uint32_t t = 0; t < ntests && !found; t++) {\n if (strcmp(av[optind], fstests[t].testname) == 0) {\n min = max = t;\n found = true;\n }\n }\n\n if (!found) {\n char* dash = strchr(av[optind], '-');\n if (!dash) {\n min = max = atoi(av[optind]);\n } else {\n *dash = '\\0';\n if (av[optind])\n min = atoi(av[optind]);\n if (*(dash + 1))\n max = atoi(dash + 1);\n }\n }\n } else if (nparts >= 0 || thispart >= 0) {\n if (nparts < 0 || thispart < 0) {\n usage(av[0]);\n return -1;\n }\n\n uint32_t partsize = (ntests + nparts - 1) \/nparts;\n min = partsize * thispart;\n max = partsize * (thispart + 1) - 1;\n }\n\n if (!check_commutativity && !run_threads) {\n fprintf(stderr, \"Must specify one of -c or -t\\n\");\n usage(av[0]);\n return -1;\n }\n\n printf(\"fstest:\");\n if (verbose)\n printf(\" verbose\");\n if (check_commutativity)\n printf(\" check\");\n if (run_threads)\n printf(\" threads\");\n if (check_results)\n printf(\" results\");\n if (min == 0 && max == ntests - 1)\n printf(\" all\");\n else if (min == max)\n printf(\" %d\", min);\n else\n printf(\" %d-%d\", min, max);\n printf(\"\\n\");\n\n testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tp != MAP_FAILED);\n assert(2*sizeof(*tp) <= 4096);\n\n testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tf != MAP_FAILED);\n assert(2*sizeof(*tf) <= 4096);\n\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n signal(SIGPIPE, SIG_IGN);\n signal(SIGBUS, pf_handler);\n signal(SIGSEGV, pf_handler);\n\n for (uint32_t t = min; t <= max && t < ntests; t++) {\n cur_test = &fstests[t];\n\n if (verbose)\n printf(\"%s (test %d) starting\\n\", fstests[t].testname, t);\n\n if (check_commutativity) {\n run_test(tp, tf, &fstests[t], 0, false);\n int ra0 = tf[0].retval;\n int ra1 = tf[1].retval;\n\n run_test(tp, tf, &fstests[t], 1, false);\n int rb0 = tf[0].retval;\n int rb1 = tf[1].retval;\n\n if (ra0 == rb0 && ra1 == rb1) {\n if (verbose)\n printf(\"%s: commutes: %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);\n } else {\n printf(\"%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,\n fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);\n }\n }\n\n if (run_threads) {\n run_test(tp, tf, &fstests[t], 0, true);\n }\n }\n\n printf(\"fstest: done\\n\");\n}\n<|endoftext|>"} {"text":"\/** @file gsGeometry.hpp\n\n @brief Provides implementation of Geometry default operatiions.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): A. Mantzaflaris\n*\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\nnamespace gismo\n{\n\ntemplate\ngsMatrix gsGeometry::parameterCenter( const boxCorner& bc )\n{\n gsMatrix supp = parameterRange();\n const index_t dim = supp.rows();\n gsMatrix coordinates(dim,1);\n gsVector boxPar = bc.parameters(dim);\n for (index_t d=0; d\ngsMatrix gsGeometry::parameterCenter( const boxSide& bc )\n{\n gsMatrix supp = parameterRange();\n const index_t dim = supp.rows();\n gsMatrix coordinates(dim,1);\n const index_t dir = bc.direction();\n for (index_t d=0; d\nboxSide gsGeometry::sideOf( const gsVector & u, )\n{\n \/\/ get the indices of the coefficients which lie on the boundary\n gsMatrix allBnd = m_basis->allBoundary();\n gsMatrix bndCoeff(allBnd.rows(), m_coefs.rows());\n\n \/\/ extract the indices of the boundary coefficients\n for(index_t r = 0; r < allBnd.rows(); r++)\n bndCoeff.row(r) = m_coefs.row(allBnd(r,0));\n\n\n for(size_t size = 0; size < allBnd.rows(); size++)\n if(boundaryPatch1[size] == 1)\n interfaceIndicesPatch1.push_back(allBnd(size, 0)); \/\/ get the indices of the coefficients on patch 1 which lie on the common interface\n\n boxSide side;\n\n for(unsigned index = 1; index <= nBoundaries; index++) {\n int contained = 0;\n side.m_index = index;\n\n gsMatrix bnd = m_basis->boundary(side);\n\n for(size_t i = 0; i < interfaceIndicesPatch1.size(); i++)\n {\n gsInfo << \"index: \" << interfaceIndicesPatch1[i] << \"\\n\";\n for (int j = 0; j < bnd.rows(); j++)\n {\n if(bnd(j, 0) == interfaceIndicesPatch1[i])\n contained++;\n }\n }\n\n if(contained == bnd.rows())\n break;\n\n \/\/gsInfo << \"indices of boundary : \" << bnd << \"\\n\";\n }\n}\n *\/\n\ntemplate\ntypename gsGeometry::uPtr\ngsGeometry::boundary(boxSide const& s) const\n{\n gsMatrix ind = this->basis().boundary(s); \/\/ get indices of the boundary DOF\n gsMatrix coeffs (ind.size(), geoDim()); \/\/ create matrix for boundary coefficients\n\n for (index_t i=0; i != ind.size(); i++ )\n {\n coeffs.row(i) = m_coefs.row( (ind)(i,0) );\n }\n\n typename gsBasis::uPtr Bs = this->basis().boundaryBasis(s); \/\/ Basis for boundary side s\n uPtr bgeo = Bs->makeGeometry( give(coeffs) );\n\n return bgeo;\n}\n\ntemplate\nvoid gsGeometry::evaluateMesh(gsMesh& mesh) const\n{\n const int pDim = parDim();\n const int gDim = geoDim();\n\n gsMatrix tmp;\n\n \/\/ For all vertices of the mesh, push forward the value by the\n \/\/ geometry mapping\n for (size_t i = 0; i!= mesh.numVertices(); ++i)\n {\n eval_into( mesh.vertex(i).topRows(pDim), tmp );\n mesh.vertex(i).topRows( gDim ) = tmp;\n }\n}\ntemplate\nstd::vector* > gsGeometry::uniformSplit(index_t) const\n{\n GISMO_NO_IMPLEMENTATION\n}\n\ntemplate\ngsGeometrySlice gsGeometry::getIsoParametricSlice(index_t dir_fixed, T par) const\n{\n return gsGeometrySlice(this,dir_fixed,par);\n}\n\ntemplate\ntypename gsMatrix::RowXpr\ngsGeometry::coefAtCorner(boxCorner const & c)\n{\n return this->m_coefs.row(this->basis().functionAtCorner(c));\n}\n\ntemplate\ntypename gsMatrix::ConstRowXpr\ngsGeometry::coefAtCorner(boxCorner const & c) const\n{\n return this->m_coefs.row(this->basis().functionAtCorner(c));\n}\n\ntemplate\nvoid gsGeometry::invertPoints(const gsMatrix & points,\n gsMatrix & result,\n const T accuracy) const\n{\n result.resize(parDim(), points.cols() );\n gsVector arg;\n for ( index_t i = 0; i!= points.cols(); ++i)\n {\n arg = parameterCenter();\n \/\/int iter =\n this->newtonRaphson(points.col(i), arg, true, accuracy, 100);\n result.col(i) = arg;\n }\n}\n\n\ntemplate\nvoid gsGeometry::merge(gsGeometry *)\n{ GISMO_NO_IMPLEMENTATION }\n\ntemplate\nvoid gsGeometry::toMesh(gsMesh &, int) const\n{ GISMO_NO_IMPLEMENTATION }\n\ntemplate\nvoid gsGeometry::outerNormal_into(const gsMatrix&, gsMatrix &) const\n{ GISMO_NO_IMPLEMENTATION }\n\ntemplate\nstd::vector *> gsGeometry:: boundary() const\n{\n \/\/ TO DO: get boundary curves, using basis().boundary();\n GISMO_NO_IMPLEMENTATION\n}\n\ntemplate\nvoid gsGeometry::degreeElevate(short_t const i, short_t const dir)\n{\n typename gsBasis::uPtr b = m_basis->clone();\n\n if ( dir == -1 )\n b->degreeElevate(i);\n else if (dir < parDim() )\n b->degreeElevate(i, dir);\n else\n GISMO_ERROR(\"Invalid direction \"<< dir <<\" to elevate.\");\n\n gsMatrix iVals, iPts = b->anchors();\n this->eval_into(iPts, iVals);\n typename gsGeometry::uPtr g = b->interpolateData(iVals, iPts);\n\n std::swap(m_basis, g->m_basis);\n g->coefs().swap(this->coefs());\n}\n\ntemplate\nvoid gsGeometry::degreeReduce(short_t const i, short_t const dir)\n{\n typename gsBasis::uPtr b = m_basis->clone();\n\n if ( dir == -1 )\n b->degreeReduce(i);\n else if (dir < parDim() )\n b->component(dir).degreeReduce(i);\n else\n GISMO_ERROR(\"Invalid direction \"<< dir <<\" to degree-reduce.\");\n\n gsMatrix iVals, iPts = b->anchors();\n this->eval_into(iPts, iVals);\n typename gsGeometry::uPtr g = b->interpolateData(iVals, iPts);\n\n std::swap(m_basis, g->m_basis);\n g->coefs().swap(this->coefs());\n}\n\ntemplate\ngsMatrix\ngsGeometry::hessian(const gsMatrix& u, unsigned coord) const\n{\n static const unsigned d = this->m_basis->dim();\n\n gsMatrix B, DD(d,d), tmp(d,d);\n gsMatrix ind;\n\n \/\/ coefficient matrix row k = coef. of basis function k\n const gsMatrix& C = this->m_coefs;\n \/\/ col j = nonzero second derivatives at column point u(..,j)\n m_basis->deriv2_into(u, B) ;\n \/\/ col j = indices of active functions at column point u(..,j)\n m_basis->active_into(u, ind);\n\n DD.setZero();\n unsigned j=0;\/\/ just one column\n \/\/for ( unsigned j=0; j< u.cols(); j++ ) \/\/ for all points (columns of u)\n for ( index_t i=0; i< ind.rows() ; i++ ) \/\/ for all non-zero basis functions)\n {\n unsigned m=i*d;\n unsigned r= ind.rows()*d + i*d*(d-1)\/2;\n \/\/construct the Hessian of basis function ind(i,0)\n for (unsigned k=0; k\nvoid extractRows( const gsMatrix &in, typename gsMatrix::constColumn actives, gsMatrix &out)\n{\n out.resize(actives.rows(), in.cols());\n for (index_t r=0; r\nvoid\ngsGeometry::compute(const gsMatrix & in, gsFuncData & out) const\n{\n\n const unsigned flags = out.flags | NEED_ACTIVE;\n const index_t numPt = in.cols();\n const index_t numCo = m_coefs.cols();\n\n gsFuncData tmp(flags);\n this->basis().compute(in, tmp);\n\n out.values.resize(out.maxDeriv()+1);\n out.dim.first = tmp.dim.first;\n out.dim.second = numCo;\n if ( flags & SAME_ELEMENT )\n {\n gsMatrix coefM;\n extractRows(m_coefs,tmp.active(0),coefM);\n\n if (flags & NEED_VALUE)\n out.values[0]=coefM.transpose()*tmp.values[0];\n if (flags & NEED_DERIV)\n {\n const index_t derS = tmp.derivSize();\n out.values[1].resize(derS*numCo,numPt);\n for (index_t p=0; p< numPt; ++p)\n out.values[1].reshapeCol(p, derS, numCo) = tmp.deriv(p)*coefM;\n }\n if (flags & NEED_DERIV2)\n {\n const index_t derS = tmp.deriv2Size();\n out.values[2].resize(derS*numCo,numPt);\n for (index_t p=0; p< numPt; ++p)\n out.values[2].reshapeCol(p, derS, numCo) = tmp.deriv2(p)*coefM;\n }\n } else\n {\n gsMatrix coefM;\n const index_t derS = tmp.derivSize();\n const index_t der2S = tmp.deriv2Size();\n\n if (flags & NEED_VALUE) out.values[0].resize(numCo,numPt);\n if (flags & NEED_DERIV) out.values[1].resize(numCo*derS,numPt);\n if (flags & NEED_DERIV2) out.values[2].resize(numCo*der2S,numPt);\n\n for (index_t p=0; p\nstd::vector gsGeometry::locateOn(const gsMatrix & u, gsVector & onGeo, gsMatrix & preIm, bool lookForBoundary, real_t tol) const\n{\n onGeo.resize(u.cols());\n std::vector sides(u.cols());\n\n for(index_t i = 0; i < onGeo.size(); i++)\n onGeo(i) = false;\n\n preIm.resize(geoDim(), u.cols());\n gsMatrix pr = this->parameterRange(), tmp;\n\n for(index_t i = 0; i < u.cols(); i++)\n {\n this->invertPoints(u.col(i), tmp, tol);\n pr = this->parameterRange();\n \/\/if ((tmp.array() >= pr.col(0).array()).all()\n \/\/ && (tmp.array() <= pr.col(1).array()).all())\n if ((tmp.array() >= pr.col(0).array() - 1.e-4).all()\n && (tmp.array() <= pr.col(1).array() + 1.e-4).all()) \/\/ be careful! if u is on the boundary then we may get a wrong result\n \/\/ the tolerance is due to imprecisions in the geometry map. E.g. If a circle is rotated then the corner need\n \/\/ not to lie exactly on the interface of the neighbour patch since we use only B-splines for the modelling\n \/\/ TODO: Maybe find a better solution!\n {\n onGeo(i) = true;\n preIm.col(i) = tmp;\n\n if (lookForBoundary == true)\n {\n boxSide s;\n for (int d = 0; d < geoDim(); d++) {\n if ((math::abs(tmp(d, 0) - pr(d, 0)) < tol))\n {\n s.m_index = 2*d+1; \/\/ lower\n break;\n }\n\n if ((math::abs(tmp(d, 0) - pr(d, 1)) < tol))\n {\n s.m_index = 2 * d + 2; \/\/ upper\n break;\n }\n }\n sides[i] = s;\n }\n }\n }\n\n return sides;\n}\n\n\n} \/\/ namespace gismo\nfix in geometry\/** @file gsGeometry.hpp\n\n @brief Provides implementation of Geometry default operatiions.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): A. Mantzaflaris\n*\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\nnamespace gismo\n{\n\ntemplate\ngsMatrix gsGeometry::parameterCenter( const boxCorner& bc )\n{\n gsMatrix supp = parameterRange();\n const index_t dim = supp.rows();\n gsMatrix coordinates(dim,1);\n gsVector boxPar = bc.parameters(dim);\n for (index_t d=0; d\ngsMatrix gsGeometry::parameterCenter( const boxSide& bc )\n{\n gsMatrix supp = parameterRange();\n const index_t dim = supp.rows();\n gsMatrix coordinates(dim,1);\n const index_t dir = bc.direction();\n for (index_t d=0; d\nboxSide gsGeometry::sideOf( const gsVector & u, )\n{\n \/\/ get the indices of the coefficients which lie on the boundary\n gsMatrix allBnd = m_basis->allBoundary();\n gsMatrix bndCoeff(allBnd.rows(), m_coefs.rows());\n\n \/\/ extract the indices of the boundary coefficients\n for(index_t r = 0; r < allBnd.rows(); r++)\n bndCoeff.row(r) = m_coefs.row(allBnd(r,0));\n\n\n for(size_t size = 0; size < allBnd.rows(); size++)\n if(boundaryPatch1[size] == 1)\n interfaceIndicesPatch1.push_back(allBnd(size, 0)); \/\/ get the indices of the coefficients on patch 1 which lie on the common interface\n\n boxSide side;\n\n for(unsigned index = 1; index <= nBoundaries; index++) {\n int contained = 0;\n side.m_index = index;\n\n gsMatrix bnd = m_basis->boundary(side);\n\n for(size_t i = 0; i < interfaceIndicesPatch1.size(); i++)\n {\n gsInfo << \"index: \" << interfaceIndicesPatch1[i] << \"\\n\";\n for (int j = 0; j < bnd.rows(); j++)\n {\n if(bnd(j, 0) == interfaceIndicesPatch1[i])\n contained++;\n }\n }\n\n if(contained == bnd.rows())\n break;\n\n \/\/gsInfo << \"indices of boundary : \" << bnd << \"\\n\";\n }\n}\n *\/\n\ntemplate\ntypename gsGeometry::uPtr\ngsGeometry::boundary(boxSide const& s) const\n{\n gsMatrix ind = this->basis().boundary(s); \/\/ get indices of the boundary DOF\n gsMatrix coeffs (ind.size(), geoDim()); \/\/ create matrix for boundary coefficients\n\n for (index_t i=0; i != ind.size(); i++ )\n {\n coeffs.row(i) = m_coefs.row( (ind)(i,0) );\n }\n\n typename gsBasis::uPtr Bs = this->basis().boundaryBasis(s); \/\/ Basis for boundary side s\n uPtr bgeo = Bs->makeGeometry( give(coeffs) );\n\n return bgeo;\n}\n\ntemplate\nvoid gsGeometry::evaluateMesh(gsMesh& mesh) const\n{\n const int pDim = parDim();\n const int gDim = geoDim();\n\n gsMatrix tmp;\n\n \/\/ For all vertices of the mesh, push forward the value by the\n \/\/ geometry mapping\n for (size_t i = 0; i!= mesh.numVertices(); ++i)\n {\n eval_into( mesh.vertex(i).topRows(pDim), tmp );\n mesh.vertex(i).topRows( gDim ) = tmp;\n }\n}\ntemplate\nstd::vector* > gsGeometry::uniformSplit(index_t) const\n{\n GISMO_NO_IMPLEMENTATION\n}\n\ntemplate\ngsGeometrySlice gsGeometry::getIsoParametricSlice(index_t dir_fixed, T par) const\n{\n return gsGeometrySlice(this,dir_fixed,par);\n}\n\ntemplate\ntypename gsMatrix::RowXpr\ngsGeometry::coefAtCorner(boxCorner const & c)\n{\n return this->m_coefs.row(this->basis().functionAtCorner(c));\n}\n\ntemplate\ntypename gsMatrix::ConstRowXpr\ngsGeometry::coefAtCorner(boxCorner const & c) const\n{\n return this->m_coefs.row(this->basis().functionAtCorner(c));\n}\n\ntemplate\nvoid gsGeometry::invertPoints(const gsMatrix & points,\n gsMatrix & result,\n const T accuracy) const\n{\n result.resize(parDim(), points.cols() );\n gsVector arg;\n for ( index_t i = 0; i!= points.cols(); ++i)\n {\n arg = parameterCenter();\n \/\/int iter =\n this->newtonRaphson(points.col(i), arg, true, accuracy, 100);\n result.col(i) = arg;\n }\n}\n\n\ntemplate\nvoid gsGeometry::merge(gsGeometry *)\n{ GISMO_NO_IMPLEMENTATION }\n\ntemplate\nvoid gsGeometry::toMesh(gsMesh &, int) const\n{ GISMO_NO_IMPLEMENTATION }\n\ntemplate\nvoid gsGeometry::outerNormal_into(const gsMatrix&, gsMatrix &) const\n{ GISMO_NO_IMPLEMENTATION }\n\ntemplate\nstd::vector *> gsGeometry:: boundary() const\n{\n \/\/ TO DO: get boundary curves, using basis().boundary();\n GISMO_NO_IMPLEMENTATION\n}\n\ntemplate\nvoid gsGeometry::degreeElevate(short_t const i, short_t const dir)\n{\n typename gsBasis::uPtr b = m_basis->clone();\n\n if ( dir == -1 )\n b->degreeElevate(i);\n else if (dir < parDim() )\n b->degreeElevate(i, dir);\n else\n GISMO_ERROR(\"Invalid direction \"<< dir <<\" to elevate.\");\n\n gsMatrix iVals, iPts = b->anchors();\n this->eval_into(iPts, iVals);\n typename gsGeometry::uPtr g = b->interpolateData(iVals, iPts);\n\n std::swap(m_basis, g->m_basis);\n g->coefs().swap(this->coefs());\n}\n\ntemplate\nvoid gsGeometry::degreeReduce(short_t const i, short_t const dir)\n{\n typename gsBasis::uPtr b = m_basis->clone();\n\n if ( dir == -1 )\n b->degreeReduce(i);\n else if (dir < parDim() )\n b->component(dir).degreeReduce(i);\n else\n GISMO_ERROR(\"Invalid direction \"<< dir <<\" to degree-reduce.\");\n\n gsMatrix iVals, iPts = b->anchors();\n this->eval_into(iPts, iVals);\n typename gsGeometry::uPtr g = b->interpolateData(iVals, iPts);\n\n std::swap(m_basis, g->m_basis);\n g->coefs().swap(this->coefs());\n}\n\ntemplate\ngsMatrix\ngsGeometry::hessian(const gsMatrix& u, unsigned coord) const\n{\n static const unsigned d = this->m_basis->dim();\n\n gsMatrix B, DD(d,d), tmp(d,d);\n gsMatrix ind;\n\n \/\/ coefficient matrix row k = coef. of basis function k\n const gsMatrix& C = this->m_coefs;\n \/\/ col j = nonzero second derivatives at column point u(..,j)\n m_basis->deriv2_into(u, B) ;\n \/\/ col j = indices of active functions at column point u(..,j)\n m_basis->active_into(u, ind);\n\n DD.setZero();\n unsigned j=0;\/\/ just one column\n \/\/for ( unsigned j=0; j< u.cols(); j++ ) \/\/ for all points (columns of u)\n for ( index_t i=0; i< ind.rows() ; i++ ) \/\/ for all non-zero basis functions)\n {\n unsigned m=i*d;\n unsigned r= ind.rows()*d + i*d*(d-1)\/2;\n \/\/construct the Hessian of basis function ind(i,0)\n for (unsigned k=0; k\nvoid extractRows( const gsMatrix &in, typename gsMatrix::constColumn actives, gsMatrix &out)\n{\n out.resize(actives.rows(), in.cols());\n for (index_t r=0; r\nvoid\ngsGeometry::compute(const gsMatrix & in, gsFuncData & out) const\n{\n const unsigned flags = out.flags | NEED_ACTIVE;\n const index_t numPt = in.cols();\n const index_t numCo = m_coefs.cols();\n\n gsFuncData tmp(flags);\n this->basis().compute(in, tmp);\n\n out.values.resize(out.maxDeriv()+1);\n out.dim.first = tmp.dim.first;\n out.dim.second = numCo;\n if ( flags & SAME_ELEMENT )\n {\n gsMatrix coefM;\n extractRows(m_coefs,tmp.active(0),coefM);\n\n if (flags & NEED_VALUE)\n out.values[0]=coefM.transpose()*tmp.values[0];\n if (flags & NEED_DERIV)\n {\n const index_t derS = tmp.derivSize();\n out.values[1].resize(derS*numCo,numPt);\n for (index_t p=0; p< numPt; ++p)\n out.values[1].reshapeCol(p, derS, numCo) = tmp.deriv(p)*coefM;\n }\n if (flags & NEED_DERIV2)\n {\n const index_t derS = tmp.deriv2Size();\n out.values[2].resize(derS*numCo,numPt);\n for (index_t p=0; p< numPt; ++p)\n out.values[2].reshapeCol(p, derS, numCo) = tmp.deriv2(p)*coefM;\n }\n if (flags & NEED_ACTIVE)\n this->active_into(in.col(0), out.actives);\n }\n else\n {\n gsMatrix coefM;\n const index_t derS = tmp.derivSize();\n const index_t der2S = tmp.deriv2Size();\n\n if (flags & NEED_VALUE) out.values[0].resize(numCo,numPt);\n if (flags & NEED_DERIV) out.values[1].resize(numCo*derS,numPt);\n if (flags & NEED_DERIV2) out.values[2].resize(numCo*der2S,numPt);\n if (flags & NEED_ACTIVE) this->active_into(in, out.actives);\n\n for (index_t p=0; p\nstd::vector gsGeometry::locateOn(const gsMatrix & u, gsVector & onGeo, gsMatrix & preIm, bool lookForBoundary, real_t tol) const\n{\n onGeo.resize(u.cols());\n std::vector sides(u.cols());\n\n for(index_t i = 0; i < onGeo.size(); i++)\n onGeo(i) = false;\n\n preIm.resize(geoDim(), u.cols());\n gsMatrix pr = this->parameterRange(), tmp;\n\n for(index_t i = 0; i < u.cols(); i++)\n {\n this->invertPoints(u.col(i), tmp, tol);\n pr = this->parameterRange();\n \/\/if ((tmp.array() >= pr.col(0).array()).all()\n \/\/ && (tmp.array() <= pr.col(1).array()).all())\n if ((tmp.array() >= pr.col(0).array() - 1.e-4).all()\n && (tmp.array() <= pr.col(1).array() + 1.e-4).all()) \/\/ be careful! if u is on the boundary then we may get a wrong result\n \/\/ the tolerance is due to imprecisions in the geometry map. E.g. If a circle is rotated then the corner need\n \/\/ not to lie exactly on the interface of the neighbour patch since we use only B-splines for the modelling\n \/\/ TODO: Maybe find a better solution!\n {\n onGeo(i) = true;\n preIm.col(i) = tmp;\n\n if (lookForBoundary == true)\n {\n boxSide s;\n for (int d = 0; d < geoDim(); d++) {\n if ((math::abs(tmp(d, 0) - pr(d, 0)) < tol))\n {\n s.m_index = 2*d+1; \/\/ lower\n break;\n }\n\n if ((math::abs(tmp(d, 0) - pr(d, 1)) < tol))\n {\n s.m_index = 2 * d + 2; \/\/ upper\n break;\n }\n }\n sides[i] = s;\n }\n }\n }\n\n return sides;\n}\n\n\n} \/\/ namespace gismo\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \"ui_newDishWindow.h\"\n\nNewDishWindow::NewDishWindow(QWidget *parent) :\n QDialog {parent},\n ui {new Ui::NewDishWindow},\n foodStringList {new QStringList},\n itemListModel {new QStringListModel {*foodStringList, NULL}} {\n\n ui->setupUi(this);\n\n ui->listView_1->setModel(itemListModel);\n\n ui->tableWidget_1->setColumnCount(2);\n\n PRINT_OBJ(\"NewDishWindow created\");\n}\n\nNewDishWindow::~NewDishWindow() {\n delete ui;\n\n PRINT_OBJ(\"NewDishWindow destroyed\");\n}\n\nvoid NewDishWindow::on_buttonBox_1_accepted() {\n emit itemObjectReady(createNewDish());\n\n this->hide();\n}\n\nvoid NewDishWindow::on_buttonBox_1_rejected() {\n this->hide();\n}\n\nvoid NewDishWindow::fillItemList(std::list *itemsList) {\n avaliableItemsList = itemsList;\n\n for ( auto& entry: *itemsList ) {\n foodStringList->append(QString::fromStdString(entry->getName()));\n }\n\n itemListModel->setStringList(*foodStringList);\n}\n\nDish* NewDishWindow::createNewDish(void) {\n return newDish;\n}\n\nvoid NewDishWindow::on_pushButton_1_clicked() {\n QModelIndexList selected = ui->listView_1->selectionModel()->selectedIndexes();\n\n if ( !selected.isEmpty() ) {\n std::list::iterator item = avaliableItemsList->begin();\n\n std::advance(item, selected.first().row());\n\n if ( std::find(dishItemsList.begin(), dishItemsList.end(), *item) == dishItemsList.end() ) {\n QTableWidgetItem *newItem;\n dishItemsList.push_back(*item);\n\n newItem = new QTableWidgetItem(tr(\"%1\").arg(QString::fromStdString((*item)->getName())));\n ui->tableWidget_1->setRowCount(ui->tableWidget_1->rowCount()+1);\n ui->tableWidget_1->setItem(ui->tableWidget_1->rowCount()-1, 0, newItem);\n }\n }\n}\n\nvoid NewDishWindow::on_pushButton_2_clicked() {\n\n}\nnewDishWindow: Reduce function call during ited adding#include \n\n#include \n#include \"ui_newDishWindow.h\"\n\nNewDishWindow::NewDishWindow(QWidget *parent) :\n QDialog {parent},\n ui {new Ui::NewDishWindow},\n foodStringList {new QStringList},\n itemListModel {new QStringListModel {*foodStringList, NULL}} {\n\n ui->setupUi(this);\n\n ui->listView_1->setModel(itemListModel);\n\n ui->tableWidget_1->setColumnCount(2);\n\n PRINT_OBJ(\"NewDishWindow created\");\n}\n\nNewDishWindow::~NewDishWindow() {\n delete ui;\n\n PRINT_OBJ(\"NewDishWindow destroyed\");\n}\n\nvoid NewDishWindow::on_buttonBox_1_accepted() {\n emit itemObjectReady(createNewDish());\n\n this->hide();\n}\n\nvoid NewDishWindow::on_buttonBox_1_rejected() {\n this->hide();\n}\n\nvoid NewDishWindow::fillItemList(std::list *itemsList) {\n avaliableItemsList = itemsList;\n\n for ( auto& entry: *itemsList ) {\n foodStringList->append(QString::fromStdString(entry->getName()));\n }\n\n itemListModel->setStringList(*foodStringList);\n}\n\nDish* NewDishWindow::createNewDish(void) {\n return newDish;\n}\n\nvoid NewDishWindow::on_pushButton_1_clicked() {\n QModelIndexList selected = ui->listView_1->selectionModel()->selectedIndexes();\n\n if ( !selected.isEmpty() ) {\n std::list::iterator item = avaliableItemsList->begin();\n\n std::advance(item, selected.first().row());\n\n if ( std::find(dishItemsList.begin(), dishItemsList.end(), *item) == dishItemsList.end() ) {\n QTableWidgetItem *newItem;\n int rowCount = ui->tableWidget_1->rowCount();\n\n dishItemsList.push_back(*item);\n\n newItem = new QTableWidgetItem(tr(\"%1\").arg(QString::fromStdString((*item)->getName())));\n ui->tableWidget_1->setRowCount(rowCount+1);\n ui->tableWidget_1->setItem(rowCount, 0, newItem);\n }\n }\n}\n\nvoid NewDishWindow::on_pushButton_2_clicked() {\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011, 2012 Esrille 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\n#include \n#include \n\n#include \"DOMImplementationImp.h\"\n#include \"ECMAScript.h\"\n#include \"WindowImp.h\"\n#include \"font\/FontDatabase.h\"\n#include \"http\/HTTPConnection.h\"\n\n#include \"Test.util.h\"\n\n#ifdef USE_V8\n#include \"v8\/ScriptV8.h\"\n#endif \/\/ USE_V8\n\nusing namespace org::w3c::dom::bootstrap;\nusing namespace org::w3c::dom;\n\nhtml::Window window(0);\n\nint main(int argc, char* argv[])\n{\n#ifdef USE_V8\n v8::HandleScope handleScope;\n#endif \/\/ USE_V8\n\n if (argc < 3) {\n std::cout << \"usage : \" << argv[0] << \" navigator_directory [user.css]\\n\";\n return EXIT_FAILURE;\n }\n\n init(&argc, argv);\n initLogLevel(&argc, argv);\n initFonts(&argc, argv);\n\n \/\/ Load the default CSS file\n std::string defaultSheet = argv[1];\n defaultSheet += \"\/default.css\";\n getDOMImplementation()->setDefaultCSSStyleSheet(loadStyleSheet(defaultSheet.c_str()));\n\n \/\/ Load the user CSS file\n if (3 <= argc)\n getDOMImplementation()->setUserCSSStyleSheet(loadStyleSheet(argv[2]));\n\n std::thread httpService(std::ref(HttpConnectionManager::getInstance()));\n\n \/\/ Set privileges to the navigator window.\n char navigatorUrl[PATH_MAX + 7];\n strcpy(navigatorUrl, \"file:\/\/\");\n realpath(argv[1], navigatorUrl + 7);\n HttpRequest::setAboutPath(navigatorUrl + 7);\n strcat(navigatorUrl, \"\/navigator.html\");\n WindowImp* imp = new WindowImp();\n window = imp;\n imp->enableZoom(false);\n imp->open(utfconv(navigatorUrl), u\"_self\", u\"\", true);\n\n glutMainLoop();\n\n window = 0;\n\n ECMAScriptContext::shutDown();\n\n HttpConnectionManager::getInstance().stop();\n httpService.join();\n}\n(main) : Fix a bug.\/*\n * Copyright 2011, 2012 Esrille 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\n#include \n#include \n\n#include \"DOMImplementationImp.h\"\n#include \"ECMAScript.h\"\n#include \"WindowImp.h\"\n#include \"font\/FontDatabase.h\"\n#include \"http\/HTTPConnection.h\"\n\n#include \"Test.util.h\"\n\n#ifdef USE_V8\n#include \"v8\/ScriptV8.h\"\n#endif \/\/ USE_V8\n\nusing namespace org::w3c::dom::bootstrap;\nusing namespace org::w3c::dom;\n\nhtml::Window window(0);\n\nint main(int argc, char* argv[])\n{\n#ifdef USE_V8\n v8::HandleScope handleScope;\n#endif \/\/ USE_V8\n\n if (argc < 2) {\n std::cout << \"usage : \" << argv[0] << \" navigator_directory [user.css]\\n\";\n return EXIT_FAILURE;\n }\n\n init(&argc, argv);\n initLogLevel(&argc, argv);\n initFonts(&argc, argv);\n\n \/\/ Load the default CSS file\n std::string defaultSheet = argv[1];\n defaultSheet += \"\/default.css\";\n getDOMImplementation()->setDefaultCSSStyleSheet(loadStyleSheet(defaultSheet.c_str()));\n\n \/\/ Load the user CSS file\n if (3 <= argc)\n getDOMImplementation()->setUserCSSStyleSheet(loadStyleSheet(argv[2]));\n\n std::thread httpService(std::ref(HttpConnectionManager::getInstance()));\n\n \/\/ Set privileges to the navigator window.\n char navigatorUrl[PATH_MAX + 7];\n strcpy(navigatorUrl, \"file:\/\/\");\n realpath(argv[1], navigatorUrl + 7);\n HttpRequest::setAboutPath(navigatorUrl + 7);\n strcat(navigatorUrl, \"\/navigator.html\");\n WindowImp* imp = new WindowImp();\n window = imp;\n imp->enableZoom(false);\n imp->open(utfconv(navigatorUrl), u\"_self\", u\"\", true);\n\n glutMainLoop();\n\n window = 0;\n\n ECMAScriptContext::shutDown();\n\n HttpConnectionManager::getInstance().stop();\n httpService.join();\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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 \"modules\/perception\/fusion\/common\/information_filter.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace fusion {\n\nInformationFilter::InformationFilter()\n : BaseFilter(\"InformationFilter\"), last_observation_init_(false) {}\n\nbool InformationFilter::Init(const Eigen::VectorXd &global_states,\n const Eigen::MatrixXd &global_uncertainty) {\n if (global_uncertainty.rows() != global_uncertainty.cols()) {\n return false;\n }\n\n states_num_ = static_cast(global_uncertainty.rows());\n\n if (states_num_ <= 0) {\n return false;\n }\n\n if (states_num_ != global_states.rows()) {\n return false;\n }\n\n global_states_ = global_states;\n global_uncertainty_ = global_uncertainty;\n tmp_states_ = global_uncertainty_.inverse() * global_states_;\n\n transform_matrix_.setIdentity(states_num_, states_num_);\n last_to_cur_transform_matrix_.setIdentity(states_num_, states_num_);\n\n cur_observation_.setZero(states_num_, 1);\n cur_observation_uncertainty_.setIdentity(states_num_, states_num_);\n\n last_observation_.setZero(states_num_, 1);\n last_observation_uncertainty_.setIdentity(states_num_, states_num_);\n\n c_matrix_.setIdentity(states_num_, states_num_);\n env_uncertainty_.setZero(states_num_, states_num_);\n\n init_ = true;\n return true;\n}\n\nbool InformationFilter::SetLastObservation(\n const Eigen::VectorXd &last_observation,\n const Eigen::MatrixXd &last_observation_uncertainty,\n const Eigen::MatrixXd &last_to_cur_transform_matrix,\n const Eigen::MatrixXd &last_to_cur_env_uncertainty) {\n if (init_ == false) {\n return false;\n }\n if (last_observation.rows() != states_num_) {\n return false;\n }\n if (last_observation_uncertainty.rows() != states_num_) {\n return false;\n }\n if (last_observation_uncertainty.cols() != states_num_) {\n return false;\n }\n if (last_to_cur_transform_matrix.rows() != states_num_) {\n return false;\n }\n if (last_to_cur_transform_matrix.cols() != states_num_) {\n return false;\n }\n if (last_to_cur_env_uncertainty.rows() != states_num_) {\n return false;\n }\n if (last_to_cur_env_uncertainty.cols() != states_num_) {\n return false;\n }\n\n last_observation_ = last_observation;\n last_observation_uncertainty_ = last_observation_uncertainty;\n last_to_cur_transform_matrix_ = last_to_cur_transform_matrix;\n last_to_cur_env_uncertainty_ = last_to_cur_env_uncertainty;\n last_observation_init_ = true;\n return true;\n}\n\nbool InformationFilter::Predict(const Eigen::MatrixXd &transform_matrix,\n const Eigen::MatrixXd &env_uncertainty) {\n if (init_ == false) {\n return false;\n }\n if (transform_matrix.rows() != states_num_) {\n return false;\n }\n if (transform_matrix.cols() != states_num_) {\n return false;\n }\n if (env_uncertainty.rows() != states_num_) {\n return false;\n }\n if (env_uncertainty.cols() != states_num_) {\n return false;\n }\n transform_matrix_ = transform_matrix;\n env_uncertainty_ = env_uncertainty;\n global_states_ = transform_matrix_ * global_states_;\n global_uncertainty_ =\n transform_matrix_ * global_uncertainty_ * transform_matrix_.transpose() +\n env_uncertainty_;\n return true;\n}\n\nbool InformationFilter::Correct(\n const Eigen::VectorXd &cur_observation,\n const Eigen::MatrixXd &cur_observation_uncertainty) {\n if (init_ == false) {\n return false;\n }\n if (cur_observation.rows() != states_num_) {\n return false;\n }\n if (cur_observation_uncertainty.rows() != states_num_) {\n return false;\n }\n if (cur_observation_uncertainty.cols() != states_num_) {\n return false;\n }\n cur_observation_ = cur_observation;\n cur_observation_uncertainty_ = cur_observation_uncertainty;\n global_uncertainty_ = global_uncertainty_.inverse();\n tmp_states_ = global_uncertainty_ * global_states_;\n cur_observation_uncertainty_ = cur_observation_uncertainty_.inverse();\n if (last_observation_init_) {\n last_observation_ = last_to_cur_transform_matrix_ * last_observation_;\n last_observation_uncertainty_ =\n last_to_cur_transform_matrix_ * last_observation_uncertainty_ *\n last_to_cur_transform_matrix_.transpose() +\n last_to_cur_env_uncertainty_;\n last_observation_uncertainty_ =\n c_matrix_ * last_observation_uncertainty_ * c_matrix_.transpose();\n global_uncertainty_ =\n c_matrix_.transpose() * global_uncertainty_ +\n (c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_ -\n c_matrix_.transpose() * last_observation_uncertainty_.inverse() *\n c_matrix_);\n tmp_states_ +=\n (c_matrix_.transpose() * cur_observation_uncertainty_ *\n cur_observation_ -\n c_matrix_.transpose() * last_observation_uncertainty_.inverse() *\n last_observation_);\n } else {\n global_uncertainty_ +=\n c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_;\n tmp_states_ +=\n c_matrix_.transpose() * cur_observation_uncertainty_ * cur_observation_;\n }\n\n global_states_ = global_uncertainty_.inverse() * tmp_states_;\n last_observation_init_ = false;\n return true;\n}\nbool InformationFilter::SetControlMatrix(\n const Eigen::MatrixXd &control_matrix) {\n if (init_ == false) {\n return false;\n }\n if (control_matrix.rows() != states_num_ ||\n control_matrix.cols() != states_num_) {\n return false;\n }\n c_matrix_ = control_matrix;\n return true;\n}\n\n} \/\/ namespace fusion\n} \/\/ namespace perception\n} \/\/ namespace apollo\nPerception: fixed a bug in information matrix update step (#6190)\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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 \"modules\/perception\/fusion\/common\/information_filter.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace fusion {\n\nInformationFilter::InformationFilter()\n : BaseFilter(\"InformationFilter\"), last_observation_init_(false) {}\n\nbool InformationFilter::Init(const Eigen::VectorXd &global_states,\n const Eigen::MatrixXd &global_uncertainty) {\n if (global_uncertainty.rows() != global_uncertainty.cols()) {\n return false;\n }\n\n states_num_ = static_cast(global_uncertainty.rows());\n\n if (states_num_ <= 0) {\n return false;\n }\n\n if (states_num_ != global_states.rows()) {\n return false;\n }\n\n global_states_ = global_states;\n global_uncertainty_ = global_uncertainty;\n tmp_states_ = global_uncertainty_.inverse() * global_states_;\n\n transform_matrix_.setIdentity(states_num_, states_num_);\n last_to_cur_transform_matrix_.setIdentity(states_num_, states_num_);\n\n cur_observation_.setZero(states_num_, 1);\n cur_observation_uncertainty_.setIdentity(states_num_, states_num_);\n\n last_observation_.setZero(states_num_, 1);\n last_observation_uncertainty_.setIdentity(states_num_, states_num_);\n\n c_matrix_.setIdentity(states_num_, states_num_);\n env_uncertainty_.setZero(states_num_, states_num_);\n\n init_ = true;\n return true;\n}\n\nbool InformationFilter::SetLastObservation(\n const Eigen::VectorXd &last_observation,\n const Eigen::MatrixXd &last_observation_uncertainty,\n const Eigen::MatrixXd &last_to_cur_transform_matrix,\n const Eigen::MatrixXd &last_to_cur_env_uncertainty) {\n if (init_ == false) {\n return false;\n }\n if (last_observation.rows() != states_num_) {\n return false;\n }\n if (last_observation_uncertainty.rows() != states_num_) {\n return false;\n }\n if (last_observation_uncertainty.cols() != states_num_) {\n return false;\n }\n if (last_to_cur_transform_matrix.rows() != states_num_) {\n return false;\n }\n if (last_to_cur_transform_matrix.cols() != states_num_) {\n return false;\n }\n if (last_to_cur_env_uncertainty.rows() != states_num_) {\n return false;\n }\n if (last_to_cur_env_uncertainty.cols() != states_num_) {\n return false;\n }\n\n last_observation_ = last_observation;\n last_observation_uncertainty_ = last_observation_uncertainty;\n last_to_cur_transform_matrix_ = last_to_cur_transform_matrix;\n last_to_cur_env_uncertainty_ = last_to_cur_env_uncertainty;\n last_observation_init_ = true;\n return true;\n}\n\nbool InformationFilter::Predict(const Eigen::MatrixXd &transform_matrix,\n const Eigen::MatrixXd &env_uncertainty) {\n if (init_ == false) {\n return false;\n }\n if (transform_matrix.rows() != states_num_) {\n return false;\n }\n if (transform_matrix.cols() != states_num_) {\n return false;\n }\n if (env_uncertainty.rows() != states_num_) {\n return false;\n }\n if (env_uncertainty.cols() != states_num_) {\n return false;\n }\n transform_matrix_ = transform_matrix;\n env_uncertainty_ = env_uncertainty;\n global_states_ = transform_matrix_ * global_states_;\n global_uncertainty_ =\n transform_matrix_ * global_uncertainty_ * transform_matrix_.transpose() +\n env_uncertainty_;\n return true;\n}\n\nbool InformationFilter::Correct(\n const Eigen::VectorXd &cur_observation,\n const Eigen::MatrixXd &cur_observation_uncertainty) {\n if (init_ == false) {\n return false;\n }\n if (cur_observation.rows() != states_num_) {\n return false;\n }\n if (cur_observation_uncertainty.rows() != states_num_) {\n return false;\n }\n if (cur_observation_uncertainty.cols() != states_num_) {\n return false;\n }\n cur_observation_ = cur_observation;\n cur_observation_uncertainty_ = cur_observation_uncertainty;\n \/\/ global_uncertainty now stores information matrix\n global_uncertainty_ = global_uncertainty_.inverse();\n \/\/ tmp_states_ is information vector\n tmp_states_ = global_uncertainty_ * global_states_;\n \/\/ cur_observation_uncertainty_ is now the inverse of covariance matrix\n cur_observation_uncertainty_ = cur_observation_uncertainty_.inverse();\n if (last_observation_init_) {\n \/\/ propate to current time\n last_observation_ = last_to_cur_transform_matrix_ * last_observation_;\n last_observation_uncertainty_ =\n last_to_cur_transform_matrix_ * last_observation_uncertainty_ *\n last_to_cur_transform_matrix_.transpose() +\n last_to_cur_env_uncertainty_;\n last_observation_uncertainty_ = \/\/ transform to measurement space\n c_matrix_ * last_observation_uncertainty_ * c_matrix_.transpose();\n global_uncertainty_ = \/\/ update information matrix\n global_uncertainty_ +\n (c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_ -\n c_matrix_.transpose() * last_observation_uncertainty_.inverse() *\n c_matrix_);\n tmp_states_ += \/\/ update information vector\n (c_matrix_.transpose() * cur_observation_uncertainty_ *\n cur_observation_ -\n c_matrix_.transpose() * last_observation_uncertainty_.inverse() *\n last_observation_);\n } else {\n global_uncertainty_ +=\n c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_;\n tmp_states_ +=\n c_matrix_.transpose() * cur_observation_uncertainty_ * cur_observation_;\n }\n\n global_states_ = global_uncertainty_.inverse() * tmp_states_;\n last_observation_init_ = false;\n return true;\n}\nbool InformationFilter::SetControlMatrix(\n const Eigen::MatrixXd &control_matrix) {\n if (init_ == false) {\n return false;\n }\n if (control_matrix.rows() != states_num_ ||\n control_matrix.cols() != states_num_) {\n return false;\n }\n c_matrix_ = control_matrix;\n return true;\n}\n\n} \/\/ namespace fusion\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkHardwareSelectionPolyDataPainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHardwareSelectionPolyDataPainter.h\"\n\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkHardwareSelector.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkUnsignedIntArray.h\"\n\nvtkStandardNewMacro(vtkHardwareSelectionPolyDataPainter);\n\/\/-----------------------------------------------------------------------------\nstatic inline int vtkHardwareSelectionPolyDataPainterGetTotalCells(vtkPolyData* pd,\n unsigned long typeflags)\n{\n int total_cells = 0;\n total_cells += (typeflags & vtkPainter::VERTS)?\n pd->GetNumberOfVerts() : 0;\n total_cells += (typeflags & vtkPainter::LINES)?\n pd->GetNumberOfLines() : 0;\n total_cells += (typeflags & vtkPainter::POLYS)?\n pd->GetNumberOfPolys() : 0;\n total_cells += (typeflags & vtkPainter::STRIPS)?\n pd->GetNumberOfStrips() : 0;\n return total_cells;\n}\n\/\/----------------------------------------------------------------------------\nvtkHardwareSelectionPolyDataPainter::vtkHardwareSelectionPolyDataPainter()\n{\n this->EnableSelection = 1;\n this->PointIdArrayName = NULL;\n this->CellIdArrayName = NULL;\n this->ProcessIdArrayName = NULL;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHardwareSelectionPolyDataPainter::~vtkHardwareSelectionPolyDataPainter()\n{\n this->SetPointIdArrayName(NULL);\n this->SetCellIdArrayName(NULL);\n this->SetProcessIdArrayName(NULL);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkHardwareSelectionPolyDataPainter::RenderInternal(\n vtkRenderer* renderer,\n vtkActor* vtkNotUsed(actor),\n unsigned long typeflags,\n bool vtkNotUsed(forceCompileOnly))\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n vtkPainterDeviceAdapter* device =\n renderer->GetRenderWindow()->GetPainterDeviceAdapter();\n if (device == NULL)\n {\n vtkErrorMacro(\"Painter Device Adapter missing!\");\n return;\n }\n\n vtkPolyData* pd = this->GetInputAsPolyData();\n this->TotalCells = vtkHardwareSelectionPolyDataPainterGetTotalCells(pd, typeflags);\n\n if (this->TotalCells == 0)\n {\n \/\/ skip empty polydatas.\n this->TimeToDraw = 0;\n return;\n }\n\n vtkHardwareSelector* selector = renderer->GetSelector();\n if (this->EnableSelection)\n {\n selector->BeginRenderProp();\n if (selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n selector->GetCurrentPass() >= vtkHardwareSelector::ID_LOW24)\n {\n device->MakeVertexEmphasis(true);\n }\n }\n\n this->Timer->StartTimer();\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, pd->GetVerts(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfVerts();\n if (typeflags & vtkPainter::LINES)\n {\n this->DrawCells(VTK_POLY_LINE, pd->GetLines(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfLines();\n if (typeflags & vtkPainter::POLYS)\n {\n this->DrawCells(VTK_POLYGON, pd->GetPolys(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfPolys();\n if (typeflags & vtkPainter::STRIPS)\n {\n this->DrawCells(VTK_TRIANGLE_STRIP, pd->GetStrips(), startCell, renderer);\n }\n if (this->EnableSelection)\n {\n selector->EndRenderProp();\n if (selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n selector->GetCurrentPass() >= vtkHardwareSelector::ID_LOW24)\n {\n device->MakeVertexEmphasis(false);\n }\n }\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkHardwareSelectionPolyDataPainter::DrawCells(\n int mode, vtkCellArray *connectivity, vtkIdType startCellId,\n vtkRenderer *renderer)\n{\n vtkPolyData* pd = this->GetInputAsPolyData();\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkHardwareSelector* selector = renderer->GetSelector();\n int attributeMode = selector->GetFieldAssociation();\n if (attributeMode == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n selector->GetCurrentPass() >= vtkHardwareSelector::ID_LOW24 &&\n this->EnableSelection)\n {\n mode = VTK_POLY_VERTEX;\n }\n\n vtkPoints* p = pd->GetPoints();\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n vtkUnsignedIntArray* procIdsArray = this->ProcessIdArrayName?\n vtkUnsignedIntArray::SafeDownCast(\n pd->GetPointData()->GetArray(this->ProcessIdArrayName)) : NULL;\n\n vtkIdTypeArray* pidArray = this->PointIdArrayName? vtkIdTypeArray::SafeDownCast(\n pd->GetPointData()->GetArray(this->PointIdArrayName)) : NULL;\n\n vtkIdTypeArray* cidArray = this->CellIdArrayName? vtkIdTypeArray::SafeDownCast(\n pd->GetCellData()->GetArray(this->CellIdArrayName)) : NULL;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n \/\/ Note that cell attributes are overridden by point attributes.\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n if (attributeMode == vtkDataObject::FIELD_ASSOCIATION_CELLS &&\n this->EnableSelection)\n {\n selector->RenderAttributeId(\n cidArray? cidArray->GetValue(cellId) : cellId);\n }\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n if (attributeMode == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n this->EnableSelection)\n {\n selector->RenderAttributeId(\n pidArray? pidArray->GetValue(pointId) : pointId);\n }\n if (this->EnableSelection && procIdsArray &&\n selector->GetUseProcessIdFromData())\n {\n selector->RenderProcessId(procIdsArray->GetPointer(0)[pointId]);\n }\n device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3,\n pointtype, voidpoints, 3*pointId);\n }\n device->EndPrimitive();\n cellId++;\n if (count == 10000)\n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHardwareSelectionPolyDataPainter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"EnableSelection: \" << this->EnableSelection << endl;\n os << indent << \"CellIdArrayName: \" <<\n (this->CellIdArrayName? this->CellIdArrayName : NULL) << endl;\n os << indent << \"PointIdArrayName: \" <<\n (this->PointIdArrayName? this->PointIdArrayName: NULL) << endl;\n}\nFix point selection by avoiding the selection to be spilled across block\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkHardwareSelectionPolyDataPainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHardwareSelectionPolyDataPainter.h\"\n\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkHardwareSelector.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkUnsignedIntArray.h\"\n\nvtkStandardNewMacro(vtkHardwareSelectionPolyDataPainter);\n\/\/-----------------------------------------------------------------------------\nstatic inline int vtkHardwareSelectionPolyDataPainterGetTotalCells(vtkPolyData* pd,\n unsigned long typeflags)\n{\n int total_cells = 0;\n total_cells += (typeflags & vtkPainter::VERTS)?\n pd->GetNumberOfVerts() : 0;\n total_cells += (typeflags & vtkPainter::LINES)?\n pd->GetNumberOfLines() : 0;\n total_cells += (typeflags & vtkPainter::POLYS)?\n pd->GetNumberOfPolys() : 0;\n total_cells += (typeflags & vtkPainter::STRIPS)?\n pd->GetNumberOfStrips() : 0;\n return total_cells;\n}\n\/\/----------------------------------------------------------------------------\nvtkHardwareSelectionPolyDataPainter::vtkHardwareSelectionPolyDataPainter()\n{\n this->EnableSelection = 1;\n this->PointIdArrayName = NULL;\n this->CellIdArrayName = NULL;\n this->ProcessIdArrayName = NULL;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHardwareSelectionPolyDataPainter::~vtkHardwareSelectionPolyDataPainter()\n{\n this->SetPointIdArrayName(NULL);\n this->SetCellIdArrayName(NULL);\n this->SetProcessIdArrayName(NULL);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkHardwareSelectionPolyDataPainter::RenderInternal(\n vtkRenderer* renderer,\n vtkActor* vtkNotUsed(actor),\n unsigned long typeflags,\n bool vtkNotUsed(forceCompileOnly))\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n vtkPainterDeviceAdapter* device =\n renderer->GetRenderWindow()->GetPainterDeviceAdapter();\n if (device == NULL)\n {\n vtkErrorMacro(\"Painter Device Adapter missing!\");\n return;\n }\n\n vtkPolyData* pd = this->GetInputAsPolyData();\n this->TotalCells = vtkHardwareSelectionPolyDataPainterGetTotalCells(pd, typeflags);\n\n if (this->TotalCells == 0)\n {\n \/\/ skip empty polydatas.\n this->TimeToDraw = 0;\n return;\n }\n\n vtkHardwareSelector* selector = renderer->GetSelector();\n if (this->EnableSelection)\n {\n selector->BeginRenderProp();\n \/\/ We emphasis the vertex size to make sure they will be properly detected.\n if (selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n selector->GetCurrentPass() > vtkHardwareSelector::ACTOR_PASS)\n {\n device->MakeVertexEmphasis(true);\n }\n }\n\n this->Timer->StartTimer();\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, pd->GetVerts(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfVerts();\n if (typeflags & vtkPainter::LINES)\n {\n this->DrawCells(VTK_POLY_LINE, pd->GetLines(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfLines();\n if (typeflags & vtkPainter::POLYS)\n {\n this->DrawCells(VTK_POLYGON, pd->GetPolys(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfPolys();\n if (typeflags & vtkPainter::STRIPS)\n {\n this->DrawCells(VTK_TRIANGLE_STRIP, pd->GetStrips(), startCell, renderer);\n }\n if (this->EnableSelection)\n {\n selector->EndRenderProp();\n \/\/ We revert back our Vertex emphasis\n if (selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n selector->GetCurrentPass() > vtkHardwareSelector::ACTOR_PASS)\n {\n device->MakeVertexEmphasis(false);\n }\n }\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkHardwareSelectionPolyDataPainter::DrawCells(\n int mode, vtkCellArray *connectivity, vtkIdType startCellId,\n vtkRenderer *renderer)\n{\n vtkPolyData* pd = this->GetInputAsPolyData();\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkHardwareSelector* selector = renderer->GetSelector();\n int attributeMode = selector->GetFieldAssociation();\n \/\/ While looking at point selection we render only vertex so each pass\n \/\/ should fill the same pixels without risking of detecting vertex belonging\n \/\/ to other cells or block. BUT we do that after the ACTOR_PASS to make sure\n \/\/ we have the proper oclusion as we keep the Z-buffer arround. In that way\n \/\/ vertex that are hidden by some surface won't get selected.\n if (attributeMode == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n selector->GetCurrentPass() > vtkHardwareSelector::ACTOR_PASS &&\n this->EnableSelection)\n {\n mode = VTK_POLY_VERTEX;\n }\n\n vtkPoints* p = pd->GetPoints();\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n vtkUnsignedIntArray* procIdsArray = this->ProcessIdArrayName?\n vtkUnsignedIntArray::SafeDownCast(\n pd->GetPointData()->GetArray(this->ProcessIdArrayName)) : NULL;\n\n vtkIdTypeArray* pidArray = this->PointIdArrayName? vtkIdTypeArray::SafeDownCast(\n pd->GetPointData()->GetArray(this->PointIdArrayName)) : NULL;\n\n vtkIdTypeArray* cidArray = this->CellIdArrayName? vtkIdTypeArray::SafeDownCast(\n pd->GetCellData()->GetArray(this->CellIdArrayName)) : NULL;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n \/\/ Note that cell attributes are overridden by point attributes.\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n if (attributeMode == vtkDataObject::FIELD_ASSOCIATION_CELLS &&\n this->EnableSelection)\n {\n selector->RenderAttributeId(\n cidArray? cidArray->GetValue(cellId) : cellId);\n }\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n if (attributeMode == vtkDataObject::FIELD_ASSOCIATION_POINTS &&\n this->EnableSelection)\n {\n selector->RenderAttributeId(\n pidArray? pidArray->GetValue(pointId) : pointId);\n }\n if (this->EnableSelection && procIdsArray &&\n selector->GetUseProcessIdFromData())\n {\n selector->RenderProcessId(procIdsArray->GetPointer(0)[pointId]);\n }\n device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3,\n pointtype, voidpoints, 3*pointId);\n }\n device->EndPrimitive();\n cellId++;\n if (count == 10000)\n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHardwareSelectionPolyDataPainter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"EnableSelection: \" << this->EnableSelection << endl;\n os << indent << \"CellIdArrayName: \" <<\n (this->CellIdArrayName? this->CellIdArrayName : NULL) << endl;\n os << indent << \"PointIdArrayName: \" <<\n (this->PointIdArrayName? this->PointIdArrayName: NULL) << endl;\n}\n<|endoftext|>"} {"text":"\/** Copyright (C) 2017-2018 European Spallation Source *\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ Unit tests for MultiBladeEventBuilder using Google Test.\n\/\/\/ Here the various counters are tested.\n\/\/\/\n\/\/\/ Author: Carsten Søgaard, Niels Bohr Institute, University of Copenhagen\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ FIXME TODO - nolonger valid , new data format\n\n#include \"mbcommon\/MultiBladeEventBuilder.h\"\n#include \"MultiBladeTestData.h\"\n#include \"test\/TestBase.h\"\n\nTEST(MBEventBuilder__Test, DataPointCounter) {\n\n \/\/ Instanciate the event-builder\n multiBladeEventBuilder p;\n\n \/\/ Test proper initialization.\n EXPECT_EQ(0U, p.getNumberOfEvents());\n\n \/\/ In the following: test proper incrementing.\n p.addDataPoint(0, 300, 0);\n EXPECT_EQ(1, p.getNumberOfDatapointsReceived());\n\n p.addDataPoint(1, 300, 1);\n EXPECT_EQ(2, p.getNumberOfDatapointsReceived());\n\n p.addDataPoint(2, 300, 2);\n EXPECT_EQ(3, p.getNumberOfDatapointsReceived());\n\n p.resetCounters();\n EXPECT_EQ(0, p.getNumberOfDatapointsReceived());\n}\n\nTEST(MBEventBuilder__Test, EventCounter) {\n\n \/\/ Test that events are counted correctly\n\n \/\/ Instanciate the event-builder\n multiBladeEventBuilder p;\n\n \/\/ Initialize the expected number of events counter\n uint nevents = 1;\n\n for (uint i = 0; i <= 15; i++) {\n\n \/\/ Read a subset of the test data\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n EXPECT_EQ(datapoint[4], p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]));\n \/\/ Strip data-points\n EXPECT_FALSE(p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]));\n\n \/\/ Validation of event counter\n if (datapoint[4]) {\n EXPECT_EQ(nevents, p.getNumberOfEvents());\n \/\/ Increment validation iterator\n nevents++;\n }\n }\n\n \/\/ Provide a non-adjacent event, which is discarded\n for (uint i = 10; i < 15; i++) {\n\n \/\/ Remove a point (making it non adjacent)\n if (i != 12) {\n \/\/ Read a subset of the test data\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n EXPECT_EQ(datapoint[4], p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]));\n \/\/ Strip data-points\n EXPECT_FALSE(p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]));\n }\n }\n\n \/\/ Validation of event counter at \"end of run\".\n \/\/ The counter was not incremented before, due to the non-adjacent point.\n p.lastPoint();\n EXPECT_EQ(nevents, p.getNumberOfEvents());\n}\n\nTEST(MBEventBuilder__Test, ClusterCounters) {\n\n \/\/ Test the counters of number of points per event\n\n \/\/ Instaciate the event-counter and configure\n multiBladeEventBuilder p;\n p.setTimeWindow(config[0]);\n p.setNumberOfWireChannels(config[1]);\n p.setNumberOfStripChannels(config[2]);\n\n \/\/ Validation counters (similar to those in the event-builder).\n \/\/ Index 0 = 1 datapoint, index 1 = 2 datapoints, etc.\n std::array wireclusterpoints = {{0, 0, 0, 0, 0, 0}};\n std::array stripclusterpoints = {{0, 0, 0, 0, 0, 0}};\n\n \/\/ Counters for number of points per event\n uint wirepoints = 0;\n uint strippoints = 0;\n\n \/\/ Iterator for validation data\n \/\/ std::vector::iterator valw = validation_weighted.begin();\n\n \/\/ Test the case when there are both wire and strip points\n for (uint i = 0; i <= 21; i++) {\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]);\n\n \/\/ Strip data-points\n p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]);\n\n if (!datapoint[4]) {\n\n wirepoints++;\n strippoints++;\n\n } else {\n\n \/\/ Increment the correct positions in the counters\n wireclusterpoints[wirepoints - 1]++;\n stripclusterpoints[strippoints - 1]++;\n\n \/\/ Check all indexes of the counters for each event.\n EXPECT_EQ(wireclusterpoints[0], p.get2DWireClusterCounter()[0]);\n EXPECT_EQ(wireclusterpoints[1], p.get2DWireClusterCounter()[1]);\n EXPECT_EQ(wireclusterpoints[2], p.get2DWireClusterCounter()[2]);\n EXPECT_EQ(wireclusterpoints[3], p.get2DWireClusterCounter()[3]);\n EXPECT_EQ(wireclusterpoints[4], p.get2DWireClusterCounter()[4]);\n EXPECT_EQ(wireclusterpoints[5], p.get2DWireClusterCounter()[5]);\n\n EXPECT_EQ(stripclusterpoints[0], p.get2DStripClusterCounter()[0]);\n EXPECT_EQ(stripclusterpoints[1], p.get2DStripClusterCounter()[1]);\n EXPECT_EQ(stripclusterpoints[2], p.get2DStripClusterCounter()[2]);\n EXPECT_EQ(stripclusterpoints[3], p.get2DStripClusterCounter()[3]);\n EXPECT_EQ(stripclusterpoints[4], p.get2DStripClusterCounter()[4]);\n EXPECT_EQ(stripclusterpoints[5], p.get2DStripClusterCounter()[5]);\n\n \/\/ Reset the points counters (1, since a point is provided when finishing\n \/\/ the cluster\n wirepoints = 1;\n strippoints = 1;\n }\n }\n\n \/\/ End the \"run\" and reset all counters\n p.lastPoint();\n p.resetCounters();\n\n \/\/ Reset counters\n wireclusterpoints = {{0, 0, 0, 0, 0, 0}};\n stripclusterpoints = {{0, 0, 0, 0, 0, 0}};\n\n \/\/ Reset the counters to \"start of run\"\n wirepoints = 0;\n strippoints = 0;\n\n \/\/ Test the case of only wire points\n for (uint i = 0; i <= 21; i++) {\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]);\n\n if (!datapoint[4]) {\n\n wirepoints++;\n\n } else {\n\n \/\/ Incement at the correct index.\n wireclusterpoints[wirepoints - 1]++;\n\n \/\/ Test counter at all indexes\n EXPECT_EQ(wireclusterpoints[0], p.get1DWireClusterCounter()[0]);\n EXPECT_EQ(wireclusterpoints[1], p.get1DWireClusterCounter()[1]);\n EXPECT_EQ(wireclusterpoints[2], p.get1DWireClusterCounter()[2]);\n EXPECT_EQ(wireclusterpoints[3], p.get1DWireClusterCounter()[3]);\n EXPECT_EQ(wireclusterpoints[4], p.get1DWireClusterCounter()[4]);\n EXPECT_EQ(wireclusterpoints[5], p.get1DWireClusterCounter()[5]);\n\n EXPECT_EQ(0, p.get1DStripClusterCounter()[0]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[1]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[2]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[3]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[4]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[5]);\n\n wirepoints = 1;\n }\n }\n\n \/\/ \"End of run\" and reset all counters\n p.lastPoint();\n p.resetCounters();\n\n \/\/ Reset validation counters\n wireclusterpoints = {{0, 0, 0, 0, 0, 0}};\n stripclusterpoints = {{0, 0, 0, 0, 0, 0}};\n\n \/\/ Reset event counters\n wirepoints = 0;\n strippoints = 0;\n\n \/\/ Test the case of only strip points\n for (uint i = 0; i <= 21; i++) {\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Strip data-points\n p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]);\n\n if (!datapoint[4]) {\n\n strippoints++;\n\n EXPECT_EQ(strippoints, p.getStripClusterSize());\n\n } else {\n\n \/\/ Incement at the correct index.\n stripclusterpoints[strippoints - 1]++;\n\n \/\/ Test counter at all indexes\n EXPECT_EQ(0, p.get1DWireClusterCounter()[0]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[1]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[2]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[3]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[4]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[5]);\n\n EXPECT_EQ(stripclusterpoints[0], p.get1DStripClusterCounter()[0]);\n EXPECT_EQ(stripclusterpoints[1], p.get1DStripClusterCounter()[1]);\n EXPECT_EQ(stripclusterpoints[2], p.get1DStripClusterCounter()[2]);\n EXPECT_EQ(stripclusterpoints[3], p.get1DStripClusterCounter()[3]);\n EXPECT_EQ(stripclusterpoints[4], p.get1DStripClusterCounter()[4]);\n EXPECT_EQ(stripclusterpoints[5], p.get1DStripClusterCounter()[5]);\n\n strippoints = 1;\n }\n }\n}\n\nTEST(MBEventBuilder__Test, NoDataRecieved) {\n\n multiBladeEventBuilder p;\n\n EXPECT_EQ(0, p.getNumberOfPositionRejected());\n\n p.lastPoint();\n\n EXPECT_DOUBLE_EQ(-1, p.getWirePosition());\n EXPECT_DOUBLE_EQ(-1, p.getStripPosition());\n\n EXPECT_EQ(1, p.getNumberOfPositionRejected());\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nminor edits II\/** Copyright (C) 2017-2018 European Spallation Source *\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ Unit tests for MultiBladeEventBuilder using Google Test.\n\/\/\/ Here the various counters are tested.\n\/\/\/\n\/\/\/ Author: Carsten Søgaard, Niels Bohr Institute, University of Copenhagen\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ \\todo - nolonger valid - new data format\n\n#include \"mbcommon\/MultiBladeEventBuilder.h\"\n#include \"MultiBladeTestData.h\"\n#include \"test\/TestBase.h\"\n\nTEST(MBEventBuilder__Test, DataPointCounter) {\n\n \/\/ Instanciate the event-builder\n multiBladeEventBuilder p;\n\n \/\/ Test proper initialization.\n EXPECT_EQ(0U, p.getNumberOfEvents());\n\n \/\/ In the following: test proper incrementing.\n p.addDataPoint(0, 300, 0);\n EXPECT_EQ(1, p.getNumberOfDatapointsReceived());\n\n p.addDataPoint(1, 300, 1);\n EXPECT_EQ(2, p.getNumberOfDatapointsReceived());\n\n p.addDataPoint(2, 300, 2);\n EXPECT_EQ(3, p.getNumberOfDatapointsReceived());\n\n p.resetCounters();\n EXPECT_EQ(0, p.getNumberOfDatapointsReceived());\n}\n\nTEST(MBEventBuilder__Test, EventCounter) {\n\n \/\/ Test that events are counted correctly\n\n \/\/ Instanciate the event-builder\n multiBladeEventBuilder p;\n\n \/\/ Initialize the expected number of events counter\n uint nevents = 1;\n\n for (uint i = 0; i <= 15; i++) {\n\n \/\/ Read a subset of the test data\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n EXPECT_EQ(datapoint[4], p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]));\n \/\/ Strip data-points\n EXPECT_FALSE(p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]));\n\n \/\/ Validation of event counter\n if (datapoint[4]) {\n EXPECT_EQ(nevents, p.getNumberOfEvents());\n \/\/ Increment validation iterator\n nevents++;\n }\n }\n\n \/\/ Provide a non-adjacent event, which is discarded\n for (uint i = 10; i < 15; i++) {\n\n \/\/ Remove a point (making it non adjacent)\n if (i != 12) {\n \/\/ Read a subset of the test data\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n EXPECT_EQ(datapoint[4], p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]));\n \/\/ Strip data-points\n EXPECT_FALSE(p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]));\n }\n }\n\n \/\/ Validation of event counter at \"end of run\".\n \/\/ The counter was not incremented before, due to the non-adjacent point.\n p.lastPoint();\n EXPECT_EQ(nevents, p.getNumberOfEvents());\n}\n\nTEST(MBEventBuilder__Test, ClusterCounters) {\n\n \/\/ Test the counters of number of points per event\n\n \/\/ Instaciate the event-counter and configure\n multiBladeEventBuilder p;\n p.setTimeWindow(config[0]);\n p.setNumberOfWireChannels(config[1]);\n p.setNumberOfStripChannels(config[2]);\n\n \/\/ Validation counters (similar to those in the event-builder).\n \/\/ Index 0 = 1 datapoint, index 1 = 2 datapoints, etc.\n std::array wireclusterpoints = {{0, 0, 0, 0, 0, 0}};\n std::array stripclusterpoints = {{0, 0, 0, 0, 0, 0}};\n\n \/\/ Counters for number of points per event\n uint wirepoints = 0;\n uint strippoints = 0;\n\n \/\/ Iterator for validation data\n \/\/ std::vector::iterator valw = validation_weighted.begin();\n\n \/\/ Test the case when there are both wire and strip points\n for (uint i = 0; i <= 21; i++) {\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]);\n\n \/\/ Strip data-points\n p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]);\n\n if (!datapoint[4]) {\n\n wirepoints++;\n strippoints++;\n\n } else {\n\n \/\/ Increment the correct positions in the counters\n wireclusterpoints[wirepoints - 1]++;\n stripclusterpoints[strippoints - 1]++;\n\n \/\/ Check all indexes of the counters for each event.\n EXPECT_EQ(wireclusterpoints[0], p.get2DWireClusterCounter()[0]);\n EXPECT_EQ(wireclusterpoints[1], p.get2DWireClusterCounter()[1]);\n EXPECT_EQ(wireclusterpoints[2], p.get2DWireClusterCounter()[2]);\n EXPECT_EQ(wireclusterpoints[3], p.get2DWireClusterCounter()[3]);\n EXPECT_EQ(wireclusterpoints[4], p.get2DWireClusterCounter()[4]);\n EXPECT_EQ(wireclusterpoints[5], p.get2DWireClusterCounter()[5]);\n\n EXPECT_EQ(stripclusterpoints[0], p.get2DStripClusterCounter()[0]);\n EXPECT_EQ(stripclusterpoints[1], p.get2DStripClusterCounter()[1]);\n EXPECT_EQ(stripclusterpoints[2], p.get2DStripClusterCounter()[2]);\n EXPECT_EQ(stripclusterpoints[3], p.get2DStripClusterCounter()[3]);\n EXPECT_EQ(stripclusterpoints[4], p.get2DStripClusterCounter()[4]);\n EXPECT_EQ(stripclusterpoints[5], p.get2DStripClusterCounter()[5]);\n\n \/\/ Reset the points counters (1, since a point is provided when finishing\n \/\/ the cluster\n wirepoints = 1;\n strippoints = 1;\n }\n }\n\n \/\/ End the \"run\" and reset all counters\n p.lastPoint();\n p.resetCounters();\n\n \/\/ Reset counters\n wireclusterpoints = {{0, 0, 0, 0, 0, 0}};\n stripclusterpoints = {{0, 0, 0, 0, 0, 0}};\n\n \/\/ Reset the counters to \"start of run\"\n wirepoints = 0;\n strippoints = 0;\n\n \/\/ Test the case of only wire points\n for (uint i = 0; i <= 21; i++) {\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Wire data-points\n p.addDataPoint(datapoint[0], datapoint[2], datapoint[3]);\n\n if (!datapoint[4]) {\n\n wirepoints++;\n\n } else {\n\n \/\/ Incement at the correct index.\n wireclusterpoints[wirepoints - 1]++;\n\n \/\/ Test counter at all indexes\n EXPECT_EQ(wireclusterpoints[0], p.get1DWireClusterCounter()[0]);\n EXPECT_EQ(wireclusterpoints[1], p.get1DWireClusterCounter()[1]);\n EXPECT_EQ(wireclusterpoints[2], p.get1DWireClusterCounter()[2]);\n EXPECT_EQ(wireclusterpoints[3], p.get1DWireClusterCounter()[3]);\n EXPECT_EQ(wireclusterpoints[4], p.get1DWireClusterCounter()[4]);\n EXPECT_EQ(wireclusterpoints[5], p.get1DWireClusterCounter()[5]);\n\n EXPECT_EQ(0, p.get1DStripClusterCounter()[0]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[1]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[2]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[3]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[4]);\n EXPECT_EQ(0, p.get1DStripClusterCounter()[5]);\n\n wirepoints = 1;\n }\n }\n\n \/\/ \"End of run\" and reset all counters\n p.lastPoint();\n p.resetCounters();\n\n \/\/ Reset validation counters\n wireclusterpoints = {{0, 0, 0, 0, 0, 0}};\n stripclusterpoints = {{0, 0, 0, 0, 0, 0}};\n\n \/\/ Reset event counters\n wirepoints = 0;\n strippoints = 0;\n\n \/\/ Test the case of only strip points\n for (uint i = 0; i <= 21; i++) {\n uint begin = i * 5;\n uint end = begin + 5;\n std::vector datapoint(&data[begin], &data[end]);\n \/\/ Strip data-points\n p.addDataPoint(datapoint[1], datapoint[2], datapoint[3]);\n\n if (!datapoint[4]) {\n\n strippoints++;\n\n EXPECT_EQ(strippoints, p.getStripClusterSize());\n\n } else {\n\n \/\/ Incement at the correct index.\n stripclusterpoints[strippoints - 1]++;\n\n \/\/ Test counter at all indexes\n EXPECT_EQ(0, p.get1DWireClusterCounter()[0]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[1]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[2]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[3]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[4]);\n EXPECT_EQ(0, p.get1DWireClusterCounter()[5]);\n\n EXPECT_EQ(stripclusterpoints[0], p.get1DStripClusterCounter()[0]);\n EXPECT_EQ(stripclusterpoints[1], p.get1DStripClusterCounter()[1]);\n EXPECT_EQ(stripclusterpoints[2], p.get1DStripClusterCounter()[2]);\n EXPECT_EQ(stripclusterpoints[3], p.get1DStripClusterCounter()[3]);\n EXPECT_EQ(stripclusterpoints[4], p.get1DStripClusterCounter()[4]);\n EXPECT_EQ(stripclusterpoints[5], p.get1DStripClusterCounter()[5]);\n\n strippoints = 1;\n }\n }\n}\n\nTEST(MBEventBuilder__Test, NoDataRecieved) {\n\n multiBladeEventBuilder p;\n\n EXPECT_EQ(0, p.getNumberOfPositionRejected());\n\n p.lastPoint();\n\n EXPECT_DOUBLE_EQ(-1, p.getWirePosition());\n EXPECT_DOUBLE_EQ(-1, p.getStripPosition());\n\n EXPECT_EQ(1, p.getNumberOfPositionRejected());\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#ifndef PLUGIN_H\n#define PLUGIN_H\n\n#include \n#include \n#include \"wayfire\/util.hpp\"\n#include \"wayfire\/bindings.hpp\"\n\n#include \n\nclass wayfire_config;\nnamespace wf\n{\nclass output_t;\n\n\/**\n * Plugins can set their capabilities to indicate what kind of plugin they are.\n * At any point, only one plugin with a given capability can be active on its\n * output (although multiple plugins with the same capability can be loaded).\n *\/\nenum plugin_capabilities_t\n{\n \/** The plugin provides view decorations *\/\n CAPABILITY_VIEW_DECORATOR = 1 << 0,\n \/** The plugin grabs input.\n * Required in order to use plugin_grab_interface_t::grab() *\/\n CAPABILITY_GRAB_INPUT = 1 << 1,\n \/** The plugin uses custom renderer *\/\n CAPABILITY_CUSTOM_RENDERER = 1 << 2,\n \/** The plugin manages the whole desktop, for ex. switches workspaces. *\/\n CAPABILITY_MANAGE_DESKTOP = 1 << 3,\n \/* Compound capabilities *\/\n\n \/** The plugin manages the whole compositor state *\/\n CAPABILITY_MANAGE_COMPOSITOR = CAPABILITY_GRAB_INPUT |\n CAPABILITY_MANAGE_DESKTOP | CAPABILITY_CUSTOM_RENDERER,\n};\n\n\/**\n * The plugin grab interface is what the plugins use to announce themselves to\n * the core and other plugins as active, and to request to grab input.\n *\/\nstruct plugin_grab_interface_t\n{\n private:\n bool grabbed = false;\n\n public:\n \/** The name of the plugin. Not important *\/\n std::string name;\n \/** The plugin capabilities. A bitmask of the values specified above *\/\n uint32_t capabilities;\n \/** The output the grab interface is on *\/\n wf::output_t*const output;\n\n plugin_grab_interface_t(wf::output_t *_output);\n\n \/**\n * Grab the input on the output. Requires CAPABILITY_GRAB_INPUT.\n * On successful grab, core will reset keyboard\/pointer\/touch focus.\n *\n * @return True if input was successfully grabbed.\n *\/\n bool grab();\n \/** @return If the grab interface is grabbed *\/\n bool is_grabbed();\n \/** Ungrab input, if it is grabbed. *\/\n void ungrab();\n\n \/**\n * When grabbed, core will redirect all input events to the grabbing plugin.\n * The grabbing plugin can subscribe to different input events by setting\n * the callbacks below.\n *\/\n struct\n {\n struct\n {\n std::function axis;\n std::function button; \/\/ button, state\n std::function motion; \/\/ x, y\n std::function relative_motion;\n } pointer;\n\n struct\n {\n std::function key; \/\/ button, state\n std::function mod; \/\/ modifier, state\n } keyboard;\n\n struct\n {\n std::function down; \/\/ id, x, y\n std::function up; \/\/ id\n std::function motion; \/\/ id, x, y\n } touch;\n\n \/**\n * Each plugin might be deactivated forcefully, for example when the\n * desktop is locked. Plugins MUST honor this signal and exit their\n * grabs\/renderers immediately.\n *\n * Note that cancel() is emitted even when the plugin is just activated\n * without grabbing input.\n *\/\n std::function cancel;\n } callbacks;\n};\n\nusing plugin_grab_interface_uptr = std::unique_ptr;\n\nclass plugin_interface_t\n{\n public:\n \/**\n * The output this plugin is running on. Initialized by core.\n * Each output has its own set of plugin instances. This way, a plugin\n * rarely if ever needs to care about multi-monitor setups.\n *\/\n wf::output_t *output;\n\n \/**\n * The grab interface of the plugin, initialized by core.\n *\/\n std::unique_ptr grab_interface;\n\n \/**\n * The init method is the entry of the plugin. In the init() method, the\n * plugin should register all bindings it provides, connect to signals, etc.\n *\/\n virtual void init() = 0;\n\n \/**\n * The fini method is called when a plugin is unloaded. It should clean up\n * all global state it has set (for ex. signal callbacks, bindings, ...),\n * because the plugin will be freed after this.\n *\/\n virtual void fini();\n\n \/**\n * A plugin can request that it is never unloaded, even if it is removed\n * from the config's plugin list.\n *\n * Note that unloading a plugin is sometimes unavoidable, for ex. when the\n * output the plugin is running on is destroyed. So non-unloadable plugins\n * should still provide proper fini() methods.\n *\/\n virtual bool is_unloadable()\n {\n return true;\n }\n\n virtual ~plugin_interface_t();\n\n \/** Handle to the plugin's .so file, used by the plugin loader *\/\n void *handle = NULL;\n};\n}\n\n\/**\n * Each plugin must provide a function which instantiates the plugin's class\n * and returns the instance.\n *\n * This function must have the name newInstance() and should be declared with\n * extern \"C\" so that the loader can find it.\n *\/\nusing wayfire_plugin_load_func = wf::plugin_interface_t * (*)();\n\n\/** The version of Wayfire's API\/ABI *\/\nconstexpr uint32_t WAYFIRE_API_ABI_VERSION = 2021'09'09;\n\n\/**\n * Each plugin must also provide a function which returns the Wayfire API\/ABI\n * that it was compiled with.\n *\n * This function must have the name getWayfireVersion() and should be declared\n * with extern \"C\" so that the loader can find it.\n *\/\nusing wayfire_plugin_version_func = uint32_t (*)();\n\n\/**\n * A macro to declare the necessary functions, given the plugin class name\n *\/\n#define DECLARE_WAYFIRE_PLUGIN(PluginClass) \\\n extern \"C\" \\\n { \\\n wf::plugin_interface_t*newInstance() { return new PluginClass; } \\\n uint32_t getWayfireVersion() { return WAYFIRE_API_ABI_VERSION; } \\\n }\n\n#endif\napi: bump version because of header changes#ifndef PLUGIN_H\n#define PLUGIN_H\n\n#include \n#include \n#include \"wayfire\/util.hpp\"\n#include \"wayfire\/bindings.hpp\"\n\n#include \n\nclass wayfire_config;\nnamespace wf\n{\nclass output_t;\n\n\/**\n * Plugins can set their capabilities to indicate what kind of plugin they are.\n * At any point, only one plugin with a given capability can be active on its\n * output (although multiple plugins with the same capability can be loaded).\n *\/\nenum plugin_capabilities_t\n{\n \/** The plugin provides view decorations *\/\n CAPABILITY_VIEW_DECORATOR = 1 << 0,\n \/** The plugin grabs input.\n * Required in order to use plugin_grab_interface_t::grab() *\/\n CAPABILITY_GRAB_INPUT = 1 << 1,\n \/** The plugin uses custom renderer *\/\n CAPABILITY_CUSTOM_RENDERER = 1 << 2,\n \/** The plugin manages the whole desktop, for ex. switches workspaces. *\/\n CAPABILITY_MANAGE_DESKTOP = 1 << 3,\n \/* Compound capabilities *\/\n\n \/** The plugin manages the whole compositor state *\/\n CAPABILITY_MANAGE_COMPOSITOR = CAPABILITY_GRAB_INPUT |\n CAPABILITY_MANAGE_DESKTOP | CAPABILITY_CUSTOM_RENDERER,\n};\n\n\/**\n * The plugin grab interface is what the plugins use to announce themselves to\n * the core and other plugins as active, and to request to grab input.\n *\/\nstruct plugin_grab_interface_t\n{\n private:\n bool grabbed = false;\n\n public:\n \/** The name of the plugin. Not important *\/\n std::string name;\n \/** The plugin capabilities. A bitmask of the values specified above *\/\n uint32_t capabilities;\n \/** The output the grab interface is on *\/\n wf::output_t*const output;\n\n plugin_grab_interface_t(wf::output_t *_output);\n\n \/**\n * Grab the input on the output. Requires CAPABILITY_GRAB_INPUT.\n * On successful grab, core will reset keyboard\/pointer\/touch focus.\n *\n * @return True if input was successfully grabbed.\n *\/\n bool grab();\n \/** @return If the grab interface is grabbed *\/\n bool is_grabbed();\n \/** Ungrab input, if it is grabbed. *\/\n void ungrab();\n\n \/**\n * When grabbed, core will redirect all input events to the grabbing plugin.\n * The grabbing plugin can subscribe to different input events by setting\n * the callbacks below.\n *\/\n struct\n {\n struct\n {\n std::function axis;\n std::function button; \/\/ button, state\n std::function motion; \/\/ x, y\n std::function relative_motion;\n } pointer;\n\n struct\n {\n std::function key; \/\/ button, state\n std::function mod; \/\/ modifier, state\n } keyboard;\n\n struct\n {\n std::function down; \/\/ id, x, y\n std::function up; \/\/ id\n std::function motion; \/\/ id, x, y\n } touch;\n\n \/**\n * Each plugin might be deactivated forcefully, for example when the\n * desktop is locked. Plugins MUST honor this signal and exit their\n * grabs\/renderers immediately.\n *\n * Note that cancel() is emitted even when the plugin is just activated\n * without grabbing input.\n *\/\n std::function cancel;\n } callbacks;\n};\n\nusing plugin_grab_interface_uptr = std::unique_ptr;\n\nclass plugin_interface_t\n{\n public:\n \/**\n * The output this plugin is running on. Initialized by core.\n * Each output has its own set of plugin instances. This way, a plugin\n * rarely if ever needs to care about multi-monitor setups.\n *\/\n wf::output_t *output;\n\n \/**\n * The grab interface of the plugin, initialized by core.\n *\/\n std::unique_ptr grab_interface;\n\n \/**\n * The init method is the entry of the plugin. In the init() method, the\n * plugin should register all bindings it provides, connect to signals, etc.\n *\/\n virtual void init() = 0;\n\n \/**\n * The fini method is called when a plugin is unloaded. It should clean up\n * all global state it has set (for ex. signal callbacks, bindings, ...),\n * because the plugin will be freed after this.\n *\/\n virtual void fini();\n\n \/**\n * A plugin can request that it is never unloaded, even if it is removed\n * from the config's plugin list.\n *\n * Note that unloading a plugin is sometimes unavoidable, for ex. when the\n * output the plugin is running on is destroyed. So non-unloadable plugins\n * should still provide proper fini() methods.\n *\/\n virtual bool is_unloadable()\n {\n return true;\n }\n\n virtual ~plugin_interface_t();\n\n \/** Handle to the plugin's .so file, used by the plugin loader *\/\n void *handle = NULL;\n};\n}\n\n\/**\n * Each plugin must provide a function which instantiates the plugin's class\n * and returns the instance.\n *\n * This function must have the name newInstance() and should be declared with\n * extern \"C\" so that the loader can find it.\n *\/\nusing wayfire_plugin_load_func = wf::plugin_interface_t * (*)();\n\n\/** The version of Wayfire's API\/ABI *\/\nconstexpr uint32_t WAYFIRE_API_ABI_VERSION = 2021'10'12;\n\n\/**\n * Each plugin must also provide a function which returns the Wayfire API\/ABI\n * that it was compiled with.\n *\n * This function must have the name getWayfireVersion() and should be declared\n * with extern \"C\" so that the loader can find it.\n *\/\nusing wayfire_plugin_version_func = uint32_t (*)();\n\n\/**\n * A macro to declare the necessary functions, given the plugin class name\n *\/\n#define DECLARE_WAYFIRE_PLUGIN(PluginClass) \\\n extern \"C\" \\\n { \\\n wf::plugin_interface_t*newInstance() { return new PluginClass; } \\\n uint32_t getWayfireVersion() { return WAYFIRE_API_ABI_VERSION; } \\\n }\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nstd::string default_method = \"radius\";\n\nint default_mean_k = 2;\ndouble default_std_dev_mul = 0.0;\nint default_negative = 1;\n\ndouble default_radius = 0.0;\nint default_min_pts = 0;\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -method X = the outlier removal method to be used (options: radius \/ statistical) (default: \");\n print_value (\"%s\", default_method.c_str ()); print_info (\")\\n\");\n print_info (\" -radius X = (RadiusOutlierRemoval) the sphere radius used for determining the k-nearest neighbors (default: \");\n print_value (\"%d\", default_min_pts); print_info (\")\\n\");\n print_info (\" -min_pts X = (RadiusOutlierRemoval) the minimum number of neighbors that a point needs to have in the given search radius in order to be considered an inlier (default: \");\n print_value (\"%d\", default_min_pts); print_info (\")\\n\");\n print_info (\" -mean_k X = (StatisticalOutlierRemoval only) the number of points to use for mean distance estimation (default: \");\n print_value (\"%d\", default_mean_k); print_info (\")\\n\");\n print_info (\" -std_dev_mul X = (StatisticalOutlierRemoval only) the standard deviation multiplier threshold (default: \");\n print_value (\"%f\", default_std_dev_mul); print_info (\")\\n\");\n print_info (\" -inliers X = (StatisticalOutlierRemoval only) decides whether the inliers should be returned (1), or the outliers (0). (default: \");\n print_value (\"%d\", default_negative); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n std::string method,\n int min_pts, double radius,\n int mean_k, double std_dev_mul, bool negative)\n{\n\n PointCloud::Ptr xyz_cloud_pre (new pcl::PointCloud ()),\n xyz_cloud (new pcl::PointCloud ());\n fromROSMsg (*input, *xyz_cloud_pre);\n \n std::vector index_vector;\n removeNaNFromPointCloud (*xyz_cloud_pre, *xyz_cloud, index_vector);\n\n \n TicToc tt;\n tt.tic ();\n PointCloud::Ptr xyz_cloud_filtered (new PointCloud ());\n if (method == \"statistical\")\n {\n StatisticalOutlierRemoval filter;\n filter.setInputCloud (xyz_cloud);\n filter.setMeanK (mean_k);\n filter.setStddevMulThresh (std_dev_mul);\n filter.setNegative (negative);\n PCL_INFO (\"Computing filtered cloud with mean_k %d, std_dev_mul %f, inliers %d\\n\", filter.getMeanK (), filter.getStddevMulThresh (), filter.getNegative ());\n filter.filter (*xyz_cloud_filtered);\n }\n else if (method == \"radius\")\n {\n RadiusOutlierRemoval filter;\n filter.setInputCloud (xyz_cloud);\n filter.setRadiusSearch (radius);\n filter.setMinNeighborsInRadius (min_pts);\n PCL_INFO (\"Computing filtered cloud with radius %f, min_pts %d\\n\", radius, min_pts);\n filter.filter (*xyz_cloud_filtered);\n }\n else\n {\n PCL_ERROR (\"%s is not a valid filter name! Quitting!\\n\", method.c_str ());\n return;\n }\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", xyz_cloud_filtered->width * xyz_cloud_filtered->height); print_info (\" points]\\n\");\n\n toROSMsg (*xyz_cloud_filtered, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n\n pcl::io::savePCDFile (filename, output, Eigen::Vector4f::Zero (),\n Eigen::Quaternionf::Identity (), true);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Statistical Outlier Removal filtering of a point cloud. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n std::string method = default_method;\n int min_pts = default_min_pts;\n double radius = default_radius;\n int mean_k = default_mean_k;\n double std_dev_mul = default_std_dev_mul;\n int negative = default_negative;\n \n\n parse_argument (argc, argv, \"-method\", method);\n parse_argument (argc, argv, \"-radius\", radius);\n parse_argument (argc, argv, \"-min_pts\", min_pts);\n parse_argument (argc, argv, \"-mean_k\", mean_k);\n parse_argument (argc, argv, \"-std_dev_mul\", std_dev_mul);\n parse_argument (argc, argv, \"-inliers\", negative);\n \n \n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud))\n return (-1);\n\n \/\/ Do the smoothing\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, method, min_pts, radius, mean_k, std_dev_mul, negative);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\nadded keep_organized switch\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nstd::string default_method = \"radius\";\n\nint default_mean_k = 2;\ndouble default_std_dev_mul = 0.0;\nint default_negative = 1;\n\ndouble default_radius = 0.0;\nint default_min_pts = 0;\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -method X = the outlier removal method to be used (options: radius \/ statistical) (default: \");\n print_value (\"%s\", default_method.c_str ()); print_info (\")\\n\");\n print_info (\" -radius X = (RadiusOutlierRemoval) the sphere radius used for determining the k-nearest neighbors (default: \");\n print_value (\"%d\", default_min_pts); print_info (\")\\n\");\n print_info (\" -min_pts X = (RadiusOutlierRemoval) the minimum number of neighbors that a point needs to have in the given search radius in order to be considered an inlier (default: \");\n print_value (\"%d\", default_min_pts); print_info (\")\\n\");\n print_info (\" -mean_k X = (StatisticalOutlierRemoval only) the number of points to use for mean distance estimation (default: \");\n print_value (\"%d\", default_mean_k); print_info (\")\\n\");\n print_info (\" -std_dev_mul X = (StatisticalOutlierRemoval only) the standard deviation multiplier threshold (default: \");\n print_value (\"%f\", default_std_dev_mul); print_info (\")\\n\");\n print_info (\" -inliers X = (StatisticalOutlierRemoval only) decides whether the inliers should be returned (1), or the outliers (0). (default: \");\n print_value (\"%d\", default_negative); print_info (\")\\n\");\n print_info (\" -keep_organized\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n std::string method,\n int min_pts, double radius,\n int mean_k, double std_dev_mul, bool negative, bool keep_organized)\n{\n\n PointCloud::Ptr xyz_cloud_pre (new pcl::PointCloud ()),\n xyz_cloud (new pcl::PointCloud ());\n fromROSMsg (*input, *xyz_cloud_pre);\n \n \/\/std::vector index_vector;\n \/\/removeNaNFromPointCloud (*xyz_cloud_pre, *xyz_cloud, index_vector);\n\n xyz_cloud = xyz_cloud_pre;\n \n TicToc tt;\n tt.tic ();\n PointCloud::Ptr xyz_cloud_filtered (new PointCloud ());\n if (method == \"statistical\")\n {\n StatisticalOutlierRemoval filter;\n filter.setInputCloud (xyz_cloud);\n filter.setMeanK (mean_k);\n filter.setStddevMulThresh (std_dev_mul);\n filter.setNegative (negative);\n filter.setKeepOrganized (keep_organized);\n PCL_INFO (\"Computing filtered cloud with mean_k %d, std_dev_mul %f, inliers %d\\n\", filter.getMeanK (), filter.getStddevMulThresh (), filter.getNegative ());\n filter.filter (*xyz_cloud_filtered);\n }\n else if (method == \"radius\")\n {\n RadiusOutlierRemoval filter;\n filter.setInputCloud (xyz_cloud);\n filter.setRadiusSearch (radius);\n filter.setMinNeighborsInRadius (min_pts);\n filter.setKeepOrganized (keep_organized);\n PCL_INFO (\"Computing filtered cloud with radius %f, min_pts %d\\n\", radius, min_pts);\n filter.filter (*xyz_cloud_filtered);\n }\n else\n {\n PCL_ERROR (\"%s is not a valid filter name! Quitting!\\n\", method.c_str ());\n return;\n }\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", xyz_cloud_filtered->width * xyz_cloud_filtered->height); print_info (\" points]\\n\");\n\n toROSMsg (*xyz_cloud_filtered, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n\n pcl::io::savePCDFile (filename, output, Eigen::Vector4f::Zero (),\n Eigen::Quaternionf::Identity (), true);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Statistical Outlier Removal filtering of a point cloud. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n std::string method = default_method;\n int min_pts = default_min_pts;\n double radius = default_radius;\n int mean_k = default_mean_k;\n double std_dev_mul = default_std_dev_mul;\n int negative = default_negative;\n \n\n parse_argument (argc, argv, \"-method\", method);\n parse_argument (argc, argv, \"-radius\", radius);\n parse_argument (argc, argv, \"-min_pts\", min_pts);\n parse_argument (argc, argv, \"-mean_k\", mean_k);\n parse_argument (argc, argv, \"-std_dev_mul\", std_dev_mul);\n parse_argument (argc, argv, \"-inliers\", negative);\n bool keep_organized = find_switch (argc, argv, \"-keep_organized\");\n \n \n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud))\n return (-1);\n\n \/\/ Do the smoothing\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, method, min_pts, radius, mean_k, std_dev_mul, negative, keep_organized);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"webrtc\/modules\/desktop_capture\/mouse_cursor_monitor.h\"\n\n#include \n#include \n#include \n\n#include \"webrtc\/modules\/desktop_capture\/desktop_capture_options.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame.h\"\n#include \"webrtc\/modules\/desktop_capture\/mouse_cursor.h\"\n#include \"webrtc\/modules\/desktop_capture\/x11\/x_error_trap.h\"\n#include \"webrtc\/system_wrappers\/include\/logging.h\"\n\nnamespace {\n\n\/\/ WindowCapturer returns window IDs of X11 windows with WM_STATE attribute.\n\/\/ These windows may not be immediate children of the root window, because\n\/\/ window managers may re-parent them to add decorations. However,\n\/\/ XQueryPointer() expects to be passed children of the root. This function\n\/\/ searches up the list of the windows to find the root child that corresponds\n\/\/ to |window|.\nWindow GetTopLevelWindow(Display* display, Window window) {\n while (true) {\n \/\/ If the window is in WithdrawnState then look at all of its children.\n ::Window root, parent;\n ::Window *children;\n unsigned int num_children;\n if (!XQueryTree(display, window, &root, &parent, &children,\n &num_children)) {\n LOG(LS_ERROR) << \"Failed to query for child windows although window\"\n << \"does not have a valid WM_STATE.\";\n return None;\n }\n if (children)\n XFree(children);\n\n if (parent == root)\n break;\n\n window = parent;\n }\n\n return window;\n}\n\n} \/\/ namespace\n\nnamespace webrtc {\n\nclass MouseCursorMonitorX11 : public MouseCursorMonitor,\n public SharedXDisplay::XEventHandler {\n public:\n MouseCursorMonitorX11(const DesktopCaptureOptions& options, Window window);\n ~MouseCursorMonitorX11() override;\n\n void Init(Callback* callback, Mode mode) override;\n void Capture() override;\n\n private:\n \/\/ SharedXDisplay::XEventHandler interface.\n bool HandleXEvent(const XEvent& event) override;\n\n Display* display() { return x_display_->display(); }\n\n \/\/ Captures current cursor shape and stores it in |cursor_shape_|.\n void CaptureCursor();\n\n rtc::scoped_refptr x_display_;\n Callback* callback_;\n Mode mode_;\n Window window_;\n\n bool have_xfixes_;\n int xfixes_event_base_;\n int xfixes_error_base_;\n\n std::unique_ptr cursor_shape_;\n};\n\nMouseCursorMonitorX11::MouseCursorMonitorX11(\n const DesktopCaptureOptions& options,\n Window window)\n : x_display_(options.x_display()),\n callback_(NULL),\n mode_(SHAPE_AND_POSITION),\n window_(window),\n have_xfixes_(false),\n xfixes_event_base_(-1),\n xfixes_error_base_(-1) {}\n\nMouseCursorMonitorX11::~MouseCursorMonitorX11() {\n if (have_xfixes_) {\n x_display_->RemoveEventHandler(xfixes_event_base_ + XFixesCursorNotify,\n this);\n }\n}\n\nvoid MouseCursorMonitorX11::Init(Callback* callback, Mode mode) {\n \/\/ Init can be called only once per instance of MouseCursorMonitor.\n assert(!callback_);\n assert(callback);\n\n callback_ = callback;\n mode_ = mode;\n\n have_xfixes_ =\n XFixesQueryExtension(display(), &xfixes_event_base_, &xfixes_error_base_);\n\n if (have_xfixes_) {\n \/\/ Register for changes to the cursor shape.\n XFixesSelectCursorInput(display(), window_, XFixesDisplayCursorNotifyMask);\n x_display_->AddEventHandler(xfixes_event_base_ + XFixesCursorNotify, this);\n\n CaptureCursor();\n } else {\n LOG(LS_INFO) << \"X server does not support XFixes.\";\n }\n}\n\nvoid MouseCursorMonitorX11::Capture() {\n assert(callback_);\n\n \/\/ Process X11 events in case XFixes has sent cursor notification.\n x_display_->ProcessPendingXEvents();\n\n \/\/ cursor_shape_| is set only if we were notified of a cursor shape change.\n if (cursor_shape_.get())\n callback_->OnMouseCursor(cursor_shape_.release());\n\n \/\/ Get cursor position if necessary.\n if (mode_ == SHAPE_AND_POSITION) {\n int root_x;\n int root_y;\n int win_x;\n int win_y;\n Window root_window;\n Window child_window;\n unsigned int mask;\n\n XErrorTrap error_trap(display());\n Bool result = XQueryPointer(display(), window_, &root_window, &child_window,\n &root_x, &root_y, &win_x, &win_y, &mask);\n CursorState state;\n if (!result || error_trap.GetLastErrorAndDisable() != 0) {\n state = OUTSIDE;\n } else {\n \/\/ In screen mode (window_ == root_window) the mouse is always inside.\n \/\/ XQueryPointer() sets |child_window| to None if the cursor is outside\n \/\/ |window_|.\n state =\n (window_ == root_window || child_window != None) ? INSIDE : OUTSIDE;\n }\n\n callback_->OnMouseCursorPosition(state,\n webrtc::DesktopVector(win_x, win_y));\n }\n}\n\nbool MouseCursorMonitorX11::HandleXEvent(const XEvent& event) {\n if (have_xfixes_ && event.type == xfixes_event_base_ + XFixesCursorNotify) {\n const XFixesCursorNotifyEvent* cursor_event =\n reinterpret_cast(&event);\n if (cursor_event->subtype == XFixesDisplayCursorNotify) {\n CaptureCursor();\n }\n \/\/ Return false, even if the event has been handled, because there might be\n \/\/ other listeners for cursor notifications.\n }\n return false;\n}\n\nvoid MouseCursorMonitorX11::CaptureCursor() {\n assert(have_xfixes_);\n\n XFixesCursorImage* img;\n {\n XErrorTrap error_trap(display());\n img = XFixesGetCursorImage(display());\n if (!img || error_trap.GetLastErrorAndDisable() != 0)\n return;\n }\n\n std::unique_ptr image(\n new BasicDesktopFrame(DesktopSize(img->width, img->height)));\n\n \/\/ Xlib stores 32-bit data in longs, even if longs are 64-bits long.\n unsigned long* src = img->pixels;\n uint32_t* dst = reinterpret_cast(image->data());\n uint32_t* dst_end = dst + (img->width * img->height);\n while (dst < dst_end) {\n *dst++ = static_cast(*src++);\n }\n\n DesktopVector hotspot(std::min(img->width, img->xhot),\n std::min(img->height, img->yhot));\n\n XFree(img);\n\n cursor_shape_.reset(new MouseCursor(image.release(), hotspot));\n}\n\n\/\/ static\nMouseCursorMonitor* MouseCursorMonitor::CreateForWindow(\n const DesktopCaptureOptions& options, WindowId window) {\n if (!options.x_display())\n return NULL;\n window = GetTopLevelWindow(options.x_display()->display(), window);\n if (window == None)\n return NULL;\n return new MouseCursorMonitorX11(options, window);\n}\n\nMouseCursorMonitor* MouseCursorMonitor::CreateForScreen(\n const DesktopCaptureOptions& options,\n ScreenId screen) {\n if (!options.x_display())\n return NULL;\n return new MouseCursorMonitorX11(\n options, DefaultRootWindow(options.x_display()->display()));\n}\n\n} \/\/ namespace webrtc\nUse a default mouse cursor if XFixes is not supported.\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"webrtc\/modules\/desktop_capture\/mouse_cursor_monitor.h\"\n\n#include \n#include \n#include \n\n#include \"webrtc\/modules\/desktop_capture\/desktop_capture_options.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame.h\"\n#include \"webrtc\/modules\/desktop_capture\/mouse_cursor.h\"\n#include \"webrtc\/modules\/desktop_capture\/x11\/x_error_trap.h\"\n#include \"webrtc\/system_wrappers\/include\/logging.h\"\n\nnamespace {\n\n\/\/ WindowCapturer returns window IDs of X11 windows with WM_STATE attribute.\n\/\/ These windows may not be immediate children of the root window, because\n\/\/ window managers may re-parent them to add decorations. However,\n\/\/ XQueryPointer() expects to be passed children of the root. This function\n\/\/ searches up the list of the windows to find the root child that corresponds\n\/\/ to |window|.\nWindow GetTopLevelWindow(Display* display, Window window) {\n while (true) {\n \/\/ If the window is in WithdrawnState then look at all of its children.\n ::Window root, parent;\n ::Window *children;\n unsigned int num_children;\n if (!XQueryTree(display, window, &root, &parent, &children,\n &num_children)) {\n LOG(LS_ERROR) << \"Failed to query for child windows although window\"\n << \"does not have a valid WM_STATE.\";\n return None;\n }\n if (children)\n XFree(children);\n\n if (parent == root)\n break;\n\n window = parent;\n }\n\n return window;\n}\n\n} \/\/ namespace\n\nnamespace webrtc {\n\nclass MouseCursorMonitorX11 : public MouseCursorMonitor,\n public SharedXDisplay::XEventHandler {\n public:\n MouseCursorMonitorX11(const DesktopCaptureOptions& options, Window window);\n ~MouseCursorMonitorX11() override;\n\n void Init(Callback* callback, Mode mode) override;\n void Capture() override;\n\n private:\n \/\/ SharedXDisplay::XEventHandler interface.\n bool HandleXEvent(const XEvent& event) override;\n\n Display* display() { return x_display_->display(); }\n\n \/\/ Captures current cursor shape and stores it in |cursor_shape_|.\n void CaptureCursor();\n\n rtc::scoped_refptr x_display_;\n Callback* callback_;\n Mode mode_;\n Window window_;\n\n bool have_xfixes_;\n int xfixes_event_base_;\n int xfixes_error_base_;\n\n std::unique_ptr cursor_shape_;\n};\n\nMouseCursorMonitorX11::MouseCursorMonitorX11(\n const DesktopCaptureOptions& options,\n Window window)\n : x_display_(options.x_display()),\n callback_(NULL),\n mode_(SHAPE_AND_POSITION),\n window_(window),\n have_xfixes_(false),\n xfixes_event_base_(-1),\n xfixes_error_base_(-1) {\n \/\/ Set a default initial cursor shape in case XFixes is not present.\n const int kSize = 5;\n std::unique_ptr default_cursor(\n new BasicDesktopFrame(DesktopSize(kSize, kSize)));\n const uint8_t pixels[kSize * kSize] = {\n 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0xff, 0xff, 0xff, 0x00,\n 0x00, 0xff, 0xff, 0xff, 0x00,\n 0x00, 0xff, 0xff, 0xff, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00\n };\n uint8_t* ptr = default_cursor->data();\n for (int y = 0; y < kSize; ++y) {\n for (int x = 0; x < kSize; ++x) {\n *ptr++ = pixels[kSize * y + x];\n *ptr++ = pixels[kSize * y + x];\n *ptr++ = pixels[kSize * y + x];\n *ptr++ = 0xff;\n }\n }\n DesktopVector hotspot(2, 2);\n cursor_shape_.reset(new MouseCursor(default_cursor.release(), hotspot));\n}\n\nMouseCursorMonitorX11::~MouseCursorMonitorX11() {\n if (have_xfixes_) {\n x_display_->RemoveEventHandler(xfixes_event_base_ + XFixesCursorNotify,\n this);\n }\n}\n\nvoid MouseCursorMonitorX11::Init(Callback* callback, Mode mode) {\n \/\/ Init can be called only once per instance of MouseCursorMonitor.\n assert(!callback_);\n assert(callback);\n\n callback_ = callback;\n mode_ = mode;\n\n have_xfixes_ =\n XFixesQueryExtension(display(), &xfixes_event_base_, &xfixes_error_base_);\n\n if (have_xfixes_) {\n \/\/ Register for changes to the cursor shape.\n XFixesSelectCursorInput(display(), window_, XFixesDisplayCursorNotifyMask);\n x_display_->AddEventHandler(xfixes_event_base_ + XFixesCursorNotify, this);\n\n CaptureCursor();\n } else {\n LOG(LS_INFO) << \"X server does not support XFixes.\";\n }\n}\n\nvoid MouseCursorMonitorX11::Capture() {\n assert(callback_);\n\n \/\/ Process X11 events in case XFixes has sent cursor notification.\n x_display_->ProcessPendingXEvents();\n\n \/\/ cursor_shape_| is set only if we were notified of a cursor shape change.\n if (cursor_shape_.get())\n callback_->OnMouseCursor(cursor_shape_.release());\n\n \/\/ Get cursor position if necessary.\n if (mode_ == SHAPE_AND_POSITION) {\n int root_x;\n int root_y;\n int win_x;\n int win_y;\n Window root_window;\n Window child_window;\n unsigned int mask;\n\n XErrorTrap error_trap(display());\n Bool result = XQueryPointer(display(), window_, &root_window, &child_window,\n &root_x, &root_y, &win_x, &win_y, &mask);\n CursorState state;\n if (!result || error_trap.GetLastErrorAndDisable() != 0) {\n state = OUTSIDE;\n } else {\n \/\/ In screen mode (window_ == root_window) the mouse is always inside.\n \/\/ XQueryPointer() sets |child_window| to None if the cursor is outside\n \/\/ |window_|.\n state =\n (window_ == root_window || child_window != None) ? INSIDE : OUTSIDE;\n }\n\n callback_->OnMouseCursorPosition(state,\n webrtc::DesktopVector(win_x, win_y));\n }\n}\n\nbool MouseCursorMonitorX11::HandleXEvent(const XEvent& event) {\n if (have_xfixes_ && event.type == xfixes_event_base_ + XFixesCursorNotify) {\n const XFixesCursorNotifyEvent* cursor_event =\n reinterpret_cast(&event);\n if (cursor_event->subtype == XFixesDisplayCursorNotify) {\n CaptureCursor();\n }\n \/\/ Return false, even if the event has been handled, because there might be\n \/\/ other listeners for cursor notifications.\n }\n return false;\n}\n\nvoid MouseCursorMonitorX11::CaptureCursor() {\n assert(have_xfixes_);\n\n XFixesCursorImage* img;\n {\n XErrorTrap error_trap(display());\n img = XFixesGetCursorImage(display());\n if (!img || error_trap.GetLastErrorAndDisable() != 0)\n return;\n }\n\n std::unique_ptr image(\n new BasicDesktopFrame(DesktopSize(img->width, img->height)));\n\n \/\/ Xlib stores 32-bit data in longs, even if longs are 64-bits long.\n unsigned long* src = img->pixels;\n uint32_t* dst = reinterpret_cast(image->data());\n uint32_t* dst_end = dst + (img->width * img->height);\n while (dst < dst_end) {\n *dst++ = static_cast(*src++);\n }\n\n DesktopVector hotspot(std::min(img->width, img->xhot),\n std::min(img->height, img->yhot));\n\n XFree(img);\n\n cursor_shape_.reset(new MouseCursor(image.release(), hotspot));\n}\n\n\/\/ static\nMouseCursorMonitor* MouseCursorMonitor::CreateForWindow(\n const DesktopCaptureOptions& options, WindowId window) {\n if (!options.x_display())\n return NULL;\n window = GetTopLevelWindow(options.x_display()->display(), window);\n if (window == None)\n return NULL;\n return new MouseCursorMonitorX11(options, window);\n}\n\nMouseCursorMonitor* MouseCursorMonitor::CreateForScreen(\n const DesktopCaptureOptions& options,\n ScreenId screen) {\n if (!options.x_display())\n return NULL;\n return new MouseCursorMonitorX11(\n options, DefaultRootWindow(options.x_display()->display()));\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2010 by Cristian Maglie \n * Copyright (c) 2014 by Paul Stoffregen (Transaction API)\n * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR)\n * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes)\n * SPI Master library for arduino.\n *\n * This file is free software; you can redistribute it and\/or modify\n * it under the terms of either the GNU General Public License version 2\n * or the GNU Lesser General Public License version 2.1, both as\n * published by the Free Software Foundation.\n *\/\n\n#include \"SPI.h\"\n\n#if defined(__PIC32_PPS__)\nSPIClass SPI(_DSPI0_BASE, _DSPI0_MISO_PIN, _DSPI0_MOSI_PIN, _DSPI0_MISO_IN, _DSPI0_MOSI_OUT);\n#else\nSPIClass SPI(_DSPI0_BASE);\n#endif\n\n#if defined(__PIC32_PPS__)\nSPIClass::SPIClass(uint32_t base, int pinMI, int pinMO, ppsFunctionType ppsMI, ppsFunctionType ppsMO) {\n pspi = (p32_spi *)base;\n pinMISO = pinMI;\n pinMOSI = pinMO;\n ppsMISO = ppsMI;\n ppsMOSI = ppsMO;\n}\n#else\nSPIClass::SPIClass(uint32_t base) {\n pspi = (p32_spi *)base;\n}\n#endif\n\n\nvoid SPIClass::begin() {\n uint32_t sreg = disableInterrupts();\n\n if (!initialized) {\n#if defined(__PIC32_PPS__)\n pinMode(pinMISO, INPUT);\n mapPps(pinMISO, ppsMISO);\n pinMode(pinMOSI, OUTPUT);\n mapPps(pinMOSI, ppsMOSI);\n#endif \n pspi->sxCon.set = (1<<_SPICON_MSTEN) | (1<<_SPICON_ON);\n setClockDivider(SPI_CLOCK_DIV128);\n setDataMode(SPI_MODE0);\n }\n\n initialized++; \/\/ reference count\n restoreInterrupts(sreg);\n}\n\nvoid SPIClass::end() {\n uint32_t sreg = disableInterrupts();\n\n \/\/ Decrease the reference counter\n if (initialized) {\n initialized--;\n\/\/ mapPps(pinMISO, 0);\n\/\/ mapPps(pinMOSI, 0);\n }\n\n \/\/ If there are no more references disable SPI\n if (!initialized) {\n pspi->sxCon.clr = 1<<_SPICON_ON;\n interruptMode = 0;\n#ifdef SPI_TRANSACTION_MISMATCH_LED\n inTransactionFlag = 0;\n#endif\n }\n\n restoreInterrupts(sreg);\n}\n\nvoid SPIClass::usingInterrupt(uint8_t interruptNumber) {\n}\n\nvoid SPIClass::notUsingInterrupt(uint8_t interruptNumber) {\n}\nAdded option to select default DSPI port for use with SPI library\/*\n * Copyright (c) 2010 by Cristian Maglie \n * Copyright (c) 2014 by Paul Stoffregen (Transaction API)\n * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR)\n * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes)\n * SPI Master library for arduino.\n *\n * This file is free software; you can redistribute it and\/or modify\n * it under the terms of either the GNU General Public License version 2\n * or the GNU Lesser General Public License version 2.1, both as\n * published by the Free Software Foundation.\n *\/\n\n#include \"SPI.h\"\n\n#ifndef _SPI_PORT\n #define _SPI_PORT 0\n#endif\n\n#if (_SPI_PORT == 0)\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI0_BASE, _DSPI0_MISO_PIN, _DSPI0_MOSI_PIN, _DSPI0_MISO_IN, _DSPI0_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI0_BASE);\n #endif\n#elif (_SPI_PORT == 1)\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI1_BASE, _DSPI1_MISO_PIN, _DSPI1_MOSI_PIN, _DSPI1_MISO_IN, _DSPI1_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI1_BASE);\n #endif\n#elif (_SPI_PORT == 2)\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI2_BASE, _DSPI2_MISO_PIN, _DSPI2_MOSI_PIN, _DSPI2_MISO_IN, _DSPI2_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI2_BASE);\n #endif\n#elif (_SPI_PORT == 3)\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI3_BASE, _DSPI3_MISO_PIN, _DSPI3_MOSI_PIN, _DSPI3_MISO_IN, _DSPI3_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI3_BASE);\n #endif\n#elif (_SPI_PORT == 4)\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI4_BASE, _DSPI4_MISO_PIN, _DSPI4_MOSI_PIN, _DSPI4_MISO_IN, _DSPI4_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI4_BASE);\n #endif\n#elif (_SPI_PORT == 5)\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI5_BASE, _DSPI5_MISO_PIN, _DSPI5_MOSI_PIN, _DSPI5_MISO_IN, _DSPI5_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI5_BASE);\n #endif\n#else\n #if defined(__PIC32_PPS__)\n SPIClass SPI(_DSPI0_BASE, _DSPI0_MISO_PIN, _DSPI0_MOSI_PIN, _DSPI0_MISO_IN, _DSPI0_MOSI_OUT);\n #else\n SPIClass SPI(_DSPI0_BASE);\n #endif\n#endif\n\n#if defined(__PIC32_PPS__)\nSPIClass::SPIClass(uint32_t base, int pinMI, int pinMO, ppsFunctionType ppsMI, ppsFunctionType ppsMO) {\n pspi = (p32_spi *)base;\n pinMISO = pinMI;\n pinMOSI = pinMO;\n ppsMISO = ppsMI;\n ppsMOSI = ppsMO;\n}\n#else\nSPIClass::SPIClass(uint32_t base) {\n pspi = (p32_spi *)base;\n}\n#endif\n\n\nvoid SPIClass::begin() {\n uint32_t sreg = disableInterrupts();\n\n if (!initialized) {\n#if defined(__PIC32_PPS__)\n pinMode(pinMISO, INPUT);\n mapPps(pinMISO, ppsMISO);\n pinMode(pinMOSI, OUTPUT);\n mapPps(pinMOSI, ppsMOSI);\n#endif \n pspi->sxCon.set = (1<<_SPICON_MSTEN) | (1<<_SPICON_ON);\n setClockDivider(SPI_CLOCK_DIV128);\n setDataMode(SPI_MODE0);\n }\n\n initialized++; \/\/ reference count\n restoreInterrupts(sreg);\n}\n\nvoid SPIClass::end() {\n uint32_t sreg = disableInterrupts();\n\n \/\/ Decrease the reference counter\n if (initialized) {\n initialized--;\n\/\/ mapPps(pinMISO, 0);\n\/\/ mapPps(pinMOSI, 0);\n }\n\n \/\/ If there are no more references disable SPI\n if (!initialized) {\n pspi->sxCon.clr = 1<<_SPICON_ON;\n interruptMode = 0;\n#ifdef SPI_TRANSACTION_MISMATCH_LED\n inTransactionFlag = 0;\n#endif\n }\n\n restoreInterrupts(sreg);\n}\n\nvoid SPIClass::usingInterrupt(uint8_t interruptNumber) {\n}\n\nvoid SPIClass::notUsingInterrupt(uint8_t interruptNumber) {\n}\n<|endoftext|>"} {"text":"\n#include \n#ifndef _WIN32\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"hyperiond.h\"\n#include \"systray.h\"\n\nSysTray::SysTray(HyperionDaemon *hyperiond)\n\t: QWidget()\n\t, _colorDlg(this)\n\t, _hyperiond(hyperiond)\n\t, _hyperion(nullptr)\n\t, _instanceManager(HyperionIManager::getInstance())\n\t, _webPort(8090)\n{\n\tQ_INIT_RESOURCE(resources);\n\n\t\/\/ webserver port\n\tWebServer* webserver = hyperiond->getWebServerInstance();\n\tconnect(webserver, &WebServer::portChanged, this, &SysTray::webserverPortChanged);\n\n\t\/\/ instance changes\n\tconnect(_instanceManager, &HyperionIManager::instanceStateChanged, this, &SysTray::handleInstanceStateChange);\n}\n\nSysTray::~SysTray()\n{\n}\n\nvoid SysTray::iconActivated(QSystemTrayIcon::ActivationReason reason)\n{\n\tswitch (reason)\n\t{\n\t\tcase QSystemTrayIcon::Trigger:\n\t\t\tbreak;\n\t\tcase QSystemTrayIcon::DoubleClick:\n\t\t\tshowColorDialog();\n\t\t\tbreak;\n\t\tcase QSystemTrayIcon::MiddleClick:\n\t\t\tbreak;\n\t\tdefault: ;\n\t}\n}\n\nvoid SysTray::createTrayIcon()\n{\n\tquitAction = new QAction(tr(\"&Quit\"), this);\n\tQIcon quitIcon = QIcon::fromTheme(\"application-exit\");\n\tquitAction->setIcon(quitIcon);\n\tconnect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\n\n\tcolorAction = new QAction(tr(\"&Color\"), this);\n\tQIcon colorIcon = QIcon::fromTheme(\"applications-graphics\");\n\tcolorAction->setIcon(colorIcon);\n\tconnect(colorAction, SIGNAL(triggered()), this, SLOT(showColorDialog()));\n\n\tsettingsAction = new QAction(tr(\"&Settings\"), this);\n\tQIcon settingsIcon = QIcon::fromTheme(\"preferences-system\");\n\tsettingsAction->setIcon(settingsIcon);\n\tconnect(settingsAction, SIGNAL(triggered()), this, SLOT(settings()));\n\n\tclearAction = new QAction(tr(\"&Clear\"), this);\n\tQIcon clearIcon = QIcon::fromTheme(\"edit-delete\");\n\tclearAction->setIcon(clearIcon);\n\tconnect(clearAction, SIGNAL(triggered()), this, SLOT(clearEfxColor()));\n\n\tconst std::list efxs = _hyperion->getEffects();\n\t_trayIconMenu = new QMenu(this);\n\t_trayIconEfxMenu = new QMenu(_trayIconMenu);\n\t_trayIconEfxMenu->setTitle(tr(\"Effects\"));\n\tQIcon efxIcon = QIcon::fromTheme(\"media-playback-start\");\n\t_trayIconEfxMenu->setIcon(efxIcon);\n\tfor (auto efx : efxs)\n\t{\n\t\tQAction *efxAction = new QAction(efx.name, this);\n\t\tconnect(efxAction, SIGNAL(triggered()), this, SLOT(setEffect()));\n\t\t_trayIconEfxMenu->addAction(efxAction);\n\t}\n\t\n\t_trayIconMenu->addAction(settingsAction);\n\t_trayIconMenu->addSeparator();\n\t_trayIconMenu->addAction(colorAction);\n\t_trayIconMenu->addMenu(_trayIconEfxMenu);\n\t_trayIconMenu->addAction(clearAction);\n\t_trayIconMenu->addSeparator();\n\t_trayIconMenu->addAction(quitAction);\n\n\t_trayIcon = new QSystemTrayIcon(this);\n\t_trayIcon->setContextMenu(_trayIconMenu);\n}\n\nvoid SysTray::setColor(const QColor & color)\n{\n\tstd::vector rgbColor{ ColorRgb{ (uint8_t)color.red(), (uint8_t)color.green(), (uint8_t)color.blue() } };\n \n \t_hyperion->setColor(1 ,rgbColor, 0);\n}\n\nvoid SysTray::showColorDialog()\n{\n\tif(_colorDlg.isVisible())\n\t{\n\t\t_colorDlg.hide();\n\t}\n\telse\n\t{\n\t\t_colorDlg.show();\n\t}\n}\n\nvoid SysTray::closeEvent(QCloseEvent *event)\n{\n\tevent->ignore();\n}\n\nvoid SysTray::settings()\n{\n#ifndef _WIN32\n\t\/\/ Hide error messages when opening webbrowser\n\n\tint out_pipe[2];\n\tint saved_stdout;\n\tint saved_stderr;\n\n\t\/\/ saving stdout and stderr file descriptor\n\tsaved_stdout = ::dup( STDOUT_FILENO );\n\tsaved_stderr = ::dup( STDERR_FILENO );\n\n\tif(::pipe(out_pipe) == 0)\n\t{\n\t\t\/\/ redirecting stdout to pipe\n\t\t::dup2(out_pipe[1], STDOUT_FILENO);\n\t\t::close(out_pipe[1]);\n\t\t\/\/ redirecting stderr to stdout\n\t\t::dup2(STDOUT_FILENO, STDERR_FILENO);\n\t}\n\t#endif\n\n\tQDesktopServices::openUrl(QUrl(\"http:\/\/localhost:\"+QString::number(_webPort)+\"\/\", QUrl::TolerantMode));\n\t\n\t#ifndef _WIN32\n\t\/\/ restoring stdout\n\t::dup2(saved_stdout, STDOUT_FILENO);\n\t\/\/ restoring stderr\n\t::dup2(saved_stderr, STDERR_FILENO);\n\t#endif\n}\n\nvoid SysTray::setEffect()\n{\n\tQString efxName = qobject_cast(sender())->text();\n\t_hyperion->setEffect(efxName, 1);\n}\n\nvoid SysTray::clearEfxColor()\n{\n\t_hyperion->clear(1);\n}\n\nvoid SysTray::handleInstanceStateChange(const instanceState& state, const quint8& instance, const QString& name)\n{\n\tswitch(state){\n\t\tcase H_STARTED:\n\t\t\tif(instance == 0)\n\t\t\t{\n\t\t\t\t_hyperion = _instanceManager->getHyperionInstance(0);\n\n\t\t\t\tcreateTrayIcon();\n\t\t\t\tconnect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\n\t\t\t\t\tthis, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));\n\n\t\t\t\tconnect(&_colorDlg, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(setColor(const QColor &)));\n\t\t\t\tQIcon icon(\":\/hyperion-icon-32px.png\");\n\t\t\t\t_trayIcon->setIcon(icon);\n\t\t\t\t_trayIcon->show();\n\t\t\t\tsetWindowIcon(icon);\n\t\t\t\t_colorDlg.setOptions(QColorDialog::NoButtons);\n\t\t\t}\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\nOpen WebUI instead of the color picker\n#include \n#ifndef _WIN32\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"hyperiond.h\"\n#include \"systray.h\"\n\nSysTray::SysTray(HyperionDaemon *hyperiond)\n\t: QWidget()\n\t, _colorDlg(this)\n\t, _hyperiond(hyperiond)\n\t, _hyperion(nullptr)\n\t, _instanceManager(HyperionIManager::getInstance())\n\t, _webPort(8090)\n{\n\tQ_INIT_RESOURCE(resources);\n\n\t\/\/ webserver port\n\tWebServer* webserver = hyperiond->getWebServerInstance();\n\tconnect(webserver, &WebServer::portChanged, this, &SysTray::webserverPortChanged);\n\n\t\/\/ instance changes\n\tconnect(_instanceManager, &HyperionIManager::instanceStateChanged, this, &SysTray::handleInstanceStateChange);\n}\n\nSysTray::~SysTray()\n{\n}\n\nvoid SysTray::iconActivated(QSystemTrayIcon::ActivationReason reason)\n{\n\tswitch (reason)\n\t{\n\t\tcase QSystemTrayIcon::Trigger:\n\t\t\tbreak;\n\t\tcase QSystemTrayIcon::DoubleClick:\n\t\t\tsettings();\n\t\t\tbreak;\n\t\tcase QSystemTrayIcon::MiddleClick:\n\t\t\tbreak;\n\t\tdefault: ;\n\t}\n}\n\nvoid SysTray::createTrayIcon()\n{\n\tquitAction = new QAction(tr(\"&Quit\"), this);\n\tQIcon quitIcon = QIcon::fromTheme(\"application-exit\");\n\tquitAction->setIcon(quitIcon);\n\tconnect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\n\n\tcolorAction = new QAction(tr(\"&Color\"), this);\n\tQIcon colorIcon = QIcon::fromTheme(\"applications-graphics\");\n\tcolorAction->setIcon(colorIcon);\n\tconnect(colorAction, SIGNAL(triggered()), this, SLOT(showColorDialog()));\n\n\tsettingsAction = new QAction(tr(\"&Settings\"), this);\n\tQIcon settingsIcon = QIcon::fromTheme(\"preferences-system\");\n\tsettingsAction->setIcon(settingsIcon);\n\tconnect(settingsAction, SIGNAL(triggered()), this, SLOT(settings()));\n\n\tclearAction = new QAction(tr(\"&Clear\"), this);\n\tQIcon clearIcon = QIcon::fromTheme(\"edit-delete\");\n\tclearAction->setIcon(clearIcon);\n\tconnect(clearAction, SIGNAL(triggered()), this, SLOT(clearEfxColor()));\n\n\tconst std::list efxs = _hyperion->getEffects();\n\t_trayIconMenu = new QMenu(this);\n\t_trayIconEfxMenu = new QMenu(_trayIconMenu);\n\t_trayIconEfxMenu->setTitle(tr(\"Effects\"));\n\tQIcon efxIcon = QIcon::fromTheme(\"media-playback-start\");\n\t_trayIconEfxMenu->setIcon(efxIcon);\n\tfor (auto efx : efxs)\n\t{\n\t\tQAction *efxAction = new QAction(efx.name, this);\n\t\tconnect(efxAction, SIGNAL(triggered()), this, SLOT(setEffect()));\n\t\t_trayIconEfxMenu->addAction(efxAction);\n\t}\n\t\n\t_trayIconMenu->addAction(settingsAction);\n\t_trayIconMenu->addSeparator();\n\t_trayIconMenu->addAction(colorAction);\n\t_trayIconMenu->addMenu(_trayIconEfxMenu);\n\t_trayIconMenu->addAction(clearAction);\n\t_trayIconMenu->addSeparator();\n\t_trayIconMenu->addAction(quitAction);\n\n\t_trayIcon = new QSystemTrayIcon(this);\n\t_trayIcon->setContextMenu(_trayIconMenu);\n}\n\nvoid SysTray::setColor(const QColor & color)\n{\n\tstd::vector rgbColor{ ColorRgb{ (uint8_t)color.red(), (uint8_t)color.green(), (uint8_t)color.blue() } };\n \n \t_hyperion->setColor(1 ,rgbColor, 0);\n}\n\nvoid SysTray::showColorDialog()\n{\n\tif(_colorDlg.isVisible())\n\t{\n\t\t_colorDlg.hide();\n\t}\n\telse\n\t{\n\t\t_colorDlg.show();\n\t}\n}\n\nvoid SysTray::closeEvent(QCloseEvent *event)\n{\n\tevent->ignore();\n}\n\nvoid SysTray::settings()\n{\n#ifndef _WIN32\n\t\/\/ Hide error messages when opening webbrowser\n\n\tint out_pipe[2];\n\tint saved_stdout;\n\tint saved_stderr;\n\n\t\/\/ saving stdout and stderr file descriptor\n\tsaved_stdout = ::dup( STDOUT_FILENO );\n\tsaved_stderr = ::dup( STDERR_FILENO );\n\n\tif(::pipe(out_pipe) == 0)\n\t{\n\t\t\/\/ redirecting stdout to pipe\n\t\t::dup2(out_pipe[1], STDOUT_FILENO);\n\t\t::close(out_pipe[1]);\n\t\t\/\/ redirecting stderr to stdout\n\t\t::dup2(STDOUT_FILENO, STDERR_FILENO);\n\t}\n\t#endif\n\n\tQDesktopServices::openUrl(QUrl(\"http:\/\/localhost:\"+QString::number(_webPort)+\"\/\", QUrl::TolerantMode));\n\t\n\t#ifndef _WIN32\n\t\/\/ restoring stdout\n\t::dup2(saved_stdout, STDOUT_FILENO);\n\t\/\/ restoring stderr\n\t::dup2(saved_stderr, STDERR_FILENO);\n\t#endif\n}\n\nvoid SysTray::setEffect()\n{\n\tQString efxName = qobject_cast(sender())->text();\n\t_hyperion->setEffect(efxName, 1);\n}\n\nvoid SysTray::clearEfxColor()\n{\n\t_hyperion->clear(1);\n}\n\nvoid SysTray::handleInstanceStateChange(const instanceState& state, const quint8& instance, const QString& name)\n{\n\tswitch(state){\n\t\tcase H_STARTED:\n\t\t\tif(instance == 0)\n\t\t\t{\n\t\t\t\t_hyperion = _instanceManager->getHyperionInstance(0);\n\n\t\t\t\tcreateTrayIcon();\n\t\t\t\tconnect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\n\t\t\t\t\tthis, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));\n\n\t\t\t\tconnect(&_colorDlg, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(setColor(const QColor &)));\n\t\t\t\tQIcon icon(\":\/hyperion-icon-32px.png\");\n\t\t\t\t_trayIcon->setIcon(icon);\n\t\t\t\t_trayIcon->show();\n\t\t\t\tsetWindowIcon(icon);\n\t\t\t\t_colorDlg.setOptions(QColorDialog::NoButtons);\n\t\t\t}\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ash\/frame\/caption_buttons\/frame_caption_button.h\"\n\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/animation\/slide_animation.h\"\n#include \"ui\/gfx\/animation\/throb_animation.h\"\n#include \"ui\/gfx\/canvas.h\"\n\nnamespace ash {\n\nnamespace {\n\n\/\/ The duration of the crossfade animation when swapping the button's images.\nconst int kSwapImagesAnimationDurationMs = 200;\n\n\/\/ The duration of the fade out animation of the old icon during a crossfade\n\/\/ animation as a ratio of |kSwapImagesAnimationDurationMs|.\nconst float kFadeOutRatio = 0.5f;\n\n\/\/ The alpha to draw inactive icons with.\nconst float kInactiveIconAlpha = 0.2f;\n\n} \/\/ namespace\n\n\/\/ static\nconst char FrameCaptionButton::kViewClassName[] = \"FrameCaptionButton\";\n\nFrameCaptionButton::FrameCaptionButton(views::ButtonListener* listener,\n CaptionButtonIcon icon)\n : CustomButton(listener),\n icon_(icon),\n paint_as_active_(false),\n alpha_(255),\n icon_image_id_(-1),\n hovered_background_image_id_(-1),\n pressed_background_image_id_(-1),\n swap_images_animation_(new gfx::SlideAnimation(this)) {\n swap_images_animation_->Reset(1);\n\n \/\/ Do not flip the gfx::Canvas passed to the OnPaint() method. The snap left\n \/\/ and snap right button icons should not be flipped. The other icons are\n \/\/ horizontally symmetrical.\n}\n\nFrameCaptionButton::~FrameCaptionButton() {\n}\n\nvoid FrameCaptionButton::SetImages(CaptionButtonIcon icon,\n Animate animate,\n int icon_image_id,\n int hovered_background_image_id,\n int pressed_background_image_id) {\n \/\/ The early return is dependant on |animate| because callers use SetImages()\n \/\/ with ANIMATE_NO to progress the crossfade animation to the end.\n if (icon == icon_ &&\n (animate == ANIMATE_YES || !swap_images_animation_->is_animating()) &&\n icon_image_id == icon_image_id_ &&\n hovered_background_image_id == hovered_background_image_id_ &&\n pressed_background_image_id == pressed_background_image_id_) {\n return;\n }\n\n if (animate == ANIMATE_YES)\n crossfade_icon_image_ = icon_image_;\n\n icon_ = icon;\n icon_image_id_ = icon_image_id;\n hovered_background_image_id_ = hovered_background_image_id;\n pressed_background_image_id_ = pressed_background_image_id;\n\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n icon_image_ = *rb.GetImageSkiaNamed(icon_image_id);\n hovered_background_image_ = *rb.GetImageSkiaNamed(\n hovered_background_image_id);\n pressed_background_image_ = *rb.GetImageSkiaNamed(\n pressed_background_image_id);\n\n if (animate == ANIMATE_YES) {\n swap_images_animation_->Reset(0);\n swap_images_animation_->SetSlideDuration(kSwapImagesAnimationDurationMs);\n swap_images_animation_->Show();\n } else {\n swap_images_animation_->Reset(1);\n }\n PreferredSizeChanged();\n SchedulePaint();\n}\n\nbool FrameCaptionButton::IsAnimatingImageSwap() const {\n return swap_images_animation_->is_animating();\n}\n\nvoid FrameCaptionButton::SetAlpha(int alpha) {\n if (alpha_ != alpha) {\n alpha_ = alpha;\n SchedulePaint();\n }\n}\n\ngfx::Size FrameCaptionButton::GetPreferredSize() const {\n return hovered_background_image_.isNull() ?\n gfx::Size() : hovered_background_image_.size();\n}\n\nconst char* FrameCaptionButton::GetClassName() const {\n return kViewClassName;\n}\n\nvoid FrameCaptionButton::OnPaint(gfx::Canvas* canvas) {\n if (hover_animation_->is_animating() || state() == STATE_HOVERED) {\n int hovered_background_alpha = hover_animation_->is_animating() ?\n hover_animation_->CurrentValueBetween(0, 255) : 255;\n SkPaint paint;\n paint.setAlpha(hovered_background_alpha);\n canvas->DrawImageInt(hovered_background_image_, 0, 0, paint);\n } else if (state() == STATE_PRESSED) {\n canvas->DrawImageInt(pressed_background_image_, 0, 0);\n }\n\n int icon_alpha = swap_images_animation_->CurrentValueBetween(0, 255);\n int crossfade_icon_alpha = 0;\n if (icon_alpha < static_cast(kFadeOutRatio * 255))\n crossfade_icon_alpha = static_cast(255 - icon_alpha \/ kFadeOutRatio);\n\n if (crossfade_icon_alpha > 0 && !crossfade_icon_image_.isNull()) {\n gfx::Canvas icon_canvas(icon_image_.size(), canvas->image_scale(), false);\n SkPaint paint;\n paint.setAlpha(icon_alpha);\n icon_canvas.DrawImageInt(icon_image_, 0, 0, paint);\n\n paint.setAlpha(crossfade_icon_alpha);\n paint.setXfermodeMode(SkXfermode::kPlus_Mode);\n icon_canvas.DrawImageInt(crossfade_icon_image_, 0, 0, paint);\n\n PaintCentered(canvas, gfx::ImageSkia(icon_canvas.ExtractImageRep()),\n alpha_);\n } else {\n if (!swap_images_animation_->is_animating())\n icon_alpha = alpha_;\n PaintCentered(canvas, icon_image_, icon_alpha);\n }\n}\n\nvoid FrameCaptionButton::OnGestureEvent(ui::GestureEvent* event) {\n \/\/ CustomButton does not become pressed when the user drags off and then back\n \/\/ onto the button. Make FrameCaptionButton pressed in this case because this\n \/\/ behavior is more consistent with AlternateFrameSizeButton.\n if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||\n event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {\n if (HitTestPoint(event->location())) {\n SetState(STATE_PRESSED);\n RequestFocus();\n event->StopPropagation();\n } else {\n SetState(STATE_NORMAL);\n }\n } else if (event->type() == ui::ET_GESTURE_SCROLL_END) {\n if (HitTestPoint(event->location())) {\n SetState(STATE_HOVERED);\n NotifyClick(*event);\n event->StopPropagation();\n }\n }\n CustomButton::OnGestureEvent(event);\n}\n\nvoid FrameCaptionButton::PaintCentered(gfx::Canvas* canvas,\n const gfx::ImageSkia& to_center,\n int alpha) {\n if (!paint_as_active_)\n alpha *= kInactiveIconAlpha;\n\n SkPaint paint;\n paint.setAlpha(alpha);\n canvas->DrawImageInt(to_center,\n (width() - to_center.width()) \/ 2,\n (height() - to_center.height()) \/ 2,\n paint);\n}\n\n} \/\/ namespace ash\nShow hovered and pressed unfocused ash caption buttons as active.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ash\/frame\/caption_buttons\/frame_caption_button.h\"\n\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/animation\/slide_animation.h\"\n#include \"ui\/gfx\/animation\/throb_animation.h\"\n#include \"ui\/gfx\/canvas.h\"\n\nnamespace ash {\n\nnamespace {\n\n\/\/ The duration of the crossfade animation when swapping the button's images.\nconst int kSwapImagesAnimationDurationMs = 200;\n\n\/\/ The duration of the fade out animation of the old icon during a crossfade\n\/\/ animation as a ratio of |kSwapImagesAnimationDurationMs|.\nconst float kFadeOutRatio = 0.5f;\n\n\/\/ The alpha to draw inactive icons with.\nconst float kInactiveIconAlpha = 0.2f;\n\n} \/\/ namespace\n\n\/\/ static\nconst char FrameCaptionButton::kViewClassName[] = \"FrameCaptionButton\";\n\nFrameCaptionButton::FrameCaptionButton(views::ButtonListener* listener,\n CaptionButtonIcon icon)\n : CustomButton(listener),\n icon_(icon),\n paint_as_active_(false),\n alpha_(255),\n icon_image_id_(-1),\n hovered_background_image_id_(-1),\n pressed_background_image_id_(-1),\n swap_images_animation_(new gfx::SlideAnimation(this)) {\n swap_images_animation_->Reset(1);\n\n \/\/ Do not flip the gfx::Canvas passed to the OnPaint() method. The snap left\n \/\/ and snap right button icons should not be flipped. The other icons are\n \/\/ horizontally symmetrical.\n}\n\nFrameCaptionButton::~FrameCaptionButton() {\n}\n\nvoid FrameCaptionButton::SetImages(CaptionButtonIcon icon,\n Animate animate,\n int icon_image_id,\n int hovered_background_image_id,\n int pressed_background_image_id) {\n \/\/ The early return is dependant on |animate| because callers use SetImages()\n \/\/ with ANIMATE_NO to progress the crossfade animation to the end.\n if (icon == icon_ &&\n (animate == ANIMATE_YES || !swap_images_animation_->is_animating()) &&\n icon_image_id == icon_image_id_ &&\n hovered_background_image_id == hovered_background_image_id_ &&\n pressed_background_image_id == pressed_background_image_id_) {\n return;\n }\n\n if (animate == ANIMATE_YES)\n crossfade_icon_image_ = icon_image_;\n\n icon_ = icon;\n icon_image_id_ = icon_image_id;\n hovered_background_image_id_ = hovered_background_image_id;\n pressed_background_image_id_ = pressed_background_image_id;\n\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n icon_image_ = *rb.GetImageSkiaNamed(icon_image_id);\n hovered_background_image_ = *rb.GetImageSkiaNamed(\n hovered_background_image_id);\n pressed_background_image_ = *rb.GetImageSkiaNamed(\n pressed_background_image_id);\n\n if (animate == ANIMATE_YES) {\n swap_images_animation_->Reset(0);\n swap_images_animation_->SetSlideDuration(kSwapImagesAnimationDurationMs);\n swap_images_animation_->Show();\n } else {\n swap_images_animation_->Reset(1);\n }\n PreferredSizeChanged();\n SchedulePaint();\n}\n\nbool FrameCaptionButton::IsAnimatingImageSwap() const {\n return swap_images_animation_->is_animating();\n}\n\nvoid FrameCaptionButton::SetAlpha(int alpha) {\n if (alpha_ != alpha) {\n alpha_ = alpha;\n SchedulePaint();\n }\n}\n\ngfx::Size FrameCaptionButton::GetPreferredSize() const {\n return hovered_background_image_.isNull() ?\n gfx::Size() : hovered_background_image_.size();\n}\n\nconst char* FrameCaptionButton::GetClassName() const {\n return kViewClassName;\n}\n\nvoid FrameCaptionButton::OnPaint(gfx::Canvas* canvas) {\n if (hover_animation_->is_animating() || state() == STATE_HOVERED) {\n int hovered_background_alpha = hover_animation_->is_animating() ?\n hover_animation_->CurrentValueBetween(0, 255) : 255;\n SkPaint paint;\n paint.setAlpha(hovered_background_alpha);\n canvas->DrawImageInt(hovered_background_image_, 0, 0, paint);\n } else if (state() == STATE_PRESSED) {\n canvas->DrawImageInt(pressed_background_image_, 0, 0);\n }\n\n int icon_alpha = swap_images_animation_->CurrentValueBetween(0, 255);\n int crossfade_icon_alpha = 0;\n if (icon_alpha < static_cast(kFadeOutRatio * 255))\n crossfade_icon_alpha = static_cast(255 - icon_alpha \/ kFadeOutRatio);\n\n if (crossfade_icon_alpha > 0 && !crossfade_icon_image_.isNull()) {\n gfx::Canvas icon_canvas(icon_image_.size(), canvas->image_scale(), false);\n SkPaint paint;\n paint.setAlpha(icon_alpha);\n icon_canvas.DrawImageInt(icon_image_, 0, 0, paint);\n\n paint.setAlpha(crossfade_icon_alpha);\n paint.setXfermodeMode(SkXfermode::kPlus_Mode);\n icon_canvas.DrawImageInt(crossfade_icon_image_, 0, 0, paint);\n\n PaintCentered(canvas, gfx::ImageSkia(icon_canvas.ExtractImageRep()),\n alpha_);\n } else {\n if (!swap_images_animation_->is_animating())\n icon_alpha = alpha_;\n PaintCentered(canvas, icon_image_, icon_alpha);\n }\n}\n\nvoid FrameCaptionButton::OnGestureEvent(ui::GestureEvent* event) {\n \/\/ CustomButton does not become pressed when the user drags off and then back\n \/\/ onto the button. Make FrameCaptionButton pressed in this case because this\n \/\/ behavior is more consistent with AlternateFrameSizeButton.\n if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||\n event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {\n if (HitTestPoint(event->location())) {\n SetState(STATE_PRESSED);\n RequestFocus();\n event->StopPropagation();\n } else {\n SetState(STATE_NORMAL);\n }\n } else if (event->type() == ui::ET_GESTURE_SCROLL_END) {\n if (HitTestPoint(event->location())) {\n SetState(STATE_HOVERED);\n NotifyClick(*event);\n event->StopPropagation();\n }\n }\n CustomButton::OnGestureEvent(event);\n}\n\nvoid FrameCaptionButton::PaintCentered(gfx::Canvas* canvas,\n const gfx::ImageSkia& to_center,\n int alpha) {\n if (!paint_as_active_) {\n \/\/ Paint icons as active when they are hovered over or pressed.\n double inactive_alpha = kInactiveIconAlpha;\n if (hover_animation_->is_animating()) {\n inactive_alpha =\n hover_animation_->CurrentValueBetween(inactive_alpha, 1.0f);\n } else if (state() == STATE_PRESSED || state() == STATE_HOVERED) {\n inactive_alpha = 1.0f;\n }\n alpha *= inactive_alpha;\n }\n\n SkPaint paint;\n paint.setAlpha(alpha);\n canvas->DrawImageInt(to_center,\n (width() - to_center.width()) \/ 2,\n (height() - to_center.height()) \/ 2,\n paint);\n}\n\n} \/\/ namespace ash\n<|endoftext|>"} {"text":"#include \"SkImageRef.h\"\n#include \"SkBitmap.h\"\n#include \"SkFlattenable.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n#include \"SkThread.h\"\n\n\/\/ can't be static, as SkImageRef_Pool needs to see it\nSkMutex gImageRefMutex;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkImageRef::SkImageRef(SkStream* stream, SkBitmap::Config config,\n int sampleSize)\n : SkPixelRef(&gImageRefMutex), fErrorInDecoding(false) {\n SkASSERT(stream);\n stream->ref();\n fStream = stream;\n fConfig = config;\n fSampleSize = sampleSize;\n fPrev = fNext = NULL;\n fFactory = NULL;\n\n#ifdef DUMP_IMAGEREF_LIFECYCLE\n SkDebugf(\"add ImageRef %p [%d] data=%d\\n\",\n this, config, (int)stream->getLength());\n#endif\n}\n\nSkImageRef::~SkImageRef() {\n SkASSERT(&gImageRefMutex == this->mutex());\n\n#ifdef DUMP_IMAGEREF_LIFECYCLE\n SkDebugf(\"delete ImageRef %p [%d] data=%d\\n\",\n this, fConfig, (int)fStream->getLength());\n#endif\n\n fStream->unref();\n fFactory->safeUnref();\n}\n\nbool SkImageRef::getInfo(SkBitmap* bitmap) {\n SkAutoMutexAcquire ac(gImageRefMutex);\n \n if (!this->prepareBitmap(SkImageDecoder::kDecodeBounds_Mode)) {\n return false;\n }\n \n SkASSERT(SkBitmap::kNo_Config != fBitmap.config());\n if (bitmap) {\n bitmap->setConfig(fBitmap.config(), fBitmap.width(), fBitmap.height());\n }\n return true;\n}\n\nSkImageDecoderFactory* SkImageRef::setDecoderFactory(\n SkImageDecoderFactory* fact) {\n SkRefCnt_SafeAssign(fFactory, fact);\n return fact;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImageRef::onDecode(SkImageDecoder* codec, SkStream* stream,\n SkBitmap* bitmap, SkBitmap::Config config,\n SkImageDecoder::Mode mode) {\n return codec->decode(stream, bitmap, config, mode);\n}\n\nbool SkImageRef::prepareBitmap(SkImageDecoder::Mode mode) {\n SkASSERT(&gImageRefMutex == this->mutex());\n\n if (fErrorInDecoding) {\n return false;\n }\n \n \/* As soon as we really know our config, we record it, so that on\n subsequent calls to the codec, we are sure we will always get the same\n result.\n *\/\n if (SkBitmap::kNo_Config != fBitmap.config()) {\n fConfig = fBitmap.config();\n }\n \n if (NULL != fBitmap.getPixels() ||\n (SkBitmap::kNo_Config != fBitmap.config() &&\n SkImageDecoder::kDecodeBounds_Mode == mode)) {\n return true;\n }\n\n SkASSERT(fBitmap.getPixels() == NULL);\n\n fStream->rewind();\n\n SkImageDecoder* codec;\n if (fFactory) {\n codec = fFactory->newDecoder(fStream);\n } else {\n codec = SkImageDecoder::Factory(fStream);\n }\n\n if (codec) {\n SkAutoTDelete ad(codec);\n\n codec->setSampleSize(fSampleSize);\n if (this->onDecode(codec, fStream, &fBitmap, fConfig, mode)) {\n return true;\n }\n }\n\n#ifdef DUMP_IMAGEREF_LIFECYCLE\n if (NULL == codec) {\n SkDebugf(\"--- ImageRef: <%s> failed to find codec\\n\", this->getURI());\n } else {\n SkDebugf(\"--- ImageRef: <%s> failed in codec for %d mode\\n\",\n this->getURI(), mode);\n }\n#endif\n fErrorInDecoding = true;\n fBitmap.reset();\n return false;\n}\n\nvoid* SkImageRef::onLockPixels(SkColorTable** ct) {\n SkASSERT(&gImageRefMutex == this->mutex());\n\n if (NULL == fBitmap.getPixels()) {\n (void)this->prepareBitmap(SkImageDecoder::kDecodePixels_Mode);\n }\n\n if (ct) {\n *ct = fBitmap.getColorTable();\n }\n return fBitmap.getPixels();\n}\n\nvoid SkImageRef::onUnlockPixels() {\n \/\/ we're already have the mutex locked\n SkASSERT(&gImageRefMutex == this->mutex());\n}\n\nsize_t SkImageRef::ramUsed() const {\n size_t size = 0;\n\n if (fBitmap.getPixels()) {\n size = fBitmap.getSize();\n if (fBitmap.getColorTable()) {\n size += fBitmap.getColorTable()->count() * sizeof(SkPMColor);\n }\n }\n return size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkImageRef::SkImageRef(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer, &gImageRefMutex), fErrorInDecoding(false) {\n fConfig = (SkBitmap::Config)buffer.readU8();\n fSampleSize = buffer.readU8();\n size_t length = buffer.readU32();\n fStream = SkNEW_ARGS(SkMemoryStream, (length));\n buffer.read((void*)fStream->getMemoryBase(), length);\n\n fPrev = fNext = NULL;\n}\n\nvoid SkImageRef::flatten(SkFlattenableWriteBuffer& buffer) const {\n this->INHERITED::flatten(buffer);\n\n buffer.write8(fConfig);\n buffer.write8(fSampleSize);\n size_t length = fStream->getLength();\n buffer.write32(length);\n fStream->rewind();\n buffer.readFromStream(fStream, length);\n}\n\nAutomated import from \/\/branches\/master\/...@141344,141344#include \"SkImageRef.h\"\n#include \"SkBitmap.h\"\n#include \"SkFlattenable.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n#include \"SkThread.h\"\n\n\/\/ can't be static, as SkImageRef_Pool needs to see it\nSkMutex gImageRefMutex;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkImageRef::SkImageRef(SkStream* stream, SkBitmap::Config config,\n int sampleSize)\n : SkPixelRef(&gImageRefMutex), fErrorInDecoding(false) {\n SkASSERT(stream);\n stream->ref();\n fStream = stream;\n fConfig = config;\n fSampleSize = sampleSize;\n fPrev = fNext = NULL;\n fFactory = NULL;\n\n#ifdef DUMP_IMAGEREF_LIFECYCLE\n SkDebugf(\"add ImageRef %p [%d] data=%d\\n\",\n this, config, (int)stream->getLength());\n#endif\n}\n\nSkImageRef::~SkImageRef() {\n SkASSERT(&gImageRefMutex == this->mutex());\n\n#ifdef DUMP_IMAGEREF_LIFECYCLE\n SkDebugf(\"delete ImageRef %p [%d] data=%d\\n\",\n this, fConfig, (int)fStream->getLength());\n#endif\n\n fStream->unref();\n fFactory->safeUnref();\n}\n\nbool SkImageRef::getInfo(SkBitmap* bitmap) {\n SkAutoMutexAcquire ac(gImageRefMutex);\n \n if (!this->prepareBitmap(SkImageDecoder::kDecodeBounds_Mode)) {\n return false;\n }\n \n SkASSERT(SkBitmap::kNo_Config != fBitmap.config());\n if (bitmap) {\n bitmap->setConfig(fBitmap.config(), fBitmap.width(), fBitmap.height());\n }\n return true;\n}\n\nSkImageDecoderFactory* SkImageRef::setDecoderFactory(\n SkImageDecoderFactory* fact) {\n SkRefCnt_SafeAssign(fFactory, fact);\n return fact;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImageRef::onDecode(SkImageDecoder* codec, SkStream* stream,\n SkBitmap* bitmap, SkBitmap::Config config,\n SkImageDecoder::Mode mode) {\n return codec->decode(stream, bitmap, config, mode);\n}\n\nbool SkImageRef::prepareBitmap(SkImageDecoder::Mode mode) {\n SkASSERT(&gImageRefMutex == this->mutex());\n\n if (fErrorInDecoding) {\n return false;\n }\n \n \/* As soon as we really know our config, we record it, so that on\n subsequent calls to the codec, we are sure we will always get the same\n result.\n *\/\n if (SkBitmap::kNo_Config != fBitmap.config()) {\n fConfig = fBitmap.config();\n }\n \n if (NULL != fBitmap.getPixels() ||\n (SkBitmap::kNo_Config != fBitmap.config() &&\n SkImageDecoder::kDecodeBounds_Mode == mode)) {\n return true;\n }\n\n SkASSERT(fBitmap.getPixels() == NULL);\n\n fStream->rewind();\n\n SkImageDecoder* codec;\n if (fFactory) {\n codec = fFactory->newDecoder(fStream);\n } else {\n codec = SkImageDecoder::Factory(fStream);\n }\n\n if (codec) {\n SkAutoTDelete ad(codec);\n\n codec->setSampleSize(fSampleSize);\n if (this->onDecode(codec, fStream, &fBitmap, fConfig, mode)) {\n return true;\n }\n }\n\n#ifdef DUMP_IMAGEREF_LIFECYCLE\n if (NULL == codec) {\n SkDebugf(\"--- ImageRef: <%s> failed to find codec\\n\", this->getURI());\n } else {\n SkDebugf(\"--- ImageRef: <%s> failed in codec for %d mode\\n\",\n this->getURI(), mode);\n }\n#endif\n fErrorInDecoding = true;\n fBitmap.reset();\n return false;\n}\n\nvoid* SkImageRef::onLockPixels(SkColorTable** ct) {\n SkASSERT(&gImageRefMutex == this->mutex());\n\n if (NULL == fBitmap.getPixels()) {\n (void)this->prepareBitmap(SkImageDecoder::kDecodePixels_Mode);\n }\n\n if (ct) {\n *ct = fBitmap.getColorTable();\n }\n return fBitmap.getPixels();\n}\n\nvoid SkImageRef::onUnlockPixels() {\n \/\/ we're already have the mutex locked\n SkASSERT(&gImageRefMutex == this->mutex());\n}\n\nsize_t SkImageRef::ramUsed() const {\n size_t size = 0;\n\n if (fBitmap.getPixels()) {\n size = fBitmap.getSize();\n if (fBitmap.getColorTable()) {\n size += fBitmap.getColorTable()->count() * sizeof(SkPMColor);\n }\n }\n return size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkImageRef::SkImageRef(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer, &gImageRefMutex), fErrorInDecoding(false) {\n fConfig = (SkBitmap::Config)buffer.readU8();\n fSampleSize = buffer.readU8();\n size_t length = buffer.readU32();\n fStream = SkNEW_ARGS(SkMemoryStream, (length));\n buffer.read((void*)fStream->getMemoryBase(), length);\n\n fPrev = fNext = NULL;\n fFactory = NULL;\n}\n\nvoid SkImageRef::flatten(SkFlattenableWriteBuffer& buffer) const {\n this->INHERITED::flatten(buffer);\n\n buffer.write8(fConfig);\n buffer.write8(fSampleSize);\n size_t length = fStream->getLength();\n buffer.write32(length);\n fStream->rewind();\n buffer.readFromStream(fStream, length);\n}\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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\/**\n * @file conti_radar_message_manager.h\n * @brief The class of ContiRadarMessageManager\n *\/\n\n#include \"modules\/drivers\/conti_radar\/conti_radar_message_manager.h\"\n\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_general_info_701.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_list_status_600.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_quality_info_702.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_extended_info_60d.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_general_info_60b.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_list_status_60a.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_quality_info_60c.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/radar_state_201.h\"\n\nnamespace apollo {\nnamespace drivers {\nnamespace conti_radar {\n\nusing ::apollo::common::adapter::AdapterManager;\n\nContiRadarMessageManager::ContiRadarMessageManager() {\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n}\n\nvoid ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {\n radar_config_.set_radar_conf(radar_conf);\n}\n\nvoid ContiRadarMessageManager::set_can_client(\n std::shared_ptr can_client) {\n can_client_ = can_client;\n}\n\nProtocolData *ContiRadarMessageManager::GetMutableProtocolDataById(\n const uint32_t message_id) {\n uint32_t converted_message_id = message_id;\n if (protocol_data_map_.find(converted_message_id) ==\n protocol_data_map_.end()) {\n ADEBUG << \"Unable to get protocol data because of invalid message_id:\"\n << message_id;\n return nullptr;\n }\n return protocol_data_map_[converted_message_id];\n}\n\nvoid ContiRadarMessageManager::Parse(const uint32_t message_id,\n const uint8_t *data, int32_t length) {\n \/*\nif (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) {\nAERROR << \"Incorrect ContiRadar message length, length:\" << length\n<< \" required length: \"\n<< ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH;\nreturn;\n}\n*\/\n ProtocolData *sensor_protocol_data =\n GetMutableProtocolDataById(message_id);\n if (sensor_protocol_data == nullptr) {\n return;\n }\n\n std::lock_guard lock(sensor_data_mutex_);\n if (!is_configured_ && message_id != 0x201) {\n \/\/ read radar state message first\n return;\n }\n\n \/\/ trigger publishment\n if (message_id == 0x600 || message_id == 0x60A) {\n ADEBUG << sensor_data_.ShortDebugString();\n\n if (sensor_data_.contiobs_size() <=\n sensor_data_.object_list_status().nof_objects()) {\n \/\/ maybe lost a object_list_status msg\n AdapterManager::PublishContiRadar(sensor_data_);\n }\n sensor_data_.Clear();\n \/\/ fill header when recieve the general info message\n AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);\n }\n\n sensor_protocol_data->Parse(data, length, &sensor_data_);\n\n if (message_id == 0x201) {\n ADEBUG << sensor_data_.ShortDebugString();\n if (sensor_data_.radar_state().send_quality() ==\n radar_config_.radar_conf().send_quality() &&\n sensor_data_.radar_state().send_ext_info() ==\n radar_config_.radar_conf().send_ext_info() &&\n sensor_data_.radar_state().max_distance() ==\n radar_config_.radar_conf().max_distance() &&\n sensor_data_.radar_state().output_type() ==\n radar_config_.radar_conf().output_type() &&\n sensor_data_.radar_state().rcs_threshold() ==\n radar_config_.radar_conf().rcs_threshold() &&\n sensor_data_.radar_state().radar_power() ==\n radar_config_.radar_conf().radar_power()) {\n is_configured_ = true;\n } else {\n AINFO << \"configure radar again\";\n SenderMessage sender_message(RadarConfig200::ID,\n &radar_config_);\n sender_message.Update();\n can_client_->SendSingleFrame({sender_message.CanFrame()});\n }\n }\n\n received_ids_.insert(message_id);\n \/\/ check if need to check period\n const auto it = check_ids_.find(message_id);\n if (it != check_ids_.end()) {\n const int64_t time = apollo::common::time::AsInt64(Clock::Now());\n it->second.real_period = time - it->second.last_time;\n \/\/ if period 1.5 large than base period, inc error_count\n const double period_multiplier = 1.5;\n if (it->second.real_period > (it->second.period * period_multiplier)) {\n it->second.error_count += 1;\n } else {\n it->second.error_count = 0;\n }\n it->second.last_time = time;\n }\n}\n\n} \/\/ namespace conti_radar\n} \/\/ namespace drivers\n} \/\/ namespace apollo\nradar: remove canbus length check. (#1706)\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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\/**\n * @file conti_radar_message_manager.h\n * @brief The class of ContiRadarMessageManager\n *\/\n\n#include \"modules\/drivers\/conti_radar\/conti_radar_message_manager.h\"\n\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_general_info_701.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_list_status_600.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_quality_info_702.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_extended_info_60d.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_general_info_60b.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_list_status_60a.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_quality_info_60c.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/radar_state_201.h\"\n\nnamespace apollo {\nnamespace drivers {\nnamespace conti_radar {\n\nusing ::apollo::common::adapter::AdapterManager;\n\nContiRadarMessageManager::ContiRadarMessageManager() {\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n AddRecvProtocolData();\n}\n\nvoid ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {\n radar_config_.set_radar_conf(radar_conf);\n}\n\nvoid ContiRadarMessageManager::set_can_client(\n std::shared_ptr can_client) {\n can_client_ = can_client;\n}\n\nProtocolData *ContiRadarMessageManager::GetMutableProtocolDataById(\n const uint32_t message_id) {\n uint32_t converted_message_id = message_id;\n if (protocol_data_map_.find(converted_message_id) ==\n protocol_data_map_.end()) {\n ADEBUG << \"Unable to get protocol data because of invalid message_id:\"\n << message_id;\n return nullptr;\n }\n return protocol_data_map_[converted_message_id];\n}\n\nvoid ContiRadarMessageManager::Parse(const uint32_t message_id,\n const uint8_t *data, int32_t length) {\n ProtocolData *sensor_protocol_data =\n GetMutableProtocolDataById(message_id);\n if (sensor_protocol_data == nullptr) {\n return;\n }\n\n std::lock_guard lock(sensor_data_mutex_);\n if (!is_configured_ && message_id != 0x201) {\n \/\/ read radar state message first\n return;\n }\n\n \/\/ trigger publishment\n if (message_id == 0x600 || message_id == 0x60A) {\n ADEBUG << sensor_data_.ShortDebugString();\n\n if (sensor_data_.contiobs_size() <=\n sensor_data_.object_list_status().nof_objects()) {\n \/\/ maybe lost a object_list_status msg\n AdapterManager::PublishContiRadar(sensor_data_);\n }\n sensor_data_.Clear();\n \/\/ fill header when recieve the general info message\n AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);\n }\n\n sensor_protocol_data->Parse(data, length, &sensor_data_);\n\n if (message_id == 0x201) {\n ADEBUG << sensor_data_.ShortDebugString();\n if (sensor_data_.radar_state().send_quality() ==\n radar_config_.radar_conf().send_quality() &&\n sensor_data_.radar_state().send_ext_info() ==\n radar_config_.radar_conf().send_ext_info() &&\n sensor_data_.radar_state().max_distance() ==\n radar_config_.radar_conf().max_distance() &&\n sensor_data_.radar_state().output_type() ==\n radar_config_.radar_conf().output_type() &&\n sensor_data_.radar_state().rcs_threshold() ==\n radar_config_.radar_conf().rcs_threshold() &&\n sensor_data_.radar_state().radar_power() ==\n radar_config_.radar_conf().radar_power()) {\n is_configured_ = true;\n } else {\n AINFO << \"configure radar again\";\n SenderMessage sender_message(RadarConfig200::ID,\n &radar_config_);\n sender_message.Update();\n can_client_->SendSingleFrame({sender_message.CanFrame()});\n }\n }\n\n received_ids_.insert(message_id);\n \/\/ check if need to check period\n const auto it = check_ids_.find(message_id);\n if (it != check_ids_.end()) {\n const int64_t time = apollo::common::time::AsInt64(Clock::Now());\n it->second.real_period = time - it->second.last_time;\n \/\/ if period 1.5 large than base period, inc error_count\n const double period_multiplier = 1.5;\n if (it->second.real_period > (it->second.period * period_multiplier)) {\n it->second.error_count += 1;\n } else {\n it->second.error_count = 0;\n }\n it->second.last_time = time;\n }\n}\n\n} \/\/ namespace conti_radar\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 Joshua Beitler, Mirus contributors\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#ifndef _MIRUS_KERNEL_SERIAL_H_\n#define _MIRUS_KERNEL_SERIAL_H_\n\n#include \n\n#define PORT 0x3f8 \/\/ com1\n\nnamespace mirus {\n void init_serial();\n int serial_received();\n char read_serial();\n int is_transmit_empty();\n void write_serial(char a);\n}\n\n#endifForgot to rename member in the header\/\/ Copyright (c) 2013 Joshua Beitler, Mirus contributors\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#ifndef _MIRUS_KERNEL_SERIAL_H_\n#define _MIRUS_KERNEL_SERIAL_H_\n\n#include \n\n#define PORT 0x3f8 \/\/ com1\n\nnamespace mirus {\n void serial_install();\n int serial_received();\n char read_serial();\n int is_transmit_empty();\n void write_serial(char a);\n}\n\n#endif<|endoftext|>"} {"text":"\/\/\n\/\/ yas_audio_device_io.cpp\n\/\/\n\n#include \"yas_audio_engine_device_io.h\"\n\n#if (TARGET_OS_MAC && !TARGET_OS_IPHONE)\n\n#include \n#include \"yas_audio_device.h\"\n#include \"yas_audio_device_io.h\"\n#include \"yas_audio_engine_tap.h\"\n#include \"yas_audio_graph.h\"\n#include \"yas_audio_time.h\"\n#include \"yas_result.h\"\n\nusing namespace yas;\n\n#pragma mark - audio::engine::device_io::impl\n\nstruct audio::engine::device_io::impl : base::impl, manageable_device_io::impl {\n audio::engine::node _node = {{.input_bus_count = 1, .output_bus_count = 1}};\n chaining::any_observer _connections_observer = nullptr;\n\n virtual ~impl() final = default;\n\n void prepare(engine::device_io const &engine_device_io, audio::device const &device) {\n set_device(device ?: device::default_output_device());\n\n auto weak_engine_device_io = to_weak(engine_device_io);\n\n _node.set_render_handler([weak_engine_device_io](auto args) {\n auto &buffer = args.buffer;\n\n if (auto engine_device_io = weak_engine_device_io.lock()) {\n if (auto const &device_io = engine_device_io.impl_ptr()->device_io()) {\n auto &input_buffer = device_io.input_buffer_on_render();\n if (input_buffer && input_buffer.format() == buffer.format()) {\n buffer.copy_from(input_buffer);\n }\n }\n }\n });\n\n this->_connections_observer = this->_node.chain(node::method::update_connections)\n .perform([weak_engine_device_io](auto const &) {\n if (auto engine_device_io = weak_engine_device_io.lock()) {\n engine_device_io.impl_ptr()->_update_device_io_connections();\n }\n })\n .end();\n }\n\n void add_device_io() override {\n _core._device_io = audio::device_io{_core.device()};\n }\n\n void remove_device_io() override {\n _core._device_io = nullptr;\n }\n\n audio::device_io &device_io() override {\n return _core._device_io;\n }\n\n void set_device(audio::device const &device) {\n _core.set_device(device);\n }\n\n audio::device device() {\n return _core.device();\n }\n\n private:\n struct core {\n audio::device_io _device_io = nullptr;\n\n void set_device(audio::device const &device) {\n _device = device;\n if (_device_io) {\n _device_io.set_device(device);\n }\n }\n\n audio::device device() {\n return _device;\n }\n\n private:\n audio::device _device = nullptr;\n };\n\n core _core;\n\n void _update_device_io_connections() {\n auto &device_io = _core._device_io;\n if (!device_io) {\n return;\n }\n\n if (!_validate_connections()) {\n device_io.set_render_handler(nullptr);\n return;\n }\n\n auto weak_engine_device_io = to_weak(cast());\n auto weak_device_io = to_weak(device_io);\n\n auto render_handler = [weak_engine_device_io, weak_device_io](auto args) {\n if (auto engine_device_io = weak_engine_device_io.lock()) {\n if (auto kernel = engine_device_io.node().kernel()) {\n if (args.output_buffer) {\n auto const connections = kernel.input_connections();\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n if (auto src_node = connection.source_node()) {\n if (connection.format() == src_node.output_format(connection.source_bus())) {\n src_node.render({.buffer = args.output_buffer,\n .bus_idx = connection.source_bus(),\n .when = args.when});\n }\n }\n }\n }\n\n if (auto const device_io = weak_device_io.lock()) {\n auto const connections = kernel.output_connections();\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n if (auto dst_node = connection.destination_node()) {\n if (dst_node.is_input_renderable()) {\n auto input_buffer = device_io.input_buffer_on_render();\n auto const &input_time = device_io.input_time_on_render();\n if (input_buffer && input_time) {\n if (connection.format() ==\n dst_node.input_format(connection.destination_bus())) {\n dst_node.render({.buffer = input_buffer, .bus_idx = 0, .when = input_time});\n }\n }\n }\n }\n }\n }\n }\n }\n };\n\n device_io.set_render_handler(std::move(render_handler));\n }\n\n bool _validate_connections() {\n if (auto const &device_io = _core._device_io) {\n auto &input_connections = _node.input_connections();\n if (input_connections.size() > 0) {\n auto const connections = lock_values(input_connections);\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n auto const &connection_format = connection.format();\n auto const &device_format = device_io.device().output_format();\n if (connection_format != device_format) {\n std::cout << __PRETTY_FUNCTION__ << \" : output device io format is not match.\" << std::endl;\n return false;\n }\n }\n }\n\n auto &output_connections = _node.output_connections();\n if (output_connections.size() > 0) {\n auto const connections = lock_values(output_connections);\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n auto const &connection_format = connection.format();\n auto const &device_format = device_io.device().input_format();\n if (connection_format != device_format) {\n std::cout << __PRETTY_FUNCTION__ << \" : input device io format is not match.\" << std::endl;\n return false;\n }\n }\n }\n }\n\n return true;\n }\n};\n\n#pragma mark - audio::engine::device_io\n\naudio::engine::device_io::device_io() : device_io(audio::device(nullptr)) {\n}\n\naudio::engine::device_io::device_io(std::nullptr_t) : base(nullptr) {\n}\n\naudio::engine::device_io::device_io(audio::device const &device) : base(std::make_unique()) {\n impl_ptr()->prepare(*this, device);\n}\n\naudio::engine::device_io::~device_io() = default;\n\nvoid audio::engine::device_io::set_device(audio::device const &device) {\n impl_ptr()->set_device(device);\n}\n\naudio::device audio::engine::device_io::device() const {\n return impl_ptr()->device();\n}\n\naudio::engine::node const &audio::engine::device_io::node() const {\n return impl_ptr()->_node;\n}\n\naudio::engine::node &audio::engine::device_io::node() {\n return impl_ptr()->_node;\n}\n\naudio::engine::manageable_device_io &audio::engine::device_io::manageable() {\n if (!_manageable) {\n _manageable = audio::engine::manageable_device_io{impl_ptr()};\n }\n return _manageable;\n}\n\n#endif\ndevice_io this\/\/\n\/\/ yas_audio_device_io.cpp\n\/\/\n\n#include \"yas_audio_engine_device_io.h\"\n\n#if (TARGET_OS_MAC && !TARGET_OS_IPHONE)\n\n#include \n#include \"yas_audio_device.h\"\n#include \"yas_audio_device_io.h\"\n#include \"yas_audio_engine_tap.h\"\n#include \"yas_audio_graph.h\"\n#include \"yas_audio_time.h\"\n#include \"yas_result.h\"\n\nusing namespace yas;\n\n#pragma mark - audio::engine::device_io::impl\n\nstruct audio::engine::device_io::impl : base::impl, manageable_device_io::impl {\n audio::engine::node _node = {{.input_bus_count = 1, .output_bus_count = 1}};\n chaining::any_observer _connections_observer = nullptr;\n\n virtual ~impl() final = default;\n\n void prepare(engine::device_io const &engine_device_io, audio::device const &device) {\n this->set_device(device ?: device::default_output_device());\n\n auto weak_engine_device_io = to_weak(engine_device_io);\n\n this->_node.set_render_handler([weak_engine_device_io](auto args) {\n auto &buffer = args.buffer;\n\n if (auto engine_device_io = weak_engine_device_io.lock()) {\n if (auto const &device_io = engine_device_io.impl_ptr()->device_io()) {\n auto &input_buffer = device_io.input_buffer_on_render();\n if (input_buffer && input_buffer.format() == buffer.format()) {\n buffer.copy_from(input_buffer);\n }\n }\n }\n });\n\n this->_connections_observer = this->_node.chain(node::method::update_connections)\n .perform([weak_engine_device_io](auto const &) {\n if (auto engine_device_io = weak_engine_device_io.lock()) {\n engine_device_io.impl_ptr()->_update_device_io_connections();\n }\n })\n .end();\n }\n\n void add_device_io() override {\n this->_core._device_io = audio::device_io{_core.device()};\n }\n\n void remove_device_io() override {\n this->_core._device_io = nullptr;\n }\n\n audio::device_io &device_io() override {\n return this->_core._device_io;\n }\n\n void set_device(audio::device const &device) {\n this->_core.set_device(device);\n }\n\n audio::device device() {\n return this->_core.device();\n }\n\n private:\n struct core {\n audio::device_io _device_io = nullptr;\n\n void set_device(audio::device const &device) {\n this->_device = device;\n if (this->_device_io) {\n this->_device_io.set_device(device);\n }\n }\n\n audio::device device() {\n return this->_device;\n }\n\n private:\n audio::device _device = nullptr;\n };\n\n core _core;\n\n void _update_device_io_connections() {\n auto &device_io = this->_core._device_io;\n if (!device_io) {\n return;\n }\n\n if (!this->_validate_connections()) {\n device_io.set_render_handler(nullptr);\n return;\n }\n\n auto weak_engine_device_io = to_weak(cast());\n auto weak_device_io = to_weak(device_io);\n\n auto render_handler = [weak_engine_device_io, weak_device_io](auto args) {\n if (auto engine_device_io = weak_engine_device_io.lock()) {\n if (auto kernel = engine_device_io.node().kernel()) {\n if (args.output_buffer) {\n auto const connections = kernel.input_connections();\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n if (auto src_node = connection.source_node()) {\n if (connection.format() == src_node.output_format(connection.source_bus())) {\n src_node.render({.buffer = args.output_buffer,\n .bus_idx = connection.source_bus(),\n .when = args.when});\n }\n }\n }\n }\n\n if (auto const device_io = weak_device_io.lock()) {\n auto const connections = kernel.output_connections();\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n if (auto dst_node = connection.destination_node()) {\n if (dst_node.is_input_renderable()) {\n auto input_buffer = device_io.input_buffer_on_render();\n auto const &input_time = device_io.input_time_on_render();\n if (input_buffer && input_time) {\n if (connection.format() ==\n dst_node.input_format(connection.destination_bus())) {\n dst_node.render({.buffer = input_buffer, .bus_idx = 0, .when = input_time});\n }\n }\n }\n }\n }\n }\n }\n }\n };\n\n device_io.set_render_handler(std::move(render_handler));\n }\n\n bool _validate_connections() {\n if (auto const &device_io = this->_core._device_io) {\n auto &input_connections = this->_node.input_connections();\n if (input_connections.size() > 0) {\n auto const connections = lock_values(input_connections);\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n auto const &connection_format = connection.format();\n auto const &device_format = device_io.device().output_format();\n if (connection_format != device_format) {\n std::cout << __PRETTY_FUNCTION__ << \" : output device io format is not match.\" << std::endl;\n return false;\n }\n }\n }\n\n auto &output_connections = _node.output_connections();\n if (output_connections.size() > 0) {\n auto const connections = lock_values(output_connections);\n if (connections.count(0) > 0) {\n auto const &connection = connections.at(0);\n auto const &connection_format = connection.format();\n auto const &device_format = device_io.device().input_format();\n if (connection_format != device_format) {\n std::cout << __PRETTY_FUNCTION__ << \" : input device io format is not match.\" << std::endl;\n return false;\n }\n }\n }\n }\n\n return true;\n }\n};\n\n#pragma mark - audio::engine::device_io\n\naudio::engine::device_io::device_io() : device_io(audio::device(nullptr)) {\n}\n\naudio::engine::device_io::device_io(std::nullptr_t) : base(nullptr) {\n}\n\naudio::engine::device_io::device_io(audio::device const &device) : base(std::make_unique()) {\n impl_ptr()->prepare(*this, device);\n}\n\naudio::engine::device_io::~device_io() = default;\n\nvoid audio::engine::device_io::set_device(audio::device const &device) {\n impl_ptr()->set_device(device);\n}\n\naudio::device audio::engine::device_io::device() const {\n return impl_ptr()->device();\n}\n\naudio::engine::node const &audio::engine::device_io::node() const {\n return impl_ptr()->_node;\n}\n\naudio::engine::node &audio::engine::device_io::node() {\n return impl_ptr()->_node;\n}\n\naudio::engine::manageable_device_io &audio::engine::device_io::manageable() {\n if (!this->_manageable) {\n this->_manageable = audio::engine::manageable_device_io{impl_ptr()};\n }\n return this->_manageable;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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 \"modules\/perception\/obstacle\/radar\/modest\/object_builder.h\"\n\n#include \n\n#include \"modules\/perception\/obstacle\/radar\/modest\/conti_radar_util.h\"\n#include \"modules\/perception\/obstacle\/radar\/modest\/radar_util.h\"\n\nnamespace apollo {\nnamespace perception {\n\nbool ObjectBuilder::Build(const ContiRadar &raw_obstacles,\n const Eigen::Matrix4d &radar_pose,\n const Eigen::Vector2d &main_velocity,\n SensorObjects *radar_objects) {\n if (radar_objects == nullptr) {\n AERROR << \"radar objects is nullptr.\";\n return false;\n }\n std::unordered_map current_con_ids;\n auto objects = &(radar_objects->objects);\n for (int i = 0; i < raw_obstacles.contiobs_size(); ++i) {\n ObjectPtr object_ptr = ObjectPtr(new Object());\n const int obstacle_id = raw_obstacles.contiobs(i).obstacle_id();\n auto continuous_id_it = continuous_ids_.find(obstacle_id);\n if (continuous_id_it != continuous_ids_.end()) {\n current_con_ids[obstacle_id] = continuous_id_it->second + 1;\n } else {\n current_con_ids[obstacle_id] = 1;\n }\n if (current_con_ids[obstacle_id] <= delay_frames_) {\n object_ptr->is_background = true;\n }\n int tracking_times = current_con_ids[obstacle_id];\n if (use_fp_filter_ &&\n ContiRadarUtil::IsFp(raw_obstacles.contiobs(i), conti_params_,\n delay_frames_, tracking_times)) {\n object_ptr->is_background = true;\n }\n object_ptr->track_id = obstacle_id;\n Eigen::Matrix location_r;\n Eigen::Matrix location_w;\n location_r << raw_obstacles.contiobs(i).longitude_dist(),\n raw_obstacles.contiobs(i).lateral_dist(), 0.0, 1.0;\n location_w = radar_pose * location_r;\n Eigen::Vector3d point;\n point = location_w.topLeftCorner(3, 1);\n object_ptr->center = point;\n object_ptr->anchor_point = object_ptr->center;\n Eigen::Matrix velocity_r;\n Eigen::Matrix velocity_w;\n velocity_r << raw_obstacles.contiobs(i).longitude_vel(),\n raw_obstacles.contiobs(i).lateral_vel(), 0.0;\n velocity_w = radar_pose.topLeftCorner(3, 3) * velocity_r;\n\n \/\/ calculate the absolute velodity\n object_ptr->velocity(0) = velocity_w[0] + main_velocity(0);\n object_ptr->velocity(1) = velocity_w[1] + main_velocity(1);\n object_ptr->velocity(2) = 0;\n\n Eigen::Vector3f ref_velocity(main_velocity(0), main_velocity(1), 0.0);\n if (ContiRadarUtil::IsConflict(ref_velocity,\n object_ptr->velocity.cast())) {\n object_ptr->is_background = true;\n }\n\n object_ptr->length = 1.0;\n object_ptr->width = 1.0;\n object_ptr->height = 1.0;\n object_ptr->type = ObjectType::UNKNOWN;\n object_ptr->score_type = ScoreType::SCORE_RADAR;\n object_ptr->score =\n static_cast(raw_obstacles.contiobs(i).probexist());\n\n Eigen::Matrix3d dist_rms;\n Eigen::Matrix3d vel_rms;\n vel_rms.setZero();\n dist_rms.setZero();\n dist_rms(0, 0) = raw_obstacles.contiobs(i).longitude_dist_rms();\n dist_rms(1, 1) = raw_obstacles.contiobs(i).lateral_dist_rms();\n vel_rms(0, 0) = raw_obstacles.contiobs(i).longitude_vel_rms();\n vel_rms(1, 1) = raw_obstacles.contiobs(i).lateral_vel_rms();\n object_ptr->position_uncertainty =\n radar_pose.topLeftCorner(3, 3) * dist_rms * dist_rms.transpose() *\n radar_pose.topLeftCorner(3, 3).transpose();\n object_ptr->velocity_uncertainty =\n radar_pose.topLeftCorner(3, 3) * vel_rms * vel_rms.transpose() *\n radar_pose.topLeftCorner(3, 3).transpose();\n\n double local_theta =\n raw_obstacles.contiobs(i).oritation_angle() \/ 180.0 * M_PI;\n Eigen::Vector3f direction =\n Eigen::Vector3f(cos(local_theta), sin(local_theta), 0);\n direction = radar_pose.topLeftCorner(3, 3).cast() * direction;\n object_ptr->direction = direction.cast();\n \/\/ the avg time diff is from manual\n object_ptr->tracking_time = current_con_ids[obstacle_id] * 0.074;\n double theta = std::atan2(direction(1), direction(0));\n object_ptr->theta = theta;\n \/\/ For radar obstacle , the polygon is supposed to have\n \/\/ four mock point: around obstacle center.\n RadarUtil::MockRadarPolygon(point, object_ptr->length, object_ptr->width,\n theta, &(object_ptr->polygon));\n if (object_ptr->radar_supplement == nullptr) {\n object_ptr->radar_supplement.reset(new RadarSupplement());\n }\n object_ptr->radar_supplement->range = std::sqrt(\n location_r[0] * location_r[0] + location_r[1] * location_r[1]);\n\n object_ptr->radar_supplement->angle = 0;\n objects->push_back(object_ptr);\n }\n continuous_ids_ = current_con_ids;\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\nfix perception compile warning\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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 \"modules\/perception\/obstacle\/radar\/modest\/object_builder.h\"\n\n#include \n\n#include \"modules\/perception\/obstacle\/radar\/modest\/conti_radar_util.h\"\n#include \"modules\/perception\/obstacle\/radar\/modest\/radar_util.h\"\n\nnamespace apollo {\nnamespace perception {\n\nbool ObjectBuilder::Build(const ContiRadar &raw_obstacles,\n const Eigen::Matrix4d &radar_pose,\n const Eigen::Vector2d &main_velocity,\n SensorObjects *radar_objects) {\n if (radar_objects == nullptr) {\n AERROR << \"radar objects is nullptr.\";\n return false;\n }\n std::unordered_map current_con_ids;\n auto objects = &(radar_objects->objects);\n for (int i = 0; i < raw_obstacles.contiobs_size(); ++i) {\n ObjectPtr object_ptr = ObjectPtr(new Object());\n const int obstacle_id = raw_obstacles.contiobs(i).obstacle_id();\n auto continuous_id_it = continuous_ids_.find(obstacle_id);\n if (continuous_id_it != continuous_ids_.end()) {\n current_con_ids[obstacle_id] = continuous_id_it->second + 1;\n } else {\n current_con_ids[obstacle_id] = 1;\n }\n if (current_con_ids[obstacle_id] <= delay_frames_) {\n object_ptr->is_background = true;\n }\n int tracking_times = current_con_ids[obstacle_id];\n if (use_fp_filter_ &&\n ContiRadarUtil::IsFp(raw_obstacles.contiobs(i), conti_params_,\n delay_frames_, tracking_times)) {\n object_ptr->is_background = true;\n }\n object_ptr->track_id = obstacle_id;\n Eigen::Matrix location_r;\n Eigen::Matrix location_w;\n location_r << raw_obstacles.contiobs(i).longitude_dist(),\n raw_obstacles.contiobs(i).lateral_dist(), 0.0, 1.0;\n location_w = radar_pose * location_r;\n Eigen::Vector3d point;\n point = location_w.topLeftCorner(3, 1);\n object_ptr->center = point;\n object_ptr->anchor_point = object_ptr->center;\n Eigen::Matrix velocity_r;\n Eigen::Matrix velocity_w;\n velocity_r << raw_obstacles.contiobs(i).longitude_vel(),\n raw_obstacles.contiobs(i).lateral_vel(), 0.0;\n velocity_w = radar_pose.topLeftCorner(3, 3) * velocity_r;\n\n \/\/ calculate the absolute velodity\n object_ptr->velocity(0) = velocity_w[0] + main_velocity(0);\n object_ptr->velocity(1) = velocity_w[1] + main_velocity(1);\n object_ptr->velocity(2) = 0;\n\n Eigen::Vector3f ref_velocity(main_velocity(0), main_velocity(1), 0.0);\n if (ContiRadarUtil::IsConflict(ref_velocity,\n object_ptr->velocity.cast())) {\n object_ptr->is_background = true;\n }\n\n object_ptr->length = 1.0;\n object_ptr->width = 1.0;\n object_ptr->height = 1.0;\n object_ptr->type = ObjectType::UNKNOWN;\n object_ptr->score_type = ScoreType::SCORE_RADAR;\n object_ptr->score =\n static_cast(raw_obstacles.contiobs(i).probexist());\n\n Eigen::Matrix3d dist_rms;\n Eigen::Matrix3d vel_rms;\n vel_rms.setZero();\n dist_rms.setZero();\n dist_rms(0, 0) = raw_obstacles.contiobs(i).longitude_dist_rms();\n dist_rms(1, 1) = raw_obstacles.contiobs(i).lateral_dist_rms();\n vel_rms(0, 0) = raw_obstacles.contiobs(i).longitude_vel_rms();\n vel_rms(1, 1) = raw_obstacles.contiobs(i).lateral_vel_rms();\n object_ptr->position_uncertainty =\n radar_pose.topLeftCorner(3, 3) * dist_rms * dist_rms.transpose() *\n radar_pose.topLeftCorner(3, 3).transpose();\n object_ptr->velocity_uncertainty =\n radar_pose.topLeftCorner(3, 3) * vel_rms * vel_rms.transpose() *\n radar_pose.topLeftCorner(3, 3).transpose();\n\n double local_theta =\n raw_obstacles.contiobs(i).oritation_angle() \/ 180.0 * M_PI;\n Eigen::Vector3f direction =\n Eigen::Vector3f(cos(local_theta), sin(local_theta), 0);\n direction = radar_pose.topLeftCorner(3, 3).cast() * direction;\n object_ptr->direction = direction.cast();\n \/\/ the avg time diff is from manual\n object_ptr->tracking_time = current_con_ids[obstacle_id] * 0.074;\n double theta = std::atan2(direction(1), direction(0));\n object_ptr->theta = theta;\n \/\/ For radar obstacle , the polygon is supposed to have\n \/\/ four mock point: around obstacle center.\n RadarUtil::MockRadarPolygon(point, object_ptr->length, object_ptr->width,\n theta, &(object_ptr->polygon));\n if (object_ptr->radar_supplement == nullptr) {\n object_ptr->radar_supplement.reset(new RadarSupplement());\n }\n object_ptr->radar_supplement->range = std::sqrt(\n location_r[0] * location_r[0] + location_r[1] * location_r[1]);\n\n object_ptr->radar_supplement->angle = 0;\n objects->push_back(object_ptr);\n }\n continuous_ids_ = current_con_ids;\n return true;\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n#include \"..\/Node_test.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing sofa::simulation::graph::DAGNode;\n\nnamespace sofa {\n\nusing namespace modeling;\nusing namespace simulation;\n\n\n\/** Check the traversal of a Directed Acyclic Graph.\n * The traversal order is recorded in a string, and compared with an expected one.\n * @author Francois Faure, Matthieu Nesme @date 2014\n *\/\nstruct DAG_test : public Sofa_test<>\n{\n DAG_test()\n {\n sofa::simulation::setSimulation(new simulation::graph::DAGSimulation());\n }\n\n\n \/**\n * The TestVisitor struct records the name of the traversed nodes in a string.\n * The string can be analyzed as a trace of the traversal.\n *\/\n struct TestVisitor: public sofa::simulation::Visitor\n {\n\n std::string visited, topdown, bottomup;\n bool tree; \/\/ enforce tree traversal\n TreeTraversalRepetition repeat; \/\/ repeat callbacks\n\n TestVisitor()\n : Visitor(sofa::core::ExecParams::defaultInstance() )\n , tree( false )\n , repeat( NO_REPETITION )\n {\n clear();\n }\n\n void clear()\n {\n visited.clear();\n topdown.clear();\n bottomup.clear();\n }\n\n Result processNodeTopDown(simulation::Node* node)\n {\n visited += node->getName();\n topdown += node->getName();\n return RESULT_CONTINUE;\n }\n\n void processNodeBottomUp(simulation::Node* node)\n {\n visited += node->getName();\n bottomup += node->getName();\n }\n\n bool treeTraversal(TreeTraversalRepetition& r) { r=repeat; return tree; }\n\n };\n\n\n\n \/\/\/ utility function testing a scene graph traversals with given expected results\n void traverse_test( Node::SPtr node, std::string treeTraverse, std::string treeTraverseRepeatAll, std::string treeTraverseRepeatOnce, std::string dagTopDown )\n {\n \/\/ dagBottumUp must be the exact inverse of dagTopDown\n std::string dagBottomUp(dagTopDown);\n std::reverse(dagBottomUp.begin(), dagBottomUp.end());\n\n TestVisitor t;\n\n t.tree = true; \/\/ visitor as TREE traversal w\/o repetition\n t.execute( node.get() );\n \/\/ cout<<\"traverse_simple_tree: visited = \" << t.visited << endl;\n if( t.visited != treeTraverse ){\n ADD_FAILURE() << \"Dag_test::traverse_test treeTraverse: wrong traversal order, expected \"<print(node.get());\n }\n\n\n \/**\n * @brief The root and two children:\n\\f$\n\\begin{array}{ccc}\n & R & \\\\\n \\diagup & & \\diagdown \\\\\n A & & B\n\\end{array}\n\\f$\nExpected output: RAABBR\n *\/\n void traverse_simple_tree()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n root->createChild(\"A\");\n root->createChild(\"B\");\n\n traverse_test( root, \"RAABBR\", \"RAABBR\", \"RAABBR\", \"RAB\" );\n }\n\n\n \/**\n * @brief Diamond-shaped graph:\n\\f$\n\\begin{array}{ccc}\n & R & \\\\\n \\diagup & & \\diagdown \\\\\n A & & B \\\\\n \\diagdown & & \\diagup \\\\\n & C\n\\end{array}\n\\f$\nExpected output: RABCCBAR\n *\/\n void traverse_simple_diamond()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = A->createChild(\"C\");\n B->addChild(C);\n\n traverse_test( root, \"RACCABBR\", \"RACCABCCBR\", \"RACCABCCBR\", \"RABC\" );\n }\n\n\n\/**\n * @brief More complex graph:\n\n R__\n \/ \\ |\n A B |\n \\ \/ |\n C \/\n \\ \/\n D\n |\n E\n\nExpected output: RABCDEEDCBAR\n *\/\n void traverse_complex()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = A->createChild(\"C\");\n B->addChild(C);\n Node::SPtr D = C->createChild(\"D\");\n root->addChild(D);\n Node::SPtr E = D->createChild(\"E\");\n\n traverse_test( root, \"RACDEEDCABBR\", \"RACDEEDCABCDEEDCBDEEDR\", \"RACDEEDCABCCBDDR\", \"RABCDE\" );\n }\n\n\n\/**\n * @brief Even more complex graph:\n\n R__\n \/ \\ |\n A B C\n \\\/ \\|\n D E\n | |\n F G\n\nExpected output: RABCDEEDCBAR\n *\/\n void traverse_morecomplex()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = root->createChild(\"C\");\n Node::SPtr D = A->createChild(\"D\");\n B->addChild(D);\n Node::SPtr E = B->createChild(\"E\");\n C->addChild(E);\n Node::SPtr F = D->createChild(\"F\");\n Node::SPtr G = E->createChild(\"G\");\n\n traverse_test( root, \"RADFFDABEGGEBCCR\", \"RADFFDABDFFDEGGEBCEGGECR\", \"RADFFDABDDEGGEBCEECR\", \"RABDFCEG\" );\n }\n\n};\n\n\nTEST_F( DAG_test, traverse )\n{\n traverse_simple_tree();\n traverse_simple_diamond();\n traverse_complex();\n traverse_morecomplex();\n}\n\nTEST(DAGNodeTest, objectDestruction_singleObject)\n{\n Node_test_objectDestruction_singleObject();\n}\n\nTEST(DAGNodeTest, objectDestruction_multipleObjects)\n{\n Node_test_objectDestruction_multipleObjects();\n}\n\nTEST(DAGNodeTest, objectDestruction_childNode_singleObject)\n{\n Node_test_objectDestruction_childNode_singleObject();\n}\n\nTEST(DAGNodeTest, objectDestruction_childNode_complexChild)\n{\n Node_test_objectDestruction_childNode_complexChild();\n}\n\n\n}\/\/ namespace sofa\nadding another (successful) DAG traversal test\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n#include \"..\/Node_test.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing sofa::simulation::graph::DAGNode;\n\nnamespace sofa {\n\nusing namespace modeling;\nusing namespace simulation;\n\n\n\/** Check the traversal of a Directed Acyclic Graph.\n * The traversal order is recorded in a string, and compared with an expected one.\n * @author Francois Faure, Matthieu Nesme @date 2014\n *\/\nstruct DAG_test : public Sofa_test<>\n{\n DAG_test()\n {\n sofa::simulation::setSimulation(new simulation::graph::DAGSimulation());\n }\n\n\n \/**\n * The TestVisitor struct records the name of the traversed nodes in a string.\n * The string can be analyzed as a trace of the traversal.\n *\/\n struct TestVisitor: public sofa::simulation::Visitor\n {\n\n std::string visited, topdown, bottomup;\n bool tree; \/\/ enforce tree traversal\n TreeTraversalRepetition repeat; \/\/ repeat callbacks\n\n TestVisitor()\n : Visitor(sofa::core::ExecParams::defaultInstance() )\n , tree( false )\n , repeat( NO_REPETITION )\n {\n clear();\n }\n\n void clear()\n {\n visited.clear();\n topdown.clear();\n bottomup.clear();\n }\n\n Result processNodeTopDown(simulation::Node* node)\n {\n visited += node->getName();\n topdown += node->getName();\n return RESULT_CONTINUE;\n }\n\n void processNodeBottomUp(simulation::Node* node)\n {\n visited += node->getName();\n bottomup += node->getName();\n }\n\n bool treeTraversal(TreeTraversalRepetition& r) { r=repeat; return tree; }\n\n };\n\n\n\n \/\/\/ utility function testing a scene graph traversals with given expected results\n void traverse_test( Node::SPtr node, std::string treeTraverse, std::string treeTraverseRepeatAll, std::string treeTraverseRepeatOnce, std::string dagTopDown )\n {\n \/\/ dagBottumUp must be the exact inverse of dagTopDown\n std::string dagBottomUp(dagTopDown);\n std::reverse(dagBottomUp.begin(), dagBottomUp.end());\n\n TestVisitor t;\n\n t.tree = true; \/\/ visitor as TREE traversal w\/o repetition\n t.execute( node.get() );\n \/\/ cout<<\"traverse_simple_tree: visited = \" << t.visited << endl;\n if( t.visited != treeTraverse ){\n ADD_FAILURE() << \"Dag_test::traverse_test treeTraverse: wrong traversal order, expected \"<print(node.get());\n }\n\n\n \/**\n * @brief The root and two children:\n\\f$\n\\begin{array}{ccc}\n & R & \\\\\n \\diagup & & \\diagdown \\\\\n A & & B\n\\end{array}\n\\f$\nExpected output: RAABBR\n *\/\n void traverse_simple_tree()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n root->createChild(\"A\");\n root->createChild(\"B\");\n\n traverse_test( root, \"RAABBR\", \"RAABBR\", \"RAABBR\", \"RAB\" );\n }\n\n\n \/**\n * @brief Diamond-shaped graph:\n\\f$\n\\begin{array}{ccc}\n & R & \\\\\n \\diagup & & \\diagdown \\\\\n A & & B \\\\\n \\diagdown & & \\diagup \\\\\n & C\n\\end{array}\n\\f$\nExpected output: RABCCBAR\n *\/\n void traverse_simple_diamond()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = A->createChild(\"C\");\n B->addChild(C);\n\n traverse_test( root, \"RACCABBR\", \"RACCABCCBR\", \"RACCABCCBR\", \"RABC\" );\n }\n\n\n\/**\n * @brief More complex graph:\n\n R__\n \/ \\ \\\n A B |\n \\ \/ |\n C \/\n \\ \/\n D\n |\n E\n\nExpected output: RABCDEEDCBAR\n *\/\n void traverse_complex()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = A->createChild(\"C\");\n B->addChild(C);\n Node::SPtr D = C->createChild(\"D\");\n root->addChild(D);\n Node::SPtr E = D->createChild(\"E\");\n\n traverse_test( root, \"RACDEEDCABBR\", \"RACDEEDCABCDEEDCBDEEDR\", \"RACDEEDCABCCBDDR\", \"RABCDE\" );\n }\n\n\n\/**\n * @brief Even more complex graph:\n\n R__\n \/ \\ \\\n A B C\n \\\/ \\|\n D E\n | |\n F G\n\n *\/\n void traverse_morecomplex()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = root->createChild(\"C\");\n Node::SPtr D = A->createChild(\"D\");\n B->addChild(D);\n Node::SPtr E = B->createChild(\"E\");\n C->addChild(E);\n Node::SPtr F = D->createChild(\"F\");\n Node::SPtr G = E->createChild(\"G\");\n\n traverse_test( root, \"RADFFDABEGGEBCCR\", \"RADFFDABDFFDEGGEBCEGGECR\", \"RADFFDABDDEGGEBCEECR\", \"RABDFCEG\" );\n }\n\n\n\/**\n * @brief another complex case\n\n R______\n \/ \\ \\ \\ \\\n A B C D E\n \\\/__\/_\/_\/\n F\n |\\\n G |\n |\/\n H\n\n *\/\n void traverse_morecomplex2()\n {\n Node::SPtr root = clearScene();\n root->setName(\"R\");\n Node::SPtr A = root->createChild(\"A\");\n Node::SPtr B = root->createChild(\"B\");\n Node::SPtr C = root->createChild(\"C\");\n Node::SPtr D = root->createChild(\"D\");\n Node::SPtr E = root->createChild(\"E\");\n Node::SPtr F = A->createChild(\"F\");\n B->addChild(F);\n C->addChild(F);\n D->addChild(F);\n E->addChild(F);\n Node::SPtr G = F->createChild(\"G\");\n Node::SPtr H = G->createChild(\"H\");\n F->addChild(H);\n\n traverse_test( root, \"RAFGHHGFABBCCDDEER\",\n \"RAFGHHGHHFABFGHHGHHFBCFGHHGHHFCDFGHHGHHFDEFGHHGHHFER\",\n \"RAFGHHGHHFABFFBCFFCDFFDEFFER\",\n \"RABCDEFGH\" );\n }\n\n};\n\n\n\nTEST_F( DAG_test, traverse )\n{\n traverse_simple_tree();\n traverse_simple_diamond();\n traverse_complex();\n traverse_morecomplex();\n traverse_morecomplex2();\n}\n\nTEST(DAGNodeTest, objectDestruction_singleObject)\n{\n Node_test_objectDestruction_singleObject();\n}\n\nTEST(DAGNodeTest, objectDestruction_multipleObjects)\n{\n Node_test_objectDestruction_multipleObjects();\n}\n\nTEST(DAGNodeTest, objectDestruction_childNode_singleObject)\n{\n Node_test_objectDestruction_childNode_singleObject();\n}\n\nTEST(DAGNodeTest, objectDestruction_childNode_complexChild)\n{\n Node_test_objectDestruction_childNode_complexChild();\n}\n\n\n}\/\/ namespace sofa\n<|endoftext|>"} {"text":"#include \"binary.h\"\n#include \"arduino_gpio.hpp\"\n#include \"arduino_clock.hpp\"\n#include \"arduino_spi.hpp\"\n#include \"arduino_serial.hpp\"\n#include \"arduino_wire.hpp\"\n#include \"Print.hpp\"\n\nusing namespace ::arduino::gpio;\nusing namespace ::arduino::clock;\nusing namespace ::arduino::wire;\nusing namespace ::arduino::serial;\nusing namespace ::arduino::spi;\nusing namespace ::arduino::print;\n\n#include \nusing namespace std;\ntypedef uint8_t\t\t\t\t\t\t\tbyte;\n#define F(X)\t\t\t\t\t\t\tX\n#define pgm_read_byte(X)\t\t\t\t(*X)\n(ARDUINO) Fix auto using namespace std in arduino frontend.#include \"binary.h\"\n#include \"arduino_gpio.hpp\"\n#include \"arduino_clock.hpp\"\n#include \"arduino_spi.hpp\"\n#include \"arduino_serial.hpp\"\n#include \"arduino_wire.hpp\"\n#include \"Print.hpp\"\n\nusing namespace ::arduino::gpio;\nusing namespace ::arduino::clock;\nusing namespace ::arduino::wire;\nusing namespace ::arduino::serial;\nusing namespace ::arduino::spi;\nusing namespace ::arduino::print;\n\n#include \ntypedef uint8_t\t\t\t\t\t\t\tbyte;\n#define F(X)\t\t\t\t\t\t\tX\n#define pgm_read_byte(X)\t\t\t\t(*X)\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#pragma once\n\n#include \n\nnamespace px4\n{\n\nclass WorkQueue; \/\/ forward declaration\n\nstruct wq_config_t {\n\tconst char *name;\n\tuint16_t stacksize;\n\tint8_t relative_priority; \/\/ relative to max\n};\n\nnamespace wq_configurations\n{\nstatic constexpr wq_config_t rate_ctrl{\"wq:rate_ctrl\", 1920, 0}; \/\/ PX4 inner loop highest priority\nstatic constexpr wq_config_t ctrl_alloc{\"wq:ctrl_alloc\", 9500, 0}; \/\/ PX4 control allocation, same priority as rate_ctrl\n\nstatic constexpr wq_config_t SPI0{\"wq:SPI0\", 2336, -1};\nstatic constexpr wq_config_t SPI1{\"wq:SPI1\", 2336, -2};\nstatic constexpr wq_config_t SPI2{\"wq:SPI2\", 2336, -3};\nstatic constexpr wq_config_t SPI3{\"wq:SPI3\", 2336, -4};\nstatic constexpr wq_config_t SPI4{\"wq:SPI4\", 2336, -5};\nstatic constexpr wq_config_t SPI5{\"wq:SPI5\", 2336, -6};\nstatic constexpr wq_config_t SPI6{\"wq:SPI6\", 2336, -7};\n\nstatic constexpr wq_config_t I2C0{\"wq:I2C0\", 2336, -8};\nstatic constexpr wq_config_t I2C1{\"wq:I2C1\", 2336, -9};\nstatic constexpr wq_config_t I2C2{\"wq:I2C2\", 2336, -10};\nstatic constexpr wq_config_t I2C3{\"wq:I2C3\", 2336, -11};\nstatic constexpr wq_config_t I2C4{\"wq:I2C4\", 2336, -12};\n\n\/\/ PX4 att\/pos controllers, highest priority after sensors.\nstatic constexpr wq_config_t nav_and_controllers{\"wq:nav_and_controllers\", 2164, -13};\n\nstatic constexpr wq_config_t INS0{\"wq:INS0\", 6000, -14};\nstatic constexpr wq_config_t INS1{\"wq:INS1\", 6000, -15};\nstatic constexpr wq_config_t INS2{\"wq:INS2\", 6000, -16};\nstatic constexpr wq_config_t INS3{\"wq:INS3\", 6000, -17};\n\nstatic constexpr wq_config_t hp_default{\"wq:hp_default\", 1900, -18};\n\nstatic constexpr wq_config_t uavcan{\"wq:uavcan\", 3624, -19};\n\nstatic constexpr wq_config_t UART0{\"wq:UART0\", 1400, -21};\nstatic constexpr wq_config_t UART1{\"wq:UART1\", 1400, -22};\nstatic constexpr wq_config_t UART2{\"wq:UART2\", 1400, -23};\nstatic constexpr wq_config_t UART3{\"wq:UART3\", 1400, -24};\nstatic constexpr wq_config_t UART4{\"wq:UART4\", 1400, -25};\nstatic constexpr wq_config_t UART5{\"wq:UART5\", 1400, -26};\nstatic constexpr wq_config_t UART6{\"wq:UART6\", 1400, -27};\nstatic constexpr wq_config_t UART7{\"wq:UART7\", 1400, -28};\nstatic constexpr wq_config_t UART8{\"wq:UART8\", 1400, -29};\nstatic constexpr wq_config_t UART_UNKNOWN{\"wq:UART_UNKNOWN\", 1400, -30};\n\nstatic constexpr wq_config_t lp_default{\"wq:lp_default\", 1920, -50};\n\nstatic constexpr wq_config_t test1{\"wq:test1\", 2000, 0};\nstatic constexpr wq_config_t test2{\"wq:test2\", 2000, 0};\n\n} \/\/ namespace wq_configurations\n\n\/**\n * Start the work queue manager task.\n *\/\nint WorkQueueManagerStart();\n\n\/**\n * Stop the work queue manager task.\n *\/\nint WorkQueueManagerStop();\n\n\/**\n * Work queue manager status.\n *\/\nint WorkQueueManagerStatus();\n\n\/**\n * Create (or find) a work queue with a particular configuration.\n *\n * @param new_wq\t\tThe work queue configuration (see WorkQueueManager.hpp).\n * @return\t\tA pointer to the WorkQueue, or nullptr on failure.\n *\/\nWorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);\n\n\/**\n * Map a PX4 driver device id to a work queue (by sensor bus).\n *\n * @param device_id\t\tThe PX4 driver's device id.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &device_bus_to_wq(uint32_t device_id);\n\n\/**\n * Map a serial device path (eg \/dev\/ttyS1) to a work queue.\n *\n * @param device_id\t\tThe device path.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &serial_port_to_wq(const char *serial);\n\nconst wq_config_t &ins_instance_to_wq(uint8_t instance);\n\n\n} \/\/ namespace px4\npx4_work_queue: increasae UART stack\/****************************************************************************\n *\n * Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#pragma once\n\n#include \n\nnamespace px4\n{\n\nclass WorkQueue; \/\/ forward declaration\n\nstruct wq_config_t {\n\tconst char *name;\n\tuint16_t stacksize;\n\tint8_t relative_priority; \/\/ relative to max\n};\n\nnamespace wq_configurations\n{\nstatic constexpr wq_config_t rate_ctrl{\"wq:rate_ctrl\", 1920, 0}; \/\/ PX4 inner loop highest priority\nstatic constexpr wq_config_t ctrl_alloc{\"wq:ctrl_alloc\", 9500, 0}; \/\/ PX4 control allocation, same priority as rate_ctrl\n\nstatic constexpr wq_config_t SPI0{\"wq:SPI0\", 2336, -1};\nstatic constexpr wq_config_t SPI1{\"wq:SPI1\", 2336, -2};\nstatic constexpr wq_config_t SPI2{\"wq:SPI2\", 2336, -3};\nstatic constexpr wq_config_t SPI3{\"wq:SPI3\", 2336, -4};\nstatic constexpr wq_config_t SPI4{\"wq:SPI4\", 2336, -5};\nstatic constexpr wq_config_t SPI5{\"wq:SPI5\", 2336, -6};\nstatic constexpr wq_config_t SPI6{\"wq:SPI6\", 2336, -7};\n\nstatic constexpr wq_config_t I2C0{\"wq:I2C0\", 2336, -8};\nstatic constexpr wq_config_t I2C1{\"wq:I2C1\", 2336, -9};\nstatic constexpr wq_config_t I2C2{\"wq:I2C2\", 2336, -10};\nstatic constexpr wq_config_t I2C3{\"wq:I2C3\", 2336, -11};\nstatic constexpr wq_config_t I2C4{\"wq:I2C4\", 2336, -12};\n\n\/\/ PX4 att\/pos controllers, highest priority after sensors.\nstatic constexpr wq_config_t nav_and_controllers{\"wq:nav_and_controllers\", 2164, -13};\n\nstatic constexpr wq_config_t INS0{\"wq:INS0\", 6000, -14};\nstatic constexpr wq_config_t INS1{\"wq:INS1\", 6000, -15};\nstatic constexpr wq_config_t INS2{\"wq:INS2\", 6000, -16};\nstatic constexpr wq_config_t INS3{\"wq:INS3\", 6000, -17};\n\nstatic constexpr wq_config_t hp_default{\"wq:hp_default\", 1900, -18};\n\nstatic constexpr wq_config_t uavcan{\"wq:uavcan\", 3624, -19};\n\nstatic constexpr wq_config_t UART0{\"wq:UART0\", 1504, -21};\nstatic constexpr wq_config_t UART1{\"wq:UART1\", 1504, -22};\nstatic constexpr wq_config_t UART2{\"wq:UART2\", 1504, -23};\nstatic constexpr wq_config_t UART3{\"wq:UART3\", 1504, -24};\nstatic constexpr wq_config_t UART4{\"wq:UART4\", 1504, -25};\nstatic constexpr wq_config_t UART5{\"wq:UART5\", 1504, -26};\nstatic constexpr wq_config_t UART6{\"wq:UART6\", 1504, -27};\nstatic constexpr wq_config_t UART7{\"wq:UART7\", 1504, -28};\nstatic constexpr wq_config_t UART8{\"wq:UART8\", 1504, -29};\nstatic constexpr wq_config_t UART_UNKNOWN{\"wq:UART_UNKNOWN\", 1504, -30};\n\nstatic constexpr wq_config_t lp_default{\"wq:lp_default\", 1920, -50};\n\nstatic constexpr wq_config_t test1{\"wq:test1\", 2000, 0};\nstatic constexpr wq_config_t test2{\"wq:test2\", 2000, 0};\n\n} \/\/ namespace wq_configurations\n\n\/**\n * Start the work queue manager task.\n *\/\nint WorkQueueManagerStart();\n\n\/**\n * Stop the work queue manager task.\n *\/\nint WorkQueueManagerStop();\n\n\/**\n * Work queue manager status.\n *\/\nint WorkQueueManagerStatus();\n\n\/**\n * Create (or find) a work queue with a particular configuration.\n *\n * @param new_wq\t\tThe work queue configuration (see WorkQueueManager.hpp).\n * @return\t\tA pointer to the WorkQueue, or nullptr on failure.\n *\/\nWorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);\n\n\/**\n * Map a PX4 driver device id to a work queue (by sensor bus).\n *\n * @param device_id\t\tThe PX4 driver's device id.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &device_bus_to_wq(uint32_t device_id);\n\n\/**\n * Map a serial device path (eg \/dev\/ttyS1) to a work queue.\n *\n * @param device_id\t\tThe device path.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &serial_port_to_wq(const char *serial);\n\nconst wq_config_t &ins_instance_to_wq(uint8_t instance);\n\n\n} \/\/ namespace px4\n<|endoftext|>"} {"text":"\/\/ The \"Square Detector\" program.\n\/\/ It loads several images sequentially and tries to find squares in\n\/\/ each image\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace cv;\n\nint thresh = 50, N = 11;\n\n\/\/ Threshold for maximum cosine between angles (x100).\nint maxCosineThresh = 25;\n\n\/\/ Threshold for ratio of shortest side \/ longest side (x100).\nint sideRatioThresh = 75;\n\n\/\/ Find colors of any hue...\nint wallHueLow = 0;\nint wallHueHigh = 179;\n\n\/\/ ...of low saturation...\nint wallSatLow = 0;\nint wallSatHigh = 40;\n\n\/\/ ...ranging down to gray, but not completely dark. That is to say, white.\nint wallValLow = 50;\nint wallValHigh = 255;\n\nros::Publisher visPub;\nosuar_vision::windowCoordinates winCoords;\n\n\/\/ helper function:\n\/\/ finds a cosine of angle between vectors\n\/\/ from pt0->pt1 and from pt0->pt2\nstatic double angle( Point pt1, Point pt2, Point pt0 )\n{\n double dx1 = pt1.x - pt0.x;\n double dy1 = pt1.y - pt0.y;\n double dx2 = pt2.x - pt0.x;\n double dy2 = pt2.y - pt0.y;\n return (dx1*dx2 + dy1*dy2)\/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);\n}\n\n\/\/ returns sequence of squares detected on the image.\n\/\/ the sequence is stored in the specified memory storage\nstatic void findSquares( const Mat& image, vector >& squares )\n{\n squares.clear();\n\n Mat pyr, timg, gray0(image.size(), CV_8U), gray;\n\n \/\/ down-scale and upscale the image to filter out the noise\n pyrDown(image, pyr, Size(image.cols\/2, image.rows\/2));\n pyrUp(pyr, timg, image.size());\n vector > contours;\n\n \/\/ find squares in every color plane of the image\n \/\/for( int c = 0; c < 3; c++ )\n \/\/{\n \/\/int ch[] = {c, 0};\n \/\/mixChannels(&timg, 1, &gray0, 1, ch, 1);\n\n \/\/ try several threshold levels\n for( int l = 0; l < N; l++ )\n {\n \/\/ hack: use Canny instead of zero threshold level.\n \/\/ Canny helps to catch squares with gradient shading\n if( l == 0 )\n {\n \/\/ apply Canny. Take the upper threshold from slider\n \/\/ and set the lower to 0 (which forces edges merging)\n Canny(image, gray, 0, thresh, 5);\n \/\/ dilate canny output to remove potential\n \/\/ holes between edge segments\n dilate(gray, gray, Mat(), Point(-1,-1));\n }\n else\n {\n \/\/ apply threshold if l!=0:\n \/\/ tgray(x,y) = gray(x,y) < (l+1)*255\/N ? 255 : 0\n gray = image >= (l+1)*255\/N;\n }\n\n \/\/ find contours and store them all as a list\n findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);\n\n vector approx;\n\n \/\/ test each contour\n for( size_t i = 0; i < contours.size(); i++ )\n {\n \/\/ approximate contour with accuracy proportional\n \/\/ to the contour perimeter\n approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);\n\n \/\/ square contours should have 4 vertices after approximation\n \/\/ relatively large area (to filter out noisy contours)\n \/\/ and be convex.\n \/\/ Note: absolute value of an area is used because\n \/\/ area may be positive or negative - in accordance with the\n \/\/ contour orientation\n if( approx.size() == 4 &&\n fabs(contourArea(Mat(approx))) > 1000 &&\n isContourConvex(Mat(approx)) )\n {\n double maxCosine = 0;\n double minSideLen = 100000;\n double maxSideLen = 0;\n double sideRatio = 0;\n\n for( int j = 2; j < 5; j++ )\n {\n \/\/ find the maximum cosine of the angle between joint edges\n double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));\n maxCosine = MAX(maxCosine, cosine);\n\n \/\/ Find the maximum difference in length of adjacent\n \/\/ sides\n double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2));\n minSideLen = MIN(minSideLen, sideLen);\n maxSideLen = MAX(maxSideLen, sideLen);\n }\n\n sideRatio = minSideLen \/ maxSideLen;\n\n std::cout << minSideLen << \" \" << maxSideLen << \"\\n\";\n\n \/\/ if cosines of all angles are small\n \/\/ (all angles are ~90 degree) then write quandrange\n \/\/ vertices to resultant sequence\n if( maxCosine < ((double) maxCosineThresh)\/100 && sideRatio >= (double) sideRatioThresh\/100 )\n squares.push_back(approx);\n }\n }\n }\n \/\/}\n}\n\n\n\/\/ the function draws all the squares in the image\nstatic void drawSquares( Mat& image, const vector >& squares )\n{\n for( size_t i = 0; i < squares.size(); i++ )\n {\n const Point* p = &squares[i][0];\n int n = (int)squares[i].size();\n polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);\n\n std::cout << \"x: \" << squares[i][0].x << \" y: \" << squares[i][0].y << \"\\n\";\n\n \/\/ Only publish coordinates for one of the squares. Coordinates are\n \/\/ shifted over by half the camera resolution (which itself is scaled\n \/\/ down by a factor of two!) on each axis. The y coordinate is inverted\n \/\/ so up is positive.\n if (i == 0) {\n winCoords.x = (squares[0][0].x + squares[0][2].x)\/2 - 180;\n winCoords.y = -((squares[0][0].y + squares[0][2].y)\/2 - 120);\n visPub.publish(winCoords);\n }\n }\n}\n\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"vision\");\n ros::NodeHandle nh;\n visPub = nh.advertise(\"window_coordinates\", 1);\n\n \/\/ Instantiate VideoCapture object. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/reading_and_writing_images_and_video.html\n VideoCapture cap(1);\n\n \/\/ Configure video. Our camera NEEDS the frame width to be set to 720\n \/\/ pixels.\n cap.set(CV_CAP_PROP_FRAME_WIDTH, 720);\n cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);\n \/\/cap.set(CV_CAP_PROP_FPS, 20);\n\n \/\/ Instantiate a Mat in which to store each video frame.\n Mat origFrame;\n Mat resizedFrame; \/\/ Scaled-down from origFrame by factor of 2.\n Mat hsvFrame; \/\/ Converted to HSV space from resizedFrame.\n Mat bwFrame; \/\/ Black\/white image after thresholding hsvFrame.\n\n namedWindow(\"origImage\", 1);\n namedWindow(\"hsvImage\", 1);\n namedWindow(\"bwImage\", 1);\n cvNamedWindow(\"control panel\");\n cvCreateTrackbar(\"threshold\", \"control panel\", &thresh, 300, NULL);\n cvCreateTrackbar(\"maxCosineThresh (x100)\", \"control panel\", &maxCosineThresh, 100, NULL);\n cvCreateTrackbar(\"sideRatioThresh (x100)\", \"control panel\", &sideRatioThresh, 100, NULL);\n cvCreateTrackbar(\"wallHueLow\", \"control panel\", &wallHueLow, 179, NULL);\n cvCreateTrackbar(\"wallHueHigh\", \"control panel\", &wallHueHigh, 179, NULL);\n cvCreateTrackbar(\"wallSatLow\", \"control panel\", &wallSatLow, 255, NULL);\n cvCreateTrackbar(\"wallSatHigh\", \"control panel\", &wallSatHigh, 255, NULL);\n cvCreateTrackbar(\"wallValLow\", \"control panel\", &wallValLow, 255, NULL);\n cvCreateTrackbar(\"wallValHigh\", \"control panel\", &wallValHigh, 255, NULL);\n vector > squares;\n\n while (true) {\n \/\/ Capture image.\n cap >> origFrame;\n\n \/\/ Resize the image to increase processing rate. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/image_filtering.html\n pyrDown(origFrame, resizedFrame, Size(origFrame.cols\/2, origFrame.rows\/2));\n\n \/\/ Convert the frame to HSV. TODO: combine this with more filtering and\n \/\/ turn into function.\n cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV);\n\n \/\/ Threshold hsvFrame for color of maze walls.\n inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow),\n Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame);\n\n \/\/ Find and draw squares.\n findSquares(bwFrame, squares);\n drawSquares(resizedFrame, squares);\n\n \/\/ Show the image, with the squares overlaid.\n imshow(\"origImage\", resizedFrame);\n imshow(\"hsvImage\", hsvFrame);\n imshow(\"bwImage\", bwFrame);\n\n \/\/ Wait 5 milliseconds for a keypress.\n int c = waitKey(5);\n \/\/ Exit if the spacebar is pressed. NOTE: killing the program with\n \/\/ Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel\n \/\/ panic! If you really like Ctrl+C, do so at your own risk!\n if ((char) c == 32) {\n return 0;\n }\n }\n\n return 0;\n}\nLabel the four corners of each recognized square.\/\/ The \"Square Detector\" program.\n\/\/ It loads several images sequentially and tries to find squares in\n\/\/ each image\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace cv;\n\nint thresh = 50, N = 11;\n\n\/\/ Threshold for maximum cosine between angles (x100).\nint maxCosineThresh = 25;\n\n\/\/ Threshold for ratio of shortest side \/ longest side (x100).\nint sideRatioThresh = 75;\n\n\/\/ Find colors of any hue...\nint wallHueLow = 0;\nint wallHueHigh = 179;\n\n\/\/ ...of low saturation...\nint wallSatLow = 0;\nint wallSatHigh = 40;\n\n\/\/ ...ranging down to gray, but not completely dark. That is to say, white.\nint wallValLow = 50;\nint wallValHigh = 255;\n\nros::Publisher visPub;\nosuar_vision::windowCoordinates winCoords;\n\n\/\/ helper function:\n\/\/ finds a cosine of angle between vectors\n\/\/ from pt0->pt1 and from pt0->pt2\nstatic double angle( Point pt1, Point pt2, Point pt0 )\n{\n double dx1 = pt1.x - pt0.x;\n double dy1 = pt1.y - pt0.y;\n double dx2 = pt2.x - pt0.x;\n double dy2 = pt2.y - pt0.y;\n return (dx1*dx2 + dy1*dy2)\/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);\n}\n\n\/\/ returns sequence of squares detected on the image.\n\/\/ the sequence is stored in the specified memory storage\nstatic void findSquares( const Mat& image, vector >& squares )\n{\n squares.clear();\n\n Mat pyr, timg, gray0(image.size(), CV_8U), gray;\n\n \/\/ down-scale and upscale the image to filter out the noise\n pyrDown(image, pyr, Size(image.cols\/2, image.rows\/2));\n pyrUp(pyr, timg, image.size());\n vector > contours;\n\n \/\/ find squares in every color plane of the image\n \/\/for( int c = 0; c < 3; c++ )\n \/\/{\n \/\/int ch[] = {c, 0};\n \/\/mixChannels(&timg, 1, &gray0, 1, ch, 1);\n\n \/\/ try several threshold levels\n for( int l = 0; l < N; l++ )\n {\n \/\/ hack: use Canny instead of zero threshold level.\n \/\/ Canny helps to catch squares with gradient shading\n if( l == 0 )\n {\n \/\/ apply Canny. Take the upper threshold from slider\n \/\/ and set the lower to 0 (which forces edges merging)\n Canny(image, gray, 0, thresh, 5);\n \/\/ dilate canny output to remove potential\n \/\/ holes between edge segments\n dilate(gray, gray, Mat(), Point(-1,-1));\n }\n else\n {\n \/\/ apply threshold if l!=0:\n \/\/ tgray(x,y) = gray(x,y) < (l+1)*255\/N ? 255 : 0\n gray = image >= (l+1)*255\/N;\n }\n\n \/\/ find contours and store them all as a list\n findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);\n\n vector approx;\n\n \/\/ test each contour\n for( size_t i = 0; i < contours.size(); i++ )\n {\n \/\/ approximate contour with accuracy proportional\n \/\/ to the contour perimeter\n approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);\n\n \/\/ square contours should have 4 vertices after approximation\n \/\/ relatively large area (to filter out noisy contours)\n \/\/ and be convex.\n \/\/ Note: absolute value of an area is used because\n \/\/ area may be positive or negative - in accordance with the\n \/\/ contour orientation\n if( approx.size() == 4 &&\n fabs(contourArea(Mat(approx))) > 1000 &&\n isContourConvex(Mat(approx)) )\n {\n double maxCosine = 0;\n double minSideLen = 100000;\n double maxSideLen = 0;\n double sideRatio = 0;\n\n for( int j = 2; j < 5; j++ )\n {\n \/\/ find the maximum cosine of the angle between joint edges\n double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));\n maxCosine = MAX(maxCosine, cosine);\n\n \/\/ Find the maximum difference in length of adjacent\n \/\/ sides\n double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2));\n minSideLen = MIN(minSideLen, sideLen);\n maxSideLen = MAX(maxSideLen, sideLen);\n }\n\n sideRatio = minSideLen \/ maxSideLen;\n\n std::cout << minSideLen << \" \" << maxSideLen << \"\\n\";\n\n \/\/ if cosines of all angles are small\n \/\/ (all angles are ~90 degree) then write quandrange\n \/\/ vertices to resultant sequence\n if( maxCosine < ((double) maxCosineThresh)\/100 && sideRatio >= (double) sideRatioThresh\/100 )\n squares.push_back(approx);\n }\n }\n }\n \/\/}\n}\n\n\n\/\/ the function draws all the squares in the image\nstatic void drawSquares( Mat& image, const vector >& squares )\n{\n for( size_t i = 0; i < squares.size(); i++ )\n {\n const Point* p = &squares[i][0];\n int n = (int)squares[i].size();\n polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);\n\n std::cout << \"x: \" << squares[i][0].x << \" y: \" << squares[i][0].y << \"\\n\";\n\n \/\/ Only publish coordinates for one of the squares. Coordinates are\n \/\/ shifted over by half the camera resolution (which itself is scaled\n \/\/ down by a factor of two!) on each axis. The y coordinate is inverted\n \/\/ so up is positive.\n if (i == 0) {\n putText(image, \"0\", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"1\", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"2\", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"3\", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n winCoords.x = (squares[0][0].x + squares[0][2].x)\/2 - 180;\n winCoords.y = -((squares[0][0].y + squares[0][2].y)\/2 - 120);\n visPub.publish(winCoords);\n }\n }\n}\n\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"vision\");\n ros::NodeHandle nh;\n visPub = nh.advertise(\"window_coordinates\", 1);\n\n \/\/ Instantiate VideoCapture object. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/reading_and_writing_images_and_video.html\n VideoCapture cap(1);\n\n \/\/ Configure video. Our camera NEEDS the frame width to be set to 720\n \/\/ pixels.\n cap.set(CV_CAP_PROP_FRAME_WIDTH, 720);\n cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);\n \/\/cap.set(CV_CAP_PROP_FPS, 20);\n\n \/\/ Instantiate a Mat in which to store each video frame.\n Mat origFrame;\n Mat resizedFrame; \/\/ Scaled-down from origFrame by factor of 2.\n Mat hsvFrame; \/\/ Converted to HSV space from resizedFrame.\n Mat bwFrame; \/\/ Black\/white image after thresholding hsvFrame.\n\n namedWindow(\"origImage\", 1);\n namedWindow(\"hsvImage\", 1);\n namedWindow(\"bwImage\", 1);\n cvNamedWindow(\"control panel\");\n cvCreateTrackbar(\"threshold\", \"control panel\", &thresh, 300, NULL);\n cvCreateTrackbar(\"maxCosineThresh (x100)\", \"control panel\", &maxCosineThresh, 100, NULL);\n cvCreateTrackbar(\"sideRatioThresh (x100)\", \"control panel\", &sideRatioThresh, 100, NULL);\n cvCreateTrackbar(\"wallHueLow\", \"control panel\", &wallHueLow, 179, NULL);\n cvCreateTrackbar(\"wallHueHigh\", \"control panel\", &wallHueHigh, 179, NULL);\n cvCreateTrackbar(\"wallSatLow\", \"control panel\", &wallSatLow, 255, NULL);\n cvCreateTrackbar(\"wallSatHigh\", \"control panel\", &wallSatHigh, 255, NULL);\n cvCreateTrackbar(\"wallValLow\", \"control panel\", &wallValLow, 255, NULL);\n cvCreateTrackbar(\"wallValHigh\", \"control panel\", &wallValHigh, 255, NULL);\n vector > squares;\n\n while (true) {\n \/\/ Capture image.\n cap >> origFrame;\n\n \/\/ Resize the image to increase processing rate. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/image_filtering.html\n pyrDown(origFrame, resizedFrame, Size(origFrame.cols\/2, origFrame.rows\/2));\n\n \/\/ Convert the frame to HSV. TODO: combine this with more filtering and\n \/\/ turn into function.\n cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV);\n\n \/\/ Threshold hsvFrame for color of maze walls.\n inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow),\n Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame);\n\n \/\/ Find and draw squares.\n findSquares(bwFrame, squares);\n drawSquares(resizedFrame, squares);\n\n \/\/ Show the image, with the squares overlaid.\n imshow(\"origImage\", resizedFrame);\n imshow(\"hsvImage\", hsvFrame);\n imshow(\"bwImage\", bwFrame);\n\n \/\/ Wait 5 milliseconds for a keypress.\n int c = waitKey(5);\n \/\/ Exit if the spacebar is pressed. NOTE: killing the program with\n \/\/ Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel\n \/\/ panic! If you really like Ctrl+C, do so at your own risk!\n if ((char) c == 32) {\n return 0;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef DLG_NEWPART_H\n#define DLG_NEWPART_H\n\r\n#include \"..\/Partmod\/disk.h\"\r\n\n\/\/(*Headers(DlgNewPart)\n#include \n#include \n#include \n#include \n#include \n\/\/*)\n\nclass DlgNewPart: public wxDialog\n{\n\tpublic:\n\n\t\tDlgNewPart(wxWindow* parent);\n\t\tvirtual ~DlgNewPart();\r\n\r\n\t\tint ShowModal(Disk *disk, int);\r\n\n\t\t\/\/(*Declarations(DlgNewPart)\n\t\twxStaticText* StaticText2;\n\t\twxChoice* ChoicePartitionType;\n\t\twxButton* ButtonOK;\n\t\twxStaticText* StaticText1;\n\t\twxChoice* ChoiceFsType;\n\t\twxButton* ButtonCancel;\n\t\twxChoice* ChoiceSizeMul;\n\t\twxSpinCtrl* SpinCtrlPartitionSize;\n\t\t\/\/*)\n\n\tprotected:\n\n\t\t\/\/(*Identifiers(DlgNewPart)\n\t\tstatic const long IDA_HSHDGSDHUF;\n\t\tstatic const long ID_SIZE_MULTIPLIER;\n\t\tstatic const long ID_STATICTEXT1;\n\t\tstatic const long ID_OK;\n\t\tstatic const long ID_CHOICE1;\n\t\tstatic const long ID_STATICTEXT2;\n\t\tstatic const long ID_CHOICE2;\n\t\t\/\/*)\n\n\tprivate:\n int selected_frs;\r\n Disk *disk;\r\n\n\t\t\/\/(*Handlers(DlgNewPart)\n\t\tvoid OnButtonOKClick(wxCommandEvent& event);\n\t\tvoid OnButtonCancelClick(wxCommandEvent& event);\n\t\tvoid OnChoicePartitionTypeSelect(wxCommandEvent& event);\n\t\t\/\/*)\n\r\n\n\t\tDECLARE_EVENT_TABLE()\n};\n\n#endif\ngit-svn-id: svn:\/\/svn.code.sf.net\/p\/partmodproject\/code\/trunk@21 3d63fe75-a90b-4577-b595-b0b07fb0d485#ifndef DLG_NEWPART_H\n#define DLG_NEWPART_H\n\r\n#include \"..\/Partmod\/disk.h\"\r\n\n\/\/(*Headers(DlgNewPart)\n#include \n#include \n#include \n#include \n#include \n\/\/*)\n\nclass DlgNewPart: public wxDialog\n{\n\tpublic:\n\n\t\tDlgNewPart(wxWindow* parent);\n\t\tvirtual ~DlgNewPart();\r\n\r\n\t\tint ShowModal(Disk *disk, int);\r\n\n\t\t\/\/(*Declarations(DlgNewPart)\n\t\twxStaticText* StaticText2;\n\t\twxChoice* ChoicePartitionType;\n\t\twxStaticText* StaticText1;\n\t\twxChoice* ChoiceFsType;\n\t\twxChoice* ChoiceSizeMul;\n\t\twxSpinCtrl* SpinCtrlPartitionSize;\n\t\t\/\/*)\n\n\tprotected:\n\n\t\t\/\/(*Identifiers(DlgNewPart)\n\t\tstatic const long ID_SPINCTRL1;\n\t\tstatic const long ID_CHOICE1;\n\t\tstatic const long ID_STATICTEXT1;\n\t\tstatic const long ID_CHOICE2;\n\t\tstatic const long ID_STATICTEXT2;\n\t\tstatic const long ID_CHOICE3;\n\t\t\/\/*)\n\n\tprivate:\n int selected_frs;\r\n Disk *disk;\r\n\n\t\t\/\/(*Handlers(DlgNewPart)\n\t\tvoid OnButtonOKClick(wxCommandEvent& event);\n\t\tvoid OnButtonCancelClick(wxCommandEvent& event);\n\t\tvoid OnChoicePartitionTypeSelect(wxCommandEvent& event);\n\t\tvoid OnChoice2Select(wxCommandEvent& event);\n\t\t\/\/*)\n\r\n\n\t\tDECLARE_EVENT_TABLE()\n};\n\n#endif\n<|endoftext|>"} {"text":"enum TagType\n{\n TAG_UI_CONTAINER =0,\n TAG_BUTTON,\n TAG_LISTBOX,\/\/No extra details\n TAG_TEXTFIELD,\n TAG_SCROLLBAR,\n TAG_LABEL,\n TAG_DYNAMIC_IMAGE,\n TAG_LABEL_FONT,\n TAG_IMAGE = 12\/\/No extra details\n};\n\n\n#define TAUI_ATTRIBUTE_SCROLLBAR_HORIZONTAL 1\n#define TAUI_ATTRIBUTE_SCROLLBAR_VERTICAL 2\n\nconst int FILE_UI_MAX_STRING_LENGTH = 32;\n\nstruct TAUIElement\n{\n char * Name;\n TagType ElementType;\n int Association,X,Y,Width,Height,ColorFore,ColorBack,TextureNumber,FontNumber;\n int Attributes, CommonAttributes;\n char * Help;\n uint8_t Visible;\/\/Pulls from active\n void * Details;\n};\n\nstruct TAUIContainer\n{\n Texture * Background;\/\/Name is in Panel\n TAUIElement * DefaultFocus;\n int NumberOfElements;\n TAUIElement * Elements;\n TextureContainer * Textures;\n};\n\nstruct TAUIButton\n{\n int StartingFrame;\/\/pulls from status\n int Stages;\n char * Text;\/\/ | seperator for multistage buttons, center aligned for simple (single stage) buttons, right aligned otherwise\n uint8_t Disabled;\/\/pulls from grayedout\n};\n\nstruct TAUITextBox\n{\n int MaximumCharacters;\n};\n\nstruct TAUIScrollbar\n{\n int Maximum;\n int Position;\n int KnobSize;\n};\n\nstruct TAUILabel\n{\n char * Text;\n TAUIButton * Link;\n};\n\nstruct TAUIDynamicImage\n{\n uint8_t DisaplySelectionRectangle;\/\/Puller from hotornot\n};\n\nstruct TAULabelFont\n{\n FNTFont * Font;\/\/from filename\n};\n\n\n\n\nstruct FILE_UINameValue\n{\n char Name[FILE_UI_MAX_STRING_LENGTH];\n char Value[FILE_UI_MAX_STRING_LENGTH];\n FILE_UINameValue * Next;\n};\n\nstruct FILE_UIElement\n{\n FILE_UIElement * Next;\n FILE_UIElement * Child;\n FILE_UINameValue * Value;\n char Name[FILE_UI_MAX_STRING_LENGTH];\n};\n\nchar * GetStringValue(FILE_UIElement * Element, const char * Name)\n{\n FILE_UINameValue * NameValue = Element->Value;\n while(NameValue)\n {\n\tif(CaseInsensitiveMatch(Name, NameValue->Name))\n\t return NameValue->Value;\n\tNameValue = NameValue->Next;\n }\n return 0;\n}\n\nint GetIntValue(FILE_UIElement * Element, const char * Name)\n{\n char * Value=GetStringValue(Element,Name);\n if(Value)\n\treturn atoi(Value);\n return -1;\n}\n \nfloat GetFloat(FILE_UIElement * Element, const char * Name)\n{\n char * Value= GetStringValue(Element,Name);\n if(Value)\n\treturn (float)atof(Value);\n return -1;\n}\n\nFILE_UIElement * GetSubElement(FILE_UIElement * Root, const char * Name)\n{\n FILE_UIElement * element = Root->Child;\n while(element)\n {\n\tif(CaseInsensitiveMatch(Name, element->Name))\n\t return element;\n\telement=element->Next;\n }\n return 0;\n}\n\nFILE_UIElement * GetNthElement(FILE_UIElement * Start, int N)\n{\n if(N ==0 || !Start)\n\treturn Start;\n return GetNthElement(Start, N-1);\n}\n\nint CountElements(FILE_UIElement * First)\n{\n int count = 0;\n while(First)\n {\n\tFirst = First->Next;\n\tcount++;\n }\n return count;\n}\n\nFILE_UINameValue * LoadUINameValueFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)\n{\n char * Buffer = *InBuffer;\n char * Start=Buffer;\n while(*Buffer != '=' && *Buffer != ' ' && *Buffer != '\\t' && *Buffer != '\\r' && *Buffer!='\\n' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n char sep = *Buffer;\n *Buffer =0;\n FILE_UINameValue * Result = PushStruct(Arena, FILE_UINameValue);\n *Result={};\n strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);\n Buffer++;\n if(sep != '=')\n {\n\twhile((*Buffer == '=' || *Buffer != ' ' || *Buffer != '\\t' || *Buffer != '\\r' || *Buffer!='\\n')\n\t && Buffer <=End) { Buffer++; }\n\tif(Buffer >= End){\treturn 0; }\n }\n Start = Buffer;\n while(*Buffer != ';' && Buffer <=End) { Buffer++; }\n if(Buffer >= End){\treturn 0; }\n *Buffer =0;\n strncpy(Result->Value, Start, FILE_UI_MAX_STRING_LENGTH);\n Buffer++;\n \n *InBuffer = Buffer;\n return Result;\n}\n\nFILE_UIElement * LoadUIElementFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)\n{\n char * Buffer = *InBuffer;\n while(*Buffer != '[' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n char * Start = Buffer+1;\n while(*Buffer != ']' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n *Buffer =0;\n \n FILE_UIElement * Result = PushStruct(Arena, FILE_UIElement);\n *Result={};\n strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);\n while(*Buffer != '{' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n Buffer++;\n\n while(Buffer<=End)\n {\n\twhile((*Buffer == ' ' || *Buffer == '\\t' || *Buffer =='\\r' || *Buffer == '\\n' )&& Buffer <=End) { Buffer++; }\n\tif(Buffer == End){\treturn 0; }\n\tif(*Buffer =='}')\n\t{\n\t Buffer++;\n\t *InBuffer = Buffer;\n\t return Result;\n\t}\n\telse if(*Buffer == '[')\n\t{\n\t if(Result->Child)\n\t {\n\t\tFILE_UIElement * Child = Result->Child;\n\t\twhile(Child->Next)\n\t\t{\n\t\t Child=Child->Next;\n\t\t}\n\t\tChild->Next=LoadUIElementFromBuffer(&Buffer,End, Arena);\n\t }\n\t else\n\t {\n\t\tResult->Child = LoadUIElementFromBuffer(&Buffer, End, Arena);\n\t }\n\t}\n\telse\n\t{\n\t if(Result->Value)\n\t {\n\t\tFILE_UINameValue * Value = Result->Value;\n\t\twhile(Value->Next)\n\t\t{\n\t\t Value=Value->Next;\n\t\t}\n\t\tValue->Next = LoadUINameValueFromBuffer(&Buffer, End, Arena);\n\t }\n\t else\n\t {\n\t\tResult->Value=LoadUINameValueFromBuffer(&Buffer, End, Arena);\n\t }\n\t}\n\t \n }\n *InBuffer = Buffer;\n return 0;\n}\n\nFILE_UIElement * LoadUIElementsFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)\n{\n FILE_UIElement * First = LoadUIElementFromBuffer(InBuffer, End, Arena);\n FILE_UIElement * Last = First;\n while(*InBuffer Next = LoadUIElementFromBuffer(InBuffer, End, Arena);\n\tif(Last->Next)\n\t{\n\t Last = Last->Next;\n\t}\n }\n return First;\n}\n\nvoid LoadElementFromTree(TAUIElement * Element, FILE_UIElement * Tree, MemoryArena * Arena, TextureContainer * Textures, GameState * CurrentGameState)\n{\n FILE_UIElement * Common = GetSubElement(Tree,\"common\");\n Element->ElementType = (TagType)GetIntValue(Common, \"ID\");\n\n Element->Association = GetIntValue(Common, \"assoc\");\n Element->X = GetIntValue(Common, \"xpos\");\n Element->Y = GetIntValue(Common, \"ypos\");\n Element->Width = GetIntValue(Common, \"width\");\n Element->Height = GetIntValue(Common, \"height\");\n Element->Attributes = GetIntValue(Common, \"attribs\");\n Element->ColorFore = GetIntValue(Common, \"colorf\");\n Element->ColorBack = GetIntValue(Common, \"colorb\");\n Element->TextureNumber = GetIntValue(Common, \"texturenumber\");\n Element->FontNumber = GetIntValue(Common, \"fontnumber\");\n Element->CommonAttributes = GetIntValue(Common, \"commonattribs\");\n Element->Visible = GetIntValue(Common, \"active\");\n\n char * Name = GetStringValue(Common, \"name\");\n int len = strlen(Name);\n Element->Name = PushArray(Arena, len+1, char);\n if(Element->Name)\n {\n\tmemcpy(Element->Name, Name, len);\n\tElement->Name[len]=0;\n }\n \n char * Help = GetStringValue(Common, \"help\");\n\n len = strlen(Help);\n Element->Help = PushArray(Arena, len+1, char);\n if(Element->Help)\n {\n\tmemcpy(Element->Help, Help, len);\n\tElement->Help[len]=0;\n }\n\n switch(Element->ElementType)\n {\n case TAG_UI_CONTAINER:\n {\n\tTAUIContainer * Container = PushStruct(Arena, TAUIContainer);\n\tElement->Details = Container;\n\tif(CaseInsensitiveMatch(Name, \"Mainmenu.gui\"))\n\t{\n\t Container->Background = AddPCXToTextureContainer(Textures,\"bitmaps\/FrontEndX.pcx\", CurrentGameState);\n\t}\n\telse\n\t{\n\t Container->Background = GetTexture(Name, Textures);\n\t}\n }\n\tbreak;\n\n }\n \n}\n\n\n\nTAUIElement * LoadGUIFromBuffer(char * Buffer, char * End, MemoryArena * Arena, MemoryArena * TempArena, char * FileName, GameState * CurrentGameState)\n{\n TextureContainer * Textures =PushStruct(Arena, TextureContainer);\n SetupTextureContainer(Textures, 1024,1024, 40, Arena);\n\n \n int len=snprintf(0,0,\"anims\/%s\",FileName)+1;\n STACK_ARRAY(GafFileName,len,char);\n snprintf(GafFileName,len,\"anims\/%s\",FileName);\n GafFileName[len-4]='g';\n GafFileName[len-3]='a';\n GafFileName[len-2]='f';\n \n HPIEntry UITextures = FindEntryInAllFiles(GafFileName, CurrentGameState);\n if(UITextures.IsDirectory)\n {\n\tLogError(\"Unexpectedly found a directory while trying to load %s\", GafFileName);\n }\n else if(!UITextures.Name)\n {\n\tLogError(\"Failed to load %s\", GafFileName);\n }\n else\n {\n\tLoadAllTexturesFromHPIEntry(&UITextures, Textures, TempArena, CurrentGameState->PaletteData);\n }\n MemoryArena * UIElementsArena = PushSubArena(TempArena, 16 * 1024);\n FILE_UIElement * First = LoadUIElementsFromBuffer(&Buffer, End, UIElementsArena);\n\n if(GetIntValue(GetSubElement(First,\"common\"),\"ID\") != 0)\n {\n\tLogError(\"First UI element is not a container (%d)!\",GetIntValue(GetSubElement(First,\"common\"),\"ID\"));\n\treturn 0;\n }\n\n TAUIElement * Container = PushStruct(Arena, TAUIElement);\n LoadElementFromTree(Container, First, Arena, Textures, CurrentGameState);\n\n TAUIContainer * ContainerDetails = (TAUIContainer *)Container->Details;\n ContainerDetails->NumberOfElements = CountElements(First)-1;\n ContainerDetails->Elements = PushArray(Arena, ContainerDetails->NumberOfElements, TAUIElement);\n ContainerDetails->Textures = Textures;\n\n for(int i=0;iNumberOfElements;i++)\n {\n\tLoadElementFromTree(&ContainerDetails->Elements[i], GetNthElement(First, i+1), Arena, Textures, CurrentGameState);\n }\n\n \n\n\n \n PopSubArena(TempArena, UIElementsArena);\n return Container;\n}\n\n\nvoid LoadCommonUITextures(GameState * CurrentGameState)\n{\n SetupTextureContainer(CurrentGameState->CommonGUITextures, COMMONUI_TEXTURE_WIDTH, COMMONUI_TEXTURE_HEIGHT, COMMONUI_MAX_TEXTURES, &CurrentGameState->GameArena);\n if(!CurrentGameState->PaletteLoaded)\n {\n\tLoadPalette(CurrentGameState);\n }\n HPIEntry CommonUI = FindEntryInAllFiles(\"anims\/commonGUI.GAF\", CurrentGameState);\n if(CommonUI.IsDirectory)\n {\n\tLogError(\"Unexpectedly found a directory while trying to load hatfont12.gaf\");\n }\n else if(!CommonUI.Name)\n {\n\tLogError(\"Failed to get commonGUI.gaf\");\n }\n else\n {\n\tLoadAllTexturesFromHPIEntry(&CommonUI, CurrentGameState->CommonGUITextures, &CurrentGameState->TempArena, CurrentGameState->PaletteData);\n }\n\n}\nLoad more types of UI elements from GUI files.enum TagType\n{\n TAG_UI_CONTAINER =0,\n TAG_BUTTON,\n TAG_LISTBOX,\/\/No extra details\n TAG_TEXTFIELD,\n TAG_SCROLLBAR,\n TAG_LABEL,\n TAG_DYNAMIC_IMAGE,\n TAG_LABEL_FONT,\n TAG_IMAGE = 12\/\/No extra details\n};\n\n\n#define TAUI_ATTRIBUTE_SCROLLBAR_HORIZONTAL 1\n#define TAUI_ATTRIBUTE_SCROLLBAR_VERTICAL 2\n\nconst int FILE_UI_MAX_STRING_LENGTH = 32;\n\nstruct TAUIElement\n{\n char * Name;\n TagType ElementType;\n int Association,X,Y,Width,Height,ColorFore,ColorBack,TextureNumber,FontNumber;\n int Attributes, CommonAttributes;\n char * Help;\n uint8_t Visible;\/\/Pulls from active\n void * Details;\n};\n\nstruct TAUIContainer\n{\n Texture * Background;\/\/Name is in Panel\n TAUIElement * DefaultFocus;\n int NumberOfElements;\n TAUIElement * Elements;\n TextureContainer * Textures;\n};\n\nstruct TAUIButton\n{\n int StartingFrame;\/\/pulls from status\n int Stages;\n char * Text;\/\/ | seperator for multistage buttons, center aligned for simple (single stage) buttons, right aligned otherwise\n uint8_t Disabled;\/\/pulls from grayedout\n};\n\nstruct TAUITextBox\n{\n int MaximumCharacters;\n};\n\nstruct TAUIScrollbar\n{\n int Maximum;\n int Position;\n int KnobSize;\n};\n\nstruct TAUILabel\n{\n char * Text;\n TAUIButton * Link;\n};\n\nstruct TAUIDynamicImage\n{\n uint8_t DisaplySelectionRectangle;\/\/Puller from hotornot\n};\n\nstruct TAULabelFont\n{\n FNTFont * Font;\/\/from filename\n};\n\n\n\n\nstruct FILE_UINameValue\n{\n char Name[FILE_UI_MAX_STRING_LENGTH];\n char Value[FILE_UI_MAX_STRING_LENGTH];\n FILE_UINameValue * Next;\n};\n\nstruct FILE_UIElement\n{\n FILE_UIElement * Next;\n FILE_UIElement * Child;\n FILE_UINameValue * Value;\n char Name[FILE_UI_MAX_STRING_LENGTH];\n};\n\nchar * GetStringValue(FILE_UIElement * Element, const char * Name)\n{\n FILE_UINameValue * NameValue = Element->Value;\n while(NameValue)\n {\n\tif(CaseInsensitiveMatch(Name, NameValue->Name))\n\t return NameValue->Value;\n\tNameValue = NameValue->Next;\n }\n return 0;\n}\n\nint GetIntValue(FILE_UIElement * Element, const char * Name)\n{\n char * Value=GetStringValue(Element,Name);\n if(Value)\n\treturn atoi(Value);\n return -1;\n}\n \nfloat GetFloat(FILE_UIElement * Element, const char * Name)\n{\n char * Value= GetStringValue(Element,Name);\n if(Value)\n\treturn (float)atof(Value);\n return -1;\n}\n\nFILE_UIElement * GetSubElement(FILE_UIElement * Root, const char * Name)\n{\n FILE_UIElement * element = Root->Child;\n while(element)\n {\n\tif(CaseInsensitiveMatch(Name, element->Name))\n\t return element;\n\telement=element->Next;\n }\n return 0;\n}\n\nFILE_UIElement * GetNthElement(FILE_UIElement * Start, int N)\n{\n if(N ==0 || !Start)\n\treturn Start;\n return GetNthElement(Start, N-1);\n}\n\nint CountElements(FILE_UIElement * First)\n{\n int count = 0;\n while(First)\n {\n\tFirst = First->Next;\n\tcount++;\n }\n return count;\n}\n\nFILE_UINameValue * LoadUINameValueFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)\n{\n char * Buffer = *InBuffer;\n char * Start=Buffer;\n while(*Buffer != '=' && *Buffer != ' ' && *Buffer != '\\t' && *Buffer != '\\r' && *Buffer!='\\n' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n char sep = *Buffer;\n *Buffer =0;\n FILE_UINameValue * Result = PushStruct(Arena, FILE_UINameValue);\n *Result={};\n strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);\n Buffer++;\n if(sep != '=')\n {\n\twhile((*Buffer == '=' || *Buffer != ' ' || *Buffer != '\\t' || *Buffer != '\\r' || *Buffer!='\\n')\n\t && Buffer <=End) { Buffer++; }\n\tif(Buffer >= End){\treturn 0; }\n }\n Start = Buffer;\n while(*Buffer != ';' && Buffer <=End) { Buffer++; }\n if(Buffer >= End){\treturn 0; }\n *Buffer =0;\n strncpy(Result->Value, Start, FILE_UI_MAX_STRING_LENGTH);\n Buffer++;\n \n *InBuffer = Buffer;\n return Result;\n}\n\nFILE_UIElement * LoadUIElementFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)\n{\n char * Buffer = *InBuffer;\n while(*Buffer != '[' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n char * Start = Buffer+1;\n while(*Buffer != ']' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n *Buffer =0;\n \n FILE_UIElement * Result = PushStruct(Arena, FILE_UIElement);\n *Result={};\n strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);\n while(*Buffer != '{' && Buffer <=End) { Buffer++; }\n if(Buffer == End){\treturn 0; }\n Buffer++;\n\n while(Buffer<=End)\n {\n\twhile((*Buffer == ' ' || *Buffer == '\\t' || *Buffer =='\\r' || *Buffer == '\\n' )&& Buffer <=End) { Buffer++; }\n\tif(Buffer == End){\treturn 0; }\n\tif(*Buffer =='}')\n\t{\n\t Buffer++;\n\t *InBuffer = Buffer;\n\t return Result;\n\t}\n\telse if(*Buffer == '[')\n\t{\n\t if(Result->Child)\n\t {\n\t\tFILE_UIElement * Child = Result->Child;\n\t\twhile(Child->Next)\n\t\t{\n\t\t Child=Child->Next;\n\t\t}\n\t\tChild->Next=LoadUIElementFromBuffer(&Buffer,End, Arena);\n\t }\n\t else\n\t {\n\t\tResult->Child = LoadUIElementFromBuffer(&Buffer, End, Arena);\n\t }\n\t}\n\telse\n\t{\n\t if(Result->Value)\n\t {\n\t\tFILE_UINameValue * Value = Result->Value;\n\t\twhile(Value->Next)\n\t\t{\n\t\t Value=Value->Next;\n\t\t}\n\t\tValue->Next = LoadUINameValueFromBuffer(&Buffer, End, Arena);\n\t }\n\t else\n\t {\n\t\tResult->Value=LoadUINameValueFromBuffer(&Buffer, End, Arena);\n\t }\n\t}\n\t \n }\n *InBuffer = Buffer;\n return 0;\n}\n\nFILE_UIElement * LoadUIElementsFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)\n{\n FILE_UIElement * First = LoadUIElementFromBuffer(InBuffer, End, Arena);\n FILE_UIElement * Last = First;\n while(*InBuffer Next = LoadUIElementFromBuffer(InBuffer, End, Arena);\n\tif(Last->Next)\n\t{\n\t Last = Last->Next;\n\t}\n }\n return First;\n}\n\nvoid LoadElementFromTree(TAUIElement * Element, FILE_UIElement * Tree, MemoryArena * Arena, TextureContainer * Textures, GameState * CurrentGameState)\n{\n FILE_UIElement * Common = GetSubElement(Tree,\"common\");\n Element->ElementType = (TagType)GetIntValue(Common, \"ID\");\n\n Element->Association = GetIntValue(Common, \"assoc\");\n Element->X = GetIntValue(Common, \"xpos\");\n Element->Y = GetIntValue(Common, \"ypos\");\n Element->Width = GetIntValue(Common, \"width\");\n Element->Height = GetIntValue(Common, \"height\");\n Element->Attributes = GetIntValue(Common, \"attribs\");\n Element->ColorFore = GetIntValue(Common, \"colorf\");\n Element->ColorBack = GetIntValue(Common, \"colorb\");\n Element->TextureNumber = GetIntValue(Common, \"texturenumber\");\n Element->FontNumber = GetIntValue(Common, \"fontnumber\");\n Element->CommonAttributes = GetIntValue(Common, \"commonattribs\");\n Element->Visible = GetIntValue(Common, \"active\");\n\n char * Name = GetStringValue(Common, \"name\");\n int len = strlen(Name);\n Element->Name = PushArray(Arena, len+1, char);\n if(Element->Name)\n {\n\tmemcpy(Element->Name, Name, len);\n\tElement->Name[len]=0;\n }\n \n char * Help = GetStringValue(Common, \"help\");\n\n len = strlen(Help);\n Element->Help = PushArray(Arena, len+1, char);\n if(Element->Help)\n {\n\tmemcpy(Element->Help, Help, len);\n\tElement->Help[len]=0;\n }\n\n switch(Element->ElementType)\n {\n case TAG_UI_CONTAINER:\n {\n\tTAUIContainer * Container = PushStruct(Arena, TAUIContainer);\n\tElement->Details = Container;\n\tif(CaseInsensitiveMatch(Name, \"Mainmenu.gui\"))\n\t{\n\t Container->Background = AddPCXToTextureContainer(Textures,\"bitmaps\/FrontEndX.pcx\", CurrentGameState);\n\t}\n\telse\n\t{\n\t Container->Background = GetTexture(Name, Textures);\n\t}\n }\n break;\n case TAG_BUTTON:\n {\n\tTAUIButton * Button = PushStruct(Arena, TAUIButton);\n\tElement->Details = Button;\n\tButton->StartingFrame = GetIntValue(Tree, \"status\");\n\tButton->Stages = GetIntValue(Tree, \"Stages\");\n\tchar * Text = GetStringValue(Tree, \"text\");\n\tint len = strlen(Text);\n\tButton->Text = PushArray(Arena, len+1, char);\n\tif(Button->Text)\n\t{\n\t memcpy(Button->Text, Text, len);\n\t Button->Text[len]=0;\n\t}\n\n\tButton->Disabled = GetIntValue(Tree, \"grayedout\");\n }\n break;\n case TAG_TEXTFIELD:\n {\n\tTAUITextBox * TextBox = PushStruct(Arena,TAUITextBox);\n\tElement->Details = TextBox;\n\tTextBox->MaximumCharacters = GetIntValue(Tree, \"maxchars\");\n }\n break;\n case TAG_SCROLLBAR:\n {\n\tTAUIScrollbar * ScrollBar = PushStruct(Arena, TAUIScrollbar);\n\tElement->Details = ScrollBar;\n\tScrollBar->Maximum = GetIntValue(Tree, \"range\");\n\tScrollBar->Position = GetIntValue(Tree, \"knobpos\");\n\tScrollBar->KnobSize = GetIntValue(Tree, \"knobsize\");\n }\n break;\n \/\/TODO(Christof): handle all UI elements\n }\n \n \n}\n\n\n\nTAUIElement * LoadGUIFromBuffer(char * Buffer, char * End, MemoryArena * Arena, MemoryArena * TempArena, char * FileName, GameState * CurrentGameState)\n{\n TextureContainer * Textures =PushStruct(Arena, TextureContainer);\n SetupTextureContainer(Textures, 1024,1024, 40, Arena);\n\n \n int len=snprintf(0,0,\"anims\/%s\",FileName)+1;\n STACK_ARRAY(GafFileName,len,char);\n snprintf(GafFileName,len,\"anims\/%s\",FileName);\n GafFileName[len-4]='g';\n GafFileName[len-3]='a';\n GafFileName[len-2]='f';\n \n HPIEntry UITextures = FindEntryInAllFiles(GafFileName, CurrentGameState);\n if(UITextures.IsDirectory)\n {\n\tLogError(\"Unexpectedly found a directory while trying to load %s\", GafFileName);\n }\n else if(!UITextures.Name)\n {\n\tLogError(\"Failed to load %s\", GafFileName);\n }\n else\n {\n\tLoadAllTexturesFromHPIEntry(&UITextures, Textures, TempArena, CurrentGameState->PaletteData);\n }\n MemoryArena * UIElementsArena = PushSubArena(TempArena, 16 * 1024);\n FILE_UIElement * First = LoadUIElementsFromBuffer(&Buffer, End, UIElementsArena);\n\n if(GetIntValue(GetSubElement(First,\"common\"),\"ID\") != 0)\n {\n\tLogError(\"First UI element is not a container (%d)!\",GetIntValue(GetSubElement(First,\"common\"),\"ID\"));\n\treturn 0;\n }\n\n TAUIElement * Container = PushStruct(Arena, TAUIElement);\n LoadElementFromTree(Container, First, Arena, Textures, CurrentGameState);\n\n TAUIContainer * ContainerDetails = (TAUIContainer *)Container->Details;\n ContainerDetails->NumberOfElements = CountElements(First)-1;\n ContainerDetails->Elements = PushArray(Arena, ContainerDetails->NumberOfElements, TAUIElement);\n ContainerDetails->Textures = Textures;\n\n for(int i=0;iNumberOfElements;i++)\n {\n\tLoadElementFromTree(&ContainerDetails->Elements[i], GetNthElement(First, i+1), Arena, Textures, CurrentGameState);\n }\n\n \n\n\n \n PopSubArena(TempArena, UIElementsArena);\n return Container;\n}\n\n\nvoid LoadCommonUITextures(GameState * CurrentGameState)\n{\n SetupTextureContainer(CurrentGameState->CommonGUITextures, COMMONUI_TEXTURE_WIDTH, COMMONUI_TEXTURE_HEIGHT, COMMONUI_MAX_TEXTURES, &CurrentGameState->GameArena);\n if(!CurrentGameState->PaletteLoaded)\n {\n\tLoadPalette(CurrentGameState);\n }\n HPIEntry CommonUI = FindEntryInAllFiles(\"anims\/commonGUI.GAF\", CurrentGameState);\n if(CommonUI.IsDirectory)\n {\n\tLogError(\"Unexpectedly found a directory while trying to load hatfont12.gaf\");\n }\n else if(!CommonUI.Name)\n {\n\tLogError(\"Failed to get commonGUI.gaf\");\n }\n else\n {\n\tLoadAllTexturesFromHPIEntry(&CommonUI, CurrentGameState->CommonGUITextures, &CurrentGameState->TempArena, CurrentGameState->PaletteData);\n }\n\n}\n<|endoftext|>"} {"text":"\n\/\/ Qt includes\n#include \n#include \n#include \n\n\/\/ Visomics includes\n#include \n\n\/\/ STD includes\n#include \n\n\/\/-----------------------------------------------------------------------------\nint voDelimitedTextImportDialogTest(int argc, char * argv [])\n{\n QApplication app(argc, argv);\n\n Q_INIT_RESOURCE(VisomicsApp);\n\n \/\/ Read file\n QString filename(\"\/home\/jchris\/Projects\/Bioinformatics\/Data\/UNC\/All_conc_kitware_transposed.csv\");\n\n voDelimitedTextImportDialog dialog;\n dialog.setFileName(filename);\n \n dialog.show();\n\n QTimer autoExit;\n if (argc < 2 || QString(argv[1]) != \"-I\")\n {\n QObject::connect(&autoExit, SIGNAL(timeout()), &dialog, SLOT(accept()));\n autoExit.start(1000);\n }\n\n return dialog.exec();\n}\n\nFix voDelimitedTextImportDialogTest\n\/\/ Qt includes\n#include \n#include \n#include \n\n\/\/ Visomics includes\n#include \n\n\/\/ STD includes\n#include \n\n\/\/-----------------------------------------------------------------------------\nint voDelimitedTextImportDialogTest(int argc, char * argv [])\n{\n QApplication app(argc, argv);\n\n Q_INIT_RESOURCE(VisomicsApp);\n\n \/\/ Read file\n QString filename(\"\/home\/jchris\/Projects\/Bioinformatics\/Data\/UNC\/All_conc_kitware_transposed.csv\");\n\n voDelimitedTextImportDialog dialog;\n dialog.setFileName(filename);\n \n dialog.show();\n\n QTimer autoExit;\n if (argc < 2 || QString(argv[1]) != \"-I\")\n {\n QObject::connect(&autoExit, SIGNAL(timeout()), &dialog, SLOT(accept()));\n autoExit.start(1000);\n }\n\n int status = dialog.exec();\n if (status != QDialog::Accepted)\n {\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"#ifndef MAIN_HPP\n#define MAIN_HPP\n\n#include\"bev_thrust.hpp\"\n#include\"cuda_error_check.hpp\"\n#include\"preprocess.hpp\"\n#include\"rgb2gray.hpp\"\n\n\n\n\n#endif\nUpdated Header#ifndef MAIN_HPP\n#define MAIN_HPP\n\n#include\"bev_thrust.hpp\"\n#include\"cuda_error_check.hpp\"\n#include\"preprocess.hpp\"\n#include\"rgb2gray.hpp\"\n#include\"hough.hpp\" \n\n\n\n#endif\n<|endoftext|>"} {"text":"#include \"Task.hpp\"\n#include \n\nstd::string Task::getName() {\n\treturn name;\n}\n\nstd::string Task::getDescription() {\n\treturn description;\n}\n\nstd::string Task::getAssignee() {\n\treturn assignee;\n}\n\nint Task::getdueDate() {\n\treturn dueDate;\n}TaskyClassy#include \"Task.hpp\"\n#include \n\nstd::string Task::getName() {\n\treturn name;\n}\n\nstd::string Task::getDescription() {\n\treturn description;\n}\n\nstd::string Task::getAssignee() {\n\treturn assignee;\n}\n\nint Task::getdueDate() {\n\treturn dueDate;\n}\n\nint Task::getDate() {\n\treturn getDate;\n}<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_ISATRAITS_HH__\n#define __ARCH_X86_ISATRAITS_HH__\n\n#include \"arch\/x86\/intregs.hh\"\n#include \"arch\/x86\/types.hh\"\n#include \"arch\/x86\/x86_traits.hh\"\n\nclass StaticInstPtr;\n\nnamespace LittleEndianGuest {}\n\nnamespace X86ISA\n{\n \/\/This makes sure the little endian version of certain functions\n \/\/are used.\n using namespace LittleEndianGuest;\n\n \/\/ X86 does not have a delay slot\n#define ISA_HAS_DELAY_SLOT 0\n\n \/\/ X86 NOP (XCHG rAX, rAX)\n \/\/XXX This needs to be set to an intermediate instruction struct\n \/\/which encodes this instruction\n\n \/\/ These enumerate all the registers for dependence tracking.\n enum DependenceTags {\n \/\/There are 16 microcode registers at the moment\n FP_Base_DepTag = 32,\n Ctrl_Base_DepTag =\n FP_Base_DepTag +\n \/\/mmx\/x87 registers\n 8 +\n \/\/xmm registers\n 16\n };\n\n \/\/ semantically meaningful register indices\n \/\/There is no such register in X86\n const int ZeroReg = NUM_INTREGS;\n const int StackPointerReg = INTREG_RSP;\n \/\/X86 doesn't seem to have a link register\n const int ReturnAddressReg = 0;\n const int ReturnValueReg = INTREG_RAX;\n const int FramePointerReg = INTREG_RBP;\n const int ArgumentReg[] = {\n INTREG_RDI,\n INTREG_RSI,\n INTREG_RDX,\n \/\/This argument register is r10 for syscalls and rcx for C.\n INTREG_R10W,\n \/\/INTREG_RCX,\n INTREG_R8W,\n INTREG_R9W\n };\n const int NumArgumentRegs = sizeof(ArgumentReg) \/ sizeof(const int);\n\n \/\/ Some OS syscalls use a second register (rdx) to return a second\n \/\/ value\n const int SyscallPseudoReturnReg = INTREG_RDX;\n\n \/\/XXX These numbers are bogus\n const int MaxInstSrcRegs = 10;\n const int MaxInstDestRegs = 10;\n\n \/\/4k. This value is not constant on x86.\n const int LogVMPageSize = 12;\n const int VMPageSize = (1 << LogVMPageSize);\n\n const int PageShift = 13;\n const int PageBytes = 1ULL << PageShift;\n\n const int BranchPredAddrShiftAmt = 0;\n\n StaticInstPtr decodeInst(ExtMachInst);\n};\n\n#endif \/\/ __ARCH_X86_ISATRAITS_HH__\nX86: Make sure FP_Base_DepTag is big enough to avoid trouble.\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_ISATRAITS_HH__\n#define __ARCH_X86_ISATRAITS_HH__\n\n#include \"arch\/x86\/intregs.hh\"\n#include \"arch\/x86\/types.hh\"\n#include \"arch\/x86\/x86_traits.hh\"\n\nclass StaticInstPtr;\n\nnamespace LittleEndianGuest {}\n\nnamespace X86ISA\n{\n \/\/This makes sure the little endian version of certain functions\n \/\/are used.\n using namespace LittleEndianGuest;\n\n \/\/ X86 does not have a delay slot\n#define ISA_HAS_DELAY_SLOT 0\n\n \/\/ X86 NOP (XCHG rAX, rAX)\n \/\/XXX This needs to be set to an intermediate instruction struct\n \/\/which encodes this instruction\n\n \/\/ These enumerate all the registers for dependence tracking.\n enum DependenceTags {\n \/\/There are 16 microcode registers at the moment\n FP_Base_DepTag = 1 << 7,\n Ctrl_Base_DepTag =\n FP_Base_DepTag +\n \/\/mmx\/x87 registers\n 8 +\n \/\/xmm registers\n 16\n };\n\n \/\/ semantically meaningful register indices\n \/\/There is no such register in X86\n const int ZeroReg = NUM_INTREGS;\n const int StackPointerReg = INTREG_RSP;\n \/\/X86 doesn't seem to have a link register\n const int ReturnAddressReg = 0;\n const int ReturnValueReg = INTREG_RAX;\n const int FramePointerReg = INTREG_RBP;\n const int ArgumentReg[] = {\n INTREG_RDI,\n INTREG_RSI,\n INTREG_RDX,\n \/\/This argument register is r10 for syscalls and rcx for C.\n INTREG_R10W,\n \/\/INTREG_RCX,\n INTREG_R8W,\n INTREG_R9W\n };\n const int NumArgumentRegs = sizeof(ArgumentReg) \/ sizeof(const int);\n\n \/\/ Some OS syscalls use a second register (rdx) to return a second\n \/\/ value\n const int SyscallPseudoReturnReg = INTREG_RDX;\n\n \/\/XXX These numbers are bogus\n const int MaxInstSrcRegs = 10;\n const int MaxInstDestRegs = 10;\n\n \/\/4k. This value is not constant on x86.\n const int LogVMPageSize = 12;\n const int VMPageSize = (1 << LogVMPageSize);\n\n const int PageShift = 13;\n const int PageBytes = 1ULL << PageShift;\n\n const int BranchPredAddrShiftAmt = 0;\n\n StaticInstPtr decodeInst(ExtMachInst);\n};\n\n#endif \/\/ __ARCH_X86_ISATRAITS_HH__\n<|endoftext|>"} {"text":"#include \"include\/Node.hpp\"\n#include \"include\/Tree.hpp\"\n#include \n#include \n\nint main() {\n Node< std::string >* node = new Node< std::string >( 1, \"Lorhan\", nullptr, nullptr );\n std::cout << node->getValue() << std::endl;\n std::cout << node->left << std::endl;\n std::cout << node->right << std::endl;\n delete node;\n\n Tree< std::string > tree = Tree< std::string >();\n tree.insert( 10, \"!\" );\n tree.insert( 1, \"Lorhan\" );\n tree.insert( 2, \"Sohaky\" );\n tree.insert( 3, \"top\" );\n tree.insert( 4, \"da\" );\n tree.insert( 5, \"balada\" );\n std::cout << tree << std::endl;\n\n std::cout << tree.searchByValue( \"top\" ) << std::endl;\n std::cout << tree.searchByKey( 3 ) << std::endl;\n\n return 0;\n}\nAdicionado mais um teste#include \"include\/Node.hpp\"\n#include \"include\/Tree.hpp\"\n#include \n#include \n\nint main() {\n Node< std::string >* node = new Node< std::string >( 1, \"Lorhan\", nullptr, nullptr );\n std::cout << node->getValue() << std::endl;\n std::cout << node->left << std::endl;\n std::cout << node->right << std::endl;\n delete node;\n\n Tree< std::string > tree = Tree< std::string >();\n tree.insert( 10, \"!\" );\n tree.insert( 1, \"Lorhan\" );\n tree.insert( 2, \"Sohaky\" );\n tree.insert( 3, \"top\" );\n tree.insert( 4, \"da\" );\n tree.insert( 5, \"balada\" );\n std::cout << tree << std::endl;\n\n std::cout << tree.searchByValue( \"top\" ) << std::endl;\n std::cout << tree.searchByKey( 3 ) << std::endl;\n\n std::cout << \"\\n\\n\";\n Tree< char > tree2 = Tree< char >();\n\n tree2.insert( 2, '2' );\n tree2.insert( 1, '1' );\n tree2.insert( 4, '4' );\n tree2.insert( 3, '3' );\n tree2.insert( 5, '5' );\n std::cout << tree2 << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"behaviour_xsensfollowing.h\"\n#include \n#include \n#include \n\nBehaviour_XsensFollowing::Behaviour_XsensFollowing(QString id, Module_ThrusterControlLoop *tcl, Module_XsensMTi *xsens)\n : RobotBehaviour(id)\n{\n this->xsens = xsens;\n this->tcl = tcl;\n turnTimer.moveToThread(this);\n timer.moveToThread(this);\n\n this->setDefaultValue(\"timer\",30);\n this->setDefaultValue(\"driveTime\",10000);\n this->setDefaultValue(\"ffSpeed\",0.3);\n this->setDefaultValue(\"kp\",0.3);\n this->setDefaultValue(\"delta\",0.3);\n}\n\nbool Behaviour_XsensFollowing::isActive()\n{\n return isEnabled();\n}\n\nvoid Behaviour_XsensFollowing::init()\n{\n logger->info(\"Xsens Following init\");\n setEnabled(false);\n connect(this,SIGNAL(newAngularSpeed(float)),tcl,SLOT(setAngularSpeed(float)));\n connect(this,SIGNAL(newForwardSpeed(float)),tcl,SLOT(setForwardSpeed(float)));\n connect(&timer,SIGNAL(timeout()),this,SLOT(controlLoop()));\n connect(&turnTimer,SIGNAL(timeout()),this,SLOT(turnNinety()));\n connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));\n}\n\nvoid Behaviour_XsensFollowing::startBehaviour()\n{\n if (this->isEnabled() == true){\n logger->info(\"Already enabled\/started!\");\n return;\n }\n logger->info(\"Starting Xsens Following\");\n this->setEnabled(true);\n\n initialHeading = xsens->getHeading();\n ctrAngle = initialHeading;\n\n emit dataChanged(this);\n\n timer.start(getSettingsValue(\"timer\").toInt());\n turnTimer.start(getSettingsValue(\"driveTime\").toInt());\n}\n\nvoid Behaviour_XsensFollowing::stop()\n{\n if(timer.isActive()){\n timer.stop();\n }\n if(turnTimer.isActive()){\n turnTimer.stop();\n }\n\n if (!isEnabled()) {\n return;\n }\n\n logger->info(\"Xsens follow stop\");\n this->setEnabled(false);\n setEnabled(false);\n emit newAngularSpeed(0.0);\n emit newForwardSpeed(0.0);\n logger->info(\"Stop Xsens Following\");\n emit finished(this,true);\n}\n\nvoid Behaviour_XsensFollowing::reset()\n{\n logger->info(\"Xsens follow reset\");\n if (this->isEnabled() == false){\n logger->info(\"Not enabled!\");\n return;\n }\n timer.stop();\n turnTimer.stop();\n emit newAngularSpeed(0.0);\n emit newForwardSpeed(0.0);\n RobotModule::reset();\n if(xsens->isEnabled()){\n if(xsens->getHealthStatus().isHealthOk()){\n initialHeading = xsens->getHeading();\n ctrAngle = initialHeading;\n emit dataChanged(this);\n this->setHealthToOk();\n timer.start(getSettingsValue(\"timer\").toInt());\n turnTimer.start(getSettingsValue(\"driveTime\").toInt());\n }else{\n this->stopOnXsensError();\n }\n }else{\n this->stop();\n }\n}\n\nvoid Behaviour_XsensFollowing::controlLoop()\n{\n if (this->isEnabled() == false){\n logger->info(\"not enabled - controlloop\");\n this->stop();\n return;\n }\n\n if(!xsens->isEnabled() || !xsens->getHealthStatus().isHealthOk())\n {\n this->stopOnXsensError();\n return;\n }\n float curHeading = xsens->getHeading();\n float curDelta = Angles::deg2deg(ctrAngle - curHeading);\n float ctrAngleSpeed = 0.0;\n float faktor = 1.0;\n if(ctrAngle-curHeading < 0)\n faktor = -1.0;\n if(curDelta > getSettingsValue(\"delta\").toFloat() || curDelta < getSettingsValue(\"delta\").toFloat())\n {\n ctrAngleSpeed = getSettingsValue(\"kp\").toFloat()* faktor * curHeading \/ ctrAngle;\n }\n addData(\"angularSpeed\",ctrAngleSpeed);\n addData(\"curDelta\", curDelta);\n addData(\"current heading\",curHeading);\n addData(\"ctrAngle\", ctrAngle);\n emit dataChanged(this);\n emit newAngularSpeed(ctrAngleSpeed);\n emit newForwardSpeed(getSettingsValue(\"ffSpeed\").toFloat());\n}\n\nvoid Behaviour_XsensFollowing::turnNinety()\n{\n if (this->isEnabled() == false){\n logger->info(\"not enabled - 90\");\n this->stop();\n return;\n }\n logger->info(\"Turn 90\");\n logger->info(\"ctrAngle %f\", ctrAngle);\n if(getSettingsValue(\"enableTurn\").toBool() == true){\n float newHeading = ctrAngle;\n\n if(getSettingsValue(\"turnClockwise\").toBool() == true){\n newHeading = newHeading + 90.0;\n ctrAngle = Angles::deg2deg(newHeading);\n } else {\n newHeading = newHeading - 90.0;\n ctrAngle = Angles::deg2deg(newHeading);\n }\n }\n logger->info(\"ctrAngle new %f\", ctrAngle);\n}\n\nvoid Behaviour_XsensFollowing::refreshHeading()\n{\n \/\/logger->debug(\"Xsens follow refresh heading\");\n if (this->isEnabled() == false){\n logger->info(\"Not enabled!\");\n return;\n }\n if(xsens->isEnabled()){\n\n this->dataLockerMutex.lock();\n\n initialHeading = this->xsens->getHeading();\n\n logger->debug( \"initial heading set to %f \", initialHeading );\n addData(\"initial_heading\", initialHeading);\n dataChanged( this );\n this->dataLockerMutex.unlock();\n\n }\n}\n\nvoid Behaviour_XsensFollowing::stopOnXsensError()\n{\n if (!isEnabled()) {\n return;\n }\n\n logger->info(\"Xsens follow stop error\");\n this->setEnabled(false);\n timer.stop();\n turnTimer.stop();\n setHealthToSick(\"xsens error\");\n setEnabled(false);\n emit newAngularSpeed(0.0);\n emit newForwardSpeed(0.0);\n emit finished(this,false);\n}\n\nQList Behaviour_XsensFollowing::getDependencies()\n{\n QList ret;\n ret.append(tcl);\n ret.append(xsens);\n return ret;\n}\n\nQWidget* Behaviour_XsensFollowing::createView(QWidget* parent)\n{\n return new XsensFollowingForm(parent, this);\n}\n\nvoid Behaviour_XsensFollowing::controlEnabledChanged(bool b){\n if(b == false){\n logger->info(\"No longer enabled!\");\n QTimer::singleShot(0, this, SLOT(stop()));\n }\n}\n#include \"behaviour_xsensfollowing.h\"\n#include \n#include \n#include \n\nBehaviour_XsensFollowing::Behaviour_XsensFollowing(QString id, Module_ThrusterControlLoop *tcl, Module_XsensMTi *xsens)\n : RobotBehaviour(id)\n{\n this->xsens = xsens;\n this->tcl = tcl;\n turnTimer.moveToThread(this);\n timer.moveToThread(this);\n\n this->setDefaultValue(\"timer\",30);\n this->setDefaultValue(\"driveTime\",10000);\n this->setDefaultValue(\"ffSpeed\",0.3);\n this->setDefaultValue(\"kp\",0.3);\n this->setDefaultValue(\"delta\",0.3);\n}\n\nbool Behaviour_XsensFollowing::isActive()\n{\n return isEnabled();\n}\n\nvoid Behaviour_XsensFollowing::init()\n{\n logger->info(\"Xsens Following init\");\n setEnabled(false);\n connect(this,SIGNAL(newAngularSpeed(float)),tcl,SLOT(setAngularSpeed(float)));\n connect(this,SIGNAL(newForwardSpeed(float)),tcl,SLOT(setForwardSpeed(float)));\n connect(&timer,SIGNAL(timeout()),this,SLOT(controlLoop()));\n connect(&turnTimer,SIGNAL(timeout()),this,SLOT(turnNinety()));\n connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));\n}\n\nvoid Behaviour_XsensFollowing::startBehaviour()\n{\n if (this->isEnabled() == true){\n logger->info(\"Already enabled\/started!\");\n return;\n }\n logger->info(\"Starting Xsens Following\");\n this->setEnabled(true);\n\n initialHeading = xsens->getHeading();\n ctrAngle = initialHeading;\n\n emit dataChanged(this);\n\n timer.start(getSettingsValue(\"timer\").toInt());\n turnTimer.start(getSettingsValue(\"driveTime\").toInt());\n}\n\nvoid Behaviour_XsensFollowing::stop()\n{\n if(timer.isActive()){\n timer.stop();\n }\n if(turnTimer.isActive()){\n turnTimer.stop();\n }\n\n if (!isEnabled()) {\n return;\n }\n\n logger->info(\"Xsens follow stop\");\n this->setEnabled(false);\n setEnabled(false);\n emit newAngularSpeed(0.0);\n emit newForwardSpeed(0.0);\n logger->info(\"Stop Xsens Following\");\n emit finished(this,true);\n}\n\nvoid Behaviour_XsensFollowing::reset()\n{\n logger->info(\"Xsens follow reset\");\n if (this->isEnabled() == false){\n logger->info(\"Not enabled!\");\n return;\n }\n timer.stop();\n turnTimer.stop();\n emit newAngularSpeed(0.0);\n emit newForwardSpeed(0.0);\n RobotModule::reset();\n if(xsens->isEnabled()){\n if(xsens->getHealthStatus().isHealthOk()){\n initialHeading = xsens->getHeading();\n ctrAngle = initialHeading;\n emit dataChanged(this);\n this->setHealthToOk();\n timer.start(getSettingsValue(\"timer\").toInt());\n turnTimer.start(getSettingsValue(\"driveTime\").toInt());\n }else{\n this->stopOnXsensError();\n }\n }else{\n this->stop();\n }\n}\n\nvoid Behaviour_XsensFollowing::controlLoop()\n{\n if (this->isEnabled() == false){\n logger->info(\"not enabled - controlloop\");\n this->stop();\n return;\n }\n\n if(!xsens->isEnabled() || !xsens->getHealthStatus().isHealthOk())\n {\n this->stopOnXsensError();\n return;\n }\n float curHeading = xsens->getHeading();\n float curDelta = Angles::deg2deg(ctrAngle - curHeading);\n float ctrAngleSpeed = 0.0;\n float faktor = 1.0;\n if(ctrAngle-curHeading < 0)\n faktor = -1.0;\n if(curDelta > getSettingsValue(\"delta\").toFloat() || curDelta < getSettingsValue(\"delta\").toFloat())\n {\n ctrAngleSpeed = getSettingsValue(\"kp\").toFloat()* faktor * curHeading \/ ctrAngle;\n }\n addData(\"angularSpeed\",ctrAngleSpeed);\n addData(\"curDelta\", curDelta);\n addData(\"current heading\",curHeading);\n addData(\"ctrAngle\", ctrAngle);\n emit dataChanged(this);\n emit newAngularSpeed(ctrAngleSpeed);\n emit newForwardSpeed(getSettingsValue(\"ffSpeed\").toFloat());\n}\n\nvoid Behaviour_XsensFollowing::turnNinety()\n{\n if (this->isEnabled() == false){\n logger->info(\"not enabled - 90\");\n this->stop();\n return;\n }\n logger->info(\"Turn 90\");\n logger->info(\"ctrAngle\", ctrAngle);\n if(getSettingsValue(\"enableTurn\").toBool() == true){\n float newHeading = ctrAngle;\n\n if(getSettingsValue(\"turnClockwise\").toBool() == true){\n newHeading = newHeading + 90.0;\n ctrAngle = Angles::deg2deg(newHeading);\n } else {\n newHeading = newHeading - 90.0;\n ctrAngle = Angles::deg2deg(newHeading);\n }\n }\n logger->info(\"ctrAngle new\", ctrAngle);\n}\n\nvoid Behaviour_XsensFollowing::refreshHeading()\n{\n \/\/logger->debug(\"Xsens follow refresh heading\");\n if (this->isEnabled() == false){\n logger->info(\"Not enabled!\");\n return;\n }\n if(xsens->isEnabled()){\n\n this->dataLockerMutex.lock();\n\n initialHeading = this->xsens->getHeading();\n\n logger->debug( \"initial heading set to\", initialHeading );\n addData(\"initial_heading\", initialHeading);\n dataChanged( this );\n this->dataLockerMutex.unlock();\n\n }\n}\n\nvoid Behaviour_XsensFollowing::stopOnXsensError()\n{\n if (!isEnabled()) {\n return;\n }\n\n logger->info(\"Xsens follow stop error\");\n this->setEnabled(false);\n timer.stop();\n turnTimer.stop();\n setHealthToSick(\"xsens error\");\n setEnabled(false);\n emit newAngularSpeed(0.0);\n emit newForwardSpeed(0.0);\n emit finished(this,false);\n}\n\nQList Behaviour_XsensFollowing::getDependencies()\n{\n QList ret;\n ret.append(tcl);\n ret.append(xsens);\n return ret;\n}\n\nQWidget* Behaviour_XsensFollowing::createView(QWidget* parent)\n{\n return new XsensFollowingForm(parent, this);\n}\n\nvoid Behaviour_XsensFollowing::controlEnabledChanged(bool b){\n if(b == false){\n logger->info(\"No longer enabled!\");\n QTimer::singleShot(0, this, SLOT(stop()));\n }\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * \n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"opt_status.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/log.h\"\n#include \"kernel\/celltypes.h\"\n#include \n#include \n#include \n#include \n\nusing RTLIL::id2cstr;\n\nstatic CellTypes ct;\n\nstatic void rmunused_module_cells(RTLIL::Module *module)\n{\n\tSigMap assign_map(module);\n\tstd::set queue, unused;\n\n\tSigSet wire2driver;\n\tfor (auto &it : module->cells) {\n\t\tRTLIL::Cell *cell = it.second;\n\t\tfor (auto &it2 : cell->connections) {\n\t\t\tif (!ct.cell_input(cell->type, it2.first)) {\n\t\t\t\tRTLIL::SigSpec sig = it2.second;\n\t\t\t\tassign_map.apply(sig);\n\t\t\t\twire2driver.insert(sig, cell);\n\t\t\t}\n\t\t}\n\t\tif (cell->type == \"$memwr\")\n\t\t\tqueue.insert(cell);\n\t\tunused.insert(cell);\n\t}\n\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tif (wire->port_output) {\n\t\t\tstd::set cell_list;\n\t\t\tRTLIL::SigSpec sig = RTLIL::SigSpec(wire);\n\t\t\tassign_map.apply(sig);\n\t\t\twire2driver.find(sig, cell_list);\n\t\t\tfor (auto cell : cell_list)\n\t\t\t\tqueue.insert(cell);\n\t\t}\n\t}\n\n\twhile (queue.size() > 0)\n\t{\n\t\tstd::set new_queue;\n\t\tfor (auto cell : queue)\n\t\t\tunused.erase(cell);\n\t\tfor (auto cell : queue) {\n\t\t\tfor (auto &it : cell->connections) {\n\t\t\t\tif (!ct.cell_output(cell->type, it.first)) {\n\t\t\t\t\tstd::set cell_list;\n\t\t\t\t\tRTLIL::SigSpec sig = it.second;\n\t\t\t\t\tassign_map.apply(sig);\n\t\t\t\t\twire2driver.find(sig, cell_list);\n\t\t\t\t\tfor (auto cell : cell_list) {\n\t\t\t\t\t\tif (unused.count(cell) > 0)\n\t\t\t\t\t\t\tnew_queue.insert(cell);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tqueue.swap(new_queue);\n\t}\n\n\tfor (auto cell : unused) {\n\t\tlog(\" removing unused `%s' cell `%s'.\\n\", cell->type.c_str(), cell->name.c_str());\n\t\tOPT_DID_SOMETHING = true;\n\t\tmodule->cells.erase(cell->name);\n\t\tdelete cell;\n\t}\n}\n\nstatic bool compare_signals(RTLIL::SigSpec &s1, RTLIL::SigSpec &s2)\n{\n\tassert(s1.width == 1);\n\tassert(s2.width == 1);\n\tassert(s1.chunks.size() == 1);\n\tassert(s2.chunks.size() == 1);\n\n\tRTLIL::Wire *w1 = s1.chunks[0].wire;\n\tRTLIL::Wire *w2 = s2.chunks[0].wire;\n\n\tif (w1 == NULL || w2 == NULL)\n\t\treturn w2 == NULL;\n\n\tif (w1->port_input != w2->port_input)\n\t\treturn w2->port_input;\n\n\tif (w1->name[0] != w2->name[0])\n\t\treturn w2->name[0] == '\\\\';\n\n\tif (w1->attributes.size() != w2->attributes.size())\n\t\treturn w2->attributes.size() > w1->attributes.size();\n\n\treturn w2->name < w1->name;\n}\n\nstatic bool check_public_name(RTLIL::IdString id)\n{\n\tif (id[0] == '$')\n\t\treturn false;\n#if 0\n\tif (id.find(\".$\") == std::string::npos)\n\t\treturn true;\n#endif\n\treturn false;\n}\n\nstatic void rmunused_module_signals(RTLIL::Module *module)\n{\n\tSigMap assign_map(module);\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tfor (int i = 0; i < wire->width; i++) {\n\t\t\tRTLIL::SigSpec s1 = RTLIL::SigSpec(wire, 1, i), s2 = assign_map(s1);\n\t\t\tif (!compare_signals(s1, s2))\n\t\t\t\tassign_map.add(s1);\n\t\t}\n\t}\n\n\tmodule->connections.clear();\n\n\tSigPool used_signals;\n\tSigPool used_signals_nodrivers;\n\tfor (auto &it : module->cells) {\n\t\tRTLIL::Cell *cell = it.second;\n\t\tfor (auto &it2 : cell->connections) {\n\t\t\tassign_map.apply(it2.second);\n\t\t\tused_signals.add(it2.second);\n\t\t\tif (!ct.cell_output(cell->type, it2.first))\n\t\t\t\tused_signals_nodrivers.add(it2.second);\n\t\t}\n\t}\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tif (wire->port_id > 0) {\n\t\t\tRTLIL::SigSpec sig = RTLIL::SigSpec(wire);\n\t\t\tassign_map.apply(sig);\n\t\t\tused_signals.add(sig);\n\t\t\tif (!wire->port_input)\n\t\t\t\tused_signals_nodrivers.add(sig);\n\t\t}\n\t}\n\n\tstd::vector del_wires;\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tif (check_public_name(wire->name)) {\n\t\t\tRTLIL::SigSpec s1 = RTLIL::SigSpec(wire), s2 = s1;\n\t\t\tassign_map.apply(s2);\n\t\t\tif (!used_signals.check_any(s2) && wire->port_id == 0) {\n\t\t\t\tlog(\" removing unused non-port wire %s.\\n\", wire->name.c_str());\n\t\t\t\tdel_wires.push_back(wire);\n\t\t\t} else {\n\t\t\t\ts1.expand();\n\t\t\t\ts2.expand();\n\t\t\t\tassert(s1.chunks.size() == s2.chunks.size());\n\t\t\t\tRTLIL::SigSig new_conn;\n\t\t\t\tfor (size_t i = 0; i < s1.chunks.size(); i++)\n\t\t\t\t\tif (s1.chunks[i] != s2.chunks[i]) {\n\t\t\t\t\t\tnew_conn.first.append(s1.chunks[i]);\n\t\t\t\t\t\tnew_conn.second.append(s2.chunks[i]);\n\t\t\t\t\t}\n\t\t\t\tif (new_conn.first.width > 0) {\n\t\t\t\t\tnew_conn.first.optimize();\n\t\t\t\t\tnew_conn.second.optimize();\n\t\t\t\t\tmodule->connections.push_back(new_conn);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (!used_signals.check_any(RTLIL::SigSpec(wire)))\n\t\t\t\tdel_wires.push_back(wire);\n\t\t}\n\t\tRTLIL::SigSpec sig = assign_map(RTLIL::SigSpec(wire));\n\t\tif (!used_signals_nodrivers.check_any(sig)) {\n\t\t\tstd::string unused_bits;\n\t\t\tsig.expand();\n\t\t\tfor (size_t i = 0; i < sig.chunks.size(); i++) {\n\t\t\t\tif (sig.chunks[i].wire == NULL)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!used_signals_nodrivers.check_any(sig)) {\n\t\t\t\t\tif (!unused_bits.empty())\n\t\t\t\t\t\tunused_bits += \" \";\n\t\t\t\t\tunused_bits += stringf(\"%zd\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unused_bits.empty() || wire->port_id != 0)\n\t\t\t\twire->attributes.erase(\"\\\\unused_bits\");\n\t\t\telse\n\t\t\t\twire->attributes[\"\\\\unused_bits\"] = RTLIL::Const(unused_bits);\n\t\t} else {\n\t\t\twire->attributes.erase(\"\\\\unused_bits\");\n\t\t}\n\t}\n\n\tfor (auto wire : del_wires) {\n\t\tmodule->wires.erase(wire->name);\n\t\tdelete wire;\n\t}\n\n\tif (del_wires.size() > 0)\n\t\tlog(\" removed %zd unused temporary wires.\\n\", del_wires.size());\n}\n\nstatic void rmunused_module(RTLIL::Module *module)\n{\n\tlog(\"Finding unused cells or wires in module %s..\\n\", module->name.c_str());\n\n\trmunused_module_cells(module);\n\trmunused_module_signals(module);\n}\n\nstruct OptRmUnusedPass : public Pass {\n\tOptRmUnusedPass() : Pass(\"opt_rmunused\", \"remove unused cells and wires\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" opt_rmunused [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass identifies wires and cells that are unused and removes them. Other\\n\");\n\t\tlog(\"often remove cells but leave the wires in the design or reconnect the wires\\n\");\n\t\tlog(\"but leave the old cells in the design. This pass can be used to clean up after\\n\");\n\t\tlog(\"the passes that do the actual work.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass only operates on completely selected modules without processes.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(\"Executing OPT_RMUNUSED pass (remove unused cells and wires).\\n\");\n\t\tlog_push();\n\n\t\textra_args(args, 1, design);\n\n\t\tct.setup_internals();\n\t\tct.setup_internals_mem();\n\t\tct.setup_stdcells();\n\t\tct.setup_stdcells_mem();\n\n\t\tfor (auto &mod_it : design->modules) {\n\t\t\tif (!design->selected_whole_module(mod_it.first)) {\n\t\t\t\tif (design->selected(mod_it.second))\n\t\t\t\t\tlog(\"Skipping module %s as it is only partially selected.\\n\", id2cstr(mod_it.second->name));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (mod_it.second->processes.size() > 0) {\n\t\t\t\tlog(\"Skipping module %s as it contains processes.\\n\", mod_it.second->name.c_str());\n\t\t\t} else {\n\t\t\t\trmunused_module(mod_it.second);\n\t\t\t}\n\t\t}\n\n\t\tct.clear();\n\t\tlog_pop();\n\t}\n} OptRmUnusedPass;\n \nFixed detection of public wires in opt_rmunused\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * \n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"opt_status.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/log.h\"\n#include \"kernel\/celltypes.h\"\n#include \n#include \n#include \n#include \n\nusing RTLIL::id2cstr;\n\nstatic CellTypes ct;\n\nstatic void rmunused_module_cells(RTLIL::Module *module)\n{\n\tSigMap assign_map(module);\n\tstd::set queue, unused;\n\n\tSigSet wire2driver;\n\tfor (auto &it : module->cells) {\n\t\tRTLIL::Cell *cell = it.second;\n\t\tfor (auto &it2 : cell->connections) {\n\t\t\tif (!ct.cell_input(cell->type, it2.first)) {\n\t\t\t\tRTLIL::SigSpec sig = it2.second;\n\t\t\t\tassign_map.apply(sig);\n\t\t\t\twire2driver.insert(sig, cell);\n\t\t\t}\n\t\t}\n\t\tif (cell->type == \"$memwr\")\n\t\t\tqueue.insert(cell);\n\t\tunused.insert(cell);\n\t}\n\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tif (wire->port_output) {\n\t\t\tstd::set cell_list;\n\t\t\tRTLIL::SigSpec sig = RTLIL::SigSpec(wire);\n\t\t\tassign_map.apply(sig);\n\t\t\twire2driver.find(sig, cell_list);\n\t\t\tfor (auto cell : cell_list)\n\t\t\t\tqueue.insert(cell);\n\t\t}\n\t}\n\n\twhile (queue.size() > 0)\n\t{\n\t\tstd::set new_queue;\n\t\tfor (auto cell : queue)\n\t\t\tunused.erase(cell);\n\t\tfor (auto cell : queue) {\n\t\t\tfor (auto &it : cell->connections) {\n\t\t\t\tif (!ct.cell_output(cell->type, it.first)) {\n\t\t\t\t\tstd::set cell_list;\n\t\t\t\t\tRTLIL::SigSpec sig = it.second;\n\t\t\t\t\tassign_map.apply(sig);\n\t\t\t\t\twire2driver.find(sig, cell_list);\n\t\t\t\t\tfor (auto cell : cell_list) {\n\t\t\t\t\t\tif (unused.count(cell) > 0)\n\t\t\t\t\t\t\tnew_queue.insert(cell);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tqueue.swap(new_queue);\n\t}\n\n\tfor (auto cell : unused) {\n\t\tlog(\" removing unused `%s' cell `%s'.\\n\", cell->type.c_str(), cell->name.c_str());\n\t\tOPT_DID_SOMETHING = true;\n\t\tmodule->cells.erase(cell->name);\n\t\tdelete cell;\n\t}\n}\n\nstatic bool compare_signals(RTLIL::SigSpec &s1, RTLIL::SigSpec &s2)\n{\n\tassert(s1.width == 1);\n\tassert(s2.width == 1);\n\tassert(s1.chunks.size() == 1);\n\tassert(s2.chunks.size() == 1);\n\n\tRTLIL::Wire *w1 = s1.chunks[0].wire;\n\tRTLIL::Wire *w2 = s2.chunks[0].wire;\n\n\tif (w1 == NULL || w2 == NULL)\n\t\treturn w2 == NULL;\n\n\tif (w1->port_input != w2->port_input)\n\t\treturn w2->port_input;\n\n\tif (w1->name[0] != w2->name[0])\n\t\treturn w2->name[0] == '\\\\';\n\n\tif (w1->attributes.size() != w2->attributes.size())\n\t\treturn w2->attributes.size() > w1->attributes.size();\n\n\treturn w2->name < w1->name;\n}\n\nstatic bool check_public_name(RTLIL::IdString id)\n{\n\tif (id[0] == '$')\n\t\treturn false;\n#if 0\n\tif (id.find(\".$\") != std::string::npos)\n\t\treturn false;\n#endif\n\treturn true;\n}\n\nstatic void rmunused_module_signals(RTLIL::Module *module)\n{\n\tSigMap assign_map(module);\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tfor (int i = 0; i < wire->width; i++) {\n\t\t\tRTLIL::SigSpec s1 = RTLIL::SigSpec(wire, 1, i), s2 = assign_map(s1);\n\t\t\tif (!compare_signals(s1, s2))\n\t\t\t\tassign_map.add(s1);\n\t\t}\n\t}\n\n\tmodule->connections.clear();\n\n\tSigPool used_signals;\n\tSigPool used_signals_nodrivers;\n\tfor (auto &it : module->cells) {\n\t\tRTLIL::Cell *cell = it.second;\n\t\tfor (auto &it2 : cell->connections) {\n\t\t\tassign_map.apply(it2.second);\n\t\t\tused_signals.add(it2.second);\n\t\t\tif (!ct.cell_output(cell->type, it2.first))\n\t\t\t\tused_signals_nodrivers.add(it2.second);\n\t\t}\n\t}\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tif (wire->port_id > 0) {\n\t\t\tRTLIL::SigSpec sig = RTLIL::SigSpec(wire);\n\t\t\tassign_map.apply(sig);\n\t\t\tused_signals.add(sig);\n\t\t\tif (!wire->port_input)\n\t\t\t\tused_signals_nodrivers.add(sig);\n\t\t}\n\t}\n\n\tstd::vector del_wires;\n\tfor (auto &it : module->wires) {\n\t\tRTLIL::Wire *wire = it.second;\n\t\tif (check_public_name(wire->name)) {\n\t\t\tRTLIL::SigSpec s1 = RTLIL::SigSpec(wire), s2 = s1;\n\t\t\tassign_map.apply(s2);\n\t\t\tif (!used_signals.check_any(s2) && wire->port_id == 0) {\n\t\t\t\tlog(\" removing unused non-port wire %s.\\n\", wire->name.c_str());\n\t\t\t\tdel_wires.push_back(wire);\n\t\t\t} else {\n\t\t\t\ts1.expand();\n\t\t\t\ts2.expand();\n\t\t\t\tassert(s1.chunks.size() == s2.chunks.size());\n\t\t\t\tRTLIL::SigSig new_conn;\n\t\t\t\tfor (size_t i = 0; i < s1.chunks.size(); i++)\n\t\t\t\t\tif (s1.chunks[i] != s2.chunks[i]) {\n\t\t\t\t\t\tnew_conn.first.append(s1.chunks[i]);\n\t\t\t\t\t\tnew_conn.second.append(s2.chunks[i]);\n\t\t\t\t\t}\n\t\t\t\tif (new_conn.first.width > 0) {\n\t\t\t\t\tnew_conn.first.optimize();\n\t\t\t\t\tnew_conn.second.optimize();\n\t\t\t\t\tmodule->connections.push_back(new_conn);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (!used_signals.check_any(RTLIL::SigSpec(wire)))\n\t\t\t\tdel_wires.push_back(wire);\n\t\t}\n\t\tRTLIL::SigSpec sig = assign_map(RTLIL::SigSpec(wire));\n\t\tif (!used_signals_nodrivers.check_any(sig)) {\n\t\t\tstd::string unused_bits;\n\t\t\tsig.expand();\n\t\t\tfor (size_t i = 0; i < sig.chunks.size(); i++) {\n\t\t\t\tif (sig.chunks[i].wire == NULL)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!used_signals_nodrivers.check_any(sig)) {\n\t\t\t\t\tif (!unused_bits.empty())\n\t\t\t\t\t\tunused_bits += \" \";\n\t\t\t\t\tunused_bits += stringf(\"%zd\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unused_bits.empty() || wire->port_id != 0)\n\t\t\t\twire->attributes.erase(\"\\\\unused_bits\");\n\t\t\telse\n\t\t\t\twire->attributes[\"\\\\unused_bits\"] = RTLIL::Const(unused_bits);\n\t\t} else {\n\t\t\twire->attributes.erase(\"\\\\unused_bits\");\n\t\t}\n\t}\n\n\tfor (auto wire : del_wires) {\n\t\tmodule->wires.erase(wire->name);\n\t\tdelete wire;\n\t}\n\n\tif (del_wires.size() > 0)\n\t\tlog(\" removed %zd unused temporary wires.\\n\", del_wires.size());\n}\n\nstatic void rmunused_module(RTLIL::Module *module)\n{\n\tlog(\"Finding unused cells or wires in module %s..\\n\", module->name.c_str());\n\n\trmunused_module_cells(module);\n\trmunused_module_signals(module);\n}\n\nstruct OptRmUnusedPass : public Pass {\n\tOptRmUnusedPass() : Pass(\"opt_rmunused\", \"remove unused cells and wires\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" opt_rmunused [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass identifies wires and cells that are unused and removes them. Other\\n\");\n\t\tlog(\"often remove cells but leave the wires in the design or reconnect the wires\\n\");\n\t\tlog(\"but leave the old cells in the design. This pass can be used to clean up after\\n\");\n\t\tlog(\"the passes that do the actual work.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass only operates on completely selected modules without processes.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(\"Executing OPT_RMUNUSED pass (remove unused cells and wires).\\n\");\n\t\tlog_push();\n\n\t\textra_args(args, 1, design);\n\n\t\tct.setup_internals();\n\t\tct.setup_internals_mem();\n\t\tct.setup_stdcells();\n\t\tct.setup_stdcells_mem();\n\n\t\tfor (auto &mod_it : design->modules) {\n\t\t\tif (!design->selected_whole_module(mod_it.first)) {\n\t\t\t\tif (design->selected(mod_it.second))\n\t\t\t\t\tlog(\"Skipping module %s as it is only partially selected.\\n\", id2cstr(mod_it.second->name));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (mod_it.second->processes.size() > 0) {\n\t\t\t\tlog(\"Skipping module %s as it contains processes.\\n\", mod_it.second->name.c_str());\n\t\t\t} else {\n\t\t\t\trmunused_module(mod_it.second);\n\t\t\t}\n\t\t}\n\n\t\tct.clear();\n\t\tlog_pop();\n\t}\n} OptRmUnusedPass;\n \n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\n\/\/ for peepopt_pm\nbool did_something;\n\n#include \"passes\/pmgen\/test_pmgen_pm.h\"\n#include \"passes\/pmgen\/ice40_dsp_pm.h\"\n#include \"passes\/pmgen\/xilinx_srl_pm.h\"\n#include \"passes\/pmgen\/peepopt_pm.h\"\n\nvoid reduce_chain(test_pmgen_pm &pm)\n{\n\tauto &st = pm.st_reduce;\n\tauto &ud = pm.ud_reduce;\n\n\tif (ud.longest_chain.empty())\n\t\treturn;\n\n\tlog(\"Found chain of length %d (%s):\\n\", GetSize(ud.longest_chain), log_id(st.first->type));\n\n\tSigSpec A;\n\tSigSpec Y = ud.longest_chain.front().first->getPort(ID(Y));\n\tauto last_cell = ud.longest_chain.back().first;\n\n\tfor (auto it : ud.longest_chain) {\n\t\tauto cell = it.first;\n\t\tif (cell == last_cell) {\n\t\t\tA.append(cell->getPort(ID(A)));\n\t\t\tA.append(cell->getPort(ID(B)));\n\t\t} else {\n\t\t\tA.append(cell->getPort(it.second == ID(A) ? ID(B) : ID(A)));\n\t\t}\n\t\tlog(\" %s\\n\", log_id(cell));\n\t\tpm.autoremove(cell);\n\t}\n\n\tCell *c;\n\n\tif (last_cell->type == ID($_AND_))\n\t\tc = pm.module->addReduceAnd(NEW_ID, A, Y);\n\telse if (last_cell->type == ID($_OR_))\n\t\tc = pm.module->addReduceOr(NEW_ID, A, Y);\n\telse if (last_cell->type == ID($_XOR_))\n\t\tc = pm.module->addReduceXor(NEW_ID, A, Y);\n\telse\n\t\tlog_abort();\n\n\tlog(\" -> %s (%s)\\n\", log_id(c), log_id(c->type));\n}\n\nvoid reduce_tree(test_pmgen_pm &pm)\n{\n\tauto &st = pm.st_reduce;\n\tauto &ud = pm.ud_reduce;\n\n\tif (ud.longest_chain.empty())\n\t\treturn;\n\n\tSigSpec A = ud.leaves;\n\tSigSpec Y = st.first->getPort(ID(Y));\n\tpm.autoremove(st.first);\n\n\tlog(\"Found %s tree with %d leaves for %s (%s).\\n\", log_id(st.first->type),\n\t\t\tGetSize(A), log_signal(Y), log_id(st.first));\n\n\tCell *c;\n\n\tif (st.first->type == ID($_AND_))\n\t\tc = pm.module->addReduceAnd(NEW_ID, A, Y);\n\telse if (st.first->type == ID($_OR_))\n\t\tc = pm.module->addReduceOr(NEW_ID, A, Y);\n\telse if (st.first->type == ID($_XOR_))\n\t\tc = pm.module->addReduceXor(NEW_ID, A, Y);\n\telse\n\t\tlog_abort();\n\n\tlog(\" -> %s (%s)\\n\", log_id(c), log_id(c->type));\n}\n\nvoid opt_eqpmux(test_pmgen_pm &pm)\n{\n\tauto &st = pm.st_eqpmux;\n\n\tSigSpec Y = st.pmux->getPort(ID::Y);\n\tint width = GetSize(Y);\n\n\tSigSpec EQ = st.pmux->getPort(ID::B).extract(st.pmux_slice_eq*width, width);\n\tSigSpec NE = st.pmux->getPort(ID::B).extract(st.pmux_slice_ne*width, width);\n\n\tlog(\"Found eqpmux circuit driving %s (eq=%s, ne=%s, pmux=%s).\\n\",\n\t\t\tlog_signal(Y), log_id(st.eq), log_id(st.ne), log_id(st.pmux));\n\n\tpm.autoremove(st.pmux);\n\tCell *c = pm.module->addMux(NEW_ID, NE, EQ, st.eq->getPort(ID::Y), Y);\n\tlog(\" -> %s (%s)\\n\", log_id(c), log_id(c->type));\n}\n\n#define GENERATE_PATTERN(pmclass, pattern) \\\n\tgenerate_pattern([](pmclass &pm, std::function f){ return pm.run_ ## pattern(f); }, #pmclass, #pattern, design)\n\nvoid pmtest_addports(Module *module)\n{\n\tpool driven_bits, used_bits;\n\tSigMap sigmap(module);\n\tint icnt = 0, ocnt = 0;\n\n\tfor (auto cell : module->cells())\n\tfor (auto conn : cell->connections())\n\t{\n\t\tif (cell->input(conn.first))\n\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\tused_bits.insert(bit);\n\t\tif (cell->output(conn.first))\n\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\tdriven_bits.insert(bit);\n\t}\n\n\tfor (auto wire : vector(module->wires()))\n\t{\n\t\tSigSpec ibits, obits;\n\t\tfor (auto bit : sigmap(wire)) {\n\t\t\tif (!used_bits.count(bit))\n\t\t\t\tobits.append(bit);\n\t\t\tif (!driven_bits.count(bit))\n\t\t\t\tibits.append(bit);\n\t\t}\n\t\tif (!ibits.empty()) {\n\t\t\tWire *w = module->addWire(stringf(\"\\\\i%d\", icnt++), GetSize(ibits));\n\t\t\tw->port_input = true;\n\t\t\tmodule->connect(ibits, w);\n\t\t}\n\t\tif (!obits.empty()) {\n\t\t\tWire *w = module->addWire(stringf(\"\\\\o%d\", ocnt++), GetSize(obits));\n\t\t\tw->port_output = true;\n\t\t\tmodule->connect(w, obits);\n\t\t}\n\t}\n\n\tmodule->fixup_ports();\n}\n\ntemplate \nvoid generate_pattern(std::function)> run, const char *pmclass, const char *pattern, Design *design)\n{\n\tlog(\"Generating \\\"%s\\\" patterns for pattern matcher \\\"%s\\\".\\n\", pattern, pmclass);\n\n\tint modcnt = 0;\n\tint maxmodcnt = 100;\n\tint maxsubcnt = 4;\n\tint timeout = 0;\n\tvector mods;\n\n\twhile (modcnt < maxmodcnt)\n\t{\n\t\tint submodcnt = 0, itercnt = 0, cellcnt = 0;\n\t\tModule *mod = design->addModule(NEW_ID);\n\n\t\twhile (modcnt < maxmodcnt && submodcnt < maxsubcnt && itercnt++ < 1000)\n\t\t{\n\t\t\tif (timeout++ > 10000)\n\t\t\t\tlog_error(\"pmgen generator is stuck: 10000 iterations with no matching module generated.\\n\");\n\n\t\t\tpm matcher(mod, mod->cells());\n\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += modcnt;\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += submodcnt;\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += itercnt;\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += cellcnt;\n\t\t\tmatcher.rng(1);\n\n\t\t\tif (GetSize(mod->cells()) != cellcnt)\n\t\t\t{\n\t\t\t\tbool found_match = false;\n\t\t\t\trun(matcher, [&](){ found_match = true; });\n\t\t\t\tcellcnt = GetSize(mod->cells());\n\n\t\t\t\tif (found_match) {\n\t\t\t\t\tModule *m = design->addModule(stringf(\"\\\\pmtest_%s_%s_%05d\",\n\t\t\t\t\t\t\tpmclass, pattern, modcnt++));\n\t\t\t\t\tlog(\"Creating module %s with %d cells.\\n\", log_id(m), cellcnt);\n\t\t\t\t\tmod->cloneInto(m);\n\t\t\t\t\tpmtest_addports(m);\n\t\t\t\t\tmods.push_back(m);\n\t\t\t\t\tsubmodcnt++;\n\t\t\t\t\ttimeout = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmatcher.generate_mode = true;\n\t\t\trun(matcher, [](){});\n\t\t}\n\n\t\tif (submodcnt)\n\t\t\tmaxsubcnt *= 2;\n\n\t\tdesign->remove(mod);\n\t}\n\n\tModule *m = design->addModule(stringf(\"\\\\pmtest_%s_%s\", pmclass, pattern));\n\tlog(\"Creating module %s with %d cells.\\n\", log_id(m), GetSize(mods));\n\tfor (auto mod : mods) {\n\t\tCell *c = m->addCell(mod->name, mod->name);\n\t\tfor (auto port : mod->ports) {\n\t\t\tWire *w = m->addWire(NEW_ID, GetSize(mod->wire(port)));\n\t\t\tc->setPort(port, w);\n\t\t}\n\t}\n\tpmtest_addports(m);\n}\n\nstruct TestPmgenPass : public Pass {\n\tTestPmgenPass() : Pass(\"test_pmgen\", \"test pass for pmgen\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -reduce_chain [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Demo for recursive pmgen patterns. Map chains of AND\/OR\/XOR to $reduce_*.\\n\");\n\t\tlog(\"\\n\");\n\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -reduce_tree [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Demo for recursive pmgen patterns. Map trees of AND\/OR\/XOR to $reduce_*.\\n\");\n\t\tlog(\"\\n\");\n\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -eqpmux [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Demo for recursive pmgen patterns. Optimize EQ\/NE\/PMUX circuits.\\n\");\n\t\tlog(\"\\n\");\n\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -generate [options] \\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Create modules that match the specified pattern.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute_reduce_chain(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-reduce_chain).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\twhile (test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_chain)) {}\n\t}\n\n\tvoid execute_reduce_tree(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-reduce_tree).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\ttest_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_tree);\n\t}\n\n\tvoid execute_eqpmux(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-eqpmux).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\ttest_pmgen_pm(module, module->selected_cells()).run_eqpmux(opt_eqpmux);\n\t}\n\n\tvoid execute_generate(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-generate).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\n\t\tif (argidx+1 != args.size())\n\t\t\tlog_cmd_error(\"Expected exactly one pattern.\\n\");\n\n\t\tstring pattern = args[argidx];\n\n\t\tif (pattern == \"reduce\")\n\t\t\treturn GENERATE_PATTERN(test_pmgen_pm, reduce);\n\n\t\tif (pattern == \"eqpmux\")\n\t\t\treturn GENERATE_PATTERN(test_pmgen_pm, eqpmux);\n\n\t\tif (pattern == \"ice40_dsp\")\n\t\t\treturn GENERATE_PATTERN(ice40_dsp_pm, ice40_dsp);\n\n\t\tif (pattern == \"xilinx_srl_fixed\")\n\t\t\treturn GENERATE_PATTERN(xilinx_srl_pm, fixed);\n\t\tif (pattern == \"xilinx_srl_variable\")\n\t\t\treturn GENERATE_PATTERN(xilinx_srl_pm, variable);\n\n\t\tif (pattern == \"peepopt-muldiv\")\n\t\t\treturn GENERATE_PATTERN(peepopt_pm, muldiv);\n\n\t\tif (pattern == \"peepopt-shiftmul\")\n\t\t\treturn GENERATE_PATTERN(peepopt_pm, shiftmul);\n\n\t\tlog_cmd_error(\"Unknown pattern: %s\\n\", pattern.c_str());\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tif (GetSize(args) > 1)\n\t\t{\n\t\t\tif (args[1] == \"-reduce_chain\")\n\t\t\t\treturn execute_reduce_chain(args, design);\n\t\t\tif (args[1] == \"-reduce_tree\")\n\t\t\t\treturn execute_reduce_tree(args, design);\n\t\t\tif (args[1] == \"-eqpmux\")\n\t\t\t\treturn execute_eqpmux(args, design);\n\t\t\tif (args[1] == \"-generate\")\n\t\t\t\treturn execute_generate(args, design);\n\t\t}\n\t\thelp();\n\t\tlog_cmd_error(\"Missing or unsupported mode parameter.\\n\");\n\t}\n} TestPmgenPass;\n\nPRIVATE_NAMESPACE_END\nAccount for maxsubcnt overflowing\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\n\/\/ for peepopt_pm\nbool did_something;\n\n#include \"passes\/pmgen\/test_pmgen_pm.h\"\n#include \"passes\/pmgen\/ice40_dsp_pm.h\"\n#include \"passes\/pmgen\/xilinx_srl_pm.h\"\n#include \"passes\/pmgen\/peepopt_pm.h\"\n\nvoid reduce_chain(test_pmgen_pm &pm)\n{\n\tauto &st = pm.st_reduce;\n\tauto &ud = pm.ud_reduce;\n\n\tif (ud.longest_chain.empty())\n\t\treturn;\n\n\tlog(\"Found chain of length %d (%s):\\n\", GetSize(ud.longest_chain), log_id(st.first->type));\n\n\tSigSpec A;\n\tSigSpec Y = ud.longest_chain.front().first->getPort(ID(Y));\n\tauto last_cell = ud.longest_chain.back().first;\n\n\tfor (auto it : ud.longest_chain) {\n\t\tauto cell = it.first;\n\t\tif (cell == last_cell) {\n\t\t\tA.append(cell->getPort(ID(A)));\n\t\t\tA.append(cell->getPort(ID(B)));\n\t\t} else {\n\t\t\tA.append(cell->getPort(it.second == ID(A) ? ID(B) : ID(A)));\n\t\t}\n\t\tlog(\" %s\\n\", log_id(cell));\n\t\tpm.autoremove(cell);\n\t}\n\n\tCell *c;\n\n\tif (last_cell->type == ID($_AND_))\n\t\tc = pm.module->addReduceAnd(NEW_ID, A, Y);\n\telse if (last_cell->type == ID($_OR_))\n\t\tc = pm.module->addReduceOr(NEW_ID, A, Y);\n\telse if (last_cell->type == ID($_XOR_))\n\t\tc = pm.module->addReduceXor(NEW_ID, A, Y);\n\telse\n\t\tlog_abort();\n\n\tlog(\" -> %s (%s)\\n\", log_id(c), log_id(c->type));\n}\n\nvoid reduce_tree(test_pmgen_pm &pm)\n{\n\tauto &st = pm.st_reduce;\n\tauto &ud = pm.ud_reduce;\n\n\tif (ud.longest_chain.empty())\n\t\treturn;\n\n\tSigSpec A = ud.leaves;\n\tSigSpec Y = st.first->getPort(ID(Y));\n\tpm.autoremove(st.first);\n\n\tlog(\"Found %s tree with %d leaves for %s (%s).\\n\", log_id(st.first->type),\n\t\t\tGetSize(A), log_signal(Y), log_id(st.first));\n\n\tCell *c;\n\n\tif (st.first->type == ID($_AND_))\n\t\tc = pm.module->addReduceAnd(NEW_ID, A, Y);\n\telse if (st.first->type == ID($_OR_))\n\t\tc = pm.module->addReduceOr(NEW_ID, A, Y);\n\telse if (st.first->type == ID($_XOR_))\n\t\tc = pm.module->addReduceXor(NEW_ID, A, Y);\n\telse\n\t\tlog_abort();\n\n\tlog(\" -> %s (%s)\\n\", log_id(c), log_id(c->type));\n}\n\nvoid opt_eqpmux(test_pmgen_pm &pm)\n{\n\tauto &st = pm.st_eqpmux;\n\n\tSigSpec Y = st.pmux->getPort(ID::Y);\n\tint width = GetSize(Y);\n\n\tSigSpec EQ = st.pmux->getPort(ID::B).extract(st.pmux_slice_eq*width, width);\n\tSigSpec NE = st.pmux->getPort(ID::B).extract(st.pmux_slice_ne*width, width);\n\n\tlog(\"Found eqpmux circuit driving %s (eq=%s, ne=%s, pmux=%s).\\n\",\n\t\t\tlog_signal(Y), log_id(st.eq), log_id(st.ne), log_id(st.pmux));\n\n\tpm.autoremove(st.pmux);\n\tCell *c = pm.module->addMux(NEW_ID, NE, EQ, st.eq->getPort(ID::Y), Y);\n\tlog(\" -> %s (%s)\\n\", log_id(c), log_id(c->type));\n}\n\n#define GENERATE_PATTERN(pmclass, pattern) \\\n\tgenerate_pattern([](pmclass &pm, std::function f){ return pm.run_ ## pattern(f); }, #pmclass, #pattern, design)\n\nvoid pmtest_addports(Module *module)\n{\n\tpool driven_bits, used_bits;\n\tSigMap sigmap(module);\n\tint icnt = 0, ocnt = 0;\n\n\tfor (auto cell : module->cells())\n\tfor (auto conn : cell->connections())\n\t{\n\t\tif (cell->input(conn.first))\n\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\tused_bits.insert(bit);\n\t\tif (cell->output(conn.first))\n\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\tdriven_bits.insert(bit);\n\t}\n\n\tfor (auto wire : vector(module->wires()))\n\t{\n\t\tSigSpec ibits, obits;\n\t\tfor (auto bit : sigmap(wire)) {\n\t\t\tif (!used_bits.count(bit))\n\t\t\t\tobits.append(bit);\n\t\t\tif (!driven_bits.count(bit))\n\t\t\t\tibits.append(bit);\n\t\t}\n\t\tif (!ibits.empty()) {\n\t\t\tWire *w = module->addWire(stringf(\"\\\\i%d\", icnt++), GetSize(ibits));\n\t\t\tw->port_input = true;\n\t\t\tmodule->connect(ibits, w);\n\t\t}\n\t\tif (!obits.empty()) {\n\t\t\tWire *w = module->addWire(stringf(\"\\\\o%d\", ocnt++), GetSize(obits));\n\t\t\tw->port_output = true;\n\t\t\tmodule->connect(w, obits);\n\t\t}\n\t}\n\n\tmodule->fixup_ports();\n}\n\ntemplate \nvoid generate_pattern(std::function)> run, const char *pmclass, const char *pattern, Design *design)\n{\n\tlog(\"Generating \\\"%s\\\" patterns for pattern matcher \\\"%s\\\".\\n\", pattern, pmclass);\n\n\tint modcnt = 0;\n\tint maxmodcnt = 100;\n\tint maxsubcnt = 4;\n\tint timeout = 0;\n\tvector mods;\n\n\twhile (modcnt < maxmodcnt)\n\t{\n\t\tint submodcnt = 0, itercnt = 0, cellcnt = 0;\n\t\tModule *mod = design->addModule(NEW_ID);\n\n\t\twhile (modcnt < maxmodcnt && submodcnt < maxsubcnt && itercnt++ < 1000)\n\t\t{\n\t\t\tif (timeout++ > 10000)\n\t\t\t\tlog_error(\"pmgen generator is stuck: 10000 iterations with no matching module generated.\\n\");\n\n\t\t\tpm matcher(mod, mod->cells());\n\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += modcnt;\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += submodcnt;\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += itercnt;\n\t\t\tmatcher.rng(1);\n\t\t\tmatcher.rngseed += cellcnt;\n\t\t\tmatcher.rng(1);\n\n\t\t\tif (GetSize(mod->cells()) != cellcnt)\n\t\t\t{\n\t\t\t\tbool found_match = false;\n\t\t\t\trun(matcher, [&](){ found_match = true; });\n\t\t\t\tcellcnt = GetSize(mod->cells());\n\n\t\t\t\tif (found_match) {\n\t\t\t\t\tModule *m = design->addModule(stringf(\"\\\\pmtest_%s_%s_%05d\",\n\t\t\t\t\t\t\tpmclass, pattern, modcnt++));\n\t\t\t\t\tlog(\"Creating module %s with %d cells.\\n\", log_id(m), cellcnt);\n\t\t\t\t\tmod->cloneInto(m);\n\t\t\t\t\tpmtest_addports(m);\n\t\t\t\t\tmods.push_back(m);\n\t\t\t\t\tsubmodcnt++;\n\t\t\t\t\ttimeout = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmatcher.generate_mode = true;\n\t\t\trun(matcher, [](){});\n\t\t}\n\n\t\tif (submodcnt && maxsubcnt < (1 << 16))\n\t\t\tmaxsubcnt *= 2;\n\n\t\tdesign->remove(mod);\n\t}\n\n\tModule *m = design->addModule(stringf(\"\\\\pmtest_%s_%s\", pmclass, pattern));\n\tlog(\"Creating module %s with %d cells.\\n\", log_id(m), GetSize(mods));\n\tfor (auto mod : mods) {\n\t\tCell *c = m->addCell(mod->name, mod->name);\n\t\tfor (auto port : mod->ports) {\n\t\t\tWire *w = m->addWire(NEW_ID, GetSize(mod->wire(port)));\n\t\t\tc->setPort(port, w);\n\t\t}\n\t}\n\tpmtest_addports(m);\n}\n\nstruct TestPmgenPass : public Pass {\n\tTestPmgenPass() : Pass(\"test_pmgen\", \"test pass for pmgen\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -reduce_chain [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Demo for recursive pmgen patterns. Map chains of AND\/OR\/XOR to $reduce_*.\\n\");\n\t\tlog(\"\\n\");\n\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -reduce_tree [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Demo for recursive pmgen patterns. Map trees of AND\/OR\/XOR to $reduce_*.\\n\");\n\t\tlog(\"\\n\");\n\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -eqpmux [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Demo for recursive pmgen patterns. Optimize EQ\/NE\/PMUX circuits.\\n\");\n\t\tlog(\"\\n\");\n\n\t\tlog(\"\\n\");\n\t\tlog(\" test_pmgen -generate [options] \\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Create modules that match the specified pattern.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute_reduce_chain(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-reduce_chain).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\twhile (test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_chain)) {}\n\t}\n\n\tvoid execute_reduce_tree(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-reduce_tree).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\ttest_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_tree);\n\t}\n\n\tvoid execute_eqpmux(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-eqpmux).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\ttest_pmgen_pm(module, module->selected_cells()).run_eqpmux(opt_eqpmux);\n\t}\n\n\tvoid execute_generate(std::vector args, RTLIL::Design *design)\n\t{\n\t\tlog_header(design, \"Executing TEST_PMGEN pass (-generate).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 2; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\n\t\tif (argidx+1 != args.size())\n\t\t\tlog_cmd_error(\"Expected exactly one pattern.\\n\");\n\n\t\tstring pattern = args[argidx];\n\n\t\tif (pattern == \"reduce\")\n\t\t\treturn GENERATE_PATTERN(test_pmgen_pm, reduce);\n\n\t\tif (pattern == \"eqpmux\")\n\t\t\treturn GENERATE_PATTERN(test_pmgen_pm, eqpmux);\n\n\t\tif (pattern == \"ice40_dsp\")\n\t\t\treturn GENERATE_PATTERN(ice40_dsp_pm, ice40_dsp);\n\n\t\tif (pattern == \"xilinx_srl_fixed\")\n\t\t\treturn GENERATE_PATTERN(xilinx_srl_pm, fixed);\n\t\tif (pattern == \"xilinx_srl_variable\")\n\t\t\treturn GENERATE_PATTERN(xilinx_srl_pm, variable);\n\n\t\tif (pattern == \"peepopt-muldiv\")\n\t\t\treturn GENERATE_PATTERN(peepopt_pm, muldiv);\n\n\t\tif (pattern == \"peepopt-shiftmul\")\n\t\t\treturn GENERATE_PATTERN(peepopt_pm, shiftmul);\n\n\t\tlog_cmd_error(\"Unknown pattern: %s\\n\", pattern.c_str());\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tif (GetSize(args) > 1)\n\t\t{\n\t\t\tif (args[1] == \"-reduce_chain\")\n\t\t\t\treturn execute_reduce_chain(args, design);\n\t\t\tif (args[1] == \"-reduce_tree\")\n\t\t\t\treturn execute_reduce_tree(args, design);\n\t\t\tif (args[1] == \"-eqpmux\")\n\t\t\t\treturn execute_eqpmux(args, design);\n\t\t\tif (args[1] == \"-generate\")\n\t\t\t\treturn execute_generate(args, design);\n\t\t}\n\t\thelp();\n\t\tlog_cmd_error(\"Missing or unsupported mode parameter.\\n\");\n\t}\n} TestPmgenPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*\n * Nouncer Implementation\n *\/\n\n#include \"nouncer.h\"\n\n\/*\n * Assembles the map dictionary by reading one line at a time,\n * separating the word from the pronunciation, encoding the phoneme, and\n * putting the pair in the map\n *\/\n\nstd::vector Nouncer::cons = {\n '9',':',';','<','I','J','K','T','U','V','W',\n 'X','Y','h','i','j','k','l','m','v','w','y','z','{'\n};\n\nNouncer::Nouncer() {\n\n dict = new std::map;\n\n std::ifstream file(DICTIONARY_FILE);\n\n if (file) {\n std::string line;\n\n while (std::getline(file,line)) {\n if (line.substr(0,3) == COMMENT_HEAD) {\n continue;\n }\n else {\n addWord(line);\n }\n }\n }\n else {\n std::cerr << \"Unable to load dictionary\" << std::endl;\n }\n}\n\nNouncer::~Nouncer() {\n dict->erase(dict->begin(), dict->end());\n delete dict;\n}\n\n\/*\n * Given a string, return a pointer to the associated nounce\n * or the nounce of \"gravy\" if the string is not found.\n *\/\nstd::string* Nouncer::lookUp(std::string word) {\n try {\n return &(dict->at(Utils::allCaps(word)));\n }\n catch (const std::out_of_range& oor) {\n return &(dict->at(\"GRAVY\"));\n }\n}\n\n\/*\n * TODO: Let's encode outside this and pass in the nounce\n *\n * Maps a phoneme dictionary entry to a\n * pair\n * and inserts in the dictionary.\n *\/\nvoid Nouncer::addWord(std::string line) {\n std::istringstream ss(line);\n std::string word;\n std::string nounce;\n std::string phoneme;\n\n ss >> word;\n\n while (ss >> phoneme) {\n char encoded_phoneme = encode(phoneme);\n nounce.push_back(encoded_phoneme);\n }\n\n std::reverse(nounce.begin(), nounce.end());\n\n std::pair word_phonemes(word, nounce);\n dict->insert(word_phonemes);\n}\n\n\/*\n * Encodes the phoneme string as a nounce\n *\/\nchar Nouncer::encode(std::string phoneme) {\n char phone = '\\0';\n\n if (phoneme == \"AA\") phone = ' ';\n else if (phoneme == \"AA0\") phone = '!';\n else if (phoneme == \"AA1\") phone = '\\\"';\n else if (phoneme == \"AA2\") phone = '#';\n else if (phoneme == \"AE\") phone = '$';\n else if (phoneme == \"AE0\") phone = '%';\n else if (phoneme == \"AE1\") phone = '&';\n else if (phoneme == \"AE2\") phone = '(';\n else if (phoneme == \"AH\") phone = ')';\n else if (phoneme == \"AH0\") phone = '*';\n else if (phoneme == \"AH1\") phone = '+';\n else if (phoneme == \"AH2\") phone = ',';\n else if (phoneme == \"AO\") phone = '-';\n else if (phoneme == \"AO0\") phone = '.';\n else if (phoneme == \"AO1\") phone = '\/';\n else if (phoneme == \"AO2\") phone = '0';\n else if (phoneme == \"AW\") phone = '1';\n else if (phoneme == \"AW0\") phone = '2';\n else if (phoneme == \"AW1\") phone = '3';\n else if (phoneme == \"AW2\") phone = '4';\n else if (phoneme == \"AY\") phone = '5';\n else if (phoneme == \"AY0\") phone = '6';\n else if (phoneme == \"AY1\") phone = '7';\n else if (phoneme == \"AY2\") phone = '8';\n else if (phoneme == \"B\") phone = '9';\n else if (phoneme == \"CH\") phone = ':';\n else if (phoneme == \"D\") phone = ';';\n else if (phoneme == \"DH\") phone = '<';\n else if (phoneme == \"EH\") phone = '=';\n else if (phoneme == \"EH0\") phone = '>';\n else if (phoneme == \"EH1\") phone = '?';\n else if (phoneme == \"EH2\") phone = '@';\n else if (phoneme == \"ER\") phone = 'A';\n else if (phoneme == \"ER0\") phone = 'B';\n else if (phoneme == \"ER1\") phone = 'C';\n else if (phoneme == \"ER2\") phone = 'D';\n else if (phoneme == \"EY\") phone = 'E';\n else if (phoneme == \"EY0\") phone = 'F';\n else if (phoneme == \"EY1\") phone = 'G';\n else if (phoneme == \"EY2\") phone = 'H';\n else if (phoneme == \"F\") phone = 'I';\n else if (phoneme == \"G\") phone = 'J';\n else if (phoneme == \"HH\") phone = 'K';\n else if (phoneme == \"IH\") phone = 'L';\n else if (phoneme == \"IH0\") phone = 'M';\n else if (phoneme == \"IH1\") phone = 'N';\n else if (phoneme == \"IH2\") phone = 'O';\n else if (phoneme == \"IY\") phone = 'P';\n else if (phoneme == \"IY0\") phone = 'Q';\n else if (phoneme == \"IY1\") phone = 'R';\n else if (phoneme == \"IY2\") phone = 'S';\n else if (phoneme == \"JH\") phone = 'T';\n else if (phoneme == \"K\") phone = 'U';\n else if (phoneme == \"L\") phone = 'V';\n else if (phoneme == \"M\") phone = 'W';\n else if (phoneme == \"N\") phone = 'X';\n else if (phoneme == \"NG\") phone = 'Y';\n else if (phoneme == \"OW\") phone = 'Z';\n else if (phoneme == \"OW0\") phone = 'a';\n else if (phoneme == \"OW1\") phone = 'b';\n else if (phoneme == \"OW2\") phone = 'c';\n else if (phoneme == \"OY\") phone = 'd';\n else if (phoneme == \"OY0\") phone = 'e';\n else if (phoneme == \"OY1\") phone = 'f';\n else if (phoneme == \"OY2\") phone = 'g';\n else if (phoneme == \"P\") phone = 'h';\n else if (phoneme == \"R\") phone = 'i';\n else if (phoneme == \"S\") phone = 'j';\n else if (phoneme == \"SH\") phone = 'k';\n else if (phoneme == \"T\") phone = 'l';\n else if (phoneme == \"TH\") phone = 'm';\n else if (phoneme == \"UH\") phone = 'n';\n else if (phoneme == \"UH0\") phone = 'o';\n else if (phoneme == \"UH1\") phone = 'p';\n else if (phoneme == \"UH2\") phone = 'q';\n else if (phoneme == \"UW\") phone = 'r';\n else if (phoneme == \"UW0\") phone = 's';\n else if (phoneme == \"UW1\") phone = 't';\n else if (phoneme == \"UW2\") phone = 'u';\n else if (phoneme == \"V\") phone = 'v';\n else if (phoneme == \"W\") phone = 'w';\n else if (phoneme == \"Y\") phone = 'y';\n else if (phoneme == \"Z\") phone = 'z';\n else if (phoneme == \"ZH\") phone = '{';\n else\n std::cerr << \"Could not identify phoneme \" << phoneme << std::endl;\n\n return phone;\n}\n\nbool Nouncer::isVowel(char& phone) {\n return !(std::find(cons.begin(),cons.end(),phone) != cons.end())\n}\n\nint Nouncer::getSylCount(std::string word) {\n int count = 0;\n std::string* nounce = lookUp(word);\n\n for (auto i = nounce->begin(); i != nounce->end(); ++i) {\n if ( isVowel(*i) ) count++;\n }\n\n return count;\n}\n\nint Nouncer::getSize() {\n return dict->size();\n}\n\n\nvoid Nouncer::print(std::string filename) {\n std::ofstream of(filename);\n for (auto it = dict->begin(); it!=dict->end(); ++it) {\n of<<(*it).first<<\":\"<<(*it).second<clean up x2\/*\n * Nouncer Implementation\n *\/\n\n#include \"nouncer.h\"\n\n\/*\n * Assembles the map dictionary by reading one line at a time,\n * separating the word from the pronunciation, encoding the phoneme, and\n * putting the pair in the map\n *\/\n\nstd::vector Nouncer::cons = {\n '9',':',';','<','I','J','K','T','U','V','W',\n 'X','Y','h','i','j','k','l','m','v','w','y','z','{'\n};\n\nNouncer::Nouncer() {\n\n dict = new std::map;\n\n std::ifstream file(DICTIONARY_FILE);\n\n if (file) {\n std::string line;\n\n while (std::getline(file,line)) {\n if (line.substr(0,3) == COMMENT_HEAD) {\n continue;\n }\n else {\n addWord(line);\n }\n }\n }\n else {\n std::cerr << \"Unable to load dictionary\" << std::endl;\n }\n}\n\nNouncer::~Nouncer() {\n dict->erase(dict->begin(), dict->end());\n delete dict;\n}\n\n\/*\n * Given a string, return a pointer to the associated nounce\n * or the nounce of \"gravy\" if the string is not found.\n *\/\nstd::string* Nouncer::lookUp(std::string word) {\n try {\n return &(dict->at(Utils::allCaps(word)));\n }\n catch (const std::out_of_range& oor) {\n return &(dict->at(\"GRAVY\"));\n }\n}\n\n\/*\n * TODO: Let's encode outside this and pass in the nounce\n *\n * Maps a phoneme dictionary entry to a\n * pair\n * and inserts in the dictionary.\n *\/\nvoid Nouncer::addWord(std::string line) {\n std::istringstream ss(line);\n std::string word;\n std::string nounce;\n std::string phoneme;\n\n ss >> word;\n\n while (ss >> phoneme) {\n char encoded_phoneme = encode(phoneme);\n nounce.push_back(encoded_phoneme);\n }\n\n std::reverse(nounce.begin(), nounce.end());\n\n std::pair word_phonemes(word, nounce);\n dict->insert(word_phonemes);\n}\n\n\/*\n * Encodes the phoneme string as a nounce\n *\/\nchar Nouncer::encode(std::string phoneme) {\n char phone = '\\0';\n\n if (phoneme == \"AA\") phone = ' ';\n else if (phoneme == \"AA0\") phone = '!';\n else if (phoneme == \"AA1\") phone = '\\\"';\n else if (phoneme == \"AA2\") phone = '#';\n else if (phoneme == \"AE\") phone = '$';\n else if (phoneme == \"AE0\") phone = '%';\n else if (phoneme == \"AE1\") phone = '&';\n else if (phoneme == \"AE2\") phone = '(';\n else if (phoneme == \"AH\") phone = ')';\n else if (phoneme == \"AH0\") phone = '*';\n else if (phoneme == \"AH1\") phone = '+';\n else if (phoneme == \"AH2\") phone = ',';\n else if (phoneme == \"AO\") phone = '-';\n else if (phoneme == \"AO0\") phone = '.';\n else if (phoneme == \"AO1\") phone = '\/';\n else if (phoneme == \"AO2\") phone = '0';\n else if (phoneme == \"AW\") phone = '1';\n else if (phoneme == \"AW0\") phone = '2';\n else if (phoneme == \"AW1\") phone = '3';\n else if (phoneme == \"AW2\") phone = '4';\n else if (phoneme == \"AY\") phone = '5';\n else if (phoneme == \"AY0\") phone = '6';\n else if (phoneme == \"AY1\") phone = '7';\n else if (phoneme == \"AY2\") phone = '8';\n else if (phoneme == \"B\") phone = '9';\n else if (phoneme == \"CH\") phone = ':';\n else if (phoneme == \"D\") phone = ';';\n else if (phoneme == \"DH\") phone = '<';\n else if (phoneme == \"EH\") phone = '=';\n else if (phoneme == \"EH0\") phone = '>';\n else if (phoneme == \"EH1\") phone = '?';\n else if (phoneme == \"EH2\") phone = '@';\n else if (phoneme == \"ER\") phone = 'A';\n else if (phoneme == \"ER0\") phone = 'B';\n else if (phoneme == \"ER1\") phone = 'C';\n else if (phoneme == \"ER2\") phone = 'D';\n else if (phoneme == \"EY\") phone = 'E';\n else if (phoneme == \"EY0\") phone = 'F';\n else if (phoneme == \"EY1\") phone = 'G';\n else if (phoneme == \"EY2\") phone = 'H';\n else if (phoneme == \"F\") phone = 'I';\n else if (phoneme == \"G\") phone = 'J';\n else if (phoneme == \"HH\") phone = 'K';\n else if (phoneme == \"IH\") phone = 'L';\n else if (phoneme == \"IH0\") phone = 'M';\n else if (phoneme == \"IH1\") phone = 'N';\n else if (phoneme == \"IH2\") phone = 'O';\n else if (phoneme == \"IY\") phone = 'P';\n else if (phoneme == \"IY0\") phone = 'Q';\n else if (phoneme == \"IY1\") phone = 'R';\n else if (phoneme == \"IY2\") phone = 'S';\n else if (phoneme == \"JH\") phone = 'T';\n else if (phoneme == \"K\") phone = 'U';\n else if (phoneme == \"L\") phone = 'V';\n else if (phoneme == \"M\") phone = 'W';\n else if (phoneme == \"N\") phone = 'X';\n else if (phoneme == \"NG\") phone = 'Y';\n else if (phoneme == \"OW\") phone = 'Z';\n else if (phoneme == \"OW0\") phone = 'a';\n else if (phoneme == \"OW1\") phone = 'b';\n else if (phoneme == \"OW2\") phone = 'c';\n else if (phoneme == \"OY\") phone = 'd';\n else if (phoneme == \"OY0\") phone = 'e';\n else if (phoneme == \"OY1\") phone = 'f';\n else if (phoneme == \"OY2\") phone = 'g';\n else if (phoneme == \"P\") phone = 'h';\n else if (phoneme == \"R\") phone = 'i';\n else if (phoneme == \"S\") phone = 'j';\n else if (phoneme == \"SH\") phone = 'k';\n else if (phoneme == \"T\") phone = 'l';\n else if (phoneme == \"TH\") phone = 'm';\n else if (phoneme == \"UH\") phone = 'n';\n else if (phoneme == \"UH0\") phone = 'o';\n else if (phoneme == \"UH1\") phone = 'p';\n else if (phoneme == \"UH2\") phone = 'q';\n else if (phoneme == \"UW\") phone = 'r';\n else if (phoneme == \"UW0\") phone = 's';\n else if (phoneme == \"UW1\") phone = 't';\n else if (phoneme == \"UW2\") phone = 'u';\n else if (phoneme == \"V\") phone = 'v';\n else if (phoneme == \"W\") phone = 'w';\n else if (phoneme == \"Y\") phone = 'y';\n else if (phoneme == \"Z\") phone = 'z';\n else if (phoneme == \"ZH\") phone = '{';\n else\n std::cerr << \"Could not identify phoneme \" << phoneme << std::endl;\n\n return phone;\n}\n\nbool Nouncer::isVowel(char& phone) {\n return !(std::find(cons.begin(),cons.end(),phone) != cons.end());\n}\n\nint Nouncer::getSylCount(std::string word) {\n int count = 0;\n std::string* nounce = lookUp(word);\n\n for (auto i = nounce->begin(); i != nounce->end(); ++i) {\n if ( isVowel(*i) ) count++;\n }\n\n return count;\n}\n\nint Nouncer::getSize() {\n return dict->size();\n}\n\n\nvoid Nouncer::print(std::string filename) {\n std::ofstream of(filename);\n for (auto it = dict->begin(); it!=dict->end(); ++it) {\n of<<(*it).first<<\":\"<<(*it).second<"} {"text":"\/***************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\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 as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\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* \"@(#) $Id: enumpropTestServer.cpp,v 1.45 2005\/10\/07 13:59:57 bjeram Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* david 2002-08-15 changed argUnpack.h to acsutilArgUnpack.h\n* bjeram 2001-12-03 created \n*\/\n\n\n#include \"vltPort.h\"\n\nstatic char *rcsId=\"@(#) $Id: enumpropTestServer.cpp,v 1.45 2005\/10\/07 13:59:57 bjeram Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"enumpropTestDeviceImpl.h\"\n\n#ifdef MAKE_VXWORKS\n#\tinclude \"rebootLib.h\"\n#\tinclude \"acsutilArgUnpack.h\"\n#endif\n\nusing namespace ACS;\nusing namespace baci;\n\n\/\/ We need an implementation of the ContainerServices here because\n\/\/ 1. the component fails if the pointer to the ContainerServices it receives\n\/\/ in the constructor is NULL\n\/\/ 2. the smart pointer used to store the ContainerServices deletes all\n\/\/ the not-NULL instances of the Container Services\n\/\/ This clla implements all the methods of the interface but does nothing\nclass TestContainerServices : public maci::ContainerServices {\n public:\n CORBA::ORB_var m_orb;\n\n TestContainerServices(ACE_CString& compName, PortableServer::POA_ptr poa, CORBA::ORB_ptr orb):\n maci::ContainerServices(compName,poa), m_orb(CORBA::ORB::_duplicate(orb)) {\n ACS_SHORT_LOG((LM_INFO,\"TestContainerServices built\"));\n }\n \n virtual ~TestContainerServices() {\n ACS_SHORT_LOG((LM_INFO,\"TestContainerServices destroyed\"));\n }\n \n CORBA::Object* getCORBAComponent(const char* name)\n {\n return (CORBA::Object*)NULL;\n }\n \n CORBA::Object* getCORBADynamicComponent(maci::ComponentSpec compSpec, bool markAsDefault)\n {\n return (CORBA::Object*)NULL;\n }\n \n CORBA::Object* getCORBADefaultComponent(const char* idlType)\n {\n return (CORBA::Object*)NULL;\n }\n \n public:\n \n maci::ComponentInfo getComponentDescriptor(const char* componentName)\n throw (acsErrTypeContainerServices::GettingCompInfoExImpl)\n {\n ComponentInfo temp;\n return temp;\n }\n \n ACE_CString_Vector findComponents(const char *nameWilcard, const char *typeWildcard)\n {\n return ACE_CString_Vector();\n }\n \n void releaseComponent(const char *name){}\n \n void releaseAllComponents(){}\n \n CDB::DAL_ptr getCDB()\n {\n\t ACE_TCHAR corbalocRef[230];\n\t ACE_TCHAR * envRef = ACE_OS::getenv (\"DAL_REFERENCE\");\n\n\t if (envRef && *envRef)\n\t\t{\n\t\tACS_LOG(0, \"TestContainerServices::getCDB\",\n\t\t\t(LM_INFO, \"CDB obtained via environment: '%s'\", envRef));\n\t\tstrcpy(corbalocRef, envRef);\n\t\t}\n\t else\n\t\t{\n\t \/\/ corbaloc:::\/CDB\n\t const char* hostname = 0;\n\t hostname = ACSPorts::getIP();\n\t if (hostname==0)\n\t\treturn (CDB::DAL *)0;\n\t \n\t ACE_TCHAR corbalocRef[230];\n\t ACE_OS::sprintf(corbalocRef, \"corbaloc::%s:%s\/CDB\", hostname, ACSPorts::getCDBPort().c_str());\n\t \n\t ACS_LOG(0, \"TestContainerServices::getCDB\",\n\t\t (LM_INFO, \"CDB reference generated using localhost address: '%s'\", corbalocRef));\n\t\t}\/\/if-else\n\t \n\t CDB::DAL_var dalObj = CDB::DAL::_nil();\n\t CORBA::Object_var obj = m_orb->string_to_object(corbalocRef);\n\t \n\t if (!CORBA::is_nil(obj.in()))\n\t\t{\n\t\tdalObj = CDB::DAL::_narrow(obj.in());\n\t\tif (CORBA::is_nil(dalObj.in())) \n\t\t {\n\t\t ACS_SHORT_LOG((LM_INFO, \"TestContainerServices::getCDB() - Failed to narrow CDB\"));\n\t\t return (CDB::DAL *)0;\n\t\t }\n\t\t}\n\t \n\t return dalObj._retn();\n }\n \n PortableServer::POA_var getOffShootPOA()\n {\n return NULL;\n }\n \n ACS::OffShoot_ptr activateOffShoot(PortableServer::Servant cbServant)\n {\n return NULL;\n }\n \n void deactivateOffShoot(PortableServer::Servant cbServant)\n throw (\n acsErrTypeContainerServices::OffShootDeactivationExImpl,\n acsErrTypeContainerServices::OffShootPOAExImpl){}\n \n PortableServer::POA_var createOffShootPOA()\n {\n return NULL;\n }\n \n ComponentStateManager* getComponentStateManager()\n {\n return NULL;\n }\n};\n\nbool EPshutting_down = false;\n\nvoid TerminationSignalHandler(int)\n{\n if (EPshutting_down) return;\n EPshutting_down=true;\n \n \/\/ initialize logger (this is a new thread)\n LoggingProxy EP_log (0, 0, 31, 0);\n LoggingProxy::init (&EP_log);\n\n ACS_LOG(0, \"termination\", (LM_INFO, \"Termination signal detected.\"));\n \n \n try\n\t{\n\t\/\/ false - avoid deadlock; true would try to wait for all requests\n\t\/\/ to complete before returning, but because we are calling it from within\n\t\/\/ a request, we would be blocking it from \n\t BACI_CORBA::getORB()->shutdown(false);\n\t \n\t}\n catch( CORBA::Exception &ex )\n\t{\n\tACE_PRINT_EXCEPTION( ex, \"TerminationSignalHandler\");\n\t}\n}\n\n\nint main(int l_argc, char* l_argv[]) \n{\n\n \n\n \/\/ create logging proxy\n \n LoggingProxy EP_log (0, 0, 31, 0);\n LoggingProxy::init (&EP_log);\n LoggingProxy::ProcessName(l_argv[0]);\n ACS_SHORT_LOG((LM_INFO, \"Logging proxy successfully created !\"));\n\n\n ACS_SHORT_LOG((LM_INFO, \"enumpropTestServer: Starting\"));\n if (l_argc < 2) {\n ACS_SHORT_LOG((LM_INFO,\"Usage: enumpropTestServer \"));\n return -1;\n }\n\n \/\/ Installs termination signal handlers, to be able\n \/\/ to terminate cleanly\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Installing signal handlers\"));\n ACE_OS::signal(SIGINT, TerminationSignalHandler); \/\/ Ctrl+C\n ACE_OS::signal(SIGTERM, TerminationSignalHandler); \/\/ termination request\n\n int devCount = l_argc-1;\n\n CORBA::String_var ior;\n enumpropTestDeviceImpl *ep_servant;\n ENUMPROP_TEST::enumpropTestDevice_var ep;\n\n int count = 0;\n char fileName[64];\n FILE *IOR_file;\n \n try {\n\n \/\/ Initialize the ORB.\n BACI_CORBA::InitCORBA(l_argc, l_argv);\n\n if (!ACSError::init (BACI_CORBA::getORB()))\n\t{\n\tACS_LOG(LM_RUNTIME_CONTEXT, \"baciTestServer\",\n\t\t(LM_INFO, \"Failed to initialize ACSError.\"));\n\treturn -1;\n\t}\n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Init DB\"));\n\n DBConnector::initDB(\":Appl_data:alma\");\n\n \/\/ Instantiate the CBDPropertySet singleton\n if (DBConnector::getDBTable())\n\tCDBPropertySet::createInstance(BACI_CORBA::getORB(), \n\t\t\t\t BACI_CORBA::getPOAManager(),\n\t\t\t\t BACI_CORBA::getPOARoot());\n\n\n for (int n=1; n <= devCount; n++)\n\t{\n \n\tACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Exporting \\\"%s\\\"\", l_argv[n]));\n \n \/\/ Build the implementation of the containerServices to pass to the constructor \n \/\/ of the component (the component will free its memory)\n ACE_CString name(l_argv[n]);\n TestContainerServices* pCS = new TestContainerServices(name,BACI_CORBA::getPOA(),BACI_CORBA::getORB());\n\tep_servant = new enumpropTestDeviceImpl(name,pCS);\n\tACS_SHORT_LOG((LM_INFO, \"enumpropTestDevice: %s created\", l_argv[n]));\n\tep = ep_servant->_this();\n\tep_servant->_remove_ref();\n\t \n\tior = BACI_CORBA::getORB()->object_to_string (ep.ptr());\n\t\n \n\tACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Writing IOR for %s into file...\", l_argv[n]));\n\tsprintf(fileName, \"%s.ior\", name.c_str());\n\tIOR_file = ACE_OS::fopen (fileName, \"w\");\n\tif (IOR_file == 0) \n {\n\t ACS_SHORT_LOG ((LM_ERROR,\n\t\t \"Cannot open output files for writing IOR: %s\", fileName));\n\t return -1;\n\t}\n\t\n\tint result = ACE_OS::fprintf (IOR_file, \"%s\", ior.in());\n\tif (result < 0)\n\t {\n\t ACS_SHORT_LOG ((LM_ERROR,\n\t\t\t \"ACE_OS::fprintf failed while writing %s into %s\\n\", ior.in(), fileName));\n\t return -1;\n\t }\n\tACE_OS::fclose (IOR_file);\n\tACS_SHORT_LOG((LM_INFO, \"enumpropTestDevice: %s exported\", l_argv[n]));\n\n\tcount++;\n\n\/\/\tPortableServer::ObjectId_var oid = BACI_CORBA::getPOA()->reference_to_id(ep.ptr());\n\/\/\tBACI_CORBA::getPOA()->deactivate_object(oid.in());\n\t\n\n\t}\/\/for\n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Waiting for requests ... \"));\n BACI_CORBA::getORB()->run();\n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Exiting.\"));\n \n ep_servant->_remove_ref(); \n \n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Releasing CORBA.\"));\n\n BACI_CORBA::DoneCORBA();\n \n DBConnector::closeDB();\n \n \/\/delete t;\n\n \n LoggingProxy::done();\n \n std::cout << std::flush; \/\/ shold be done by: LoggingProxy::done()\n\n return 0; \n\n }catch(CORBA::Exception &ex) {\n ACS_SHORT_LOG((LM_INFO, \"enumpropTestServer: Exceptions raised while creating Component\"));\n return -1;\n }\n return 0;\n} \n\n\n#ifdef MAKE_VXWORKS\n\nint startEnumpropTestServer (char *szCmdLn)\n{\n int l_argc;\n char *l_argv[100];\n\n\/\/ ACE_MAIN_OBJECT_MANAGER;\n\n l_argc = argUnpack(szCmdLn, l_argv);\n l_argv[0] = \"enumpropTestServer\";\n\n return ace_main_i(l_argc, l_argv);\n}\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\nadded getCORBACollocatedComponent\/***************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\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 as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\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* \"@(#) $Id: enumpropTestServer.cpp,v 1.46 2006\/06\/13 09:18:16 bjeram Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* david 2002-08-15 changed argUnpack.h to acsutilArgUnpack.h\n* bjeram 2001-12-03 created \n*\/\n\n\n#include \"vltPort.h\"\n\nstatic char *rcsId=\"@(#) $Id: enumpropTestServer.cpp,v 1.46 2006\/06\/13 09:18:16 bjeram Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"enumpropTestDeviceImpl.h\"\n\n#ifdef MAKE_VXWORKS\n#\tinclude \"rebootLib.h\"\n#\tinclude \"acsutilArgUnpack.h\"\n#endif\n\nusing namespace ACS;\nusing namespace baci;\n\n\/\/ We need an implementation of the ContainerServices here because\n\/\/ 1. the component fails if the pointer to the ContainerServices it receives\n\/\/ in the constructor is NULL\n\/\/ 2. the smart pointer used to store the ContainerServices deletes all\n\/\/ the not-NULL instances of the Container Services\n\/\/ This clla implements all the methods of the interface but does nothing\nclass TestContainerServices : public maci::ContainerServices {\n public:\n CORBA::ORB_var m_orb;\n\n TestContainerServices(ACE_CString& compName, PortableServer::POA_ptr poa, CORBA::ORB_ptr orb):\n maci::ContainerServices(compName,poa), m_orb(CORBA::ORB::_duplicate(orb)) {\n ACS_SHORT_LOG((LM_INFO,\"TestContainerServices built\"));\n }\n \n virtual ~TestContainerServices() {\n ACS_SHORT_LOG((LM_INFO,\"TestContainerServices destroyed\"));\n }\n \n CORBA::Object* getCORBAComponent(const char* name)\n {\n return (CORBA::Object*)NULL;\n }\n \n CORBA::Object* getCORBADynamicComponent(maci::ComponentSpec compSpec, bool markAsDefault)\n {\n return (CORBA::Object*)NULL;\n }\n \n CORBA::Object* getCORBADefaultComponent(const char* idlType)\n {\n return (CORBA::Object*)NULL;\n }\n\n virtual CORBA::Object* getCORBACollocatedComponent(maci::ComponentSpec, bool, const char*)\n\t{\n\t return (CORBA::Object*)NULL;\n\t}\n\n public:\n \n maci::ComponentInfo getComponentDescriptor(const char* componentName)\n throw (acsErrTypeContainerServices::GettingCompInfoExImpl)\n {\n ComponentInfo temp;\n return temp;\n }\n \n ACE_CString_Vector findComponents(const char *nameWilcard, const char *typeWildcard)\n {\n return ACE_CString_Vector();\n }\n \n void releaseComponent(const char *name){}\n \n void releaseAllComponents(){}\n \n CDB::DAL_ptr getCDB()\n {\n\t ACE_TCHAR corbalocRef[230];\n\t ACE_TCHAR * envRef = ACE_OS::getenv (\"DAL_REFERENCE\");\n\n\t if (envRef && *envRef)\n\t\t{\n\t\tACS_LOG(0, \"TestContainerServices::getCDB\",\n\t\t\t(LM_INFO, \"CDB obtained via environment: '%s'\", envRef));\n\t\tstrcpy(corbalocRef, envRef);\n\t\t}\n\t else\n\t\t{\n\t \/\/ corbaloc:::\/CDB\n\t const char* hostname = 0;\n\t hostname = ACSPorts::getIP();\n\t if (hostname==0)\n\t\treturn (CDB::DAL *)0;\n\t \n\t ACE_TCHAR corbalocRef[230];\n\t ACE_OS::sprintf(corbalocRef, \"corbaloc::%s:%s\/CDB\", hostname, ACSPorts::getCDBPort().c_str());\n\t \n\t ACS_LOG(0, \"TestContainerServices::getCDB\",\n\t\t (LM_INFO, \"CDB reference generated using localhost address: '%s'\", corbalocRef));\n\t\t}\/\/if-else\n\t \n\t CDB::DAL_var dalObj = CDB::DAL::_nil();\n\t CORBA::Object_var obj = m_orb->string_to_object(corbalocRef);\n\t \n\t if (!CORBA::is_nil(obj.in()))\n\t\t{\n\t\tdalObj = CDB::DAL::_narrow(obj.in());\n\t\tif (CORBA::is_nil(dalObj.in())) \n\t\t {\n\t\t ACS_SHORT_LOG((LM_INFO, \"TestContainerServices::getCDB() - Failed to narrow CDB\"));\n\t\t return (CDB::DAL *)0;\n\t\t }\n\t\t}\n\t \n\t return dalObj._retn();\n }\n \n PortableServer::POA_var getOffShootPOA()\n {\n return NULL;\n }\n \n ACS::OffShoot_ptr activateOffShoot(PortableServer::Servant cbServant)\n {\n return NULL;\n }\n \n void deactivateOffShoot(PortableServer::Servant cbServant)\n throw (\n acsErrTypeContainerServices::OffShootDeactivationExImpl,\n acsErrTypeContainerServices::OffShootPOAExImpl){}\n \n PortableServer::POA_var createOffShootPOA()\n {\n return NULL;\n }\n \n ComponentStateManager* getComponentStateManager()\n {\n return NULL;\n }\n};\n\nbool EPshutting_down = false;\n\nvoid TerminationSignalHandler(int)\n{\n if (EPshutting_down) return;\n EPshutting_down=true;\n \n \/\/ initialize logger (this is a new thread)\n LoggingProxy EP_log (0, 0, 31, 0);\n LoggingProxy::init (&EP_log);\n\n ACS_LOG(0, \"termination\", (LM_INFO, \"Termination signal detected.\"));\n \n \n try\n\t{\n\t\/\/ false - avoid deadlock; true would try to wait for all requests\n\t\/\/ to complete before returning, but because we are calling it from within\n\t\/\/ a request, we would be blocking it from \n\t BACI_CORBA::getORB()->shutdown(false);\n\t \n\t}\n catch( CORBA::Exception &ex )\n\t{\n\tACE_PRINT_EXCEPTION( ex, \"TerminationSignalHandler\");\n\t}\n}\n\n\nint main(int l_argc, char* l_argv[]) \n{\n\n \n\n \/\/ create logging proxy\n \n LoggingProxy EP_log (0, 0, 31, 0);\n LoggingProxy::init (&EP_log);\n LoggingProxy::ProcessName(l_argv[0]);\n ACS_SHORT_LOG((LM_INFO, \"Logging proxy successfully created !\"));\n\n\n ACS_SHORT_LOG((LM_INFO, \"enumpropTestServer: Starting\"));\n if (l_argc < 2) {\n ACS_SHORT_LOG((LM_INFO,\"Usage: enumpropTestServer \"));\n return -1;\n }\n\n \/\/ Installs termination signal handlers, to be able\n \/\/ to terminate cleanly\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Installing signal handlers\"));\n ACE_OS::signal(SIGINT, TerminationSignalHandler); \/\/ Ctrl+C\n ACE_OS::signal(SIGTERM, TerminationSignalHandler); \/\/ termination request\n\n int devCount = l_argc-1;\n\n CORBA::String_var ior;\n enumpropTestDeviceImpl *ep_servant;\n ENUMPROP_TEST::enumpropTestDevice_var ep;\n\n int count = 0;\n char fileName[64];\n FILE *IOR_file;\n \n try {\n\n \/\/ Initialize the ORB.\n BACI_CORBA::InitCORBA(l_argc, l_argv);\n\n if (!ACSError::init (BACI_CORBA::getORB()))\n\t{\n\tACS_LOG(LM_RUNTIME_CONTEXT, \"baciTestServer\",\n\t\t(LM_INFO, \"Failed to initialize ACSError.\"));\n\treturn -1;\n\t}\n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Init DB\"));\n\n DBConnector::initDB(\":Appl_data:alma\");\n\n \/\/ Instantiate the CBDPropertySet singleton\n if (DBConnector::getDBTable())\n\tCDBPropertySet::createInstance(BACI_CORBA::getORB(), \n\t\t\t\t BACI_CORBA::getPOAManager(),\n\t\t\t\t BACI_CORBA::getPOARoot());\n\n\n for (int n=1; n <= devCount; n++)\n\t{\n \n\tACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Exporting \\\"%s\\\"\", l_argv[n]));\n \n \/\/ Build the implementation of the containerServices to pass to the constructor \n \/\/ of the component (the component will free its memory)\n ACE_CString name(l_argv[n]);\n TestContainerServices* pCS = new TestContainerServices(name,BACI_CORBA::getPOA(),BACI_CORBA::getORB());\n\tep_servant = new enumpropTestDeviceImpl(name,pCS);\n\tACS_SHORT_LOG((LM_INFO, \"enumpropTestDevice: %s created\", l_argv[n]));\n\tep = ep_servant->_this();\n\tep_servant->_remove_ref();\n\t \n\tior = BACI_CORBA::getORB()->object_to_string (ep.ptr());\n\t\n \n\tACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Writing IOR for %s into file...\", l_argv[n]));\n\tsprintf(fileName, \"%s.ior\", name.c_str());\n\tIOR_file = ACE_OS::fopen (fileName, \"w\");\n\tif (IOR_file == 0) \n {\n\t ACS_SHORT_LOG ((LM_ERROR,\n\t\t \"Cannot open output files for writing IOR: %s\", fileName));\n\t return -1;\n\t}\n\t\n\tint result = ACE_OS::fprintf (IOR_file, \"%s\", ior.in());\n\tif (result < 0)\n\t {\n\t ACS_SHORT_LOG ((LM_ERROR,\n\t\t\t \"ACE_OS::fprintf failed while writing %s into %s\\n\", ior.in(), fileName));\n\t return -1;\n\t }\n\tACE_OS::fclose (IOR_file);\n\tACS_SHORT_LOG((LM_INFO, \"enumpropTestDevice: %s exported\", l_argv[n]));\n\n\tcount++;\n\n\/\/\tPortableServer::ObjectId_var oid = BACI_CORBA::getPOA()->reference_to_id(ep.ptr());\n\/\/\tBACI_CORBA::getPOA()->deactivate_object(oid.in());\n\t\n\n\t}\/\/for\n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Waiting for requests ... \"));\n BACI_CORBA::getORB()->run();\n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Exiting.\"));\n \n ep_servant->_remove_ref(); \n \n\n ACS_SHORT_LOG((LM_INFO,\"enumpropTestServer: Releasing CORBA.\"));\n\n BACI_CORBA::DoneCORBA();\n \n DBConnector::closeDB();\n \n \/\/delete t;\n\n \n LoggingProxy::done();\n \n std::cout << std::flush; \/\/ shold be done by: LoggingProxy::done()\n\n return 0; \n\n }catch(CORBA::Exception &ex) {\n ACS_SHORT_LOG((LM_INFO, \"enumpropTestServer: Exceptions raised while creating Component\"));\n return -1;\n }\n return 0;\n} \n\n\n#ifdef MAKE_VXWORKS\n\nint startEnumpropTestServer (char *szCmdLn)\n{\n int l_argc;\n char *l_argv[100];\n\n\/\/ ACE_MAIN_OBJECT_MANAGER;\n\n l_argc = argUnpack(szCmdLn, l_argv);\n l_argv[0] = \"enumpropTestServer\";\n\n return ace_main_i(l_argc, l_argv);\n}\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n\n#include \"..\/..\/Foundation\/Characters\/FloatConversion.h\"\n#include \"..\/..\/Foundation\/Characters\/Format.h\"\n#include \"..\/..\/Foundation\/Characters\/String2Int.h\"\n#include \"..\/..\/Foundation\/Characters\/String_Constant.h\"\n#include \"..\/..\/Foundation\/Characters\/ToString.h\"\n#include \"..\/..\/Foundation\/Containers\/Common.h\"\n#include \"..\/..\/Foundation\/DataExchange\/BadFormatException.h\"\n#include \"..\/..\/Foundation\/Debug\/Assertions.h\"\n#include \"..\/..\/Foundation\/Execution\/Exceptions.h\"\n#include \"..\/..\/Foundation\/IO\/FileSystem\/FileOutputStream.h\"\n#include \"..\/..\/Foundation\/IO\/FileSystem\/WellKnownLocations.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Headers.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/MessageStartTextInputStreamBinaryAdapter.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Methods.h\"\n#include \"..\/..\/Foundation\/Memory\/SmallStackBuffer.h\"\n#include \"..\/..\/Foundation\/Streams\/LoggingInputOutputStream.h\"\n#include \"..\/..\/Foundation\/Streams\/SplitterOutputStream.h\"\n\n#include \"ClientErrorException.h\"\n\n#include \"Connection.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Memory;\n\nusing namespace Stroika::Frameworks;\nusing namespace Stroika::Frameworks::WebServer;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n ***************************** WebServer::Connection ****************************\n ********************************************************************************\n *\/\nConnection::Connection (const ConnectionOrientedSocket::Ptr& s, const InterceptorChain& interceptorChain)\n : fInterceptorChain_{interceptorChain}\n , fSocket_ (s)\n{\n Require (s != nullptr);\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Created connection for socket %s\", Characters::ToString (s).c_str ());\n#endif\n fSocketStream_ = SocketStream::New (fSocket_);\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n constexpr bool kWriteLogData_ = true;\n#else\n constexpr bool kWriteLogData_ = false;\n#endif\n if (kWriteLogData_) {\n fSocketStream_ = Streams::LoggingInputOutputStream::New (\n fSocketStream_,\n IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + Characters::Format (L\"socket-%s-input-trace.txt\", Characters::ToString (s).c_str ())),\n IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + Characters::Format (L\"socket-%s-output-trace.txt\", Characters::ToString (s).c_str ())));\n }\n}\n\nConnection::~Connection ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Destroying connection for socket %s, message=%s\", Characters::ToString (fSocket_).c_str (), Characters::ToString (fMessage_).c_str ());\n#endif\n if (fMessage_ != nullptr) {\n if (fMessage_->PeekResponse ()->GetState () != Response::State::eCompleted) {\n IgnoreExceptionsForCall (fMessage_->PeekResponse ()->Abort ());\n }\n Require (fMessage_->PeekResponse ()->GetState () == Response::State::eCompleted);\n }\n \/*\n * When the connection is completed, make sure the socket is closed so that the calling client knows\n * as quickly as possible. Probably not generally necessary since when the last reference to the socket\n * goes away, it will also be closed, but that might take a little longer as its held in some object\n * that hasn't gone away yet.\n *\/\n AssertNotNull (fSocket_);\n try {\n fSocket_.Close ();\n }\n catch (...) {\n DbgTrace (L\"Exception ignored closing socket: %s\", Characters::ToString (current_exception ()).c_str ());\n }\n}\n\nbool Connection::ReadHeaders_ (Message* msg)\n{\n \/*\n * DONT use TextStream::ReadLine - because that asserts SEEKABLE - which may not be true \n * (and probably isn't here anymore)\n * Instead - we need a special variant that looks for CRLF - which doesn't require backtracking...!!!\n *\/\n using Foundation::IO::Network::HTTP::MessageStartTextInputStreamBinaryAdapter;\n Request* request = msg->PeekRequest ();\n MessageStartTextInputStreamBinaryAdapter::Ptr inTextStream = MessageStartTextInputStreamBinaryAdapter::New (request->GetInputStream ());\n {\n \/\/ Read METHOD line\n String line = inTextStream.ReadLine ();\n if (line.length () == 0) {\n \/\/ inTextStream.IsAtEOF () would be blocking, and that's not desired here\n if (inTextStream.ReadNonBlocking () == 0) {\n \/*\n * This is relatively common. There is an outstanding connection (so client did tcp_connect) - but never got around\n * to sending data cuz the need for the data evaporated.\n *\n * I've seen this not so uncommonly with chrome (hit refresh button fast and wait a while) -- LGP 2018-03-04\n *\/\n return false;\n }\n }\n Sequence tokens{line.Tokenize (Set{' '})};\n if (tokens.size () < 3) {\n DbgTrace (L\"tokens=%s, line='%s', inTextStream=%s\", Characters::ToString (tokens).c_str (), line.c_str (), inTextStream.ToString ().c_str ());\n Execution::Throw (ClientErrorException (Characters::Format (L\"Bad METHOD REQUEST HTTP line (%s)\", line.c_str ())));\n }\n request->SetHTTPMethod (tokens[0]);\n request->SetHTTPVersion (tokens[2]);\n if (tokens[1].empty ()) {\n \/\/ should check if GET\/PUT\/DELETE etc...\n DbgTrace (L\"tokens=%s, line='%s'\", Characters::ToString (tokens).c_str (), line.c_str ());\n Execution::Throw (ClientErrorException (String_Constant (L\"Bad HTTP REQUEST line - missing host-relative URL\")));\n }\n using IO::Network::URL;\n request->SetURL (URL::Parse (tokens[1], URL::eAsRelativeURL));\n if (request->GetHTTPMethod ().empty ()) {\n \/\/ should check if GET\/PUT\/DELETE etc...\n DbgTrace (L\"tokens=%s, line='%s'\", Characters::ToString (tokens).c_str (), line.c_str ());\n Execution::Throw (ClientErrorException (String_Constant (L\"Bad METHOD in REQUEST HTTP line\")));\n }\n }\n while (true) {\n String line = inTextStream.ReadLine ();\n if (line == String_Constant (L\"\\r\\n\") or line.empty ()) {\n break; \/\/ done\n }\n\n \/\/ add subsequent items to the header map\n size_t i = line.find (':');\n if (i == string::npos) {\n DbgTrace (L\"line=%s\", Characters::ToString (line).c_str ());\n Execution::Throw (ClientErrorException (String_Constant (L\"Bad HTTP REQUEST missing colon in headers\")));\n }\n else {\n String hdr = line.SubString (0, i).Trim ();\n String value = line.SubString (i + 1).Trim ();\n request->AddHeader (hdr, value);\n }\n }\n return true;\n}\n\nvoid Connection::Close ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (L\"Connection::Close\");\n#endif\n fMessage_->PeekResponse ()->End ();\n fSocket_.Close ();\n}\n\nbool Connection::ReadAndProcessMessage ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"Connection::ReadAndProcessMessage\", L\"this->socket=%s\", Characters::ToString (fSocket_).c_str ())};\n#endif\n#if qCompilerAndStdLib_copy_elision_Warning_too_aggressive_when_not_copyable_Buggy\n DISABLE_COMPILER_CLANG_WARNING_START (\"clang diagnostic ignored \\\"-Wpessimizing-move\\\"\");\n#endif\n {\n fMessage_ = make_shared (\n move (Request (fSocketStream_)),\n move (Response (fSocket_, fSocketStream_, DataExchange::PredefinedInternetMediaType::kOctetStream)),\n fSocket_.GetPeerAddress ());\n }\n#if qCompilerAndStdLib_copy_elision_Warning_too_aggressive_when_not_copyable_Buggy\n DISABLE_COMPILER_CLANG_WARNING_END (\"clang diagnostic ignored \\\"-Wpessimizing-move\\\"\");\n#endif\n\n if (not ReadHeaders_ (fMessage_.get ())) {\n DbgTrace (L\"ReadHeaders failed - typically because the client closed the connection before we could handle it (e.g. in web browser hitting refresh button fast).\");\n return false;\n }\n\n {\n \/\/ @see https:\/\/tools.ietf.org\/html\/rfc2068#page-43 19.7.1.1 The Keep-Alive Header\n if (auto aliveHeaderValue = fMessage_->PeekRequest ()->GetHeaders ().Lookup (IO::Network::HTTP::HeaderName::kKeepAlive)) {\n for (String token : aliveHeaderValue->Tokenize (Set{' ', ','})) {\n Containers::Sequence kvp = token.Tokenize (Set{'='});\n if (kvp.length () == 2) {\n \/\/ https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Headers\/Keep-Alive\n if (kvp[0] == L\"timeout\") {\n Time::DurationSecondsType toAt = Characters::String2Float<> (kvp[1]);\n Remaining r = GetRemainingConnectionLimits ().Value ();\n r.fTimeoutAt = Time::GetTickCount () + toAt;\n this->SetRemainingConnectionMessages (r);\n }\n else if (kvp[0] == L\"max\") {\n unsigned int maxMsg = Characters::String2Int (kvp[1]);\n Remaining r = GetRemainingConnectionLimits ().Value ();\n r.fMessages = maxMsg;\n this->SetRemainingConnectionMessages (r);\n }\n else {\n DbgTrace (L\"Keep-Alive header bad: %s\", aliveHeaderValue->c_str ());\n }\n }\n else {\n DbgTrace (L\"Keep-Alive header bad: %s\", aliveHeaderValue->c_str ());\n }\n }\n }\n }\n\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Handing request %s to interceptor chain\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n try {\n fInterceptorChain_.HandleMessage (fMessage_.get ());\n }\n catch (...) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Interceptor-Chain caught exception handling message: %s\", Characters::ToString (current_exception ()).c_str ());\n#endif\n }\n\n bool thisMessageKeepAlive = fMessage_->PeekRequest ()->GetKeepAliveRequested ();\n if (thisMessageKeepAlive) {\n if (not GetResponse ().IsContentLengthKnown ()) {\n thisMessageKeepAlive = false;\n }\n }\n if (thisMessageKeepAlive) {\n \/\/ if missing, no limits\n if (auto oRemaining = GetRemainingConnectionLimits ()) {\n if (oRemaining->fMessages) {\n if (oRemaining->fMessages == 0) {\n thisMessageKeepAlive = false;\n }\n else {\n oRemaining->fMessages = *oRemaining->fMessages - 1;\n }\n }\n if (oRemaining->fTimeoutAt) {\n if (*oRemaining->fTimeoutAt < Time::GetTickCount ()) {\n thisMessageKeepAlive = false;\n }\n }\n }\n }\n\n if (thisMessageKeepAlive) {\n \/\/ be sure we advance the read pointer over the message body, lest we start reading part of the previous message as the next message\n\n \/\/ @todo must fix this for support of Transfer-Encoding, but from:\n \/\/\n \/*\n * https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec4.html\n * The rules for when a message-body is allowed in a message differ for requests and responses.\n *\n * The presence of a message-body in a request is signaled by the inclusion of a Content-Length \n * or Transfer-Encoding header field in the request's message-headers\/\n *\/\n if (GetRequest ().GetContentLength ()) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Assuring all data read; REQ=%s\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n \/\/ @todo - this can be more efficient in the rare case we ignore the body - but thats rare enough to not matter mcuh\n (void)fMessage_->GetRequestBody ();\n }\n#if 0\n else if (GetRequest ().GetHTTPMethod ().Equals (IO::Network::HTTP::Methods::kGet, Characters::CompareOptions::eCaseInsensitive)) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"This request should be closed but thats much less efficient, and chrome seems todo this - sure???; REQ=%s\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n }\n else {\n thisMessageKeepAlive = false;\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"forced close connection because the request header lacked a Content-Length: REQ=%s\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n }\n#endif\n }\n\n \/\/ From https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec14.html\n \/\/ HTTP\/1.1 applications that do not support persistent connections MUST include the \"close\" connection option in every message.\n GetResponse ().AddHeader (IO::Network::HTTP::HeaderName::kConnection,\n thisMessageKeepAlive ? String_Constant{L\"Keep-Alive\"} : String_Constant{L\"close\"});\n\n GetResponse ().End ();\n return thisMessageKeepAlive;\n}\ntweak kWriteLogData_ support in WebServer\/Connection\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n\n#include \"..\/..\/Foundation\/Characters\/FloatConversion.h\"\n#include \"..\/..\/Foundation\/Characters\/Format.h\"\n#include \"..\/..\/Foundation\/Characters\/String2Int.h\"\n#include \"..\/..\/Foundation\/Characters\/String_Constant.h\"\n#include \"..\/..\/Foundation\/Characters\/ToString.h\"\n#include \"..\/..\/Foundation\/Containers\/Common.h\"\n#include \"..\/..\/Foundation\/DataExchange\/BadFormatException.h\"\n#include \"..\/..\/Foundation\/Debug\/Assertions.h\"\n#include \"..\/..\/Foundation\/Execution\/Exceptions.h\"\n#include \"..\/..\/Foundation\/IO\/FileSystem\/FileOutputStream.h\"\n#include \"..\/..\/Foundation\/IO\/FileSystem\/WellKnownLocations.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Headers.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/MessageStartTextInputStreamBinaryAdapter.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Methods.h\"\n#include \"..\/..\/Foundation\/Memory\/SmallStackBuffer.h\"\n#include \"..\/..\/Foundation\/Streams\/LoggingInputOutputStream.h\"\n#include \"..\/..\/Foundation\/Streams\/SplitterOutputStream.h\"\n#include \"..\/..\/Foundation\/Time\/DateTime.h\"\n\n#include \"ClientErrorException.h\"\n\n#include \"Connection.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Memory;\n\nusing namespace Stroika::Frameworks;\nusing namespace Stroika::Frameworks::WebServer;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n ***************************** WebServer::Connection ****************************\n ********************************************************************************\n *\/\nConnection::Connection (const ConnectionOrientedSocket::Ptr& s, const InterceptorChain& interceptorChain)\n : fInterceptorChain_{interceptorChain}\n , fSocket_ (s)\n{\n Require (s != nullptr);\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Created connection for socket %s\", Characters::ToString (s).c_str ());\n#endif\n fSocketStream_ = SocketStream::New (fSocket_);\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n constexpr bool kWriteLogData_ = true;\n#else\n constexpr bool kWriteLogData_ = false;\n#endif\n if (kWriteLogData_) {\n String socketName = Characters::Format (L\"%s-%d\", Time::DateTime::Now ().Format (Time::DateTime::PrintFormat::eISO8601).ReplaceAll (L\":\", L\"-\").c_str (), s.GetNativeSocket ());\n fSocketStream_ = Streams::LoggingInputOutputStream::New (\n fSocketStream_,\n IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + Characters::Format (L\"socket-%s-input-trace.txt\", socketName.c_str ())),\n IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + Characters::Format (L\"socket-%s-output-trace.txt\", socketName.c_str ())));\n }\n}\n\nConnection::~Connection ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Destroying connection for socket %s, message=%s\", Characters::ToString (fSocket_).c_str (), Characters::ToString (fMessage_).c_str ());\n#endif\n if (fMessage_ != nullptr) {\n if (fMessage_->PeekResponse ()->GetState () != Response::State::eCompleted) {\n IgnoreExceptionsForCall (fMessage_->PeekResponse ()->Abort ());\n }\n Require (fMessage_->PeekResponse ()->GetState () == Response::State::eCompleted);\n }\n \/*\n * When the connection is completed, make sure the socket is closed so that the calling client knows\n * as quickly as possible. Probably not generally necessary since when the last reference to the socket\n * goes away, it will also be closed, but that might take a little longer as its held in some object\n * that hasn't gone away yet.\n *\/\n AssertNotNull (fSocket_);\n try {\n fSocket_.Close ();\n }\n catch (...) {\n DbgTrace (L\"Exception ignored closing socket: %s\", Characters::ToString (current_exception ()).c_str ());\n }\n}\n\nbool Connection::ReadHeaders_ (Message* msg)\n{\n \/*\n * DONT use TextStream::ReadLine - because that asserts SEEKABLE - which may not be true \n * (and probably isn't here anymore)\n * Instead - we need a special variant that looks for CRLF - which doesn't require backtracking...!!!\n *\/\n using Foundation::IO::Network::HTTP::MessageStartTextInputStreamBinaryAdapter;\n Request* request = msg->PeekRequest ();\n MessageStartTextInputStreamBinaryAdapter::Ptr inTextStream = MessageStartTextInputStreamBinaryAdapter::New (request->GetInputStream ());\n {\n \/\/ Read METHOD line\n String line = inTextStream.ReadLine ();\n if (line.length () == 0) {\n \/\/ inTextStream.IsAtEOF () would be blocking, and that's not desired here\n if (inTextStream.ReadNonBlocking () == 0) {\n \/*\n * This is relatively common. There is an outstanding connection (so client did tcp_connect) - but never got around\n * to sending data cuz the need for the data evaporated.\n *\n * I've seen this not so uncommonly with chrome (hit refresh button fast and wait a while) -- LGP 2018-03-04\n *\/\n return false;\n }\n }\n Sequence tokens{line.Tokenize (Set{' '})};\n if (tokens.size () < 3) {\n DbgTrace (L\"tokens=%s, line='%s', inTextStream=%s\", Characters::ToString (tokens).c_str (), line.c_str (), inTextStream.ToString ().c_str ());\n Execution::Throw (ClientErrorException (Characters::Format (L\"Bad METHOD REQUEST HTTP line (%s)\", line.c_str ())));\n }\n request->SetHTTPMethod (tokens[0]);\n request->SetHTTPVersion (tokens[2]);\n if (tokens[1].empty ()) {\n \/\/ should check if GET\/PUT\/DELETE etc...\n DbgTrace (L\"tokens=%s, line='%s'\", Characters::ToString (tokens).c_str (), line.c_str ());\n Execution::Throw (ClientErrorException (String_Constant (L\"Bad HTTP REQUEST line - missing host-relative URL\")));\n }\n using IO::Network::URL;\n request->SetURL (URL::Parse (tokens[1], URL::eAsRelativeURL));\n if (request->GetHTTPMethod ().empty ()) {\n \/\/ should check if GET\/PUT\/DELETE etc...\n DbgTrace (L\"tokens=%s, line='%s'\", Characters::ToString (tokens).c_str (), line.c_str ());\n Execution::Throw (ClientErrorException (String_Constant (L\"Bad METHOD in REQUEST HTTP line\")));\n }\n }\n while (true) {\n String line = inTextStream.ReadLine ();\n if (line == String_Constant (L\"\\r\\n\") or line.empty ()) {\n break; \/\/ done\n }\n\n \/\/ add subsequent items to the header map\n size_t i = line.find (':');\n if (i == string::npos) {\n DbgTrace (L\"line=%s\", Characters::ToString (line).c_str ());\n Execution::Throw (ClientErrorException (String_Constant (L\"Bad HTTP REQUEST missing colon in headers\")));\n }\n else {\n String hdr = line.SubString (0, i).Trim ();\n String value = line.SubString (i + 1).Trim ();\n request->AddHeader (hdr, value);\n }\n }\n return true;\n}\n\nvoid Connection::Close ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (L\"Connection::Close\");\n#endif\n fMessage_->PeekResponse ()->End ();\n fSocket_.Close ();\n}\n\nbool Connection::ReadAndProcessMessage ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"Connection::ReadAndProcessMessage\", L\"this->socket=%s\", Characters::ToString (fSocket_).c_str ())};\n#endif\n#if qCompilerAndStdLib_copy_elision_Warning_too_aggressive_when_not_copyable_Buggy\n DISABLE_COMPILER_CLANG_WARNING_START (\"clang diagnostic ignored \\\"-Wpessimizing-move\\\"\");\n#endif\n {\n fMessage_ = make_shared (\n move (Request (fSocketStream_)),\n move (Response (fSocket_, fSocketStream_, DataExchange::PredefinedInternetMediaType::kOctetStream)),\n fSocket_.GetPeerAddress ());\n }\n#if qCompilerAndStdLib_copy_elision_Warning_too_aggressive_when_not_copyable_Buggy\n DISABLE_COMPILER_CLANG_WARNING_END (\"clang diagnostic ignored \\\"-Wpessimizing-move\\\"\");\n#endif\n\n if (not ReadHeaders_ (fMessage_.get ())) {\n DbgTrace (L\"ReadHeaders failed - typically because the client closed the connection before we could handle it (e.g. in web browser hitting refresh button fast).\");\n return false;\n }\n\n {\n \/\/ @see https:\/\/tools.ietf.org\/html\/rfc2068#page-43 19.7.1.1 The Keep-Alive Header\n if (auto aliveHeaderValue = fMessage_->PeekRequest ()->GetHeaders ().Lookup (IO::Network::HTTP::HeaderName::kKeepAlive)) {\n for (String token : aliveHeaderValue->Tokenize (Set{' ', ','})) {\n Containers::Sequence kvp = token.Tokenize (Set{'='});\n if (kvp.length () == 2) {\n \/\/ https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Headers\/Keep-Alive\n if (kvp[0] == L\"timeout\") {\n Time::DurationSecondsType toAt = Characters::String2Float<> (kvp[1]);\n Remaining r = GetRemainingConnectionLimits ().Value ();\n r.fTimeoutAt = Time::GetTickCount () + toAt;\n this->SetRemainingConnectionMessages (r);\n }\n else if (kvp[0] == L\"max\") {\n unsigned int maxMsg = Characters::String2Int (kvp[1]);\n Remaining r = GetRemainingConnectionLimits ().Value ();\n r.fMessages = maxMsg;\n this->SetRemainingConnectionMessages (r);\n }\n else {\n DbgTrace (L\"Keep-Alive header bad: %s\", aliveHeaderValue->c_str ());\n }\n }\n else {\n DbgTrace (L\"Keep-Alive header bad: %s\", aliveHeaderValue->c_str ());\n }\n }\n }\n }\n\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Handing request %s to interceptor chain\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n try {\n fInterceptorChain_.HandleMessage (fMessage_.get ());\n }\n catch (...) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Interceptor-Chain caught exception handling message: %s\", Characters::ToString (current_exception ()).c_str ());\n#endif\n }\n\n bool thisMessageKeepAlive = fMessage_->PeekRequest ()->GetKeepAliveRequested ();\n if (thisMessageKeepAlive) {\n if (not GetResponse ().IsContentLengthKnown ()) {\n thisMessageKeepAlive = false;\n }\n }\n if (thisMessageKeepAlive) {\n \/\/ if missing, no limits\n if (auto oRemaining = GetRemainingConnectionLimits ()) {\n if (oRemaining->fMessages) {\n if (oRemaining->fMessages == 0) {\n thisMessageKeepAlive = false;\n }\n else {\n oRemaining->fMessages = *oRemaining->fMessages - 1;\n }\n }\n if (oRemaining->fTimeoutAt) {\n if (*oRemaining->fTimeoutAt < Time::GetTickCount ()) {\n thisMessageKeepAlive = false;\n }\n }\n }\n }\n\n if (thisMessageKeepAlive) {\n \/\/ be sure we advance the read pointer over the message body, lest we start reading part of the previous message as the next message\n\n \/\/ @todo must fix this for support of Transfer-Encoding, but from:\n \/\/\n \/*\n * https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec4.html\n * The rules for when a message-body is allowed in a message differ for requests and responses.\n *\n * The presence of a message-body in a request is signaled by the inclusion of a Content-Length \n * or Transfer-Encoding header field in the request's message-headers\/\n *\/\n if (GetRequest ().GetContentLength ()) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Assuring all data read; REQ=%s\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n \/\/ @todo - this can be more efficient in the rare case we ignore the body - but thats rare enough to not matter mcuh\n (void)fMessage_->GetRequestBody ();\n }\n#if 0\n else if (GetRequest ().GetHTTPMethod ().Equals (IO::Network::HTTP::Methods::kGet, Characters::CompareOptions::eCaseInsensitive)) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"This request should be closed but thats much less efficient, and chrome seems todo this - sure???; REQ=%s\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n }\n else {\n thisMessageKeepAlive = false;\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"forced close connection because the request header lacked a Content-Length: REQ=%s\", Characters::ToString (GetRequest ()).c_str ());\n#endif\n }\n#endif\n }\n\n \/\/ From https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec14.html\n \/\/ HTTP\/1.1 applications that do not support persistent connections MUST include the \"close\" connection option in every message.\n GetResponse ().AddHeader (IO::Network::HTTP::HeaderName::kConnection,\n thisMessageKeepAlive ? String_Constant{L\"Keep-Alive\"} : String_Constant{L\"close\"});\n\n GetResponse ().End ();\n return thisMessageKeepAlive;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Kyle on 5\/11\/2016.\n\/\/\n\n#include \"GLWindow.h\"\n\nPeon::GLWindow::GLWindow(const GLVideoMode & videoMode, \n const GLContextSettings & ctxSettings,\n const GLWindowSettings & windowSettings)\n : mIsFullscreen(false),\n mIsVsyncEnabled(false),\n mFullscreenMonitor(nullptr),\n mContext(Shared(new GLContext(videoMode, ctxSettings, windowSettings))) \n{ \n}\n\nPeon::GLWindow::GLWindow(Shared context,\n const GLVideoMode & videoMode,\n const GLWindowSettings & windowSettings)\n : GLWindow(context.get(), videoMode, windowSettings) \n{ }\n\nPeon::GLWindow::GLWindow(const GLContext* const context,\n const GLVideoMode & videoMode,\n const GLWindowSettings & windowSettings) \n : mIsFullscreen(false),\n mIsVsyncEnabled(false),\n mFullscreenMonitor(nullptr),\n mContext(nullptr)\n{\n assert(context != nullptr);\n mContext = Shared(new GLContext(videoMode, context->mSettings, windowSettings, context->mWindow));\n}\n\nPeon::GLWindow::~GLWindow() {\n if (!glfwWindowShouldClose(mContext->mWindow)) {\n glfwSetWindowShouldClose(mContext->mWindow, GL_TRUE);\n }\n}\n\nvoid Peon::GLWindow::CloseWindow() {\n assert(mContext->mWindow);\n glfwSetWindowShouldClose(mContext->mWindow, true);\n}\n\nvoid Peon::GLWindow::SetTitle(const string & title) {\n assert(mContext->mWindow);\n glfwSetWindowTitle(mContext->mWindow, title.c_str());\n}\n\nvoid Peon::GLWindow::SetIcon(unsigned int width, unsigned int height, uint8* pixels) {\n assert(pixels);\n assert(width > 0 && height > 0);\n GLFWimage image;\n image.height = height;\n image.width = width;\n image.pixels = static_cast(pixels);\n glfwSetWindowIcon(mContext->mWindow, 1, &image);\n}\n\nvoid Peon::GLWindow::SetPosition(const ivec2 & position) {\n assert(mContext->mWindow);\n glfwSetWindowPos(mContext->mWindow, position.x, position.y);\n}\n\nvoid Peon::GLWindow::SetVideoMode(const GLVideoMode & videoMode) {\n if (!mIsFullscreen) {\n uvec2 pos = GetPosition();\n glfwSetWindowMonitor(mContext->mWindow, nullptr, pos.x, pos.y, \n videoMode.width, videoMode.height, videoMode.refreshRate);\n } else {\n glfwSetWindowMonitor(mContext->mWindow, mFullscreenMonitor.mMonitor, \n 0, 0, videoMode.width, videoMode.height, videoMode.refreshRate);\n }\n mVideoMode = videoMode;\n}\n\nvoid Peon::GLWindow::SetFullscreen(bool fullscreen, GLMonitor monitor) {\n if (!mIsFullscreen && fullscreen) {\n mWindowedPos = GetPosition();\n mFullscreenMonitor = monitor;\n glfwSetWindowMonitor(mContext->mWindow, monitor.mMonitor, 0, 0,\n mVideoMode.width, mVideoMode.height, mVideoMode.refreshRate);\n } else if (mIsFullscreen && !fullscreen) {\n glfwSetWindowMonitor(mContext->mWindow, nullptr, mWindowedPos.x, mWindowedPos.y, \n mVideoMode.width, mVideoMode.height, mVideoMode.refreshRate);\n }\n mIsFullscreen = fullscreen;\n}\n\nvoid Peon::GLWindow::SetVsync(bool on) {\n glfwSwapInterval(static_cast(on));\n mIsVsyncEnabled = on;\n}\n\nPeon::GLVideoMode Peon::GLWindow::GetVideoMode() const {\n return mVideoMode;\n}\n\nivec2 Peon::GLWindow::GetPosition() const {\n ivec2 position;\n glfwGetWindowPos(mContext->mWindow, &position.x, &position.y);\n return position;\n}\n\nivec2 Peon::GLWindow::GetFramebufferSize() const {\n ivec2 size;\n glfwGetFramebufferSize(mContext->mWindow, &size.x, &size.y);\n return size;\n}\n\nPeon::Shared Peon::GLWindow::GetContext() const {\n assert(mContext.get() != nullptr);\n return mContext;\n}\n\nPeon::GLMonitor Peon::GLWindow::GetCurrentMonitor() const {\n uvec2 thisPos = this->GetPosition();\n vector monitors = GLMonitor::GetMonitors();\n for (GLMonitor & monitor : monitors) {\n const uvec2 & thatPos = monitor.GetPosition();\n const GLVideoMode & thatMode = monitor.GetVideoMode();\n if (thisPos.x >= thatPos.x && thisPos.x < thatPos.x + thatMode.width &&\n thisPos.y >= thatPos.y && thisPos.y < thatPos.y + thatMode.height) {\n return monitor;\n }\n }\n return GLMonitor(nullptr);\n}\n\nvoid Peon::GLWindow::Maximize() {\n assert(mContext->mWindow);\n glfwMaximizeWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Minimize() {\n assert(mContext->mWindow);\n glfwIconifyWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Restore() {\n assert(mContext->mWindow);\n glfwRestoreWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Show() {\n assert(mContext->mWindow);\n glfwShowWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Hide() {\n assert(mContext->mWindow);\n glfwHideWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Focus() {\n assert(mContext->mWindow);\n if (!this->IsMinimized() && this->IsVisible()) {\n glfwFocusWindow(mContext->mWindow);\n }\n}\n\nbool Peon::GLWindow::IsOpen() const {\n return glfwWindowShouldClose(mContext->mWindow) == 0;\n}\n\nbool Peon::GLWindow::IsVisible() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_VISIBLE) != 0;\n}\n\nbool Peon::GLWindow::IsFocused() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_FOCUSED) != 0;\n}\n\nbool Peon::GLWindow::IsMinimized() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_ICONIFIED) != 0;\n}\n\nbool Peon::GLWindow::IsMaximized() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_MAXIMIZED) != 0;\n}\n\n\nbool Peon::GLWindow::IsFullscreen() const {\n return mIsFullscreen;\n}\n\nbool Peon::GLWindow::IsVsyncEnabled() const {\n return mIsVsyncEnabled;\n}\n\nvoid Peon::GLWindow::SwapBuffers() {\n assert(mContext->mWindow);\n glfwSwapBuffers(mContext->mWindow);\n glfwPollEvents();\n}\n\nvoid Peon::GLWindow::MakeContextCurrent() {\n mContext->MakeContextCurrent();\n}\nget current monitor for fullscreen fix\/\/\n\/\/ Created by Kyle on 5\/11\/2016.\n\/\/\n\n#include \"GLWindow.h\"\n\nPeon::GLWindow::GLWindow(const GLVideoMode & videoMode, \n const GLContextSettings & ctxSettings,\n const GLWindowSettings & windowSettings)\n : mIsFullscreen(false),\n mIsVsyncEnabled(false),\n mFullscreenMonitor(nullptr),\n mContext(Shared(new GLContext(videoMode, ctxSettings, windowSettings))) \n{ \n}\n\nPeon::GLWindow::GLWindow(Shared context,\n const GLVideoMode & videoMode,\n const GLWindowSettings & windowSettings)\n : GLWindow(context.get(), videoMode, windowSettings) \n{ }\n\nPeon::GLWindow::GLWindow(const GLContext* const context,\n const GLVideoMode & videoMode,\n const GLWindowSettings & windowSettings) \n : mIsFullscreen(false),\n mIsVsyncEnabled(false),\n mFullscreenMonitor(nullptr),\n mContext(nullptr)\n{\n assert(context != nullptr);\n mContext = Shared(new GLContext(videoMode, context->mSettings, windowSettings, context->mWindow));\n}\n\nPeon::GLWindow::~GLWindow() {\n if (!glfwWindowShouldClose(mContext->mWindow)) {\n glfwSetWindowShouldClose(mContext->mWindow, GL_TRUE);\n }\n}\n\nvoid Peon::GLWindow::CloseWindow() {\n assert(mContext->mWindow);\n glfwSetWindowShouldClose(mContext->mWindow, true);\n}\n\nvoid Peon::GLWindow::SetTitle(const string & title) {\n assert(mContext->mWindow);\n glfwSetWindowTitle(mContext->mWindow, title.c_str());\n}\n\nvoid Peon::GLWindow::SetIcon(unsigned int width, unsigned int height, uint8* pixels) {\n assert(pixels);\n assert(width > 0 && height > 0);\n GLFWimage image;\n image.height = height;\n image.width = width;\n image.pixels = static_cast(pixels);\n glfwSetWindowIcon(mContext->mWindow, 1, &image);\n}\n\nvoid Peon::GLWindow::SetPosition(const ivec2 & position) {\n assert(mContext->mWindow);\n glfwSetWindowPos(mContext->mWindow, position.x, position.y);\n}\n\nvoid Peon::GLWindow::SetVideoMode(const GLVideoMode & videoMode) {\n if (!mIsFullscreen) {\n uvec2 pos = GetPosition();\n glfwSetWindowMonitor(mContext->mWindow, nullptr, pos.x, pos.y, \n videoMode.width, videoMode.height, videoMode.refreshRate);\n } else {\n glfwSetWindowMonitor(mContext->mWindow, mFullscreenMonitor.mMonitor, \n 0, 0, videoMode.width, videoMode.height, videoMode.refreshRate);\n }\n mVideoMode = videoMode;\n}\n\nvoid Peon::GLWindow::SetFullscreen(bool fullscreen, GLMonitor monitor) {\n if (!mIsFullscreen && fullscreen) {\n mWindowedPos = GetPosition();\n mFullscreenMonitor = monitor;\n glfwSetWindowMonitor(mContext->mWindow, monitor.mMonitor, 0, 0,\n mVideoMode.width, mVideoMode.height, mVideoMode.refreshRate);\n } else if (mIsFullscreen && !fullscreen) {\n glfwSetWindowMonitor(mContext->mWindow, nullptr, mWindowedPos.x, mWindowedPos.y, \n mVideoMode.width, mVideoMode.height, mVideoMode.refreshRate);\n }\n mIsFullscreen = fullscreen;\n}\n\nvoid Peon::GLWindow::SetVsync(bool on) {\n glfwSwapInterval(static_cast(on));\n mIsVsyncEnabled = on;\n}\n\nPeon::GLVideoMode Peon::GLWindow::GetVideoMode() const {\n return mVideoMode;\n}\n\nivec2 Peon::GLWindow::GetPosition() const {\n ivec2 position;\n glfwGetWindowPos(mContext->mWindow, &position.x, &position.y);\n return position;\n}\n\nivec2 Peon::GLWindow::GetFramebufferSize() const {\n ivec2 size;\n glfwGetFramebufferSize(mContext->mWindow, &size.x, &size.y);\n return size;\n}\n\nPeon::Shared Peon::GLWindow::GetContext() const {\n assert(mContext.get() != nullptr);\n return mContext;\n}\n\nPeon::GLMonitor Peon::GLWindow::GetCurrentMonitor() const {\n if (mIsFullscreen) {\n return mFullscreenMonitor;\n }\n uvec2 thisPos = this->GetPosition();\n vector monitors = GLMonitor::GetMonitors();\n for (GLMonitor & monitor : monitors) {\n const uvec2 & thatPos = monitor.GetPosition();\n const GLVideoMode & thatMode = monitor.GetVideoMode();\n if (thisPos.x >= thatPos.x && thisPos.x < thatPos.x + thatMode.width &&\n thisPos.y >= thatPos.y && thisPos.y < thatPos.y + thatMode.height) {\n return monitor;\n }\n }\n return GLMonitor(nullptr);\n}\n\nvoid Peon::GLWindow::Maximize() {\n assert(mContext->mWindow);\n glfwMaximizeWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Minimize() {\n assert(mContext->mWindow);\n glfwIconifyWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Restore() {\n assert(mContext->mWindow);\n glfwRestoreWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Show() {\n assert(mContext->mWindow);\n glfwShowWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Hide() {\n assert(mContext->mWindow);\n glfwHideWindow(mContext->mWindow);\n}\n\nvoid Peon::GLWindow::Focus() {\n assert(mContext->mWindow);\n if (!this->IsMinimized() && this->IsVisible()) {\n glfwFocusWindow(mContext->mWindow);\n }\n}\n\nbool Peon::GLWindow::IsOpen() const {\n return glfwWindowShouldClose(mContext->mWindow) == 0;\n}\n\nbool Peon::GLWindow::IsVisible() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_VISIBLE) != 0;\n}\n\nbool Peon::GLWindow::IsFocused() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_FOCUSED) != 0;\n}\n\nbool Peon::GLWindow::IsMinimized() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_ICONIFIED) != 0;\n}\n\nbool Peon::GLWindow::IsMaximized() const {\n assert(mContext->mWindow);\n return glfwGetWindowAttrib(mContext->mWindow, GLFW_MAXIMIZED) != 0;\n}\n\n\nbool Peon::GLWindow::IsFullscreen() const {\n return mIsFullscreen;\n}\n\nbool Peon::GLWindow::IsVsyncEnabled() const {\n return mIsVsyncEnabled;\n}\n\nvoid Peon::GLWindow::SwapBuffers() {\n assert(mContext->mWindow);\n glfwSwapBuffers(mContext->mWindow);\n glfwPollEvents();\n}\n\nvoid Peon::GLWindow::MakeContextCurrent() {\n mContext->MakeContextCurrent();\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"stdafx.h\"\n#include \"TimeoutGuard.h\"\n\nnamespace utility\n{\n\tTimeoutGuard::TimeoutGuard(\n\t\tclock::duration timeout,\n\t\tstd::function alarm,\n\t\tclock::duration naptime\n\t)\n\t\t: timeout( timeout )\n\t\t, alarm( alarm )\n\t\t, naptime( naptime )\n\t{\n\t\tidle.store( true );\n\t\tlive.store( true );\n\n\t\tguard_thread = std::thread( std::bind( &TimeoutGuard::guard, this ) );\n\t}\n\n\tTimeoutGuard::TimeoutGuard(\n\t\tclock::duration timeout,\n\t\tstd::function alarm\n\t)\n\t: TimeoutGuard( timeout, alarm, timeout )\n\t{};\n\n\tTimeoutGuard::~TimeoutGuard()\n\t{\n\t\tlive.store( false );\n\t\twakeup.notify_all();\n\t\tguard_thread.join();\n\t}\n\n\tvoid TimeoutGuard::guard()\n\t{\n\t\twhile ( live.load() )\n\t\t{\n\t\t\tif ( idle.load() )\n\t\t\t{\n\t\t\t\t\/\/ Sleep indefinitely until either told to become active or destruct\n\t\t\t\tstd::unique_lock live_lock( guard_mutex );\n\t\t\t\twakeup.wait( live_lock, [this]() { return ! idle.load() || ! this->live.load(); } );\n\t\t\t};\n\n\t\t\t\/\/ quit the loop if destructing\n\t\t\tif ( ! live.load() ) break;\n\n\t\t\t\/\/ the actual timeout checking\n\t\t\tauto now = clock::now();\n\n\t\t\tif ( ( now - touched.load() ) > timeout )\n\t\t\t{\n\t\t\t\tidle.store( true );\n\t\t\t\talarm();\n\t\t\t}\n\n\t\t\t{\n\t\t\t\t\/\/ sleep until next timeout check or destruction\n\t\t\t\tstd::unique_lock live_lock( guard_mutex );\n\t\t\t\twakeup.wait_for( live_lock, naptime, [this](){ return ! this->live.load(); } );\n\t\t\t}\n\t\t};\n\t}\n\n\tvoid TimeoutGuard::watch()\n\t{\n\t\ttouch();\n\t\tidle.store( false );\n\t\twakeup.notify_all();\n\t}\n\n\tvoid TimeoutGuard::touch()\n\t{\n\t\ttouched.store( clock::now() );\n\t}\n}\nFixed a bug when the guard will not react to watch() immediately#include \"stdafx.h\"\n#include \"TimeoutGuard.h\"\n\nnamespace utility\n{\n\tTimeoutGuard::TimeoutGuard(\n\t\tclock::duration timeout,\n\t\tstd::function alarm,\n\t\tclock::duration naptime\n\t)\n\t\t: timeout( timeout )\n\t\t, alarm( alarm )\n\t\t, naptime( naptime )\n\t{\n\t\tidle.store( true );\n\t\tlive.store( true );\n\n\t\tguard_thread = std::thread( std::bind( &TimeoutGuard::guard, this ) );\n\t}\n\n\tTimeoutGuard::TimeoutGuard(\n\t\tclock::duration timeout,\n\t\tstd::function alarm\n\t)\n\t: TimeoutGuard( timeout, alarm, timeout )\n\t{};\n\n\tTimeoutGuard::~TimeoutGuard()\n\t{\n\t\tlive.store( false );\n\t\twakeup.notify_all();\n\t\tguard_thread.join();\n\t}\n\n\tvoid TimeoutGuard::guard()\n\t{\n\t\twhile ( live.load() )\n\t\t{\n\t\t\tif ( idle.load() )\n\t\t\t{\n\t\t\t\t\/\/ Sleep indefinitely until either told to become active or destruct\n\t\t\t\tstd::unique_lock live_lock( guard_mutex );\n\t\t\t\twakeup.wait( live_lock, [this]() { return ! this->idle.load() || ! this->live.load(); } );\n\t\t\t};\n\n\t\t\t\/\/ quit the loop if destructing\n\t\t\tif ( ! live.load() ) break;\n\n\t\t\t\/\/ the actual timeout checking\n\t\t\tauto now = clock::now();\n\n\t\t\tif ( ( now - touched.load() ) > timeout )\n\t\t\t{\n\t\t\t\tidle.store( true );\n\t\t\t\talarm();\n\t\t\t\tcontinue; \/\/ skip waiting for next timeout\n\t\t\t}\n\n\t\t\t{\n\t\t\t\t\/\/ sleep until next timeout check or destruction\n\t\t\t\tstd::unique_lock live_lock( guard_mutex );\n\t\t\t\twakeup.wait_for( live_lock, naptime, [this](){ return ! this->live.load(); } );\n\t\t\t}\n\t\t};\n\t}\n\n\tvoid TimeoutGuard::watch()\n\t{\n\t\ttouch();\n\t\tidle.store( false );\n\t\twakeup.notify_all();\n\t}\n\n\tvoid TimeoutGuard::touch()\n\t{\n\t\ttouched.store( clock::now() );\n\t}\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2006 by FThauer FHammer *\n * f.thauer@web.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program 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 General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\t#include \n#endif\n\n#include \n\n#include \"session.h\"\n#include \"startwindowimpl.h\"\n#include \"configfile.h\"\n#include \"startsplash.h\"\n#include \"game_defs.h\"\n#include \n#include \n\n#ifdef _MSC_VER\n\t#ifdef _DEBUG\n\t\t#define _CRTDBG_MAP_ALLOC\n\t\t#include \n\n\t\t#define ENABLE_LEAK_CHECK() \\\n\t\t\t{ \\\n\t\t\t\tint tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \\\n\t\t\t\ttmpFlag |= _CRTDBG_LEAK_CHECK_DF; \\\n\t\t\t\t_CrtSetDbgFlag(tmpFlag); \\\n\t\t\t}\n\t#endif\n#endif\n\n#ifndef ENABLE_LEAK_CHECK\n\t#define ENABLE_LEAK_CHECK()\n#endif\n\n\/\/Uncomment this for RELEASE on Linux\/Unix\/BSD (static Qt only)\n\/\/#include \n\/\/Q_IMPORT_PLUGIN(qjpeg)\n\/\/Q_IMPORT_PLUGIN(qgif)\n\n\n#ifdef _WIN32 \/\/ Always use static Qt on Windows.\n#include \nQ_IMPORT_PLUGIN(qjpeg)\nQ_IMPORT_PLUGIN(qgif)\n#endif\n\nusing namespace std;\n\nclass startWindowImpl;\nclass Game;\n\nint main( int argc, char **argv )\n{\n\t\n\t\/\/ENABLE_LEAK_CHECK();\n\n\t\/\/_CrtSetBreakAlloc(49937);\n\tsocket_startup();\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n\n\t\/\/\/\/\/\/\/ can be removed for non-qt-guis \/\/\/\/\/\/\/\/\/\/\/\/\n\tQApplication a( argc, argv );\n\n\t\/*if (a.sendMessage(\"Wake up!\")) {\n\t\treturn 0;\n\t}*\/\n\n#ifdef __APPLE__\n\t\/\/ The following needs to be done directly after the application is created.\n\tQDir dir(QApplication::applicationDirPath());\n\tdir.cdUp();\n\tdir.cd(\"plugins\");\n\tQApplication::setLibraryPaths(QStringList(dir.absolutePath()));\n#endif\n\n\t\/\/create defaultconfig\n\tConfigFile *myConfig = new ConfigFile(argv[0], false);\n\n\t\/\/ set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets\n a.setStyle(new QPlastiqueStyle);\n\n\tQString\tmyAppDataPath = QString::fromUtf8(myConfig->readConfigString(\"AppDataDir\").c_str());\n\t\/\/set QApplication default font\t\n\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/n019003l.pfb\");\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/VeraBd.ttf\");\t\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/c059013l.pfb\");\n\n#ifdef _WIN32\n QString font1String(\"QApplication, QWidget, QDialog { font-size: 12px; }\");\n#else\n #ifdef __APPLE__\n\/\/ QString font1String(\"font-family: \\\"Lucida Grande\\\";\");\n QString font1String(\"QApplication, QWidget, QDialog { font-size: 11px; }\");\n #else\n QString font1String(\"QApplication, QWidget, QDialog { font-family: \\\"Nimbus Sans L\\\"; font-size: 12px; }\");\n #endif\n#endif\n a.setStyleSheet(font1String + \" QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-cancel-icon: url(:\/gfx\/dialog_close.png); dialog-close-icon: url(:\/gfx\/dialog_close.png); dialog-yes-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-no-icon: url(:\/gfx\/dialog_close.png) }\");\n\n\tQPixmap *pixmap = new QPixmap(myAppDataPath + \"gfx\/gui\/misc\/welcomepokerth.png\");\n\tStartSplash splash(*pixmap);\n\tif(!myConfig->readConfigInt(\"DisableSplashScreenOnStartup\")) {\n\t\tsplash.show();\n\t\tsplash.showMessage(QString(\"Version %1\").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0));\n\t}\n\t\n\t\/\/Set translations\n\tQTranslator qtTranslator;\n qtTranslator.load(QString(myAppDataPath +\"translations\/qt_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n a.installTranslator(&qtTranslator);\n\n\tQTranslator translator;\n\ttranslator.load(QString(myAppDataPath +\"translations\/pokerth_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n\ta.installTranslator(&translator);\n\n\tqRegisterMetaType(\"unsigned\");\n\tqRegisterMetaType >(\"boost::shared_ptr\");\n\tqRegisterMetaType(\"ServerStats\");\n qRegisterMetaType(\"DenyGameInvitationReason\");\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\t\n\n startWindowImpl mainWin(myConfig);\n \/\/a.setActivationWindow(&mainWin, true);\n\n\tint retVal = a.exec();\n\t\n\tcurl_global_cleanup();\n\tsocket_cleanup();\n \n \n\treturn retVal;\n\t\n}\nFix qtsingleapplication.\/***************************************************************************\n * Copyright (C) 2006 by FThauer FHammer *\n * f.thauer@web.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program 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 General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\t#include \n#endif\n\n#include \n\n#include \"session.h\"\n#include \"startwindowimpl.h\"\n#include \"configfile.h\"\n#include \"startsplash.h\"\n#include \"game_defs.h\"\n#include \n#include \n\n#ifdef _MSC_VER\n\t#ifdef _DEBUG\n\t\t#define _CRTDBG_MAP_ALLOC\n\t\t#include \n\n\t\t#define ENABLE_LEAK_CHECK() \\\n\t\t\t{ \\\n\t\t\t\tint tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \\\n\t\t\t\ttmpFlag |= _CRTDBG_LEAK_CHECK_DF; \\\n\t\t\t\t_CrtSetDbgFlag(tmpFlag); \\\n\t\t\t}\n\t#endif\n#endif\n\n#ifndef ENABLE_LEAK_CHECK\n\t#define ENABLE_LEAK_CHECK()\n#endif\n\n\/\/Uncomment this for RELEASE on Linux\/Unix\/BSD (static Qt only)\n\/\/#include \n\/\/Q_IMPORT_PLUGIN(qjpeg)\n\/\/Q_IMPORT_PLUGIN(qgif)\n\n\n#ifdef _WIN32 \/\/ Always use static Qt on Windows.\n#include \nQ_IMPORT_PLUGIN(qjpeg)\nQ_IMPORT_PLUGIN(qgif)\n#endif\n\nusing namespace std;\n\nclass startWindowImpl;\nclass Game;\n\nint main( int argc, char **argv )\n{\n\t\n\t\/\/ENABLE_LEAK_CHECK();\n\n\t\/\/_CrtSetBreakAlloc(49937);\n\tsocket_startup();\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n\n\t\/\/\/\/\/\/\/ can be removed for non-qt-guis \/\/\/\/\/\/\/\/\/\/\/\/\n\tQtSingleApplication a( argc, argv );\n\n\tif (a.sendMessage(\"Wake up!\")) {\n\t\treturn 0;\n\t}\n\n#ifdef __APPLE__\n\t\/\/ The following needs to be done directly after the application is created.\n\tQDir dir(QApplication::applicationDirPath());\n\tdir.cdUp();\n\tdir.cd(\"plugins\");\n\tQApplication::setLibraryPaths(QStringList(dir.absolutePath()));\n#endif\n\n\t\/\/create defaultconfig\n\tConfigFile *myConfig = new ConfigFile(argv[0], false);\n\n\t\/\/ set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets\n a.setStyle(new QPlastiqueStyle);\n\n\tQString\tmyAppDataPath = QString::fromUtf8(myConfig->readConfigString(\"AppDataDir\").c_str());\n\t\/\/set QApplication default font\t\n\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/n019003l.pfb\");\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/VeraBd.ttf\");\t\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/c059013l.pfb\");\n\n#ifdef _WIN32\n QString font1String(\"QApplication, QWidget, QDialog { font-size: 12px; }\");\n#else\n #ifdef __APPLE__\n\/\/ QString font1String(\"font-family: \\\"Lucida Grande\\\";\");\n QString font1String(\"QApplication, QWidget, QDialog { font-size: 11px; }\");\n #else\n QString font1String(\"QApplication, QWidget, QDialog { font-family: \\\"Nimbus Sans L\\\"; font-size: 12px; }\");\n #endif\n#endif\n a.setStyleSheet(font1String + \" QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-cancel-icon: url(:\/gfx\/dialog_close.png); dialog-close-icon: url(:\/gfx\/dialog_close.png); dialog-yes-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-no-icon: url(:\/gfx\/dialog_close.png) }\");\n\n\tQPixmap *pixmap = new QPixmap(myAppDataPath + \"gfx\/gui\/misc\/welcomepokerth.png\");\n\tStartSplash splash(*pixmap);\n\tif(!myConfig->readConfigInt(\"DisableSplashScreenOnStartup\")) {\n\t\tsplash.show();\n\t\tsplash.showMessage(QString(\"Version %1\").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0));\n\t}\n\t\n\t\/\/Set translations\n\tQTranslator qtTranslator;\n qtTranslator.load(QString(myAppDataPath +\"translations\/qt_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n a.installTranslator(&qtTranslator);\n\n\tQTranslator translator;\n\ttranslator.load(QString(myAppDataPath +\"translations\/pokerth_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n\ta.installTranslator(&translator);\n\n\tqRegisterMetaType(\"unsigned\");\n\tqRegisterMetaType >(\"boost::shared_ptr\");\n\tqRegisterMetaType(\"ServerStats\");\n qRegisterMetaType(\"DenyGameInvitationReason\");\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\t\n\n startWindowImpl mainWin(myConfig);\n\t\ta.setActivationWindow(&mainWin, true);\n\n\tint retVal = a.exec();\n\t\n\tcurl_global_cleanup();\n\tsocket_cleanup();\n \n \n\treturn retVal;\n\t\n}\n<|endoftext|>"} {"text":"#include \"musicnetworktestwidget.h\"\n#include \"ui_musicnetworktestwidget.h\"\n#include \"musicbgthememanager.h\"\n#include \"musicuiobject.h\"\n#include \"musicnetworktestthread.h\"\n#include \"musicutils.h\"\n#include \"musicdatadownloadthread.h\"\n#include \"musicmessagebox.h\"\n\nMusicNetworkTestWidget::MusicNetworkTestWidget(QWidget *parent)\n : MusicAbstractMoveDialog(parent),\n ui(new Ui::MusicNetworkTestWidget), m_thead(nullptr), m_testDownload(nullptr)\n{\n ui->setupUi(this);\n\n ui->topTitleCloseButton->setIcon(QIcon(\":\/share\/searchclosed\"));\n ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle03);\n ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor));\n ui->topTitleCloseButton->setToolTip(tr(\"Close\"));\n connect(ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close()));\n\n m_totalUp = 0;\n m_totalDown = 0;\n m_testAverage = 0;\n ui->speedWidget->setAnimating(false);\n ui->speedWidget->setRatio(50);\n\n ui->suspensionButton->setStyleSheet(MusicUIObject::MPushButtonStyle06);\n ui->suspensionButton->setCursor(QCursor((Qt::PointingHandCursor)));\n ui->testButton->setStyleSheet(MusicUIObject::MPushButtonStyle06);\n ui->testButton->setCursor(QCursor((Qt::PointingHandCursor)));\n connect(ui->suspensionButton, SIGNAL(clicked()), SLOT(suspensionOpen()));\n connect(ui->testButton, SIGNAL(clicked()), SLOT(networkTestStart()));\n\n m_thead = new MusicNetworkTestThread(this);\n connect(m_thead, SIGNAL(networkData(ulong,ulong)), SLOT(networkData(ulong,ulong)));\n m_thead->start();\n\n m_testTimer.setInterval(5*1000);\n connect(&m_testTimer, SIGNAL(timeout()), SLOT(networkTestStop()));\n}\n\nMusicNetworkTestWidget::~MusicNetworkTestWidget()\n{\n m_testTimer.stop();\n m_thead->stopAndQuitThread();\n delete m_thead;\n delete m_testDownload;\n delete ui;\n}\n\nvoid MusicNetworkTestWidget::networkData(ulong upload, ulong download)\n{\n m_totalUp += upload\/5;\n m_totalDown += download\/5;\n\n ui->uploadSpeedValue->setText(MusicUtils::speed2Label(upload));\n ui->downloadSpeedValue->setText(MusicUtils::speed2Label(download));\n ui->uploadAllSpeedValue->setText(MusicUtils::speed2Label(m_totalUp));\n ui->downloadAllSpeedValue->setText(MusicUtils::speed2Label(m_totalDown));\n\n if(m_testTimer.isActive())\n {\n int value = MusicUtils::sizeByte2KByte(download\/5);\n if(value > 100*ui->speedWidget->ratio())\n {\n value = 100*ui->speedWidget->ratio();\n }\n m_testAverage += value;\n ui->speedWidget->setValue(value);\n }\n}\n\nvoid MusicNetworkTestWidget::suspensionOpen()\n{\n\n}\n\nvoid MusicNetworkTestWidget::networkTestStart()\n{\n ui->testButton->setEnabled(false);\n m_testTimer.stop();\n delete m_testDownload;\n m_testDownload = new MusicDataDownloadThread(testUrl, testName,\n MusicDownLoadThreadAbstract::Download_BigBG, this);\n m_testDownload->startToDownload();\n m_testTimer.start();\n}\n\nvoid MusicNetworkTestWidget::networkTestStop()\n{\n delete m_testDownload;\n m_testDownload = NULL;\n m_testTimer.stop();\n \/\/\/remove temp file\n QFile::remove(testName);\n ui->testButton->setEnabled(true);\n\n MusicMessageBox message(this);\n message.setText(tr(\"Average is %1 kb\/s\").arg(m_testAverage\/5));\n message.exec();\n}\n\nint MusicNetworkTestWidget::exec()\n{\n QPixmap pix(M_BG_MANAGER->getMBackground());\n ui->background->setPixmap(pix.scaled( size() ));\n return MusicAbstractMoveDialog::exec();\n}\nreset average flag to zero[564982]#include \"musicnetworktestwidget.h\"\n#include \"ui_musicnetworktestwidget.h\"\n#include \"musicbgthememanager.h\"\n#include \"musicuiobject.h\"\n#include \"musicnetworktestthread.h\"\n#include \"musicutils.h\"\n#include \"musicdatadownloadthread.h\"\n#include \"musicmessagebox.h\"\n\nMusicNetworkTestWidget::MusicNetworkTestWidget(QWidget *parent)\n : MusicAbstractMoveDialog(parent),\n ui(new Ui::MusicNetworkTestWidget), m_thead(nullptr), m_testDownload(nullptr)\n{\n ui->setupUi(this);\n\n ui->topTitleCloseButton->setIcon(QIcon(\":\/share\/searchclosed\"));\n ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle03);\n ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor));\n ui->topTitleCloseButton->setToolTip(tr(\"Close\"));\n connect(ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close()));\n\n m_totalUp = 0;\n m_totalDown = 0;\n m_testAverage = 0;\n ui->speedWidget->setAnimating(false);\n ui->speedWidget->setRatio(50);\n\n ui->suspensionButton->setStyleSheet(MusicUIObject::MPushButtonStyle06);\n ui->suspensionButton->setCursor(QCursor((Qt::PointingHandCursor)));\n ui->testButton->setStyleSheet(MusicUIObject::MPushButtonStyle06);\n ui->testButton->setCursor(QCursor((Qt::PointingHandCursor)));\n connect(ui->suspensionButton, SIGNAL(clicked()), SLOT(suspensionOpen()));\n connect(ui->testButton, SIGNAL(clicked()), SLOT(networkTestStart()));\n\n m_thead = new MusicNetworkTestThread(this);\n connect(m_thead, SIGNAL(networkData(ulong,ulong)), SLOT(networkData(ulong,ulong)));\n m_thead->start();\n\n m_testTimer.setInterval(5*1000);\n connect(&m_testTimer, SIGNAL(timeout()), SLOT(networkTestStop()));\n}\n\nMusicNetworkTestWidget::~MusicNetworkTestWidget()\n{\n m_testTimer.stop();\n m_thead->stopAndQuitThread();\n delete m_thead;\n delete m_testDownload;\n delete ui;\n}\n\nvoid MusicNetworkTestWidget::networkData(ulong upload, ulong download)\n{\n m_totalUp += upload\/5;\n m_totalDown += download\/5;\n\n ui->uploadSpeedValue->setText(MusicUtils::speed2Label(upload));\n ui->downloadSpeedValue->setText(MusicUtils::speed2Label(download));\n ui->uploadAllSpeedValue->setText(MusicUtils::speed2Label(m_totalUp));\n ui->downloadAllSpeedValue->setText(MusicUtils::speed2Label(m_totalDown));\n\n if(m_testTimer.isActive())\n {\n int value = MusicUtils::sizeByte2KByte(download\/5);\n if(value > 100*ui->speedWidget->ratio())\n {\n value = 100*ui->speedWidget->ratio();\n }\n m_testAverage += value;\n ui->speedWidget->setValue(value);\n }\n}\n\nvoid MusicNetworkTestWidget::suspensionOpen()\n{\n\n}\n\nvoid MusicNetworkTestWidget::networkTestStart()\n{\n ui->testButton->setEnabled(false);\n m_testTimer.stop();\n delete m_testDownload;\n m_testDownload = new MusicDataDownloadThread(testUrl, testName,\n MusicDownLoadThreadAbstract::Download_BigBG, this);\n m_testDownload->startToDownload();\n m_testTimer.start();\n}\n\nvoid MusicNetworkTestWidget::networkTestStop()\n{\n m_testAverage = 0;\n delete m_testDownload;\n m_testDownload = NULL;\n m_testTimer.stop();\n \/\/\/remove temp file\n QFile::remove(testName);\n ui->testButton->setEnabled(true);\n\n MusicMessageBox message(this);\n message.setText(tr(\"Average is %1 kb\/s\").arg(m_testAverage\/5));\n message.exec();\n}\n\nint MusicNetworkTestWidget::exec()\n{\n QPixmap pix(M_BG_MANAGER->getMBackground());\n ui->background->setPixmap(pix.scaled( size() ));\n return MusicAbstractMoveDialog::exec();\n}\n<|endoftext|>"} {"text":"\/* \n* Copyright (C) 2019 German Aerospace Center (DLR\/SC)\n*\n* Created: 2019-05-14 Martin Siggel with Marko Alder \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 \"CCPACSFuselageWallSegment.h\"\n#include \"generated\/CPACSWallSegments.h\"\n#include \"generated\/CPACSWalls.h\"\n#include \"CCPACSFuselageStructure.h\"\n#include \"CCPACSFuselage.h\"\n#include \"CCPACSFuselageSegment.h\"\n#include \"CNamedShape.h\"\n#include \"CCPACSWallPosition.h\"\n#include \"CTiglUIDManager.h\"\n#include \"tiglcommonfunctions.h\"\n#include \"to_string.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace {\n\n\/\/ create a face out of four points\nTopoDS_Face MakeFace(gp_Pnt const& p1, gp_Pnt const& p2, gp_Pnt const& p3, gp_Pnt const& p4) {\n TopoDS_Edge e1 = BRepBuilderAPI_MakeEdge(p1, p2).Edge();\n TopoDS_Edge e2 = BRepBuilderAPI_MakeEdge(p2, p3).Edge();\n TopoDS_Edge e3 = BRepBuilderAPI_MakeEdge(p3, p4).Edge();\n TopoDS_Edge e4 = BRepBuilderAPI_MakeEdge(p4, p1).Edge();\n TopoDS_Wire w = BRepBuilderAPI_MakeWire(e1, e2, e3, e4).Wire();\n return BRepBuilderAPI_MakeFace(w, false).Face();\n}\n\n\/\/ Given a CCPACSWallposition with a defined shape, project the point pnt along the direction dir onto the\n\/\/ plane, in which the shape lies. The shape must be convertable to a planar TopoDS_Face.\nvoid FlushPointAlongVec(tigl::CCPACSWallPosition const& p, gp_Vec const dir, double extents, gp_Pnt& pnt)\n{\n if (!p.GetShape()) {\n throw tigl::CTiglError(\"Cannot flush point for wall position without shape definition.\");\n }\n gp_Pln pln;\n TopoDS_Shape shape = *p.GetShape();\n Handle(Geom_Surface) surf = BRep_Tool::Surface(TopoDS::Face(*p.GetShape()));\n GeomLib_IsPlanarSurface surf_check(surf);\n if (surf_check.IsPlanar()) {\n pln = surf_check.Plan();\n }\n else {\n throw tigl::CTiglError(\"Cannot flush point at non-planar surface\");\n }\n\n pln.SetLocation(p.GetBasePoint());\n TopoDS_Face face = BRepBuilderAPI_MakeFace(pln);\n TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(pnt.Translated( dir*extents),\n pnt.Translated(-dir*extents)).Edge();\n GetIntersectionPoint(face, edge, pnt);\n}\n\n}\n\nnamespace tigl\n{\n\nCCPACSFuselageWallSegment::CCPACSFuselageWallSegment(CCPACSWallSegments* parent, tigl::CTiglUIDManager *uidMgr)\n : generated::CPACSWallSegment(parent, uidMgr)\n{\n}\n\nTopoDS_Compound CCPACSFuselageWallSegment::GetCutPlanes() const\n{\n \/\/ Makes sure, that the cut planes are already computed\n if (m_cutPlanes.IsNull()) {\n BuildLoft();\n }\n return m_cutPlanes;\n}\n\nconst CCPACSWalls& CCPACSFuselageWallSegment::GetWalls() const\n{\n const CCPACSWallSegments* wallSegments = GetParent();\n if (!wallSegments) {\n throw CTiglError(\"Error in CCPACSFuselageWallSegment::GetWalls. Null pointer returned.\", TIGL_NULL_POINTER);\n }\n \n const CCPACSWalls* walls = wallSegments->GetParent();\n if (!walls) {\n throw CTiglError(\"Error in CCPACSFuselageWallSegment::GetWalls. Null pointer returned.\", TIGL_NULL_POINTER);\n }\n \n return *walls;\n}\n\nconst CCPACSFuselage &CCPACSFuselageWallSegment::GetFuselage() const\n{\n const CCPACSWalls& walls = GetWalls();\n \n const CCPACSFuselageStructure* fuselageStructure = walls.GetParent();\n if (!fuselageStructure) {\n throw CTiglError(\"Cannot get fuselage in CCPACSFuselageWallSegment::GetFuselage. Null pointer parent.\", TIGL_NULL_POINTER);\n }\n\n const CCPACSFuselage* fuselage = fuselageStructure->GetParent();\n if (!fuselageStructure) {\n throw CTiglError(\"Cannot get fuselage in CCPACSFuselageWallSegment::GetFuselage. Null pointer parent.\", TIGL_NULL_POINTER);\n }\n\n return *fuselage;\n}\n\nPNamedShape CCPACSFuselageWallSegment::BuildLoft() const\n{ \n \/\/ A bounding box is created to use its diagonal as reference for the\n \/\/ extrusion length (edge length). This ensures that these always go\n \/\/ beyond the model, but do not reach into infinity.\n Bnd_Box boundingBox;\n const CCPACSFuselage& fuselage = GetFuselage();\n TopoDS_Shape fuselageShape = fuselage.GetLoft()->Shape();\n BRepBndLib::Add(fuselageShape, boundingBox);\n double bboxSize = sqrt(boundingBox.SquareExtent());\n \n size_t nWallPositions = GetWallPositionUIDs().GetWallPositionUIDs().size();\n\n \/\/ list with base points:\n std::vector base_pnts;\n base_pnts.reserve(nWallPositions);\n\n \/\/ extrusion in negative direction is realized by setting u_neg to\n \/\/ -bboxSize:\n bool negativeExtrusion = GetNegativeExtrusion().value_or(false);\n double u_pos = bboxSize;\n double u_neg = 0.;\n if (negativeExtrusion) {\n u_neg = -bboxSize;\n }\n\n gp_Pnt upper, lower; \/\/ upper and lower extrusion points for each base point\n gp_Vec x_vec; \/\/ vector from one base point to the next\n\n \/\/ build for untrimmed wall\n TopoDS_Builder builder_wall, builder_cutter;\n TopoDS_Compound wall;\n builder_wall.MakeCompound(wall);\n builder_cutter.MakeCompound(m_cutPlanes);\n\n size_t count = 0;\n const auto& walls = GetWalls();\n for (auto wallPositionUID : GetWallPositionUIDs().GetWallPositionUIDs()) {\n const CCPACSWallPosition& p = walls.GetWallPosition(wallPositionUID);\n\n \/\/ get current base point and x_vec pointing from previous base point to current\n gp_Pnt base_point = p.GetBasePoint();\n if ( count > 0 ) {\n x_vec = gp_Vec(base_pnts.back(), base_point);\n }\n\n \/\/ extrusion vector\n double phiRad = Radians(GetPhi());\n gp_Vec ext_vec(0., -sin(phiRad), cos(phiRad));\n\n if (count==1) {\n \/\/ flush first position to shape\n if( p.GetShape() && GetFlushConnectionStart().value_or(false) ) {\n std::string uid_prev = GetWallPositionUIDs().GetWallPositionUIDs().front();\n const CCPACSWallPosition& p_prev = walls.GetWallPosition(uid_prev);\n FlushPointAlongVec(p_prev, x_vec, bboxSize, upper);\n FlushPointAlongVec(p_prev, x_vec, bboxSize, lower);\n }\n }\n\n gp_Pnt upper_new = base_point.Translated(u_pos*ext_vec);\n gp_Pnt lower_new = base_point.Translated(u_neg*ext_vec);\n\n if (count==nWallPositions-1) {\n \/\/ flush last position to shape\n if( p.GetShape() && GetFlushConnectionEnd().value_or(false) ) {\n FlushPointAlongVec(p, x_vec, bboxSize, upper_new);\n FlushPointAlongVec(p, x_vec, bboxSize, lower_new);\n }\n }\n\n \/\/ create the wall segment from the four corner points lower, upper, lower_new, upper_new\n if (count > 0 ) {\n TopoDS_Face face = MakeFace(lower, lower_new, upper_new, upper);\n builder_wall.Add(wall, face);\n\n \/\/first and last face are enlarged for the cutting tool\n gp_Pnt lower_cut = lower;\n gp_Pnt upper_cut = upper;\n gp_Pnt lower_new_cut = lower_new;\n gp_Pnt upper_new_cut = upper_new;\n if (count==1) {\n lower_cut = lower.Translated(-bboxSize*x_vec);\n upper_cut = upper.Translated(-bboxSize*x_vec);\n }\n if (count==nWallPositions-1) {\n lower_new_cut = lower_new.Translated(bboxSize*x_vec);\n upper_new_cut = upper_new.Translated(bboxSize*x_vec);\n }\n face = MakeFace(lower_cut, lower_new_cut, upper_new_cut, upper_cut);\n builder_cutter.Add(m_cutPlanes, face);\n }\n\n \/\/ store base_pnts and remember current lower and upper point for next position\n base_pnts.push_back(base_point);\n upper = upper_new;\n lower = lower_new;\n ++count;\n }\n\n \/\/ trim the wall\n \/\/ Step 1\/2: Trim the wall by the fuselage\n {\n TopoDS_Compound cut_wall;\n builder_wall.MakeCompound(cut_wall);\n\n TopoDS_Shape result = SplitShape(wall, fuselageShape);\n TopTools_IndexedMapOfShape faceMap;\n TopExp::MapShapes(result, TopAbs_FACE, faceMap);\n for (int i = 0; i < faceMap.Extent(); ++i) {\n TopoDS_Face face = TopoDS::Face(faceMap(i+1));\n gp_Pnt faceCenter = GetCentralFacePoint(face);\n \/\/ TODO: This is fast but could be potentially dangerous.\n \/\/ Maybe we should check if the point is outside the fuselage\n \/\/ shape rather than the bounding box.\n if (!boundingBox.IsOut(faceCenter)) {\n builder_wall.Add(cut_wall, face);\n }\n }\n wall = cut_wall;\n }\n\n \/\/ Step 2\/2: Cut the wall with bounding elements:\n if (GetBoundingElementUIDs()) {\n for (std::string bounding_element_uid : GetBoundingElementUIDs()->GetBoundingElementUIDs()) {\n const CCPACSFuselageWallSegment& bounding_element = GetWalls().GetWallSegment(bounding_element_uid);\n \/\/ TODO: Check: The order of whoch the walls are evaulated seem to matter here!\n TopoDS_Compound bounding_cutPlane = bounding_element.GetCutPlanes();\n TopoDS_Shape result = SplitShape(wall, bounding_cutPlane);\n \n TopoDS_Compound cut_wall;\n builder_wall.MakeCompound(cut_wall);\n TopTools_IndexedMapOfShape faceMap;\n TopExp::MapShapes(result, TopAbs_FACE, faceMap);\n\n \/\/ Loop over the split faces and check weather one of the\n \/\/ base points belongs to the face.\n for (int i = 0; i classify point using fuselage shape not bounding box\/* \n* Copyright (C) 2019 German Aerospace Center (DLR\/SC)\n*\n* Created: 2019-05-14 Martin Siggel with Marko Alder \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 \"CCPACSFuselageWallSegment.h\"\n#include \"generated\/CPACSWallSegments.h\"\n#include \"generated\/CPACSWalls.h\"\n#include \"CCPACSFuselageStructure.h\"\n#include \"CCPACSFuselage.h\"\n#include \"CCPACSFuselageSegment.h\"\n#include \"CNamedShape.h\"\n#include \"CCPACSWallPosition.h\"\n#include \"CTiglUIDManager.h\"\n#include \"tiglcommonfunctions.h\"\n#include \"to_string.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace {\n\n\/\/ create a face out of four points\nTopoDS_Face MakeFace(gp_Pnt const& p1, gp_Pnt const& p2, gp_Pnt const& p3, gp_Pnt const& p4) {\n TopoDS_Edge e1 = BRepBuilderAPI_MakeEdge(p1, p2).Edge();\n TopoDS_Edge e2 = BRepBuilderAPI_MakeEdge(p2, p3).Edge();\n TopoDS_Edge e3 = BRepBuilderAPI_MakeEdge(p3, p4).Edge();\n TopoDS_Edge e4 = BRepBuilderAPI_MakeEdge(p4, p1).Edge();\n TopoDS_Wire w = BRepBuilderAPI_MakeWire(e1, e2, e3, e4).Wire();\n return BRepBuilderAPI_MakeFace(w, false).Face();\n}\n\n\/\/ Given a CCPACSWallposition with a defined shape, project the point pnt along the direction dir onto the\n\/\/ plane, in which the shape lies. The shape must be convertable to a planar TopoDS_Face.\nvoid FlushPointAlongVec(tigl::CCPACSWallPosition const& p, gp_Vec const dir, double extents, gp_Pnt& pnt)\n{\n if (!p.GetShape()) {\n throw tigl::CTiglError(\"Cannot flush point for wall position without shape definition.\");\n }\n gp_Pln pln;\n TopoDS_Shape shape = *p.GetShape();\n Handle(Geom_Surface) surf = BRep_Tool::Surface(TopoDS::Face(*p.GetShape()));\n GeomLib_IsPlanarSurface surf_check(surf);\n if (surf_check.IsPlanar()) {\n pln = surf_check.Plan();\n }\n else {\n throw tigl::CTiglError(\"Cannot flush point at non-planar surface\");\n }\n\n pln.SetLocation(p.GetBasePoint());\n TopoDS_Face face = BRepBuilderAPI_MakeFace(pln);\n TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(pnt.Translated( dir*extents),\n pnt.Translated(-dir*extents)).Edge();\n GetIntersectionPoint(face, edge, pnt);\n}\n\n}\n\nnamespace tigl\n{\n\nCCPACSFuselageWallSegment::CCPACSFuselageWallSegment(CCPACSWallSegments* parent, tigl::CTiglUIDManager *uidMgr)\n : generated::CPACSWallSegment(parent, uidMgr)\n{\n}\n\nTopoDS_Compound CCPACSFuselageWallSegment::GetCutPlanes() const\n{\n \/\/ Makes sure, that the cut planes are already computed\n if (m_cutPlanes.IsNull()) {\n BuildLoft();\n }\n return m_cutPlanes;\n}\n\nconst CCPACSWalls& CCPACSFuselageWallSegment::GetWalls() const\n{\n const CCPACSWallSegments* wallSegments = GetParent();\n if (!wallSegments) {\n throw CTiglError(\"Error in CCPACSFuselageWallSegment::GetWalls. Null pointer returned.\", TIGL_NULL_POINTER);\n }\n \n const CCPACSWalls* walls = wallSegments->GetParent();\n if (!walls) {\n throw CTiglError(\"Error in CCPACSFuselageWallSegment::GetWalls. Null pointer returned.\", TIGL_NULL_POINTER);\n }\n \n return *walls;\n}\n\nconst CCPACSFuselage &CCPACSFuselageWallSegment::GetFuselage() const\n{\n const CCPACSWalls& walls = GetWalls();\n \n const CCPACSFuselageStructure* fuselageStructure = walls.GetParent();\n if (!fuselageStructure) {\n throw CTiglError(\"Cannot get fuselage in CCPACSFuselageWallSegment::GetFuselage. Null pointer parent.\", TIGL_NULL_POINTER);\n }\n\n const CCPACSFuselage* fuselage = fuselageStructure->GetParent();\n if (!fuselageStructure) {\n throw CTiglError(\"Cannot get fuselage in CCPACSFuselageWallSegment::GetFuselage. Null pointer parent.\", TIGL_NULL_POINTER);\n }\n\n return *fuselage;\n}\n\nPNamedShape CCPACSFuselageWallSegment::BuildLoft() const\n{ \n \/\/ A bounding box is created to use its diagonal as reference for the\n \/\/ extrusion length (edge length). This ensures that these always go\n \/\/ beyond the model, but do not reach into infinity.\n Bnd_Box boundingBox;\n const CCPACSFuselage& fuselage = GetFuselage();\n TopoDS_Shape fuselageShape = fuselage.GetLoft()->Shape();\n BRepBndLib::Add(fuselageShape, boundingBox);\n double bboxSize = sqrt(boundingBox.SquareExtent());\n \n size_t nWallPositions = GetWallPositionUIDs().GetWallPositionUIDs().size();\n\n \/\/ list with base points:\n std::vector base_pnts;\n base_pnts.reserve(nWallPositions);\n\n \/\/ extrusion in negative direction is realized by setting u_neg to\n \/\/ -bboxSize:\n bool negativeExtrusion = GetNegativeExtrusion().value_or(false);\n double u_pos = bboxSize;\n double u_neg = 0.;\n if (negativeExtrusion) {\n u_neg = -bboxSize;\n }\n\n gp_Pnt upper, lower; \/\/ upper and lower extrusion points for each base point\n gp_Vec x_vec; \/\/ vector from one base point to the next\n\n \/\/ build for untrimmed wall\n TopoDS_Builder builder_wall, builder_cutter;\n TopoDS_Compound wall;\n builder_wall.MakeCompound(wall);\n builder_cutter.MakeCompound(m_cutPlanes);\n\n size_t count = 0;\n const auto& walls = GetWalls();\n for (auto wallPositionUID : GetWallPositionUIDs().GetWallPositionUIDs()) {\n const CCPACSWallPosition& p = walls.GetWallPosition(wallPositionUID);\n\n \/\/ get current base point and x_vec pointing from previous base point to current\n gp_Pnt base_point = p.GetBasePoint();\n if ( count > 0 ) {\n x_vec = gp_Vec(base_pnts.back(), base_point);\n }\n\n \/\/ extrusion vector\n double phiRad = Radians(GetPhi());\n gp_Vec ext_vec(0., -sin(phiRad), cos(phiRad));\n\n if (count==1) {\n \/\/ flush first position to shape\n if( p.GetShape() && GetFlushConnectionStart().value_or(false) ) {\n std::string uid_prev = GetWallPositionUIDs().GetWallPositionUIDs().front();\n const CCPACSWallPosition& p_prev = walls.GetWallPosition(uid_prev);\n FlushPointAlongVec(p_prev, x_vec, bboxSize, upper);\n FlushPointAlongVec(p_prev, x_vec, bboxSize, lower);\n }\n }\n\n gp_Pnt upper_new = base_point.Translated(u_pos*ext_vec);\n gp_Pnt lower_new = base_point.Translated(u_neg*ext_vec);\n\n if (count==nWallPositions-1) {\n \/\/ flush last position to shape\n if( p.GetShape() && GetFlushConnectionEnd().value_or(false) ) {\n FlushPointAlongVec(p, x_vec, bboxSize, upper_new);\n FlushPointAlongVec(p, x_vec, bboxSize, lower_new);\n }\n }\n\n \/\/ create the wall segment from the four corner points lower, upper, lower_new, upper_new\n if (count > 0 ) {\n TopoDS_Face face = MakeFace(lower, lower_new, upper_new, upper);\n builder_wall.Add(wall, face);\n\n \/\/first and last face are enlarged for the cutting tool\n gp_Pnt lower_cut = lower;\n gp_Pnt upper_cut = upper;\n gp_Pnt lower_new_cut = lower_new;\n gp_Pnt upper_new_cut = upper_new;\n if (count==1) {\n lower_cut = lower.Translated(-bboxSize*x_vec);\n upper_cut = upper.Translated(-bboxSize*x_vec);\n }\n if (count==nWallPositions-1) {\n lower_new_cut = lower_new.Translated(bboxSize*x_vec);\n upper_new_cut = upper_new.Translated(bboxSize*x_vec);\n }\n face = MakeFace(lower_cut, lower_new_cut, upper_new_cut, upper_cut);\n builder_cutter.Add(m_cutPlanes, face);\n }\n\n \/\/ store base_pnts and remember current lower and upper point for next position\n base_pnts.push_back(base_point);\n upper = upper_new;\n lower = lower_new;\n ++count;\n }\n\n \/\/ trim the wall\n \/\/ Step 1\/2: Trim the wall by the fuselage\n {\n TopoDS_Compound cut_wall;\n builder_wall.MakeCompound(cut_wall);\n\n TopoDS_Shape result = SplitShape(wall, fuselageShape);\n TopTools_IndexedMapOfShape faceMap;\n TopExp::MapShapes(result, TopAbs_FACE, faceMap);\n for (int i = 0; i < faceMap.Extent(); ++i) {\n \/\/ check if face center is on the interior of the fuselage\n TopoDS_Face face = TopoDS::Face(faceMap(i+1));\n gp_Pnt faceCenter = GetCentralFacePoint(face);\n\n BRepClass3d_SolidClassifier clas3d(fuselageShape);\n clas3d.Perform(faceCenter, Precision::Confusion());\n\n if (clas3d.State() == TopAbs_IN) {\n builder_wall.Add(cut_wall, face);\n }\n }\n wall = cut_wall;\n }\n\n \/\/ Step 2\/2: Cut the wall with bounding elements:\n if (GetBoundingElementUIDs()) {\n for (std::string bounding_element_uid : GetBoundingElementUIDs()->GetBoundingElementUIDs()) {\n const CCPACSFuselageWallSegment& bounding_element = GetWalls().GetWallSegment(bounding_element_uid);\n \/\/ TODO: Check: The order of whoch the walls are evaulated seem to matter here!\n TopoDS_Compound bounding_cutPlane = bounding_element.GetCutPlanes();\n TopoDS_Shape result = SplitShape(wall, bounding_cutPlane);\n \n TopoDS_Compound cut_wall;\n builder_wall.MakeCompound(cut_wall);\n TopTools_IndexedMapOfShape faceMap;\n TopExp::MapShapes(result, TopAbs_FACE, faceMap);\n\n \/\/ Loop over the split faces and check weather one of the\n \/\/ base points belongs to the face.\n for (int i = 0; i "} {"text":"#include \"Tutorial4ActorModule.h\"\n#include \"NFComm\/NFCore\/NFTimer.h\"\n#include \n\nbool HelloWorld4ActorModule::Init()\n{\n \/\/ʼ\n std::cout << \"Hello, world4, Init ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n return true;\n}\n\nint HelloWorld4ActorModule::OnASyncEvent(const NFIDENTID& self, const int event, std::string& arg)\n{\n \/\/¼ص\n std::cout << \"Begin OnEvent EventID: \" << event << \" self: \" << self.nData64 << \" argList: \" << arg << \" ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\targ += \" event test ok\";\n\n return 0;\n}\n\nint HelloWorld4ActorModule::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)\n{\n\t\/\/¼ص\n\tstd::cout << \"End OnEvent EventID: \" << event << \" self: \" << self.nData64 << \" argList: \" << arg << \" ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\treturn 0;\n}\n\nbool HelloWorld4ActorModule::AfterInit()\n{\n\n \/\/ʼ\n std::cout << \"Hello, world4, AfterInit, ThreadID: \" << GetCurrentThreadId() << std::endl;\n\n m_pKernelModule = dynamic_cast(pPluginManager->FindModule(\"NFCKernelModule\"));\n m_pEventProcessModule = dynamic_cast(pPluginManager->FindModule(\"NFCEventProcessModule\"));\n m_pElementInfoModule = dynamic_cast(pPluginManager->FindModule(\"NFCElementInfoModule\"));\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ͬ\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tm_pEventProcessModule->AddAsyncEventCallBack(NFIDENTID(), 2222, this, &HelloWorld4ActorModule::OnASyncEvent, &HelloWorld4ActorModule::OnSyncEvent);\n\n\tfor (int i = 0; i < 20; ++i)\n\t{\n\t\tm_pEventProcessModule->DoEvent(NFIDENTID(), 2222, NFCDataList() << boost::lexical_cast(i), false);\n\n\t}\n\n\tstd::cout << \"End Test Actor, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n return true;\n}\n\nbool HelloWorld4ActorModule::Execute( const float fLasFrametime, const float fStartedTime )\n{\n \/\/ÿִ֡\n \/\/std::cout << \"Hello, world3, Execute\" << std::endl;\n\n return true;\n}\n\nbool HelloWorld4ActorModule::BeforeShut()\n{\n \/\/ʼ֮ǰ\n std::cout << \"Hello, world4, BeforeShut\" << std::endl;\n\n m_pKernelModule->DestroyAll();\n\n return true;\n}\n\nbool HelloWorld4ActorModule::Shut()\n{\n \/\/ʼ\n std::cout << \"Hello, world4, Shut\" << std::endl;\n\n return true;\n}\nmodify GetCurrentThreadID() as std::this_thread::get_id()#include \"Tutorial4ActorModule.h\"\n#include \"NFComm\/NFCore\/NFTimer.h\"\n#include \n\nbool HelloWorld4ActorModule::Init()\n{\n \/\/ʼ\n std::cout << \"Hello, world4, Init ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n return true;\n}\n\nint HelloWorld4ActorModule::OnASyncEvent(const NFIDENTID& self, const int event, std::string& arg)\n{\n \/\/¼ص\n std::cout << \"Begin OnEvent EventID: \" << event << \" self: \" << self.nData64 << \" argList: \" << arg << \" ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\targ += \" event test ok\";\n\n return 0;\n}\n\nint HelloWorld4ActorModule::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)\n{\n\t\/\/¼ص\n\tstd::cout << \"End OnEvent EventID: \" << event << \" self: \" << self.nData64 << \" argList: \" << arg << \" ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\treturn 0;\n}\n\nbool HelloWorld4ActorModule::AfterInit()\n{\n\n \/\/ʼ\n std::cout << \"Hello, world4, AfterInit, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n m_pKernelModule = dynamic_cast(pPluginManager->FindModule(\"NFCKernelModule\"));\n m_pEventProcessModule = dynamic_cast(pPluginManager->FindModule(\"NFCEventProcessModule\"));\n m_pElementInfoModule = dynamic_cast(pPluginManager->FindModule(\"NFCElementInfoModule\"));\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ͬ\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tm_pEventProcessModule->AddAsyncEventCallBack(NFIDENTID(), 2222, this, &HelloWorld4ActorModule::OnASyncEvent, &HelloWorld4ActorModule::OnSyncEvent);\n\n\tfor (int i = 0; i < 20; ++i)\n\t{\n\t\tm_pEventProcessModule->DoEvent(NFIDENTID(), 2222, NFCDataList() << boost::lexical_cast(i), false);\n\n\t}\n\n\tstd::cout << \"End Test Actor, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n return true;\n}\n\nbool HelloWorld4ActorModule::Execute( const float fLasFrametime, const float fStartedTime )\n{\n \/\/ÿִ֡\n \/\/std::cout << \"Hello, world3, Execute\" << std::endl;\n\n return true;\n}\n\nbool HelloWorld4ActorModule::BeforeShut()\n{\n \/\/ʼ֮ǰ\n std::cout << \"Hello, world4, BeforeShut\" << std::endl;\n\n m_pKernelModule->DestroyAll();\n\n return true;\n}\n\nbool HelloWorld4ActorModule::Shut()\n{\n \/\/ʼ\n std::cout << \"Hello, world4, Shut\" << std::endl;\n\n return true;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/reduce_ops\/reduce_min_max_op.h\"\n#include \"paddle\/fluid\/platform\/device\/npu\/npu_op_runner.h\"\n\nnamespace paddle {\nnamespace operators {\n\nusing Tensor = framework::Tensor;\ntemplate \nclass ReduceMaxNPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& ctx) const override {\n auto* x = ctx.Input(\"X\");\n auto* out = ctx.Output(\"Out\");\n auto dims = ctx.Attr>(\"dim\");\n bool keep_dim = ctx.Attr(\"keep_dim\");\n bool reduce_all = ctx.Attr(\"reduce_all\");\n int out_dtype = ctx.Attr(\"out_dtype\");\n\n auto place = ctx.GetPlace();\n\n framework::Tensor cast_out(x->type());\n cast_out.Resize(out->dims());\n cast_out.mutable_data(place);\n\n auto cast_out_dtype = framework::TransToProtoVarType(x->dtype());\n if (out_dtype != -1) {\n cast_out_dtype = static_cast(out_dtype);\n }\n\n if (framework::TransToProtoVarType(x->dtype()) != cast_out_dtype) {\n if (cast_out_dtype == framework::proto::VarType::FP32) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::FP16) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::INT16) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::INT32) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::INT64) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::FP64) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::BOOL) {\n out->mutable_data(place);\n }\n } else {\n out->ShareDataWith(cast_out);\n }\n\n framework::NPUAttributeMap attr_input = {{\"axes\", dims},\n {\"keep_dims\", keep_dim}};\n\n if (reduce_all) {\n std::vector dim_vec;\n for (int i = 0; i < x->dims().size(); i++) {\n dim_vec.push_back(i);\n }\n\n attr_input = {{\"axes\", dim_vec}, {\"keep_dims\", keep_dim}};\n }\n\n const auto& dev_ctx =\n ctx.template device_context();\n if (framework::TransToProtoVarType(x->dtype()) ==\n framework::proto::VarType::INT64) {\n auto op_func = [](const std::vector& inputs,\n const std::vector& outputs,\n const NPUAttributeMap& attrs,\n const platform::NPUDeviceContext& dev_ctx) {\n const auto& runner =\n NpuOpRunner(\"ReduceMaxD\", {inputs[0]}, {outputs[0]}, attrs);\n runner.Run(dev_ctx.stream());\n };\n\n NpuOpRunner::TypeAdapter({*x}, {cast_out}, attr_input, dev_ctx, op_func,\n {framework::proto::VarType::INT32},\n {framework::proto::VarType::INT32});\n } else {\n const auto& runner =\n NpuOpRunner(\"ReduceMaxD\", {*x}, {cast_out}, attr_input);\n runner.Run(dev_ctx.stream());\n }\n\n if (framework::TransToProtoVarType(x->dtype()) != cast_out_dtype) {\n auto dst_dtype = ConvertToNpuDtype(cast_out_dtype);\n const auto& runner_cast =\n NpuOpRunner(\"Cast\", {cast_out}, {*out},\n {{\"dst_type\", static_cast(dst_dtype)}});\n runner_cast.Run(dev_ctx.stream());\n }\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nnamespace plat = paddle::platform;\nREGISTER_OP_NPU_KERNEL(\n reduce_max, ops::ReduceMaxNPUKernel,\n ops::ReduceMaxNPUKernel,\n ops::ReduceMaxNPUKernel,\n ops::ReduceMaxNPUKernel);\n[NPU] add reduce_max_grad op (#42672)\/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/reduce_ops\/reduce_min_max_op.h\"\n#include \"paddle\/fluid\/platform\/device\/npu\/npu_op_runner.h\"\n\nnamespace paddle {\nnamespace operators {\n\nusing Tensor = framework::Tensor;\ntemplate \nclass ReduceMaxNPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& ctx) const override {\n auto* x = ctx.Input(\"X\");\n auto* out = ctx.Output(\"Out\");\n auto dims = ctx.Attr>(\"dim\");\n bool keep_dim = ctx.Attr(\"keep_dim\");\n bool reduce_all = ctx.Attr(\"reduce_all\");\n int out_dtype = ctx.Attr(\"out_dtype\");\n\n auto place = ctx.GetPlace();\n\n framework::Tensor cast_out(x->type());\n cast_out.Resize(out->dims());\n cast_out.mutable_data(place);\n\n auto cast_out_dtype = framework::TransToProtoVarType(x->dtype());\n if (out_dtype != -1) {\n cast_out_dtype = static_cast(out_dtype);\n }\n\n if (framework::TransToProtoVarType(x->dtype()) != cast_out_dtype) {\n if (cast_out_dtype == framework::proto::VarType::FP32) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::FP16) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::INT16) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::INT32) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::INT64) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::FP64) {\n out->mutable_data(place);\n } else if (cast_out_dtype == framework::proto::VarType::BOOL) {\n out->mutable_data(place);\n }\n } else {\n out->ShareDataWith(cast_out);\n }\n\n framework::NPUAttributeMap attr_input = {{\"axes\", dims},\n {\"keep_dims\", keep_dim}};\n\n if (reduce_all) {\n std::vector dim_vec;\n for (int i = 0; i < x->dims().size(); i++) {\n dim_vec.push_back(i);\n }\n\n attr_input = {{\"axes\", dim_vec}, {\"keep_dims\", keep_dim}};\n }\n\n const auto& dev_ctx =\n ctx.template device_context();\n if (framework::TransToProtoVarType(x->dtype()) ==\n framework::proto::VarType::INT64) {\n auto op_func = [](const std::vector& inputs,\n const std::vector& outputs,\n const NPUAttributeMap& attrs,\n const platform::NPUDeviceContext& dev_ctx) {\n const auto& runner =\n NpuOpRunner(\"ReduceMaxD\", {inputs[0]}, {outputs[0]}, attrs);\n runner.Run(dev_ctx.stream());\n };\n\n NpuOpRunner::TypeAdapter({*x}, {cast_out}, attr_input, dev_ctx, op_func,\n {framework::proto::VarType::INT32},\n {framework::proto::VarType::INT32});\n } else {\n const auto& runner =\n NpuOpRunner(\"ReduceMaxD\", {*x}, {cast_out}, attr_input);\n runner.Run(dev_ctx.stream());\n }\n\n if (framework::TransToProtoVarType(x->dtype()) != cast_out_dtype) {\n auto dst_dtype = ConvertToNpuDtype(cast_out_dtype);\n const auto& runner_cast =\n NpuOpRunner(\"Cast\", {cast_out}, {*out},\n {{\"dst_type\", static_cast(dst_dtype)}});\n runner_cast.Run(dev_ctx.stream());\n }\n }\n};\n\ntemplate \nclass ReduceMaxGradNPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& context) const override {\n auto* x = context.Input(\"X\");\n auto* out = context.Input(\"Out\");\n auto* out_grad = context.Input(framework::GradVarName(\"Out\"));\n int in_dtype = context.Attr(\"in_dtype\");\n\n PADDLE_ENFORCE_EQ(\n in_dtype == -1, true,\n platform::errors::InvalidArgument(\n \"NPU only support in_dtype == -1 in reduce_max_grad op.\"));\n\n auto* x_grad = context.Output(framework::GradVarName(\"X\"));\n x_grad->mutable_data(context.GetPlace());\n\n auto& dev_ctx =\n context.template device_context();\n auto place = context.GetPlace();\n auto stream = dev_ctx.stream();\n\n \/\/ broadcast\n auto x_dims_vec = phi::vectorize(x->dims());\n Tensor transformed_out(x->type());\n transformed_out.Resize(phi::make_ddim(x_dims_vec));\n transformed_out.mutable_data(place);\n NpuOpRunner r_brd_out;\n r_brd_out.SetType(\"BroadcastTo\")\n .AddInput(*out)\n .AddInput(std::move(x_dims_vec))\n .AddOutput(transformed_out)\n .Run(stream);\n Tensor transformed_out_grad(x->type());\n transformed_out_grad.Resize(phi::make_ddim(x_dims_vec));\n transformed_out_grad.mutable_data(place);\n NpuOpRunner r_brd_out_grad;\n r_brd_out_grad.SetType(\"BroadcastTo\")\n .AddInput(*out_grad)\n .AddInput(std::move(x_dims_vec))\n .AddOutput(transformed_out_grad)\n .Run(stream);\n\n \/\/ compare\n Tensor equal_cond;\n equal_cond.mutable_data(x_grad->dims(), place);\n const auto& r_equal =\n NpuOpRunner(\"Equal\", {*x, transformed_out}, {equal_cond}, {});\n r_equal.Run(stream);\n\n \/\/ select\n Tensor t_zero;\n t_zero.mutable_data(x_grad->dims(), place);\n FillNpuTensorWithConstant(&t_zero, static_cast(0));\n t_zero.Resize(x_grad->dims());\n\n const auto& r_sel = NpuOpRunner(\n \"SelectV2\", {equal_cond, transformed_out_grad, t_zero}, {*x_grad}, {});\n r_sel.Run(stream);\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nnamespace plat = paddle::platform;\nREGISTER_OP_NPU_KERNEL(\n reduce_max, ops::ReduceMaxNPUKernel,\n ops::ReduceMaxNPUKernel,\n ops::ReduceMaxNPUKernel,\n ops::ReduceMaxNPUKernel);\nREGISTER_OP_NPU_KERNEL(\n reduce_max_grad, ops::ReduceMaxGradNPUKernel,\n ops::ReduceMaxGradNPUKernel,\n ops::ReduceMaxGradNPUKernel,\n ops::ReduceMaxGradNPUKernel);\n<|endoftext|>"} {"text":"\/\/ Time: O(n)\n\/\/ Space: O(1)\n\n\/\/ DP with rolling window.\nclass Solution {\npublic:\n \/**\n * @param values: a vector of integers\n * @return: a boolean which equals to true if the first player will win\n *\/\n bool firstWillWin(vector &values) {\n vector P(5, 0);\n int sum = 0;\n \/\/ P[i] = max(values[i] + min(P[i + 2], P[i + 3]),\n \/\/ values[i] + values[i + 1] + min(P[i + 3], P[i + 4]))\n for (int i = values.size() - 1; i >= 0; --i) {\n sum += values[i];\n int a = i + 2 < values.size() ? P[(i + 2) % 5] : 0;\n int b = i + 3 < values.size() ? P[(i + 3) % 5] : 0;\n int c = i + 4 < values.size() ? P[(i + 4) % 5] : 0;\n P[i % 5] = max(values[i] + min(a, b), \n values[i] + values[i + 1] + min(b, c));\n }\n \n return P[0] > sum - P[0];\n }\n};\n\n\n\/\/ Time: O(n)\n\/\/ Space: O(n)\nclass Solution2 {\npublic:\n \/**\n * @param values: a vector of integers\n * @return: a boolean which equals to true if the first player will win\n *\/\n bool firstWillWin(vector &values) {\n vector P(values.size(), 0);\n int sum = 0;\n \/\/ P[i] = max(values[i] + min(P[i + 2], P[i + 3]),\n \/\/ values[i] + values[i + 1] + min(P[i + 3], P[i + 4]))\n for (int i = values.size() - 1; i >= 0; --i) {\n sum += values[i];\n int a = i + 2 < values.size() ? P[i + 2] : 0;\n int b = i + 3 < values.size() ? P[i + 3] : 0;\n int c = i + 4 < values.size() ? P[i + 4] : 0;\n P[i] = max(values[i] + min(a, b), \n values[i] + values[i + 1] + min(b, c));\n }\n \n return P[0] > sum - P[0];\n }\n};\nUpdate coins-in-a-line-ii.cpp\/\/ Time: O(n)\n\/\/ Space: O(1)\n\n\/\/ DP with rolling window.\nclass Solution {\npublic:\n \/**\n * @param values: a vector of integers\n * @return: a boolean which equals to true if the first player will win\n *\/\n\/\/ Time: O(n)\n\/\/ Space: O(1)\n\n\/\/ DP with rolling window.\nclass Solution {\npublic:\n \/**\n * @param values: a vector of integers\n * @return: a boolean which equals to true if the first player will win\n *\/\n bool firstWillWin(vector &values) {\n \/\/ For corner case.\n if (values.size() < 2) {\n return values.size() % 2;\n }\n \n vector P(5, 0);\n int sum = 0;\n \/\/ P[i] = max(values[i] + min(P[i + 2], P[i + 3]),\n \/\/ values[i] + values[i + 1] + min(P[i + 3], P[i + 4]))\n for (int i = values.size() - 1; i >= 0; --i) {\n sum += values[i];\n int values_i_plus_1 = i + 1 < values.size() ? values[i + 1]: 0;\n int a = i + 2 < values.size() ? P[(i + 2) % 5] : 0;\n int b = i + 3 < values.size() ? P[(i + 3) % 5] : 0;\n int c = i + 4 < values.size() ? P[(i + 4) % 5] : 0;\n \n P[i % 5] = max(values[i] + min(a, b), \n values[i] + values_i_plus_1 + min(b, c));\n }\n \n return P[0] > sum - P[0];\n }\n};\n\n\n\/\/ Time: O(n)\n\/\/ Space: O(n)\nclass Solution2 {\npublic:\n \/**\n * @param values: a vector of integers\n * @return: a boolean which equals to true if the first player will win\n *\/\n bool firstWillWin(vector &values) {\n vector P(values.size(), 0);\n int sum = 0;\n \/\/ P[i] = max(values[i] + min(P[i + 2], P[i + 3]),\n \/\/ values[i] + values[i + 1] + min(P[i + 3], P[i + 4]))\n for (int i = values.size() - 1; i >= 0; --i) {\n sum += values[i];\n int values_i_plus_1 = i + 1 < values.size() ? values[i + 1]: 0;\n int a = i + 2 < values.size() ? P[i + 2] : 0;\n int b = i + 3 < values.size() ? P[i + 3] : 0;\n int c = i + 4 < values.size() ? P[i + 4] : 0;\n P[i] = max(values[i] + min(a, b), \n values[i] + values_i_plus_1 + min(b, c));\n }\n \n return P[0] > sum - P[0];\n }\n};\n<|endoftext|>"} {"text":"\/*\n This file is part of Magnum.\n\n Original authors — credit is appreciated but not required:\n\n 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 —\n Vladimír Vondruš \n 2015 — Jonathan Hale \n\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n this software, either in source code form or as a compiled binary, for any\n purpose, commercial or non-commercial, and by any means.\n\n In jurisdictions that recognize copyright laws, the author or authors of\n this software dedicate any and all copyright interest in the software to\n the public domain. We make this dedication for the benefit of the public\n at large and to the detriment of our heirs and successors. We intend this\n dedication to be an overt act of relinquishment in perpetuity of all\n present and future rights to this software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"configure.h\"\n\nnamespace Magnum { namespace Examples {\n\nusing namespace Magnum::SceneGraph;\nusing namespace Magnum::Math::Literals;\n\ntypedef Scene Scene3D;\ntypedef Object Object3D;\n\nclass AudioExample: public Platform::Application {\n public:\n explicit AudioExample(const Arguments& arguments);\n\n private:\n void drawEvent() override;\n\n void keyPressEvent(KeyEvent& event);\n\n DebugTools::ResourceManager _manager;\n\n \/* Audio related members *\/\n Audio::Context _context;\n Audio::Buffer _testBuffer;\n Audio::Source _source;\n Corrade::Containers::Array _bufferData;\n\n \/* Scene objects *\/\n Scene3D _scene;\n Object3D _sourceRig;\n Object3D _sourceObject;\n Object3D _cameraObject;\n SceneGraph::Camera3D _camera;\n SceneGraph::DrawableGroup3D _drawables;\n\n Audio::PlayableGroup3D _playables;\n Audio::Playable3D _playable;\n Audio::Listener3D _listener;\n\n Shapes::ShapeGroup3D _shapes;\n};\n\nAudioExample::AudioExample(const Arguments& arguments):\n Platform::Application{arguments, NoCreate},\n \/* Create the audio context. Without this, sound will not be initialized:\n Needs to be done before Playables and Sources are initialized. *\/\n _context(Audio::Context::Configuration().setHrtf(Audio::Context::Configuration::Hrtf::Enabled)),\n _sourceRig(&_scene),\n _sourceObject(&_sourceRig),\n _cameraObject(&_scene),\n _camera(_cameraObject),\n _playable(_sourceObject, &_playables),\n _listener(_scene)\n{\n \/* Try 16x MSAA *\/\n Configuration conf;\n conf.setTitle(\"Magnum Audio Example\")\n .setSampleCount(16);\n if(!tryCreateContext(conf))\n createContext(conf.setSampleCount(0));\n\n \/* Setup the camera *\/\n _camera.setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)\n .setProjectionMatrix(Matrix4::perspectiveProjection(Deg(90.0f), 1.0f, 0.001f, 100.0f))\n .setViewport(defaultFramebuffer.viewport().size());\n\n \/* Load importer plugin *\/\n PluginManager::Manager audioManager{MAGNUM_PLUGINS_AUDIOIMPORTER_DIR};\n std::unique_ptr importer = audioManager.loadAndInstantiate(\"StbVorbisAudioImporter\");\n if(!importer)\n std::exit(1);\n\n \/* Load audio file from compiled resources *\/\n const Utility::Resource rs{\"audio-data\"};\n if(!importer->openData(rs.getRaw(\"chimes.ogg\")))\n std::exit(2);\n\n _bufferData = importer->data(); \/* Get the data from importer *\/\n \/* Add the sample data to the buffer *\/\n _testBuffer.setData(importer->format(), _bufferData, importer->frequency());\n\n \/* Make our sound source play the buffer again and again... *\/\n _playable.source().setBuffer(&_testBuffer);\n _playable.source().setLooping(true);\n _playable.source().play();\n\n \/* Initial offset of the sound source *\/\n _sourceObject.translate({0.0f, 0.0f, -5.0f});\n\n \/* Camera placement *\/\n _cameraObject.rotateX(-45.0_degf).rotateY(45.0_degf);\n _cameraObject.translate({8.0f, 10.0f, 8.0f});\n\n \/* Setup simple shape rendering for listener and source *\/\n _manager.set(\"pink\", DebugTools::ShapeRendererOptions().setColor({1.0f, 0.0f, 1.0f}));\n Shapes::Shape* sphere = new Shapes::Shape(_sourceObject, {{}, 0.5f}, &_shapes);\n new DebugTools::ShapeRenderer3D(*sphere, ResourceKey(\"pink\"), &_drawables);\n\n _manager.set(\"white\", DebugTools::ShapeRendererOptions().setColor({1.0f, 1.0f, 1.0f}));\n Shapes::Shape* box = new Shapes::Shape(_scene, {Matrix4{}}, &_shapes);\n new DebugTools::ShapeRenderer3D(*box, ResourceKey(\"white\"), &_drawables);\n\n \/* Enable depth testing for correct overlap of shapes *\/\n Renderer::enable(Renderer::Feature::DepthTest);\n\n \/* Print hrft status information *\/\n Debug() << \"Hrtf status:\" << _context.hrtfStatus();\n Debug() << \"Hrtf enabled:\" << _context.isHrtfEnabled();\n Debug() << \"Hrtf specifier:\" << _context.hrtfSpecifier();\n\n \/* Loop at 60 Hz max *\/\n setSwapInterval(1);\n setMinimalLoopPeriod(16);\n}\n\nvoid AudioExample::drawEvent() {\n defaultFramebuffer.clear(FramebufferClear::Color | FramebufferClear::Depth);\n\n _shapes.setClean();\n\n \/* Update listener and sound source positions *\/\n _listener.update({_playables});\n\n _camera.draw(_drawables);\n\n swapBuffers();\n redraw();\n}\n\nvoid AudioExample::keyPressEvent(KeyEvent& event) {\n if(event.key() == KeyEvent::Key::Down) {\n _sourceRig.rotateXLocal(Deg(-5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::Up) {\n _sourceRig.rotateXLocal(Deg(5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::Left) {\n _sourceRig.rotateY(Deg(5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::Right) {\n _sourceRig.rotateY(Deg(-5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::PageUp)\n _sourceObject.translate({0.0f, 0.0f, -.25f});\n else if(event.key() == KeyEvent::Key::PageDown && _sourceObject.transformation().translation().z() < 0.0f)\n _sourceObject.translate({0.0f, 0.0f, .25f});\n else if(event.key() == KeyEvent::Key::Esc)\n this->exit();\n\n event.setAccepted();\n}\n\n}}\n\nMAGNUM_APPLICATION_MAIN(Magnum::Examples::AudioExample)\naudio: don't use deprecated functionality.\/*\n This file is part of Magnum.\n\n Original authors — credit is appreciated but not required:\n\n 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 —\n Vladimír Vondruš \n 2015 — Jonathan Hale \n\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n this software, either in source code form or as a compiled binary, for any\n purpose, commercial or non-commercial, and by any means.\n\n In jurisdictions that recognize copyright laws, the author or authors of\n this software dedicate any and all copyright interest in the software to\n the public domain. We make this dedication for the benefit of the public\n at large and to the detriment of our heirs and successors. We intend this\n dedication to be an overt act of relinquishment in perpetuity of all\n present and future rights to this software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"configure.h\"\n\nnamespace Magnum { namespace Examples {\n\nusing namespace Magnum::SceneGraph;\nusing namespace Magnum::Math::Literals;\n\ntypedef Scene Scene3D;\ntypedef Object Object3D;\n\nclass AudioExample: public Platform::Application {\n public:\n explicit AudioExample(const Arguments& arguments);\n\n private:\n void drawEvent() override;\n\n void keyPressEvent(KeyEvent& event);\n\n DebugTools::ResourceManager _manager;\n\n \/* Audio related members *\/\n Audio::Context _context;\n Audio::Buffer _testBuffer;\n Audio::Source _source;\n Corrade::Containers::Array _bufferData;\n\n \/* Scene objects *\/\n Scene3D _scene;\n Object3D _sourceRig;\n Object3D _sourceObject;\n Object3D _cameraObject;\n SceneGraph::Camera3D _camera;\n SceneGraph::DrawableGroup3D _drawables;\n\n Audio::PlayableGroup3D _playables;\n Audio::Playable3D _playable;\n Audio::Listener3D _listener;\n\n Shapes::ShapeGroup3D _shapes;\n};\n\nAudioExample::AudioExample(const Arguments& arguments):\n Platform::Application{arguments, NoCreate},\n \/* Create the audio context. Without this, sound will not be initialized:\n Needs to be done before Playables and Sources are initialized. *\/\n _context(Audio::Context::Configuration().setHrtf(Audio::Context::Configuration::Hrtf::Enabled)),\n _sourceRig(&_scene),\n _sourceObject(&_sourceRig),\n _cameraObject(&_scene),\n _camera(_cameraObject),\n _playable(_sourceObject, &_playables),\n _listener(_scene)\n{\n \/* Try 16x MSAA *\/\n Configuration conf;\n conf.setTitle(\"Magnum Audio Example\")\n .setSampleCount(16);\n if(!tryCreateContext(conf))\n createContext(conf.setSampleCount(0));\n\n \/* Setup the camera *\/\n _camera.setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)\n .setProjectionMatrix(Matrix4::perspectiveProjection(Deg(90.0f), 1.0f, 0.001f, 100.0f))\n .setViewport(defaultFramebuffer.viewport().size());\n\n \/* Load importer plugin *\/\n PluginManager::Manager audioManager{MAGNUM_PLUGINS_AUDIOIMPORTER_DIR};\n std::unique_ptr importer = audioManager.loadAndInstantiate(\"StbVorbisAudioImporter\");\n if(!importer)\n std::exit(1);\n\n \/* Load audio file from compiled resources *\/\n const Utility::Resource rs{\"audio-data\"};\n if(!importer->openData(rs.getRaw(\"chimes.ogg\")))\n std::exit(2);\n\n _bufferData = importer->data(); \/* Get the data from importer *\/\n \/* Add the sample data to the buffer *\/\n _testBuffer.setData(importer->format(), _bufferData, importer->frequency());\n\n \/* Make our sound source play the buffer again and again... *\/\n _playable.source().setBuffer(&_testBuffer);\n _playable.source().setLooping(true);\n _playable.source().play();\n\n \/* Initial offset of the sound source *\/\n _sourceObject.translate({0.0f, 0.0f, -5.0f});\n\n \/* Camera placement *\/\n _cameraObject.rotateX(-45.0_degf).rotateY(45.0_degf);\n _cameraObject.translate({8.0f, 10.0f, 8.0f});\n\n \/* Setup simple shape rendering for listener and source *\/\n _manager.set(\"pink\", DebugTools::ShapeRendererOptions().setColor({1.0f, 0.0f, 1.0f}));\n Shapes::Shape* sphere = new Shapes::Shape(_sourceObject, {{}, 0.5f}, &_shapes);\n new DebugTools::ShapeRenderer3D(*sphere, ResourceKey(\"pink\"), &_drawables);\n\n _manager.set(\"white\", DebugTools::ShapeRendererOptions().setColor({1.0f, 1.0f, 1.0f}));\n Shapes::Shape* box = new Shapes::Shape(_scene, {Matrix4{}}, &_shapes);\n new DebugTools::ShapeRenderer3D(*box, ResourceKey(\"white\"), &_drawables);\n\n \/* Enable depth testing for correct overlap of shapes *\/\n Renderer::enable(Renderer::Feature::DepthTest);\n\n \/* Print hrft status information *\/\n Debug() << \"Hrtf status:\" << _context.hrtfStatus();\n Debug() << \"Hrtf enabled:\" << _context.isHrtfEnabled();\n Debug() << \"Hrtf specifier:\" << _context.hrtfSpecifierString();\n\n \/* Loop at 60 Hz max *\/\n setSwapInterval(1);\n setMinimalLoopPeriod(16);\n}\n\nvoid AudioExample::drawEvent() {\n defaultFramebuffer.clear(FramebufferClear::Color | FramebufferClear::Depth);\n\n _shapes.setClean();\n\n \/* Update listener and sound source positions *\/\n _listener.update({_playables});\n\n _camera.draw(_drawables);\n\n swapBuffers();\n redraw();\n}\n\nvoid AudioExample::keyPressEvent(KeyEvent& event) {\n if(event.key() == KeyEvent::Key::Down) {\n _sourceRig.rotateXLocal(Deg(-5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::Up) {\n _sourceRig.rotateXLocal(Deg(5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::Left) {\n _sourceRig.rotateY(Deg(5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::Right) {\n _sourceRig.rotateY(Deg(-5.0f));\n _sourceRig.normalizeRotation();\n } else if(event.key() == KeyEvent::Key::PageUp)\n _sourceObject.translate({0.0f, 0.0f, -.25f});\n else if(event.key() == KeyEvent::Key::PageDown && _sourceObject.transformation().translation().z() < 0.0f)\n _sourceObject.translate({0.0f, 0.0f, .25f});\n else if(event.key() == KeyEvent::Key::Esc)\n this->exit();\n\n event.setAccepted();\n}\n\n}}\n\nMAGNUM_APPLICATION_MAIN(Magnum::Examples::AudioExample)\n<|endoftext|>"} {"text":"\/*******************************************************\n * Copyright (c) 2017, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n\nnamespace af {\n namespace autograd {\n\n Variable operator +(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() + rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output);\n inputs[1].addGrad(grad_output);\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable operator -(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() - rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output);\n inputs[1].addGrad(negate(grad_output));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable operator *(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() * rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output * inputs[1]);\n inputs[1].addGrad(grad_output * inputs[0]);\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable operator \/(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() \/ rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto inputs_1_rec = reciprocal(inputs[1]);\n auto grad_input_0 = grad_output * inputs_1_rec;\n inputs[0].addGrad(grad_input_0);\n inputs[1].addGrad(grad_input_0 * negate(inputs[0]) * inputs_1_rec);\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n#define INSTANTIATE_OPERATOR(OP) \\\n Variable operator OP(const double &lhs_val, const Variable &rhs) \\\n { \\\n auto lhs = Variable( \\\n af::constant(lhs_val, \\\n rhs.array().dims(), \\\n rhs.array().type()), \\\n false); \\\n return lhs OP rhs; \\\n } \\\n Variable operator OP(const Variable &lhs, const double &rhs_val) \\\n { \\\n auto rhs = Variable( \\\n af::constant(rhs_val, \\\n lhs.array().dims(), lhs.array().type()), \\\n false); \\\n return lhs OP rhs; \\\n } \\\n\n INSTANTIATE_OPERATOR(+)\n INSTANTIATE_OPERATOR(-)\n INSTANTIATE_OPERATOR(*)\n INSTANTIATE_OPERATOR(\/)\n\n#undef INSTANTIATE_OPERATOR\n\n Variable negate(const Variable &input)\n {\n auto result = 0.0 - input.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(negate(grad_output));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable reciprocal(const Variable &input)\n {\n auto result = 1.0 \/ input.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto res = reciprocal(inputs[0]);\n inputs[0].addGrad(negate(grad_output) * res * res);\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable exp(const Variable &input)\n {\n auto result = exp(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(exp(inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable sin(const Variable &input)\n {\n auto result = sin(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(cos(inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable cos(const Variable &input)\n {\n auto result = cos(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(negate(sin(inputs[0])));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable tanh(const Variable &input)\n {\n auto result = tanh(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto tmp = tanh(inputs[0]);\n inputs[0].addGrad(1.0 - tmp * tmp);\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable sigmoid(const Variable &input)\n {\n auto result = sigmoid(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto tmp = sigmoid(inputs[0]);\n inputs[0].addGrad(tmp * (1 - tmp));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable transpose(const Variable &input)\n {\n auto result = transpose(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(transpose(grad_output));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable expandAs(const Variable &input, const Variable &reference)\n {\n dim4 dims(1,1,1,1);\n dim4 idims = input.array().dims();\n dim4 rdims = reference.array().dims();\n for (int i = 0; i < 4; i++) {\n dims[i] = rdims[i] \/ idims[i];\n }\n auto result = tile(input.array(), dims);\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(reduceAs(grad_output, inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable reduceAs(const Variable &input, const Variable &reference)\n {\n dim4 idims = input.array().dims();\n dim4 rdims = reference.array().dims();\n auto result = input.array();\n for (int i = 0; i < 4; i++) {\n if (idims[i] != rdims[i]) result = sum(result, i);\n }\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(expandAs(grad_output, inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable matmul(const Variable &lhs, const Variable &rhs)\n {\n \/\/ lhs:Input[0] -- [M, N]\n \/\/ rhs:Input[1] -- [N, K]\n \/\/matmul(lhs, rhs)\n \/\/ -- matmul([M, N], [N, K]) -- [M, K]\n \/\/ result:grad_output -- [M, K]\n auto result = matmul(lhs.array(), rhs.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n \/\/ matmulNT(grad_output, inputs[1])\n \/\/ -- matmulNT([M, K], [N, K])\n \/\/ -- matmul([M, K], [K, N]) -- [M, K]\n inputs[0].addGrad(matmulNT(grad_output, inputs[1]));\n \/\/ matmulTN(inputs[0], grad_output)\n \/\/ -- matmulTN([M, N], [M, K])\n \/\/ -- matmul([N, M], [M, K]) -- [N, K]\n inputs[1].addGrad(matmulTN(inputs[0], grad_output));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable matmulTN(const Variable &lhs, const Variable &rhs)\n {\n \/\/ lhs:Input[0] -- [N, M]\n \/\/ rhs:Input[1] -- [N, K]\n \/\/ matmulTN(lhs, rhs)\n \/\/ -- matmulTN([N, M], [N, K])\n \/\/ -- matmul([M, N], [N, K]) -- [M, K]\n \/\/ result:grad_output -- [M, K]\n auto result = matmulTN(lhs.array(), rhs.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n \/\/ matmulNT(inputs[1], grad_output)\n \/\/ -- matmulNT([N, K], [M, K])\n \/\/ -- matmul([N, K], [K, M]) -- [N, M]\n inputs[0].addGrad(matmulNT(inputs[1], grad_output));\n \/\/ matmul(inputs[0], grad_output)\n \/\/ -- matmulNT([N, M], [M, K]) -- [N, K]\n inputs[1].addGrad(matmul(inputs[0], grad_output));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable matmulNT(const Variable &lhs, const Variable &rhs)\n {\n \/\/ lhs:Input[0] -- [M, N]\n \/\/ rhs:Input[1] -- [K, N]\n \/\/ matmulNT(lhs, rhs)\n \/\/ -- matmulNT([M, N], [K, N])\n \/\/ -- matmul([M, N], [N, K]) -- [M, K]\n \/\/ result:grad_output -- [M, K]\n auto result = matmulNT(lhs.array(), rhs.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n \/\/ matmul(grad_output, inputs[1])\n \/\/ -- matmul([M, K], [K, N]) -- [M, N]\n inputs[0].addGrad(matmul(grad_output, inputs[1]));\n \/\/ matmulTN(grad_output, inputs[0])\n \/\/ -- matmulTN([M, K], [M, N])\n \/\/ -- matmul([K, M], [M, N]) -- [K, N]\n inputs[1].addGrad(matmulTN(grad_output, inputs[0]));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n }\n}\nFixing bugs in backward pass for activation functions\/*******************************************************\n * Copyright (c) 2017, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n\nnamespace af {\n namespace autograd {\n\n Variable operator +(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() + rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output);\n inputs[1].addGrad(grad_output);\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable operator -(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() - rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output);\n inputs[1].addGrad(negate(grad_output));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable operator *(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() * rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output * inputs[1]);\n inputs[1].addGrad(grad_output * inputs[0]);\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable operator \/(const Variable &lhs, const Variable &rhs)\n {\n auto result = lhs.array() \/ rhs.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto inputs_1_rec = reciprocal(inputs[1]);\n auto grad_input_0 = grad_output * inputs_1_rec;\n inputs[0].addGrad(grad_input_0);\n inputs[1].addGrad(grad_input_0 * negate(inputs[0]) * inputs_1_rec);\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n#define INSTANTIATE_OPERATOR(OP) \\\n Variable operator OP(const double &lhs_val, const Variable &rhs) \\\n { \\\n auto lhs = Variable( \\\n af::constant(lhs_val, \\\n rhs.array().dims(), \\\n rhs.array().type()), \\\n false); \\\n return lhs OP rhs; \\\n } \\\n Variable operator OP(const Variable &lhs, const double &rhs_val) \\\n { \\\n auto rhs = Variable( \\\n af::constant(rhs_val, \\\n lhs.array().dims(), lhs.array().type()), \\\n false); \\\n return lhs OP rhs; \\\n } \\\n\n INSTANTIATE_OPERATOR(+)\n INSTANTIATE_OPERATOR(-)\n INSTANTIATE_OPERATOR(*)\n INSTANTIATE_OPERATOR(\/)\n\n#undef INSTANTIATE_OPERATOR\n\n Variable negate(const Variable &input)\n {\n auto result = 0.0 - input.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(negate(grad_output));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable reciprocal(const Variable &input)\n {\n auto result = 1.0 \/ input.array();\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto res = reciprocal(inputs[0]);\n inputs[0].addGrad(negate(grad_output) * res * res);\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable exp(const Variable &input)\n {\n auto result = exp(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output * exp(inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable sin(const Variable &input)\n {\n auto result = sin(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output * cos(inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable cos(const Variable &input)\n {\n auto result = cos(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(grad_output * negate(sin(inputs[0])));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable tanh(const Variable &input)\n {\n auto result = tanh(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto tmp = tanh(inputs[0]);\n inputs[0].addGrad(grad_output * (1.0 - tmp * tmp));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable sigmoid(const Variable &input)\n {\n auto result = sigmoid(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n auto tmp = sigmoid(inputs[0]);\n inputs[0].addGrad(grad_output * tmp * (1 - tmp));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable transpose(const Variable &input)\n {\n auto result = transpose(input.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(transpose(grad_output));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable expandAs(const Variable &input, const Variable &reference)\n {\n dim4 dims(1,1,1,1);\n dim4 idims = input.array().dims();\n dim4 rdims = reference.array().dims();\n for (int i = 0; i < 4; i++) {\n dims[i] = rdims[i] \/ idims[i];\n }\n auto result = tile(input.array(), dims);\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(reduceAs(grad_output, inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable reduceAs(const Variable &input, const Variable &reference)\n {\n dim4 idims = input.array().dims();\n dim4 rdims = reference.array().dims();\n auto result = input.array();\n for (int i = 0; i < 4; i++) {\n if (idims[i] != rdims[i]) result = sum(result, i);\n }\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n inputs[0].addGrad(expandAs(grad_output, inputs[0]));\n };\n return Variable(result, {input}, grad_func);\n }\n\n Variable matmul(const Variable &lhs, const Variable &rhs)\n {\n \/\/ lhs:Input[0] -- [M, N]\n \/\/ rhs:Input[1] -- [N, K]\n \/\/matmul(lhs, rhs)\n \/\/ -- matmul([M, N], [N, K]) -- [M, K]\n \/\/ result:grad_output -- [M, K]\n auto result = matmul(lhs.array(), rhs.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n \/\/ matmulNT(grad_output, inputs[1])\n \/\/ -- matmulNT([M, K], [N, K])\n \/\/ -- matmul([M, K], [K, N]) -- [M, K]\n inputs[0].addGrad(matmulNT(grad_output, inputs[1]));\n \/\/ matmulTN(inputs[0], grad_output)\n \/\/ -- matmulTN([M, N], [M, K])\n \/\/ -- matmul([N, M], [M, K]) -- [N, K]\n inputs[1].addGrad(matmulTN(inputs[0], grad_output));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable matmulTN(const Variable &lhs, const Variable &rhs)\n {\n \/\/ lhs:Input[0] -- [N, M]\n \/\/ rhs:Input[1] -- [N, K]\n \/\/ matmulTN(lhs, rhs)\n \/\/ -- matmulTN([N, M], [N, K])\n \/\/ -- matmul([M, N], [N, K]) -- [M, K]\n \/\/ result:grad_output -- [M, K]\n auto result = matmulTN(lhs.array(), rhs.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n \/\/ matmulNT(inputs[1], grad_output)\n \/\/ -- matmulNT([N, K], [M, K])\n \/\/ -- matmul([N, K], [K, M]) -- [N, M]\n inputs[0].addGrad(matmulNT(inputs[1], grad_output));\n \/\/ matmul(inputs[0], grad_output)\n \/\/ -- matmulNT([N, M], [M, K]) -- [N, K]\n inputs[1].addGrad(matmul(inputs[0], grad_output));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n\n Variable matmulNT(const Variable &lhs, const Variable &rhs)\n {\n \/\/ lhs:Input[0] -- [M, N]\n \/\/ rhs:Input[1] -- [K, N]\n \/\/ matmulNT(lhs, rhs)\n \/\/ -- matmulNT([M, N], [K, N])\n \/\/ -- matmul([M, N], [N, K]) -- [M, K]\n \/\/ result:grad_output -- [M, K]\n auto result = matmulNT(lhs.array(), rhs.array());\n auto grad_func = [](std::vector &inputs, const Variable &grad_output) {\n \/\/ matmul(grad_output, inputs[1])\n \/\/ -- matmul([M, K], [K, N]) -- [M, N]\n inputs[0].addGrad(matmul(grad_output, inputs[1]));\n \/\/ matmulTN(grad_output, inputs[0])\n \/\/ -- matmulTN([M, K], [M, N])\n \/\/ -- matmul([K, M], [M, N]) -- [K, N]\n inputs[1].addGrad(matmulTN(grad_output, inputs[0]));\n };\n return Variable(result, {lhs, rhs}, grad_func);\n }\n }\n}\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n *\n * dll.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/n-store\/src\/bridge\/ddl.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \"postgres.h\"\n#include \"c.h\"\n\n#include \"bridge\/bridge.h\"\n#include \"nodes\/parsenodes.h\"\n#include \"parser\/parse_utilcmd.h\"\n#include \"parser\/parse_type.h\"\n#include \"access\/htup_details.h\"\n#include \"utils\/resowner.h\"\n#include \"utils\/syscache.h\"\n#include \"catalog\/pg_type.h\"\n\n#include \"backend\/bridge\/ddl.h\"\n#include \"backend\/catalog\/catalog.h\"\n#include \"backend\/catalog\/schema.h\"\n#include \"backend\/common\/logger.h\"\n#include \"backend\/common\/types.h\"\n#include \"backend\/index\/index.h\"\n#include \"backend\/index\/index_factory.h\"\n#include \"backend\/storage\/backend_vm.h\"\n#include \"backend\/storage\/table_factory.h\"\n\n#include \n#include \n\nnamespace peloton {\nnamespace bridge {\n\nstatic std::vector index_infos;\n\n\/**\n * @brief Process utility statement.\n * @param parsetree Parse tree\n *\/\nvoid DDL::ProcessUtility(Node *parsetree,\n const char *queryString){\n assert(parsetree != nullptr);\n assert(queryString != nullptr);\n\n \/\/ Process depending on type of utility statement\n switch (nodeTag(parsetree))\n {\n case T_CreateStmt:\n case T_CreateForeignTableStmt:\n {\n List *stmts;\n ListCell *l;\n\n assert(CurrentResourceOwner != NULL);\n\n \/* Run parse analysis ... *\/\n stmts = transformCreateStmt((CreateStmt *) parsetree,\n queryString);\n\n \/* ... and do it *\/\n foreach(l, stmts)\n {\n Node *stmt = (Node *) lfirst(l);\n if (IsA(stmt, CreateStmt))\n {\n CreateStmt* Cstmt = (CreateStmt*)stmt;\n List* schema = (List*)(Cstmt->tableElts);\n\n char* relation_name = Cstmt->relation->relname;\n std::vector column_infos;\n std::vector reference_table_names;\n\n bool status;\n\n \/\/ Construct DDL_ColumnInfo with schema\n if( schema != NULL ){\n column_infos = peloton::bridge::DDL::ConstructColumnInfoByParsingCreateStmt( Cstmt, reference_table_names );\n status = peloton::bridge::DDL::CreateTable( relation_name, column_infos );\n }\n else {\n \/\/ Create Table without column info\n status = peloton::bridge::DDL::CreateTable( relation_name, column_infos );\n }\n\n fprintf(stderr, \"DDL_CreateTable(%s) :: %d \\n\", relation_name, status);\n\n \/\/ TODO :: Change location or \n \/\/ Foreign keys\n for( auto reference_table_name : reference_table_names ){\n oid_t database_oid = GetCurrentDatabaseOid();\n assert( database_oid );\n storage::DataTable* current_table = (storage::DataTable*) catalog::Manager::GetInstance().GetLocation(database_oid, relation_name);\n storage::DataTable* reference_table = (storage::DataTable*) catalog::Manager::GetInstance().GetLocation(database_oid, reference_table_name);\n\n current_table->AddReferenceTable(reference_table);\n }\n \n }\n }\n }\n\n break;\n\n case T_IndexStmt: \/* CREATE INDEX *\/\n {\n bool status;\n IndexStmt *Istmt = (IndexStmt *) parsetree;\n\n \/\/ Construct IndexInfo \n IndexInfo* index_info = ConstructIndexInfoByParsingIndexStmt( Istmt );\n\n \/\/ If this index is either unique or primary key, store the index information and skip\n \/\/ the rest part since the table has not been created yet.\n if( Istmt->isconstraint ){\n index_infos.push_back(*index_info);\n break;\n }\n\n status = peloton::bridge::DDL::CreateIndex( index_info->GetIndexName(),\n index_info->GetTableName(),\n index_info->GetMethodType(), \n index_info->GetType(),\n index_info->IsUnique(),\n index_info->GetKeyColumnNames());\n\n fprintf(stderr, \"DDLCreateIndex :: %d \\n\", status);\n\n }\n break;\n\n case T_DropStmt:\n { DropStmt* drop;\n ListCell *cell;\n int table_oid_itr = 0;\n bool ret;\n Oid* table_oid_list;\n drop = (DropStmt*) parsetree;\n table_oid_list = (Oid*) malloc ( sizeof(Oid)*(drop->objects->length));\n\n foreach(cell, drop->objects)\n {\n if (drop->removeType == OBJECT_TABLE )\n {\n List* names = ((List *) lfirst(cell));\n char* table_name = strVal(linitial(names));\n table_oid_list[table_oid_itr++] = GetRelationOid(table_name);\n }\n }\n\n while(table_oid_itr > 0)\n {\n ret = peloton::bridge::DDL::DropTable(table_oid_list[--table_oid_itr]);\n fprintf(stderr, \"DDLDropTable :: %d \\n\", ret);\n }\n\n }\n break;\n\n default:\n elog(LOG, \"unrecognized node type: %d\",\n (int) nodeTag(parsetree));\n break;\n }\n\n}\n\n\/**\n * @brief Construct ColumnInfo vector from a create statement\n * @param Cstmt a create statement \n * @return ColumnInfo vector \n *\/\nstd::vector DDL::ConstructColumnInfoByParsingCreateStmt( CreateStmt* Cstmt, std::vector& reference_table_names){\n assert(Cstmt);\n\n \/\/ Get the column list from the create statement\n List* ColumnList = (List*)(Cstmt->tableElts);\n std::vector column_infos;\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Column Type Information\n \/\/===--------------------------------------------------------------------===\/\/\n\n \/\/ Parse the CreateStmt and construct ColumnInfo\n ListCell *entry;\n foreach(entry, ColumnList){\n\n ColumnDef *coldef = lfirst(entry);\n\n \/\/ Parsing the column value type\n Oid typeoid;\n int32 typemod;\n int typelen;\n\n\n \/\/ Get the type oid and type mod with given typeName\n typeoid = typenameTypeId(NULL, coldef->typeName);\n typenameTypeIdAndMod(NULL, coldef->typeName, &typeoid, &typemod);\n\n \/\/ Get type length\n Type tup = typeidType(typeoid);\n typelen = typeLen(tup);\n ReleaseSysCache(tup);\n\n \/* TODO :: Simple version, but need to check whether it is the same with above or not\n \/\/ Get the type oid\n typeoid = typenameTypeId(NULL, coldef->typeName);\n\n \/\/ type mod\n typemod = get_typmodin(typeoid);\n\n \/\/ Get type length\n typelen = get_typlen(typeoid);\n *\/\n\n \/\/ For a fixed-size type, typlen is the number of bytes in the internal\n \/\/ representation of the type. But for a variable-length type, typlen is negative.\n if( typelen == - 1 )\n typelen = typemod;\n\n ValueType column_valueType = PostgresValueTypeToPelotonValueType( (PostgresValueType) typeoid );\n int column_length = typelen;\n std::string column_name = coldef->colname;\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Column Constraint Information\n \/\/===--------------------------------------------------------------------===\/\/\n std::vector column_constraints;\n\n if( coldef->constraints != NULL){\n ListCell* constNodeEntry;\n\n foreach(constNodeEntry, coldef->constraints)\n {\n Constraint* ConstraintNode = lfirst(constNodeEntry);\n ConstraintType contype;\n std::string conname;\n std::string reference_table_name;\n\n \/\/ Get constraint type\n contype = PostgresConstraintTypeToPelotonConstraintType( (PostgresConstraintType) ConstraintNode->contype );\n\n if( ConstraintNode->pktable != NULL ){\n reference_table_name = ConstraintNode->pktable->relname;\n reference_table_names.push_back( reference_table_name );\n }\n\n \/\/ Get constraint name\n if( ConstraintNode->conname != NULL)\n conname = ConstraintNode->conname;\n\n catalog::Constraint* constraint = new catalog::Constraint( contype, conname, reference_table_name );\n column_constraints.push_back(*constraint);\n }\n }\/\/ end of parsing constraint \n\n catalog::ColumnInfo *column_info = new catalog::ColumnInfo( column_valueType, \n column_length, \n column_name, \n column_constraints);\n\n \/\/ Insert column_info into ColumnInfos\n column_infos.push_back(*column_info);\n }\/\/ end of parsing column list\n\n return column_infos;\n}\n\n\/**\n * @brief Construct IndexInfo from a index statement\n * @param Istmt an index statement \n * @return IndexInfo \n *\/\nIndexInfo* DDL::ConstructIndexInfoByParsingIndexStmt( IndexStmt* Istmt ){\n std::string index_name;\n std::string table_name;\n IndexMethodType method_type;\n IndexType type;\n bool unique_keys;\n std::vector key_column_names;\n\n \/\/ Table name\n table_name = Istmt->relation->relname;\n\n \/\/ Index name and index type\n if( Istmt->idxname == NULL && Istmt->isconstraint ){\n if( Istmt->primary ) {\n index_name = table_name+\"_pkey\";\n type = INDEX_TYPE_PRIMARY_KEY;\n }else if( Istmt->unique ){\n index_name = table_name+\"_key\";\n type = INDEX_TYPE_UNIQUE;\n }\n }else{\n type = INDEX_TYPE_NORMAL;\n }\n\n\n \/\/ Key column names\n ListCell *entry;\n foreach(entry, Istmt->indexParams){\n IndexElem *indexElem = lfirst(entry);\n if( indexElem->name != NULL ){\n key_column_names.push_back(indexElem->name);\n }\n }\n\n \/\/ Index method type\n \/\/ TODO :: More access method types need\n method_type = INDEX_METHOD_TYPE_BTREE_MULTIMAP;\n \n IndexInfo* index_info = new IndexInfo( index_name, \n table_name, \n method_type,\n type,\n Istmt->unique,\n key_column_names);\n return index_info;\n}\n\n\/**\n * @brief Create table.\n * @param table_name Table name\n * @param column_infos Information about the columns\n * @param schema Schema for the table\n * @return true if we created a table, false otherwise\n *\/\nbool DDL::CreateTable( std::string table_name,\n std::vector column_infos,\n catalog::Schema *schema){\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Check Parameters \n \/\/===--------------------------------------------------------------------===\/\/\n assert( !table_name.empty() );\n assert( column_infos.size() > 0 || schema != NULL );\n\n Oid database_oid = GetCurrentDatabaseOid();\n if(database_oid == InvalidOid)\n return false;\n\n \/\/ Construct our schema from vector of ColumnInfo\n if( schema == NULL) \n schema = new catalog::Schema(column_infos);\n\n \/\/ FIXME: Construct table backend\n storage::VMBackend *backend = new storage::VMBackend();\n\n \/\/ Build a table from schema\n storage::DataTable *table = storage::TableFactory::GetDataTable(database_oid, schema, table_name);\n catalog::Schema* our_schema = table->GetSchema();\n\n\n \/* DEBUGGING *\/\n \/\/std::cout << \"table name : \" << table_name << \"\\n\" << *our_schema << std::endl;\n\n \/\/ In Postgres, indexes such as primary key index, unique indexy are created before table.\n \/\/ In Peloton, however, the table is required to create an index. For that reason, index information\n \/\/ was stored before and now it will be created. \n for( auto index_info : index_infos){\n bool status;\n status = peloton::bridge::DDL::CreateIndex( index_info.GetIndexName(),\n index_info.GetTableName(),\n index_info.GetMethodType(), \n index_info.GetType(),\n index_info.IsUnique(),\n index_info.GetKeyColumnNames());\n fprintf(stderr, \"DDLCreateIndex :: %d \\n\", status);\n }\n index_infos.clear();\n\n if(table != nullptr) {\n LOG_INFO(\"Created table : %s\", table_name.c_str());\n return true;\n }\n\n return false;\n}\n\n\n\/**\n * @brief Drop table.\n * @param table_oid Table id.\n * @return true if we dropped the table, false otherwise\n *\/\nbool DDL::DropTable(Oid table_oid) {\n\n oid_t database_oid = GetCurrentDatabaseOid();\n\n if(database_oid == InvalidOid || table_oid == InvalidOid) {\n LOG_WARN(\"Could not drop table :: db oid : %u table oid : %u\", database_oid, table_oid);\n return false;\n }\n\n bool status = storage::TableFactory::DropDataTable(database_oid, table_oid);\n if(status == true) {\n LOG_INFO(\"Dropped table with oid : %u\\n\", table_oid);\n return true;\n }\n\n return false;\n}\n\n\/**\n * @brief Create index.\n * @param index_name Index name\n * @param table_name Table name\n * @param type Type of the index\n * @param unique Index is unique or not ?\n * @param key_column_names column names for the key table \n * @return true if we create the index, false otherwise\n *\/\nbool DDL::CreateIndex(std::string index_name,\n std::string table_name,\n IndexMethodType index_method_type,\n IndexType index_type,\n bool unique_keys,\n std::vector key_column_names,\n bool bootstrap ){\n\n assert( !index_name.empty() );\n assert( !table_name.empty() );\n assert( key_column_names.size() > 0 );\n\n \/\/ NOTE: We currently only support btree as our index implementation\n \/\/ TODO : Support other types based on \"type\" argument\n IndexMethodType our_index_type = INDEX_METHOD_TYPE_BTREE_MULTIMAP;\n\n \/\/ Get the database oid and table oid\n oid_t database_oid = GetCurrentDatabaseOid();\n assert( database_oid );\n\n \/\/oid_t table_oid = GetRelationOid(table_name.c_str());\n\n \/\/ Get the table location from manager\n auto table = catalog::Manager::GetInstance().GetLocation(database_oid, table_name);\n storage::DataTable* data_table = (storage::DataTable*) table;\n auto tuple_schema = data_table->GetSchema();\n\n \/\/ Construct key schema\n std::vector key_columns;\n\n \/\/ Based on the key column info, get the oid of the given 'key' columns in the tuple schema\n for( auto key_column_name : key_column_names ){\n for( oid_t tuple_schema_column_itr = 0; tuple_schema_column_itr < tuple_schema->GetColumnCount();\n tuple_schema_column_itr++){\n\n \/\/ Get the current column info from tuple schema\n catalog::ColumnInfo column_info = tuple_schema->GetColumnInfo(tuple_schema_column_itr);\n \/\/ Compare Key Schema's current column name and Tuple Schema's current column name\n if( key_column_name == column_info.name ){\n key_columns.push_back(tuple_schema_column_itr);\n\n \/\/ TODO :: Need to talk with Joy\n \/\/ NOTE :: Since pg_attribute doesn't have any information about primary key and unique key,\n \/\/ I try to store these information when we create an unique and primary key index\n if( bootstrap ){\n if( index_type == INDEX_TYPE_PRIMARY_KEY ){ \n catalog::Constraint* constraint = new catalog::Constraint( CONSTRAINT_TYPE_PRIMARY );\n tuple_schema->AddConstraintInColumn( tuple_schema_column_itr, constraint); \n }else if( index_type == INDEX_TYPE_UNIQUE ){ \n catalog::Constraint* constraint = new catalog::Constraint( CONSTRAINT_TYPE_UNIQUE );\n tuple_schema->AddConstraintInColumn( tuple_schema_column_itr, constraint); \n }\n }\n\n }\n }\n }\n\n auto key_schema = catalog::Schema::CopySchema(tuple_schema, key_columns);\n\n \/\/ Create index metadata and physical index\n index::IndexMetadata* metadata = new index::IndexMetadata(index_name, our_index_type,\n tuple_schema, key_schema,\n unique_keys);\n index::Index* index = index::IndexFactory::GetInstance(metadata);\n\n \/\/ Record the built index in the table\n switch( index_type ){\n case INDEX_TYPE_NORMAL:\n\t data_table->AddIndex(index);\n\t break;\n case INDEX_TYPE_PRIMARY_KEY:\n\t data_table->SetPrimaryIndex(index);\n\t break;\n case INDEX_TYPE_UNIQUE:\n\t data_table->AddUniqueIndex(index);\n\t break;\n default:\n elog(LOG, \"unrecognized index type: %d\", index_type);\n }\n\n return true;\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\nMinor fix - unique index name\/*-------------------------------------------------------------------------\n *\n * dll.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/n-store\/src\/bridge\/ddl.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \"postgres.h\"\n#include \"c.h\"\n\n#include \"bridge\/bridge.h\"\n#include \"nodes\/parsenodes.h\"\n#include \"parser\/parse_utilcmd.h\"\n#include \"parser\/parse_type.h\"\n#include \"access\/htup_details.h\"\n#include \"utils\/resowner.h\"\n#include \"utils\/syscache.h\"\n#include \"catalog\/pg_type.h\"\n\n#include \"backend\/bridge\/ddl.h\"\n#include \"backend\/catalog\/catalog.h\"\n#include \"backend\/catalog\/schema.h\"\n#include \"backend\/common\/logger.h\"\n#include \"backend\/common\/types.h\"\n#include \"backend\/index\/index.h\"\n#include \"backend\/index\/index_factory.h\"\n#include \"backend\/storage\/backend_vm.h\"\n#include \"backend\/storage\/table_factory.h\"\n\n#include \n#include \n\nnamespace peloton {\nnamespace bridge {\n\nstatic std::vector index_infos;\n\n\/**\n * @brief Process utility statement.\n * @param parsetree Parse tree\n *\/\nvoid DDL::ProcessUtility(Node *parsetree,\n const char *queryString){\n assert(parsetree != nullptr);\n assert(queryString != nullptr);\n\n \/\/ Process depending on type of utility statement\n switch (nodeTag(parsetree))\n {\n case T_CreateStmt:\n case T_CreateForeignTableStmt:\n {\n List *stmts;\n ListCell *l;\n\n assert(CurrentResourceOwner != NULL);\n\n \/* Run parse analysis ... *\/\n stmts = transformCreateStmt((CreateStmt *) parsetree,\n queryString);\n\n \/* ... and do it *\/\n foreach(l, stmts)\n {\n Node *stmt = (Node *) lfirst(l);\n if (IsA(stmt, CreateStmt))\n {\n CreateStmt* Cstmt = (CreateStmt*)stmt;\n List* schema = (List*)(Cstmt->tableElts);\n\n char* relation_name = Cstmt->relation->relname;\n std::vector column_infos;\n std::vector reference_table_names;\n\n bool status;\n\n \/\/ Construct DDL_ColumnInfo with schema\n if( schema != NULL ){\n column_infos = peloton::bridge::DDL::ConstructColumnInfoByParsingCreateStmt( Cstmt, reference_table_names );\n status = peloton::bridge::DDL::CreateTable( relation_name, column_infos );\n }\n else {\n \/\/ Create Table without column info\n status = peloton::bridge::DDL::CreateTable( relation_name, column_infos );\n }\n\n fprintf(stderr, \"DDL_CreateTable(%s) :: %d \\n\", relation_name, status);\n\n \/\/ TODO :: Change location or \n \/\/ Foreign keys\n for( auto reference_table_name : reference_table_names ){\n oid_t database_oid = GetCurrentDatabaseOid();\n assert( database_oid );\n storage::DataTable* current_table = (storage::DataTable*) catalog::Manager::GetInstance().GetLocation(database_oid, relation_name);\n storage::DataTable* reference_table = (storage::DataTable*) catalog::Manager::GetInstance().GetLocation(database_oid, reference_table_name);\n\n current_table->AddReferenceTable(reference_table);\n }\n \n }\n }\n }\n\n break;\n\n case T_IndexStmt: \/* CREATE INDEX *\/\n {\n bool status;\n IndexStmt *Istmt = (IndexStmt *) parsetree;\n\n \/\/ Construct IndexInfo \n IndexInfo* index_info = ConstructIndexInfoByParsingIndexStmt( Istmt );\n\n \/\/ If this index is either unique or primary key, store the index information and skip\n \/\/ the rest part since the table has not been created yet.\n if( Istmt->isconstraint ){\n index_infos.push_back(*index_info);\n break;\n }\n\n status = peloton::bridge::DDL::CreateIndex( index_info->GetIndexName(),\n index_info->GetTableName(),\n index_info->GetMethodType(), \n index_info->GetType(),\n index_info->IsUnique(),\n index_info->GetKeyColumnNames());\n\n fprintf(stderr, \"DDLCreateIndex %s :: %d \\n\", index_info->GetIndexName().c_str(), status);\n\n }\n break;\n\n case T_DropStmt:\n { DropStmt* drop;\n ListCell *cell;\n int table_oid_itr = 0;\n bool ret;\n Oid* table_oid_list;\n drop = (DropStmt*) parsetree;\n table_oid_list = (Oid*) malloc ( sizeof(Oid)*(drop->objects->length));\n\n foreach(cell, drop->objects)\n {\n if (drop->removeType == OBJECT_TABLE )\n {\n List* names = ((List *) lfirst(cell));\n char* table_name = strVal(linitial(names));\n table_oid_list[table_oid_itr++] = GetRelationOid(table_name);\n }\n }\n\n while(table_oid_itr > 0)\n {\n ret = peloton::bridge::DDL::DropTable(table_oid_list[--table_oid_itr]);\n fprintf(stderr, \"DDLDropTable :: %d \\n\", ret);\n }\n\n }\n break;\n\n default:\n elog(LOG, \"unrecognized node type: %d\",\n (int) nodeTag(parsetree));\n break;\n }\n\n}\n\n\/**\n * @brief Construct ColumnInfo vector from a create statement\n * @param Cstmt a create statement \n * @return ColumnInfo vector \n *\/\nstd::vector DDL::ConstructColumnInfoByParsingCreateStmt( CreateStmt* Cstmt, std::vector& reference_table_names){\n assert(Cstmt);\n\n \/\/ Get the column list from the create statement\n List* ColumnList = (List*)(Cstmt->tableElts);\n std::vector column_infos;\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Column Type Information\n \/\/===--------------------------------------------------------------------===\/\/\n\n \/\/ Parse the CreateStmt and construct ColumnInfo\n ListCell *entry;\n foreach(entry, ColumnList){\n\n ColumnDef *coldef = lfirst(entry);\n\n \/\/ Parsing the column value type\n Oid typeoid;\n int32 typemod;\n int typelen;\n\n\n \/\/ Get the type oid and type mod with given typeName\n typeoid = typenameTypeId(NULL, coldef->typeName);\n typenameTypeIdAndMod(NULL, coldef->typeName, &typeoid, &typemod);\n\n \/\/ Get type length\n Type tup = typeidType(typeoid);\n typelen = typeLen(tup);\n ReleaseSysCache(tup);\n\n \/* TODO :: Simple version, but need to check whether it is the same with above or not\n \/\/ Get the type oid\n typeoid = typenameTypeId(NULL, coldef->typeName);\n\n \/\/ type mod\n typemod = get_typmodin(typeoid);\n\n \/\/ Get type length\n typelen = get_typlen(typeoid);\n *\/\n\n \/\/ For a fixed-size type, typlen is the number of bytes in the internal\n \/\/ representation of the type. But for a variable-length type, typlen is negative.\n if( typelen == - 1 )\n typelen = typemod;\n\n ValueType column_valueType = PostgresValueTypeToPelotonValueType( (PostgresValueType) typeoid );\n int column_length = typelen;\n std::string column_name = coldef->colname;\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Column Constraint Information\n \/\/===--------------------------------------------------------------------===\/\/\n std::vector column_constraints;\n\n if( coldef->constraints != NULL){\n ListCell* constNodeEntry;\n\n foreach(constNodeEntry, coldef->constraints)\n {\n Constraint* ConstraintNode = lfirst(constNodeEntry);\n ConstraintType contype;\n std::string conname;\n std::string reference_table_name;\n\n \/\/ Get constraint type\n contype = PostgresConstraintTypeToPelotonConstraintType( (PostgresConstraintType) ConstraintNode->contype );\n\n if( ConstraintNode->pktable != NULL ){\n reference_table_name = ConstraintNode->pktable->relname;\n reference_table_names.push_back( reference_table_name );\n }\n\n \/\/ Get constraint name\n if( ConstraintNode->conname != NULL)\n conname = ConstraintNode->conname;\n\n catalog::Constraint* constraint = new catalog::Constraint( contype, conname, reference_table_name );\n column_constraints.push_back(*constraint);\n }\n }\/\/ end of parsing constraint \n\n catalog::ColumnInfo *column_info = new catalog::ColumnInfo( column_valueType, \n column_length, \n column_name, \n column_constraints);\n\n \/\/ Insert column_info into ColumnInfos\n column_infos.push_back(*column_info);\n }\/\/ end of parsing column list\n\n return column_infos;\n}\n\n\/**\n * @brief Construct IndexInfo from a index statement\n * @param Istmt an index statement \n * @return IndexInfo \n *\/\nIndexInfo* DDL::ConstructIndexInfoByParsingIndexStmt( IndexStmt* Istmt ){\n std::string index_name;\n std::string table_name;\n IndexMethodType method_type;\n IndexType type;\n bool unique_keys;\n std::vector key_column_names;\n\n \/\/ Table name\n table_name = Istmt->relation->relname;\n\n \/\/ Key column names\n ListCell *entry;\n foreach(entry, Istmt->indexParams){\n IndexElem *indexElem = lfirst(entry);\n if( indexElem->name != NULL ){\n key_column_names.push_back(indexElem->name);\n }\n }\n\n \/\/ Index name and index type\n if( Istmt->idxname == NULL && Istmt->isconstraint ){\n if( Istmt->primary ) {\n index_name = table_name+\"_pkey\";\n type = INDEX_TYPE_PRIMARY_KEY;\n }else if( Istmt->unique ){\n index_name = table_name;\n for( auto column_name : key_column_names ){\n index_name += \"_\"+column_name+\"_\";\n }\n index_name += \"key\";\n type = INDEX_TYPE_UNIQUE;\n }\n }else{\n type = INDEX_TYPE_NORMAL;\n }\n\n \/\/ Index method type\n \/\/ TODO :: More access method types need\n method_type = INDEX_METHOD_TYPE_BTREE_MULTIMAP;\n \n IndexInfo* index_info = new IndexInfo( index_name, \n table_name, \n method_type,\n type,\n Istmt->unique,\n key_column_names);\n return index_info;\n}\n\n\/**\n * @brief Create table.\n * @param table_name Table name\n * @param column_infos Information about the columns\n * @param schema Schema for the table\n * @return true if we created a table, false otherwise\n *\/\nbool DDL::CreateTable( std::string table_name,\n std::vector column_infos,\n catalog::Schema *schema){\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Check Parameters \n \/\/===--------------------------------------------------------------------===\/\/\n assert( !table_name.empty() );\n assert( column_infos.size() > 0 || schema != NULL );\n\n Oid database_oid = GetCurrentDatabaseOid();\n if(database_oid == InvalidOid)\n return false;\n\n \/\/ Construct our schema from vector of ColumnInfo\n if( schema == NULL) \n schema = new catalog::Schema(column_infos);\n\n \/\/ FIXME: Construct table backend\n storage::VMBackend *backend = new storage::VMBackend();\n\n \/\/ Build a table from schema\n storage::DataTable *table = storage::TableFactory::GetDataTable(database_oid, schema, table_name);\n catalog::Schema* our_schema = table->GetSchema();\n\n\n \/* DEBUGGING *\/\n \/\/std::cout << \"table name : \" << table_name << \"\\n\" << *our_schema << std::endl;\n\n \/\/ In Postgres, indexes such as primary key index, unique indexy are created before table.\n \/\/ In Peloton, however, the table is required to create an index. For that reason, index information\n \/\/ was stored before and now it will be created. \n for( auto index_info : index_infos){\n bool status;\n status = peloton::bridge::DDL::CreateIndex( index_info.GetIndexName(),\n index_info.GetTableName(),\n index_info.GetMethodType(), \n index_info.GetType(),\n index_info.IsUnique(),\n index_info.GetKeyColumnNames());\n fprintf(stderr, \"DDLCreateIndex %s :: %d \\n\", index_info.GetIndexName().c_str(), status);\n }\n index_infos.clear();\n\n if(table != nullptr) {\n LOG_INFO(\"Created table : %s\", table_name.c_str());\n return true;\n }\n\n return false;\n}\n\n\n\/**\n * @brief Drop table.\n * @param table_oid Table id.\n * @return true if we dropped the table, false otherwise\n *\/\nbool DDL::DropTable(Oid table_oid) {\n\n oid_t database_oid = GetCurrentDatabaseOid();\n\n if(database_oid == InvalidOid || table_oid == InvalidOid) {\n LOG_WARN(\"Could not drop table :: db oid : %u table oid : %u\", database_oid, table_oid);\n return false;\n }\n\n bool status = storage::TableFactory::DropDataTable(database_oid, table_oid);\n if(status == true) {\n LOG_INFO(\"Dropped table with oid : %u\\n\", table_oid);\n return true;\n }\n\n return false;\n}\n\n\/**\n * @brief Create index.\n * @param index_name Index name\n * @param table_name Table name\n * @param type Type of the index\n * @param unique Index is unique or not ?\n * @param key_column_names column names for the key table \n * @return true if we create the index, false otherwise\n *\/\nbool DDL::CreateIndex(std::string index_name,\n std::string table_name,\n IndexMethodType index_method_type,\n IndexType index_type,\n bool unique_keys,\n std::vector key_column_names,\n bool bootstrap ){\n\n assert( !index_name.empty() );\n assert( !table_name.empty() );\n assert( key_column_names.size() > 0 );\n\n \/\/ NOTE: We currently only support btree as our index implementation\n \/\/ TODO : Support other types based on \"type\" argument\n IndexMethodType our_index_type = INDEX_METHOD_TYPE_BTREE_MULTIMAP;\n\n \/\/ Get the database oid and table oid\n oid_t database_oid = GetCurrentDatabaseOid();\n assert( database_oid );\n\n \/\/oid_t table_oid = GetRelationOid(table_name.c_str());\n\n \/\/ Get the table location from manager\n auto table = catalog::Manager::GetInstance().GetLocation(database_oid, table_name);\n storage::DataTable* data_table = (storage::DataTable*) table;\n auto tuple_schema = data_table->GetSchema();\n\n \/\/ Construct key schema\n std::vector key_columns;\n\n \/\/ Based on the key column info, get the oid of the given 'key' columns in the tuple schema\n for( auto key_column_name : key_column_names ){\n for( oid_t tuple_schema_column_itr = 0; tuple_schema_column_itr < tuple_schema->GetColumnCount();\n tuple_schema_column_itr++){\n\n \/\/ Get the current column info from tuple schema\n catalog::ColumnInfo column_info = tuple_schema->GetColumnInfo(tuple_schema_column_itr);\n \/\/ Compare Key Schema's current column name and Tuple Schema's current column name\n if( key_column_name == column_info.name ){\n key_columns.push_back(tuple_schema_column_itr);\n\n \/\/ TODO :: Need to talk with Joy\n \/\/ NOTE :: Since pg_attribute doesn't have any information about primary key and unique key,\n \/\/ I try to store these information when we create an unique and primary key index\n if( bootstrap ){\n if( index_type == INDEX_TYPE_PRIMARY_KEY ){ \n catalog::Constraint* constraint = new catalog::Constraint( CONSTRAINT_TYPE_PRIMARY );\n tuple_schema->AddConstraintInColumn( tuple_schema_column_itr, constraint); \n }else if( index_type == INDEX_TYPE_UNIQUE ){ \n catalog::Constraint* constraint = new catalog::Constraint( CONSTRAINT_TYPE_UNIQUE );\n tuple_schema->AddConstraintInColumn( tuple_schema_column_itr, constraint); \n }\n }\n\n }\n }\n }\n\n auto key_schema = catalog::Schema::CopySchema(tuple_schema, key_columns);\n\n \/\/ Create index metadata and physical index\n index::IndexMetadata* metadata = new index::IndexMetadata(index_name, our_index_type,\n tuple_schema, key_schema,\n unique_keys);\n index::Index* index = index::IndexFactory::GetInstance(metadata);\n\n \/\/ Record the built index in the table\n switch( index_type ){\n case INDEX_TYPE_NORMAL:\n\t data_table->AddIndex(index);\n\t break;\n case INDEX_TYPE_PRIMARY_KEY:\n\t data_table->SetPrimaryIndex(index);\n\t break;\n case INDEX_TYPE_UNIQUE:\n\t data_table->AddUniqueIndex(index);\n\t break;\n default:\n elog(LOG, \"unrecognized index type: %d\", index_type);\n }\n\n return true;\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"\/\/ ParallelExecutionOfCommands.cpp : \n\/\/ This aplication aims to provide functionality for parallel execution of Behat commands.\n\/\/\n\n\/\/#include \"stdafx.h\"\n#include \n#include \n#include \n#include \n\/\/#include \n#include \n\nusing namespace std;\n\nint main()\n{\t\n\t\/\/ Declaration of needed variables.\n\tint processes_Count;\n\tchar command[128];\n\tstring behat_Profile;\n\tstring behat_Feature_Folder;\n\tstring behat_Bin = \"bin\/behat -p \";\n\tstring result_Command_String;\n\tthread thread_Array[100];\n\tbool parallel_Execution = true;\n\t\n\t\/\/ Entering values for the variables.\n\tcout << \"Enter number of processes you want to execute: \";\n\tcin >> processes_Count;\n\tcout << \"Enter Behat profile you want to use: \";\n\tcin >> behat_Profile;\n\tcout << \"Enter Behat feature folder or file location you want to execute: \";\n\tcin >> behat_Feature_Folder;\n\n\t\/\/ Creting command for execution.\n\tresult_Command_String = behat_Bin + behat_Profile + \" features\/\" + behat_Feature_Folder;\n\tstrcpy(command, result_Command_String.c_str());\n\n\tcout << \"You will execute \" << processes_Count << \" processes with the following command: \" << command << \".\\n\";\n\n\t\/\/ Creating threads to handle the command execution.\n\tfor (size_t i = 0; i < processes_Count; i++)\n\t{\n\t\tthread_Array[i] = thread(system, command);\n\t\tthread_Array[i].join();\n\t}\n\tfor (size_t i = 0; i < sizeof(thread_Array); i++)\n\t{\n\t\tthread_Array[i].detach();\n\t}\n\n\n\t\/\/\/\/ Creating process for execution of the command.\n\t\/\/pid_t pids[processes_Count];\n\t\/\/for (size_t i = 0; i < processes_Count; i++)\n\t\/\/{\n\t\/\/\tif ((pids[i] = fork()) < 0)\n\t\/\/\t{\n\t\/\/\t\tperror(\"Process was unable to be created.\");\n\t\/\/\t\tabort();\n\t\/\/\t}\n\t\/\/\telse if (pids[i] == 0)\n\t\/\/\t{\n\t\/\/\t\tsystem(command);\n\t\/\/\t\texit(0);\n\t\/\/\t}\n\t\/\/}\n\n return 0;\n}\n\ntesing.\/\/ ParallelExecutionOfCommands.cpp : \n\/\/ This aplication aims to provide functionality for parallel execution of Behat commands.\n\/\/\n\n\/\/#include \"stdafx.h\"\n#include \n#include \n#include \n#include \n\/\/#include \n#include \n\nusing namespace std;\n\nint main()\n{\t\n\t\/\/ Declaration of needed variables.\n\tint processes_Count;\n\tchar command[128];\n\tstring behat_Profile;\n\tstring behat_Feature_Folder;\n\tstring behat_Bin = \"bin\/behat -p \";\n\tstring result_Command_String;\n\tthread thread_Array[100];\n\tbool parallel_Execution = true;\n\t\n\t\/\/ Entering values for the variables.\n\tcout << \"Enter number of processes you want to execute: \";\n\tcin >> processes_Count;\n\tcout << \"Enter Behat profile you want to use: \";\n\tcin >> behat_Profile;\n\tcout << \"Enter Behat feature folder or file location you want to execute: \";\n\tcin >> behat_Feature_Folder;\n\n\t\/\/ Creting command for execution.\n\tresult_Command_String = behat_Bin + behat_Profile + \" features\/\" + behat_Feature_Folder;\n\tstrcpy(command, result_Command_String.c_str());\n\n\tcout << \"You will execute \" << processes_Count << \" processes with the following command: \" << command << \".\\n\";\n\n\t\/\/ Creating threads to handle the command execution.\n\tfor (size_t i = 0; i < processes_Count; i++)\n\t{\n\t\tthread_Array[i] = thread(system, command);\n\t\t\n\t}\n\tfor (size_t i = 0; i < processes_Count; i++)\n\t{\n\t\tthread_Array[i].join();\n\t}\n\n\n\t\/\/\/\/ Creating process for execution of the command.\n\t\/\/pid_t pids[processes_Count];\n\t\/\/for (size_t i = 0; i < processes_Count; i++)\n\t\/\/{\n\t\/\/\tif ((pids[i] = fork()) < 0)\n\t\/\/\t{\n\t\/\/\t\tperror(\"Process was unable to be created.\");\n\t\/\/\t\tabort();\n\t\/\/\t}\n\t\/\/\telse if (pids[i] == 0)\n\t\/\/\t{\n\t\/\/\t\tsystem(command);\n\t\/\/\t\texit(0);\n\t\/\/\t}\n\t\/\/}\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ BenchmarkRegex.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass timer\n{\npublic: \n\ttimer() = default;\n\tvoid start_timing(const std::string& text_)\n\t{\n\t\ttext = text_;\n\t\tbegin = std::chrono::high_resolution_clock::now();\n\t}\n\tvoid stop_timing()\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now();\n\t\tauto dur = end - begin;\n\t\tauto ms = std::chrono::duration_cast(dur).count();\n\t\tstd::cout << std::setw(16) << text << \":\" << std::setw(5) << ms << \"ms\" << std::endl;\n\t}\n\nprivate:\n\tstd::string text;\n\tstd::chrono::steady_clock::time_point begin;\n};\n\n#ifdef WIN32\n\n#pragma optimize(\"\", off)\ntemplate \nvoid do_not_optimize_away(T* datum) {\n\tdatum = datum;\n}\n#pragma optimize(\"\", on)\n\n#else\nstatic void do_not_optimize_away(void* p) { \n\tasm volatile(\"\" : : \"g\"(p) : \"memory\");\n}\n#endif\n\nstruct singleton\n{\npublic:\n\tstatic void set(const std::regex* obj_ptr) { s_regex_ptr = obj_ptr; }\n\tstatic const std::regex* get()\n\t{\n\t\tstd::lock_guard lock(s_mutex);\n\n\t\tstd::thread::id thread_id = std::this_thread::get_id();\n\t\tstd::map::iterator it = s_map.find(thread_id);\n\t\tif (it == s_map.end())\n\t\t{\n\t\t\tconst std::regex* ptr = new std::regex(*s_regex_ptr);\n\t\t\ts_map[thread_id] = ptr;\n\t\t\treturn ptr;\n\t\t}\n\t\treturn it->second;\n\t}\nprivate:\n\tstatic std::map s_map;\n\tstatic const std::regex* s_regex_ptr;\n\tstatic std::mutex s_mutex;\n};\nstd::map singleton::s_map;\nconst std::regex* singleton::s_regex_ptr = nullptr;\nstd::mutex singleton::s_mutex;\n\nconst std::string local_match(const std::string& text);\nconst std::string static_match(const std::string& text); \/\/ not reentrant-safe\nconst std::string singleton_match(const std::string& text);\n\nint main(int argc, char* argv[])\n{\n\tconst int LOOP = 100000;\n\tstd::string str1 = \"Zoomer PRICE: HK$1.23 PER SHARE\";\n\tstd::string str2 = \"Boomer PRICE: HK$4.56 PER SHARE\";\n\n\tstd::vector vec;\n\tvec.push_back(str1);\n\tvec.push_back(str2);\n\n\ttimer stopwatch;\n\n\tstopwatch.start_timing(\"local regex object\");\n\tfor(int j = 0; j < LOOP; ++j)\n\t{\n\t\tfor(size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tdo_not_optimize_away(local_match(vec[i]).c_str());\n\t\t}\n\t}\n\tstopwatch.stop_timing();\n\n\tstopwatch.start_timing(\"static regex object\");\n\tfor(int j = 0; j < LOOP; ++j)\n\t{\n\t\tfor(size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tdo_not_optimize_away(static_match(vec[i]).c_str());\n\t\t}\n\t}\n\tstopwatch.stop_timing();\n\n\tconst std::regex regex(\".*PRICE:.*HK\\\\$(\\\\d+\\\\.\\\\d+|[-+]*\\\\d+).*PER SHARE\");\n\tsingleton::set(®ex);\n\n\tstopwatch.start_timing(\"singleton regex object\");\n\tfor (int j = 0; j < LOOP; ++j)\n\t{\n\t\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tdo_not_optimize_away(singleton_match(vec[i]).c_str());\n\t\t}\n\t}\n\tstopwatch.stop_timing();\n\n\t\/*\n\tstd::cout << local_match(str1) << std::endl;\n\tstd::cout << local_match(str2) << std::endl;\n\tstd::cout << static_match(str1) << std::endl;\n\tstd::cout << static_match(str2) << std::endl;\n\tstd::cout << singleton_match(str1) << std::endl;\n\tstd::cout << singleton_match(str2) << std::endl;\n\t*\/\n\n\treturn 0;\n}\n\nconst std::string local_match(const std::string& text)\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tconst std::regex regex(\".*PRICE:.*HK\\\\$(\\\\d+\\\\.\\\\d+|[-+]*\\\\d+).*PER SHARE\");\n\tif (std::regex_match(text, what, regex))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\n\nconst std::string static_match(const std::string& text) \/\/ not reentrant-safe\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tstatic const std::regex regex(\".*PRICE:.*HK\\\\$(\\\\d+\\\\.\\\\d+|[-+]*\\\\d+).*PER SHARE\");\n\tif (std::regex_match(text, what, regex))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\n\nconst std::string singleton_match(const std::string& text)\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tconst std::regex* regex_ptr = singleton::get();\n\tif (std::regex_match(text, what, *regex_ptr))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\nAdd factory class\/\/ BenchmarkRegex.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass timer\n{\npublic: \n\ttimer() = default;\n\tvoid start_timing(const std::string& text_)\n\t{\n\t\ttext = text_;\n\t\tbegin = std::chrono::high_resolution_clock::now();\n\t}\n\tvoid stop_timing()\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now();\n\t\tauto dur = end - begin;\n\t\tauto ms = std::chrono::duration_cast(dur).count();\n\t\tstd::cout << std::setw(16) << text << \":\" << std::setw(5) << ms << \"ms\" << std::endl;\n\t}\n\nprivate:\n\tstd::string text;\n\tstd::chrono::steady_clock::time_point begin;\n};\n\n#ifdef WIN32\n\n#pragma optimize(\"\", off)\ntemplate \nvoid do_not_optimize_away(T* datum) {\n\tdatum = datum;\n}\n#pragma optimize(\"\", on)\n\n#else\nstatic void do_not_optimize_away(void* p) { \n\tasm volatile(\"\" : : \"g\"(p) : \"memory\");\n}\n#endif\n\nstruct singleton\n{\npublic:\n\ttypedef std::unordered_map > MapType;\n\tstatic void set(const std::string& reg_exp) { s_reg_exp = reg_exp; }\n\tstatic const std::regex& get()\n\t{\n\t\tstd::lock_guard lock(s_mutex);\n\n\t\tstd::thread::id thread_id = std::this_thread::get_id();\n\t\tMapType::iterator it = s_map.find(thread_id);\n\t\tif (it == s_map.end())\n\t\t{\n\t\t\tstd::unique_ptr p = std::unique_ptr(new char[1000]);\n\t\t\ts_map[thread_id] = std::unique_ptr(new std::regex(s_reg_exp));\n\t\t\treturn *s_map[thread_id];\n\t\t}\n\t\treturn *(it->second);\n\t}\nprivate:\n\tstatic MapType s_map;\n\tstatic std::string s_reg_exp;\n\tstatic std::mutex s_mutex;\n};\nsingleton::MapType singleton::s_map;\nstd::string singleton::s_reg_exp;\nstd::mutex singleton::s_mutex;\n\nstruct factory\n{\npublic:\n\tstatic std::unique_ptr get(const std::string& reg_exp)\n\t{\n\t\tstd::lock_guard lock(s_mutex);\n\t\tstd::unique_ptr p = std::unique_ptr(new char[1000]);\n\t\treturn std::unique_ptr(new std::regex(reg_exp));\n\t}\nprivate:\n\tstatic std::mutex s_mutex;\n};\nstd::mutex factory::s_mutex;\n\nconst std::string local_match(const std::string& text);\nconst std::string static_match(const std::string& text); \/\/ not reentrant-safe\nconst std::string singleton_match(const std::string& text);\nconst std::string factory_match(const std::string& text, const std::regex& regex);\n\nvoid parallel_invoke(int size, int threads, std::function func)\n{\n\ttypedef std::unique_ptr PtrType;\n\tstd::vector< PtrType > vec;\n\tint each = size \/ threads;\n\n\tfor (int i = 0; i < threads; ++i)\n\t{\n\t\tif (i == threads - 1) \/\/ last thread\n\t\t{\n\t\t\tvec.emplace_back(PtrType(new std::thread(func, each*i, each*(i + 1) + (size % threads))));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvec.emplace_back(PtrType(new std::thread(func, each*i, each*(i + 1) )));\n\t\t}\n\t}\n\n\tfor (size_t i = 0; i < vec.size(); ++i)\n\t{\n\t\tvec[i]->join();\n\t}\n}\n\nconst std::string REG_EXP = \".*PRICE:.*US\\\\$(\\\\d+\\\\.\\\\d+|[-+]*\\\\d+).*PER SHARE\";\n\nint main(int argc, char* argv[])\n{\n\tconst int LOOP = 1000000;\n\tstd::string str1 = \"Zoomer PRICE: US$1.23 PER SHARE\";\n\tstd::string str2 = \"Boomer PRICE: US$4.56 PER SHARE\";\n\t\n\tstd::vector vec;\n\tvec.push_back(str1);\n\tvec.push_back(str2);\n\t\n\ttimer stopwatch;\n\n\tstopwatch.start_timing(\"local regex object\");\n\tfor(int j = 0; j < LOOP; ++j)\n\t{\n\t\tfor(size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tdo_not_optimize_away(local_match(vec[i]).c_str());\n\t\t}\n\t}\n\tstopwatch.stop_timing();\n\n\tstopwatch.start_timing(\"static regex object\");\n\tfor(int j = 0; j < LOOP; ++j)\n\t{\n\t\tfor(size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tdo_not_optimize_away(static_match(vec[i]).c_str());\n\t\t}\n\t}\n\tstopwatch.stop_timing();\n\n\tsingleton::set(REG_EXP);\n\tstopwatch.start_timing(\"singleton regex object\");\n\tfor (int j = 0; j < LOOP; ++j)\n\t{\n\t\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tdo_not_optimize_away(singleton_match(vec[i]).c_str());\n\t\t}\n\t}\n\tstopwatch.stop_timing();\n\n\tstopwatch.start_timing(\"local regex object(4 threads)\");\n\tparallel_invoke(LOOP, 4, [&vec](int start, int end) {\n\t\tfor (int j = start; j < end; ++j)\n\t\t{\n\t\t\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\t\t{\n\t\t\t\tdo_not_optimize_away(local_match(vec[i]).c_str());\n\t\t\t}\n\t\t}\n\t});\n\tstopwatch.stop_timing();\n\n\tstopwatch.start_timing(\"singleton regex object(4 threads)\");\n\tparallel_invoke(LOOP, 4, [&vec] (int start, int end) {\n\t\tfor (int j = start; j < end; ++j)\n\t\t{\n\t\t\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\t\t{\n\t\t\t\tdo_not_optimize_away(singleton_match(vec[i]).c_str());\n\t\t\t}\n\t\t}\n\t});\n\tstopwatch.stop_timing();\n\n\tstopwatch.start_timing(\"factory regex object(4 threads)\");\n\tparallel_invoke(LOOP, 4, [&vec](int start, int end) {\n\t\tstd::unique_ptr ptr = factory::get(REG_EXP);\n\t\tconst std::regex& regex = *ptr;\n\n\t\tfor (int j = start; j < end; ++j)\n\t\t{\n\t\t\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\t\t{\n\t\t\t\tdo_not_optimize_away(factory_match(vec[i], regex).c_str());\n\t\t\t}\n\t\t}\n\t});\n\tstopwatch.stop_timing();\n\t\n\t\/*\n\tstd::cout << local_match(str1) << std::endl;\n\tstd::cout << local_match(str2) << std::endl;\n\tstd::cout << static_match(str1) << std::endl;\n\tstd::cout << static_match(str2) << std::endl;\n\tsingleton::set(REG_EXP);\n\tstd::cout << singleton_match(str1) << std::endl;\n\tstd::cout << singleton_match(str2) << std::endl;\n\tconst std::regex regex(REG_EXP);\n\tstd::cout << factory_match(str1, regex) << std::endl;\n\tstd::cout << factory_match(str2, regex) << std::endl;\n\t*\/\n\n\treturn 0;\n}\n\nconst std::string local_match(const std::string& text)\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tconst std::regex regex(REG_EXP);\n\tif (std::regex_match(text, what, regex))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\n\nconst std::string static_match(const std::string& text) \/\/ not reentrant-safe\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tstatic const std::regex regex(REG_EXP);\n\tif (std::regex_match(text, what, regex))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\n\nconst std::string singleton_match(const std::string& text)\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tconst std::regex& regex = singleton::get();\n\tif (std::regex_match(text, what, regex))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\n\nconst std::string factory_match(const std::string& text, const std::regex& regex)\n{\n\tstd::string ipo_price = \"\";\n\tstd::smatch what;\n\tif (std::regex_match(text, what, regex))\n\t{\n\t\tipo_price = what[1];\n\t}\n\treturn ipo_price;\n}\n<|endoftext|>"} {"text":"\/\/ MolarMass.cpp\n\/\/ This program should loop through the csv file Atomic Masses.csv and sum the masses of elements\n#include \n#include \n#include \n#include \n\/\/#include \n\n\nint main() \n{\n\tstring line; \/\/ Holds the line in the file\n\tstring element; \/\/The variable for the element being searched\n\n\tofstream myfile (\"AtomicMasses.csv\"); \/\/ Opens the file\n\n\tif (myfile.is_open())\n\t{\n\t\twhile (myfile.good()) \/\/ The resources I found online had this. Not quite sure of the nuances, but it seems to work\n\t\t{\n\t\t\tgetline(myfile, line);\/\/ Gets the current line in the file\n\t\t\tif (element == line)\n\t\t\t{\n\t\t\t\t\/\/Find a way to search through the different columns of a csv file for the atomic mass\n\t\t\t}\n\t\t}\n\t}\n\n\t\tmyfile.close();\n\n\n\telse \n\t{\n\t\tstd::cout << \"Unable to open file\\n\";\n\t}\n\n\treturn 0;\n}\nUpdate MolarMass.cpp\/\/ MolarMass.cpp\n\/\/ This program should loop through the csv file Atomic Masses.csv and sum the masses of elements\n#include \n#include \n#include \n#include \n#include \n\/\/#include \n\n\nint main() \n{\n\tstd::string line; \/\/ Holds the line in the file\n\tstd::string element; \/\/The variable for the element being searched\n\n\n\t\/\/This temporarily allows for an element to be entered for testing. \n\tstd::cin >> element;\n\t\/\/This should be removed after testing\n\n\n\tofstream myfile (\"AtomicMasses.csv\"); \/\/XKCD Undelclared Identifier\n\n\tif (myfile.is_open())\n\t{\n\t\twhile (myfile.good()) \/\/ The resources I found online had this. Not quite sure of the nuances, but it seems to work\n\t\t{\n\t\t\tgetline(myfile, line);\n\t\t\tif (std::string::find(element) != 0);\n\t\t\t{\n\t\t\t\t\/\/Function that finds a certain element in the line (in this case, the third)\n\t\t\t\tstd::string::columnValue;\n\t\t\t\t\tfor (i = 1, i <= 3, i++);\n\t\t\t\t{\n\t\t\t\t\tstd::string::find(\",\");\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\telse \n\t{\n\t\tstd::cout << \"Unable to open file\\n\";\n\t}\n\t\tmyfile.close(); \/\/Closes the file\n\t\n\t_getch();\n\n\treturn 0;\n<|endoftext|>"} {"text":"#include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP 89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\nvoid CMoveDummy::SetCollisionMask(int m)\n{\n\tm_pShape->SetCollisionMask(m);\n}\n\nint CMoveDummy::GetCollisionMask() const\n{\n\treturn m_nCollisionMask;\n}\n\nvoid CMoveDummy::SetGround(int g)\n{\n\tm_nGround = g;\n}\n\nint CMoveDummy::GetGround() const\n{\n\treturn m_nGround;\n}\n\nvoid CMoveDummy::SetCeiling(int c)\n{\n\tm_nCeiling = c;\n}\n\nint CMoveDummy::GetCeiling() const\n{\n\treturn m_nCeiling;\n}\n\nvoid CMoveDummy::SetPosition(const MathLib::vec3& p)\n{\n\tm_vPosition = p;\n}\n\nconst MathLib::vec3& CMoveDummy::GetPosition() const\n{\n\treturn m_vPosition;\n}\n\nvoid CMoveDummy::SetCollisionRadius(float radius)\n{\n\tif (!Compare(m_pShape->GetRadius(), radius))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());\n\t\tm_pShape->SetRadius(radius);\n\t}\n\n\tUpdate_Bounds();\n}\n\n\nfloat CMoveDummy::GetCollisionRadius() const\n{\n\treturn m_pShape->GetRadius();\n}\n\nvoid CMoveDummy::SetCollisionHeight(float height)\n{\n\tif (!Compare(m_pShape->GetHeight(), height))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());\n\t\tm_pShape->SetHeight(height);\n\t}\n\n\tUpdate_Bounds();\n}\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\n\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nint CMoveDummy::GetEnabled() const\n{\n\treturn m_nEnabled;\n}\n\nvoid CMoveDummy::SetVelocity(const MathLib::vec3& v)\n{\n\tm_vVelocity = v;\n}\n\nconst MathLib::vec3& CMoveDummy::GetVelocity() const\n{\n\treturn m_vVelocity;\n}\n\nvoid CMoveDummy::SetMaxVelocity(float v)\n{\n\tm_fMaxVelocity = v;\n}\nfloat CMoveDummy::GetMaxVelocity() const\n{\n\treturn m_fMaxVelocity;\n}\n\nvoid CMoveDummy::SetAcceleration(float a)\n{\n\tm_fAcceleration = a;\n}\nfloat CMoveDummy::GetAcceleration() const\n{\n\treturn m_fAcceleration;\n}\nfloat CMoveDummy::GetMaxThrough() const\n{\n\treturn m_fMaxThrough;\n}\nvoid CMoveDummy::Clear()\n{\n\tSetVelocity(vec3_zero);\n\tSetMaxVelocity(2.5f);\n\tSetAcceleration(15.0f);\n\tSetCollision(1);\n\tSetCollisionMask(1);\n\tSetGround(0);\n\tSetCeiling(0);\n\tSetPosition(vec3_zero);\n\tSetUp(vec3(0.0f, 0.0f, 1.0f));\n\tSetEnabled(1);\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\tm_pShape->SetExclusionMask(2);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\n\tSetCollisionRadius(0.5f);\n\tSetCollisionHeight(1.0f);\n\n\n\tSetMaxThrough(0.4f);\n\n\tm_vecContacts.Clear();\n\n}\nSigned-off-by: mrlitong #include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP 89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\nvoid CMoveDummy::SetCollisionMask(int m)\n{\n\tm_pShape->SetCollisionMask(m);\n}\n\nint CMoveDummy::GetCollisionMask() const\n{\n\treturn m_nCollisionMask;\n}\n\nvoid CMoveDummy::SetGround(int g)\n{\n\tm_nGround = g;\n}\n\nint CMoveDummy::GetGround() const\n{\n\treturn m_nGround;\n}\n\nvoid CMoveDummy::SetCeiling(int c)\n{\n\tm_nCeiling = c;\n}\n\nint CMoveDummy::GetCeiling() const\n{\n\treturn m_nCeiling;\n}\n\nvoid CMoveDummy::SetPosition(const MathLib::vec3& p)\n{\n\tm_vPosition = p;\n}\n\nconst MathLib::vec3& CMoveDummy::GetPosition() const\n{\n\treturn m_vPosition;\n}\n\nvoid CMoveDummy::SetCollisionRadius(float radius)\n{\n\tif (!Compare(m_pShape->GetRadius(), radius))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());\n\t\tm_pShape->SetRadius(radius);\n\t}\n\n\tUpdate_Bounds();\n}\n\n\nfloat CMoveDummy::GetCollisionRadius() const\n{\n\treturn m_pShape->GetRadius();\n}\n\nvoid CMoveDummy::SetCollisionHeight(float height)\n{\n\tif (!Compare(m_pShape->GetHeight(), height))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());\n\t\tm_pShape->SetHeight(height);\n\t}\n\n\tUpdate_Bounds();\n}\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\n\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nint CMoveDummy::GetEnabled() const\n{\n\treturn m_nEnabled;\n}\n\nvoid CMoveDummy::SetVelocity(const MathLib::vec3& v)\n{\n\tm_vVelocity = v;\n}\n\nconst MathLib::vec3& CMoveDummy::GetVelocity() const\n{\n\treturn m_vVelocity;\n}\n\nvoid CMoveDummy::SetMaxVelocity(float v)\n{\n\tm_fMaxVelocity = v;\n}\nfloat CMoveDummy::GetMaxVelocity() const\n{\n\treturn m_fMaxVelocity;\n}\n\nvoid CMoveDummy::SetAcceleration(float a)\n{\n\tm_fAcceleration = a;\n}\nfloat CMoveDummy::GetAcceleration() const\n{\n\treturn m_fAcceleration;\n}\nfloat CMoveDummy::GetMaxThrough() const\n{\n\treturn m_fMaxThrough;\n}\nvoid CMoveDummy::Clear()\n{\n\tSetVelocity(vec3_zero);\n\tSetMaxVelocity(2.5f);\n\tSetAcceleration(15.0f);\n\tSetCollision(1);\n\tSetCollisionMask(1);\n\tSetGround(0);\n\tSetCeiling(0);\n\tSetPosition(vec3_zero);\n\tSetUp(vec3(0.0f, 0.0f, 1.0f));\n\tSetEnabled(1);\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\tm_pShape->SetExclusionMask(2);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\n\tSetCollisionRadius(0.5f);\n\tSetCollisionHeight(1.0f);\n\n\n\tSetMaxThrough(0.4f);\n\n\tm_vecContacts.Clear();\n\n}\nint CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection)\n{\n\treturn Update(fIfps, vDirection, m_vPosition);\n}<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2020 The Android Open Source Project\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 \"src\/trace_processor\/dynamic\/thread_state_generator.h\"\n\n#include \n#include \n\n#include \"src\/trace_processor\/containers\/row_map.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nThreadStateGenerator::ThreadStateGenerator(TraceProcessorContext* context)\n : running_string_id_(context->storage->InternString(\"Running\")),\n runnable_string_id_(context->storage->InternString(\"R\")),\n context_(context) {}\n\nThreadStateGenerator::~ThreadStateGenerator() = default;\n\nutil::Status ThreadStateGenerator::ValidateConstraints(\n const QueryConstraints&) {\n return util::OkStatus();\n}\n\nstd::unique_ptr ThreadStateGenerator::ComputeTable(\n const std::vector&,\n const std::vector&) {\n if (!unsorted_thread_state_table_) {\n int64_t trace_end_ts =\n context_->storage->GetTraceTimestampBoundsNs().second;\n\n unsorted_thread_state_table_ = ComputeThreadStateTable(trace_end_ts);\n\n \/\/ We explicitly sort by ts here as ComputeThreadStateTable does not insert\n \/\/ rows in sorted order but we expect our clients to always want to sort\n \/\/ on ts. Writing ComputeThreadStateTable to insert in sorted order is\n \/\/ more trouble than its worth.\n sorted_thread_state_table_ = unsorted_thread_state_table_->Sort(\n {unsorted_thread_state_table_->ts().ascending()});\n }\n PERFETTO_CHECK(sorted_thread_state_table_);\n return std::unique_ptr
(new Table(sorted_thread_state_table_->Copy()));\n}\n\nstd::unique_ptr\nThreadStateGenerator::ComputeThreadStateTable(int64_t trace_end_ts) {\n std::unique_ptr table(new tables::ThreadStateTable(\n context_->storage->mutable_string_pool(), nullptr));\n\n const auto& raw_sched = context_->storage->sched_slice_table();\n const auto& instants = context_->storage->instant_table();\n\n \/\/ In both tables, exclude utid == 0 which represents the idle thread.\n Table sched = raw_sched.Filter({raw_sched.utid().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n Table waking = instants.Filter(\n {instants.name().eq(\"sched_waking\"), instants.ref().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n\n \/\/ We prefer to use waking if at all possible and fall back to wakeup if not\n \/\/ available.\n if (waking.row_count() == 0) {\n waking = instants.Filter(\n {instants.name().eq(\"sched_wakeup\"), instants.ref().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n }\n\n Table sched_blocked_reason = instants.Filter(\n {instants.name().eq(\"sched_blocked_reason\"), instants.ref().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n\n const auto& sched_ts_col = sched.GetTypedColumnByName(\"ts\");\n const auto& waking_ts_col = waking.GetTypedColumnByName(\"ts\");\n const auto& blocked_ts_col =\n sched_blocked_reason.GetTypedColumnByName(\"ts\");\n\n uint32_t sched_idx = 0;\n uint32_t waking_idx = 0;\n uint32_t blocked_idx = 0;\n std::unordered_map state_map;\n while (sched_idx < sched.row_count() || waking_idx < waking.row_count() ||\n blocked_idx < sched_blocked_reason.row_count()) {\n int64_t sched_ts = sched_idx < sched.row_count()\n ? sched_ts_col[sched_idx]\n : std::numeric_limits::max();\n int64_t waking_ts = waking_idx < waking.row_count()\n ? waking_ts_col[waking_idx]\n : std::numeric_limits::max();\n int64_t blocked_ts = blocked_idx < sched_blocked_reason.row_count()\n ? blocked_ts_col[blocked_idx]\n : std::numeric_limits::max();\n\n \/\/ We go through all tables, picking the earliest timestamp from any\n \/\/ to process that event.\n int64_t min_ts = std::min({sched_ts, waking_ts, blocked_ts});\n if (min_ts == sched_ts) {\n AddSchedEvent(sched, sched_idx++, state_map, trace_end_ts, table.get());\n } else if (min_ts == waking_ts) {\n AddWakingEvent(waking, waking_idx++, state_map);\n } else \/* (min_ts == blocked_ts) *\/ {\n AddBlockedReasonEvent(sched_blocked_reason, blocked_idx++, state_map);\n }\n }\n\n \/\/ At the end, go through and flush any remaining pending events.\n for (const auto& utid_to_pending_info : state_map) {\n UniqueTid utid = utid_to_pending_info.first;\n const ThreadSchedInfo& pending_info = utid_to_pending_info.second;\n FlushPendingEventsForThread(utid, pending_info, table.get(), base::nullopt);\n }\n\n return table;\n}\n\nvoid ThreadStateGenerator::AddSchedEvent(\n const Table& sched,\n uint32_t sched_idx,\n std::unordered_map& state_map,\n int64_t trace_end_ts,\n tables::ThreadStateTable* table) {\n int64_t ts = sched.GetTypedColumnByName(\"ts\")[sched_idx];\n UniqueTid utid = sched.GetTypedColumnByName(\"utid\")[sched_idx];\n ThreadSchedInfo* info = &state_map[utid];\n\n \/\/ Due to races in the kernel, it is possible for the same thread to be\n \/\/ scheduled on different CPUs at the same time. This will manifest itself\n \/\/ here by having |info->desched_ts| in the future of this scheduling slice\n \/\/ (i.e. there was a scheduling slice in the past which ended after the start\n \/\/ of the current scheduling slice).\n \/\/\n \/\/ We work around this problem by truncating the previous slice to the start\n \/\/ of this slice and not adding the descheduled slice (i.e. we don't call\n \/\/ |FlushPendingEventsForThread| which adds this slice).\n \/\/\n \/\/ See b\/186509316 for details and an example on when this happens.\n if (info->desched_ts && info->desched_ts.value() > ts) {\n uint32_t prev_sched_row = info->scheduled_row.value();\n int64_t prev_sched_start = table->ts()[prev_sched_row];\n\n \/\/ Just a double check that descheduling slice would have started at the\n \/\/ same time the scheduling slice would have ended.\n PERFETTO_DCHECK(prev_sched_start + table->dur()[prev_sched_row] ==\n info->desched_ts.value());\n\n \/\/ Truncate the duration of the old slice to end at the start of this\n \/\/ scheduling slice.\n table->mutable_dur()->Set(prev_sched_row, ts - prev_sched_start);\n } else {\n FlushPendingEventsForThread(utid, *info, table, ts);\n }\n\n \/\/ Reset so we don't have any leftover data on the next round.\n *info = {};\n\n \/\/ Undo the expansion of the final sched slice for each CPU to the end of the\n \/\/ trace by setting the duration back to -1. This counteracts the code in\n \/\/ SchedEventTracker::FlushPendingEvents\n \/\/ TODO(lalitm): remove this hack when we stop expanding the last slice to the\n \/\/ end of the trace.\n int64_t dur = sched.GetTypedColumnByName(\"dur\")[sched_idx];\n if (ts + dur == trace_end_ts) {\n dur = -1;\n }\n\n \/\/ Now add the sched slice itself as \"Running\" with the other fields\n \/\/ unchanged.\n tables::ThreadStateTable::Row sched_row;\n sched_row.ts = ts;\n sched_row.dur = dur;\n sched_row.cpu = sched.GetTypedColumnByName(\"cpu\")[sched_idx];\n sched_row.state = running_string_id_;\n sched_row.utid = utid;\n\n auto id_and_row = table->Insert(sched_row);\n\n \/\/ If the sched row had a negative duration, don't add any descheduled slice\n \/\/ because it would be meaningless.\n if (sched_row.dur == -1) {\n return;\n }\n\n \/\/ This will be flushed to the table on the next sched slice (or the very end\n \/\/ of the big loop).\n info->desched_ts = ts + dur;\n info->desched_end_state =\n sched.GetTypedColumnByName(\"end_state\")[sched_idx];\n info->scheduled_row = id_and_row.row;\n}\n\nvoid ThreadStateGenerator::AddWakingEvent(\n const Table& waking,\n uint32_t waking_idx,\n std::unordered_map& state_map) {\n int64_t ts = waking.GetTypedColumnByName(\"ts\")[waking_idx];\n UniqueTid utid = static_cast(\n waking.GetTypedColumnByName(\"ref\")[waking_idx]);\n ThreadSchedInfo* info = &state_map[utid];\n\n \/\/ Occasionally, it is possible to get a waking event for a thread\n \/\/ which is already in a runnable state. When this happens, we just\n \/\/ ignore the waking event.\n \/\/ See b\/186509316 for details and an example on when this happens.\n if (info->desched_end_state &&\n *info->desched_end_state == runnable_string_id_) {\n return;\n }\n\n \/\/ As counter-intuitive as it seems, occasionally we can get a waking\n \/\/ event for a thread which is currently running.\n \/\/\n \/\/ There are two cases when this can happen:\n \/\/ 1. The kernel legitimately send a waking event for a \"running\" thread\n \/\/ because the thread was woken up before the kernel switched away\n \/\/ from it. In this case, the waking timestamp will be in the past\n \/\/ because we added the descheduled slice when we processed the sched\n \/\/ event.\n \/\/ 2. We're close to the end of the trace or had data-loss and we missed\n \/\/ the switch out event for a thread but we see a waking after.\n\n \/\/ Case 1 described above. In this situation, we should drop the waking\n \/\/ entirely.\n if (info->desched_ts && *info->desched_ts > ts) {\n return;\n }\n\n \/\/ For case 2 and otherwise, we should just note the fact that the thread\n \/\/ became runnable at this time. Note that we cannot check if runnable is\n \/\/ already not set because we could have data-loss which leads to us getting\n \/\/ back to back waking for a single thread.\n info->runnable_ts = ts;\n}\n\nTable::Schema ThreadStateGenerator::CreateSchema() {\n auto schema = tables::ThreadStateTable::Schema();\n\n \/\/ Because we expect our users to generally want ordered by ts, we set the\n \/\/ ordering for the schema to match our forced sort pass in ComputeTable.\n auto ts_it = std::find_if(\n schema.columns.begin(), schema.columns.end(),\n [](const Table::Schema::Column& col) { return col.name == \"ts\"; });\n ts_it->is_sorted = true;\n auto id_it = std::find_if(\n schema.columns.begin(), schema.columns.end(),\n [](const Table::Schema::Column& col) { return col.name == \"id\"; });\n id_it->is_sorted = false;\n\n return schema;\n}\n\nvoid ThreadStateGenerator::FlushPendingEventsForThread(\n UniqueTid utid,\n const ThreadSchedInfo& info,\n tables::ThreadStateTable* table,\n base::Optional end_ts) {\n \/\/ First, let's flush the descheduled period (if any) to the table.\n if (info.desched_ts) {\n PERFETTO_DCHECK(info.desched_end_state);\n\n int64_t dur;\n if (end_ts) {\n int64_t desched_end_ts = info.runnable_ts ? *info.runnable_ts : *end_ts;\n dur = desched_end_ts - *info.desched_ts;\n } else {\n dur = -1;\n }\n\n tables::ThreadStateTable::Row row;\n row.ts = *info.desched_ts;\n row.dur = dur;\n row.state = *info.desched_end_state;\n row.utid = utid;\n row.io_wait = info.io_wait;\n row.blocked_function = info.blocked_function;\n table->Insert(row);\n }\n\n \/\/ Next, flush the runnable period (if any) to the table.\n if (info.runnable_ts) {\n tables::ThreadStateTable::Row row;\n row.ts = *info.runnable_ts;\n row.dur = end_ts ? *end_ts - row.ts : -1;\n row.state = runnable_string_id_;\n row.utid = utid;\n table->Insert(row);\n }\n}\n\nvoid ThreadStateGenerator::AddBlockedReasonEvent(\n const Table& blocked_reason,\n uint32_t blocked_idx,\n std::unordered_map& state_map) {\n const auto& utid_col = blocked_reason.GetTypedColumnByName(\"ref\");\n const auto& arg_set_id_col =\n blocked_reason.GetTypedColumnByName(\"arg_set_id\");\n\n UniqueTid utid = static_cast(utid_col[blocked_idx]);\n uint32_t arg_set_id = arg_set_id_col[blocked_idx];\n ThreadSchedInfo& info = state_map[utid];\n\n base::Optional opt_value;\n util::Status status =\n context_->storage->ExtractArg(arg_set_id, \"io_wait\", &opt_value);\n\n \/\/ We can't do anything better than ignoring any errors here.\n \/\/ TODO(lalitm): see if there's a better way to handle this.\n if (status.ok() && opt_value) {\n PERFETTO_CHECK(opt_value->type == Variadic::Type::kBool);\n info.io_wait = opt_value->bool_value;\n }\n\n status = context_->storage->ExtractArg(arg_set_id, \"function\", &opt_value);\n if (status.ok() && opt_value) {\n PERFETTO_CHECK(opt_value->type == Variadic::Type::kString);\n info.blocked_function = opt_value->string_value;\n }\n}\n\nstd::string ThreadStateGenerator::TableName() {\n return \"thread_state\";\n}\n\nuint32_t ThreadStateGenerator::EstimateRowCount() {\n return context_->storage->sched_slice_table().row_count();\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\ntp: fix compile am: 82b99102e5 am: 5203a5a811 am: fd975182a2\/*\n * Copyright (C) 2020 The Android Open Source Project\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 \"src\/trace_processor\/dynamic\/thread_state_generator.h\"\n\n#include \n#include \n\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nThreadStateGenerator::ThreadStateGenerator(TraceProcessorContext* context)\n : running_string_id_(context->storage->InternString(\"Running\")),\n runnable_string_id_(context->storage->InternString(\"R\")),\n context_(context) {}\n\nThreadStateGenerator::~ThreadStateGenerator() = default;\n\nutil::Status ThreadStateGenerator::ValidateConstraints(\n const QueryConstraints&) {\n return util::OkStatus();\n}\n\nstd::unique_ptr
ThreadStateGenerator::ComputeTable(\n const std::vector&,\n const std::vector&) {\n if (!unsorted_thread_state_table_) {\n int64_t trace_end_ts =\n context_->storage->GetTraceTimestampBoundsNs().second;\n\n unsorted_thread_state_table_ = ComputeThreadStateTable(trace_end_ts);\n\n \/\/ We explicitly sort by ts here as ComputeThreadStateTable does not insert\n \/\/ rows in sorted order but we expect our clients to always want to sort\n \/\/ on ts. Writing ComputeThreadStateTable to insert in sorted order is\n \/\/ more trouble than its worth.\n sorted_thread_state_table_ = unsorted_thread_state_table_->Sort(\n {unsorted_thread_state_table_->ts().ascending()});\n }\n PERFETTO_CHECK(sorted_thread_state_table_);\n return std::unique_ptr
(new Table(sorted_thread_state_table_->Copy()));\n}\n\nstd::unique_ptr\nThreadStateGenerator::ComputeThreadStateTable(int64_t trace_end_ts) {\n std::unique_ptr table(new tables::ThreadStateTable(\n context_->storage->mutable_string_pool(), nullptr));\n\n const auto& raw_sched = context_->storage->sched_slice_table();\n const auto& instants = context_->storage->instant_table();\n\n \/\/ In both tables, exclude utid == 0 which represents the idle thread.\n Table sched = raw_sched.Filter({raw_sched.utid().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n Table waking = instants.Filter(\n {instants.name().eq(\"sched_waking\"), instants.ref().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n\n \/\/ We prefer to use waking if at all possible and fall back to wakeup if not\n \/\/ available.\n if (waking.row_count() == 0) {\n waking = instants.Filter(\n {instants.name().eq(\"sched_wakeup\"), instants.ref().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n }\n\n Table sched_blocked_reason = instants.Filter(\n {instants.name().eq(\"sched_blocked_reason\"), instants.ref().ne(0)},\n RowMap::OptimizeFor::kLookupSpeed);\n\n const auto& sched_ts_col = sched.GetTypedColumnByName(\"ts\");\n const auto& waking_ts_col = waking.GetTypedColumnByName(\"ts\");\n const auto& blocked_ts_col =\n sched_blocked_reason.GetTypedColumnByName(\"ts\");\n\n uint32_t sched_idx = 0;\n uint32_t waking_idx = 0;\n uint32_t blocked_idx = 0;\n std::unordered_map state_map;\n while (sched_idx < sched.row_count() || waking_idx < waking.row_count() ||\n blocked_idx < sched_blocked_reason.row_count()) {\n int64_t sched_ts = sched_idx < sched.row_count()\n ? sched_ts_col[sched_idx]\n : std::numeric_limits::max();\n int64_t waking_ts = waking_idx < waking.row_count()\n ? waking_ts_col[waking_idx]\n : std::numeric_limits::max();\n int64_t blocked_ts = blocked_idx < sched_blocked_reason.row_count()\n ? blocked_ts_col[blocked_idx]\n : std::numeric_limits::max();\n\n \/\/ We go through all tables, picking the earliest timestamp from any\n \/\/ to process that event.\n int64_t min_ts = std::min({sched_ts, waking_ts, blocked_ts});\n if (min_ts == sched_ts) {\n AddSchedEvent(sched, sched_idx++, state_map, trace_end_ts, table.get());\n } else if (min_ts == waking_ts) {\n AddWakingEvent(waking, waking_idx++, state_map);\n } else \/* (min_ts == blocked_ts) *\/ {\n AddBlockedReasonEvent(sched_blocked_reason, blocked_idx++, state_map);\n }\n }\n\n \/\/ At the end, go through and flush any remaining pending events.\n for (const auto& utid_to_pending_info : state_map) {\n UniqueTid utid = utid_to_pending_info.first;\n const ThreadSchedInfo& pending_info = utid_to_pending_info.second;\n FlushPendingEventsForThread(utid, pending_info, table.get(), base::nullopt);\n }\n\n return table;\n}\n\nvoid ThreadStateGenerator::AddSchedEvent(\n const Table& sched,\n uint32_t sched_idx,\n std::unordered_map& state_map,\n int64_t trace_end_ts,\n tables::ThreadStateTable* table) {\n int64_t ts = sched.GetTypedColumnByName(\"ts\")[sched_idx];\n UniqueTid utid = sched.GetTypedColumnByName(\"utid\")[sched_idx];\n ThreadSchedInfo* info = &state_map[utid];\n\n \/\/ Due to races in the kernel, it is possible for the same thread to be\n \/\/ scheduled on different CPUs at the same time. This will manifest itself\n \/\/ here by having |info->desched_ts| in the future of this scheduling slice\n \/\/ (i.e. there was a scheduling slice in the past which ended after the start\n \/\/ of the current scheduling slice).\n \/\/\n \/\/ We work around this problem by truncating the previous slice to the start\n \/\/ of this slice and not adding the descheduled slice (i.e. we don't call\n \/\/ |FlushPendingEventsForThread| which adds this slice).\n \/\/\n \/\/ See b\/186509316 for details and an example on when this happens.\n if (info->desched_ts && info->desched_ts.value() > ts) {\n uint32_t prev_sched_row = info->scheduled_row.value();\n int64_t prev_sched_start = table->ts()[prev_sched_row];\n\n \/\/ Just a double check that descheduling slice would have started at the\n \/\/ same time the scheduling slice would have ended.\n PERFETTO_DCHECK(prev_sched_start + table->dur()[prev_sched_row] ==\n info->desched_ts.value());\n\n \/\/ Truncate the duration of the old slice to end at the start of this\n \/\/ scheduling slice.\n table->mutable_dur()->Set(prev_sched_row, ts - prev_sched_start);\n } else {\n FlushPendingEventsForThread(utid, *info, table, ts);\n }\n\n \/\/ Reset so we don't have any leftover data on the next round.\n *info = {};\n\n \/\/ Undo the expansion of the final sched slice for each CPU to the end of the\n \/\/ trace by setting the duration back to -1. This counteracts the code in\n \/\/ SchedEventTracker::FlushPendingEvents\n \/\/ TODO(lalitm): remove this hack when we stop expanding the last slice to the\n \/\/ end of the trace.\n int64_t dur = sched.GetTypedColumnByName(\"dur\")[sched_idx];\n if (ts + dur == trace_end_ts) {\n dur = -1;\n }\n\n \/\/ Now add the sched slice itself as \"Running\" with the other fields\n \/\/ unchanged.\n tables::ThreadStateTable::Row sched_row;\n sched_row.ts = ts;\n sched_row.dur = dur;\n sched_row.cpu = sched.GetTypedColumnByName(\"cpu\")[sched_idx];\n sched_row.state = running_string_id_;\n sched_row.utid = utid;\n\n auto id_and_row = table->Insert(sched_row);\n\n \/\/ If the sched row had a negative duration, don't add any descheduled slice\n \/\/ because it would be meaningless.\n if (sched_row.dur == -1) {\n return;\n }\n\n \/\/ This will be flushed to the table on the next sched slice (or the very end\n \/\/ of the big loop).\n info->desched_ts = ts + dur;\n info->desched_end_state =\n sched.GetTypedColumnByName(\"end_state\")[sched_idx];\n info->scheduled_row = id_and_row.row;\n}\n\nvoid ThreadStateGenerator::AddWakingEvent(\n const Table& waking,\n uint32_t waking_idx,\n std::unordered_map& state_map) {\n int64_t ts = waking.GetTypedColumnByName(\"ts\")[waking_idx];\n UniqueTid utid = static_cast(\n waking.GetTypedColumnByName(\"ref\")[waking_idx]);\n ThreadSchedInfo* info = &state_map[utid];\n\n \/\/ Occasionally, it is possible to get a waking event for a thread\n \/\/ which is already in a runnable state. When this happens, we just\n \/\/ ignore the waking event.\n \/\/ See b\/186509316 for details and an example on when this happens.\n if (info->desched_end_state &&\n *info->desched_end_state == runnable_string_id_) {\n return;\n }\n\n \/\/ As counter-intuitive as it seems, occasionally we can get a waking\n \/\/ event for a thread which is currently running.\n \/\/\n \/\/ There are two cases when this can happen:\n \/\/ 1. The kernel legitimately send a waking event for a \"running\" thread\n \/\/ because the thread was woken up before the kernel switched away\n \/\/ from it. In this case, the waking timestamp will be in the past\n \/\/ because we added the descheduled slice when we processed the sched\n \/\/ event.\n \/\/ 2. We're close to the end of the trace or had data-loss and we missed\n \/\/ the switch out event for a thread but we see a waking after.\n\n \/\/ Case 1 described above. In this situation, we should drop the waking\n \/\/ entirely.\n if (info->desched_ts && *info->desched_ts > ts) {\n return;\n }\n\n \/\/ For case 2 and otherwise, we should just note the fact that the thread\n \/\/ became runnable at this time. Note that we cannot check if runnable is\n \/\/ already not set because we could have data-loss which leads to us getting\n \/\/ back to back waking for a single thread.\n info->runnable_ts = ts;\n}\n\nTable::Schema ThreadStateGenerator::CreateSchema() {\n auto schema = tables::ThreadStateTable::Schema();\n\n \/\/ Because we expect our users to generally want ordered by ts, we set the\n \/\/ ordering for the schema to match our forced sort pass in ComputeTable.\n auto ts_it = std::find_if(\n schema.columns.begin(), schema.columns.end(),\n [](const Table::Schema::Column& col) { return col.name == \"ts\"; });\n ts_it->is_sorted = true;\n auto id_it = std::find_if(\n schema.columns.begin(), schema.columns.end(),\n [](const Table::Schema::Column& col) { return col.name == \"id\"; });\n id_it->is_sorted = false;\n\n return schema;\n}\n\nvoid ThreadStateGenerator::FlushPendingEventsForThread(\n UniqueTid utid,\n const ThreadSchedInfo& info,\n tables::ThreadStateTable* table,\n base::Optional end_ts) {\n \/\/ First, let's flush the descheduled period (if any) to the table.\n if (info.desched_ts) {\n PERFETTO_DCHECK(info.desched_end_state);\n\n int64_t dur;\n if (end_ts) {\n int64_t desched_end_ts = info.runnable_ts ? *info.runnable_ts : *end_ts;\n dur = desched_end_ts - *info.desched_ts;\n } else {\n dur = -1;\n }\n\n tables::ThreadStateTable::Row row;\n row.ts = *info.desched_ts;\n row.dur = dur;\n row.state = *info.desched_end_state;\n row.utid = utid;\n row.io_wait = info.io_wait;\n row.blocked_function = info.blocked_function;\n table->Insert(row);\n }\n\n \/\/ Next, flush the runnable period (if any) to the table.\n if (info.runnable_ts) {\n tables::ThreadStateTable::Row row;\n row.ts = *info.runnable_ts;\n row.dur = end_ts ? *end_ts - row.ts : -1;\n row.state = runnable_string_id_;\n row.utid = utid;\n table->Insert(row);\n }\n}\n\nvoid ThreadStateGenerator::AddBlockedReasonEvent(\n const Table& blocked_reason,\n uint32_t blocked_idx,\n std::unordered_map& state_map) {\n const auto& utid_col = blocked_reason.GetTypedColumnByName(\"ref\");\n const auto& arg_set_id_col =\n blocked_reason.GetTypedColumnByName(\"arg_set_id\");\n\n UniqueTid utid = static_cast(utid_col[blocked_idx]);\n uint32_t arg_set_id = arg_set_id_col[blocked_idx];\n ThreadSchedInfo& info = state_map[utid];\n\n base::Optional opt_value;\n util::Status status =\n context_->storage->ExtractArg(arg_set_id, \"io_wait\", &opt_value);\n\n \/\/ We can't do anything better than ignoring any errors here.\n \/\/ TODO(lalitm): see if there's a better way to handle this.\n if (status.ok() && opt_value) {\n PERFETTO_CHECK(opt_value->type == Variadic::Type::kBool);\n info.io_wait = opt_value->bool_value;\n }\n\n status = context_->storage->ExtractArg(arg_set_id, \"function\", &opt_value);\n if (status.ok() && opt_value) {\n PERFETTO_CHECK(opt_value->type == Variadic::Type::kString);\n info.blocked_function = opt_value->string_value;\n }\n}\n\nstd::string ThreadStateGenerator::TableName() {\n return \"thread_state\";\n}\n\nuint32_t ThreadStateGenerator::EstimateRowCount() {\n return context_->storage->sched_slice_table().row_count();\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2019 The Android Open Source Project\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 \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include \n\n#include \n#include \n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n : context_(ctx),\n trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector& clocks) {\n const auto snapshot_id = cur_snapshot_id_++;\n\n \/\/ Clear the cache\n cache_.fill({});\n\n \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n \/\/ used by the clock pathfinding logic.\n base::Hash hasher;\n for (const auto& clock : clocks)\n hasher.Update(clock.clock_id);\n const auto snapshot_hash = static_cast(hasher.digest());\n\n \/\/ Add a new entry in each clock's snapshot vector.\n for (const auto& clock : clocks) {\n ClockId clock_id = clock.clock_id;\n ClockDomain& domain = clocks_[clock_id];\n if (domain.snapshots.empty()) {\n if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n \" cannot use incremental encoding; this is only \"\n \"supported for sequence-scoped clocks.\",\n clock_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n domain.is_incremental = clock.is_incremental;\n } else if (PERFETTO_UNLIKELY(\n domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n domain.is_incremental != clock.is_incremental)) {\n PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n \" (unit=%\" PRIu64\n \", incremental=%d), was previously registered with \"\n \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n domain.unit_multiplier_ns, domain.is_incremental);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n const int64_t timestamp_ns =\n clock.absolute_timestamp * domain.unit_multiplier_ns;\n domain.last_timestamp_ns = timestamp_ns;\n\n ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n if (!vect.snapshot_ids.empty() &&\n PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n \" at snapshot %\" PRIu32 \".\",\n clock_id, snapshot_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n \/\/ this function.\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n \/\/ Snapshot IDs must be always monotonic.\n PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n vect.snapshot_ids.back() < snapshot_id);\n\n if (!vect.timestamps_ns.empty() &&\n timestamp_ns < vect.timestamps_ns.back()) {\n \/\/ Clock is not monotonic.\n\n if (clock_id == trace_time_clock_id_) {\n \/\/ The trace clock cannot be non-monotonic.\n PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n \" not >= %\" PRId64 \".\",\n clock_id, snapshot_id, timestamp_ns,\n vect.timestamps_ns.back());\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n \/\/ For the other clocks the best thing we can do is mark it as\n \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n \/\/ graph. We can still use it as a target clock, but not viceversa.\n \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n \/\/ daylight saving. We can still answer the question \"what was the\n \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n \/\/ same REALTIME instant because of the 1:many relationship.\n non_monotonic_clocks_.insert(clock_id);\n\n \/\/ Erase all edges from the graph that start from this clock (but keep the\n \/\/ ones that end on this clock).\n auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n graph_.erase(begin, end);\n }\n vect.snapshot_ids.emplace_back(snapshot_id);\n vect.timestamps_ns.emplace_back(timestamp_ns);\n }\n\n \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n \/\/ This is to store the information: Clock A is syncable to Clock B via the\n \/\/ snapshots of type (hash).\n \/\/ Clocks that were previously marked as non-monotonic won't be added as\n \/\/ valid sources.\n for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n auto it2 = it1;\n ++it2;\n for (; it2 != clocks.end(); ++it2) {\n if (!non_monotonic_clocks_.count(it1->clock_id))\n graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n if (!non_monotonic_clocks_.count(it2->clock_id))\n graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n }\n }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n \/\/ This is a classic breadth-first search. Each node in the queue holds also\n \/\/ the full path to reach that node.\n \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n \/\/ stop the search anyways.\n PERFETTO_CHECK(src != target);\n std::queue queue;\n queue.emplace(src);\n\n while (!queue.empty()) {\n ClockPath cur_path = queue.front();\n queue.pop();\n\n const ClockId cur_clock_id = cur_path.last;\n if (cur_clock_id == target)\n return cur_path;\n\n if (cur_path.len >= ClockPath::kMaxLen)\n continue;\n\n \/\/ Expore all the adjacent clocks.\n \/\/ The lower_bound() below returns an iterator to the first edge that starts\n \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n ClockGraphEdge(cur_clock_id, 0, 0));\n it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n ClockId next_clock_id = std::get<1>(*it);\n SnapshotHash hash = std::get<2>(*it);\n queue.push(ClockPath(cur_path, next_clock_id, hash));\n }\n }\n return ClockPath(); \/\/ invalid path.\n}\n\nbase::Optional ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n int64_t src_timestamp,\n ClockId target_clock_id) {\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n ClockPath path = FindPath(src_clock_id, target_clock_id);\n if (!path.valid()) {\n PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n \" at timestamp %\" PRId64,\n src_clock_id, target_clock_id, src_timestamp);\n context_->storage->IncrementStats(stats::clock_sync_failure);\n return base::nullopt;\n }\n\n \/\/ We can cache only single-path resolutions between two clocks.\n \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n \/\/ too frequent these days, so we focus only on caching the more frequent\n \/\/ one-step resolutions (typically from any clock to the trace clock).\n const bool cacheable = path.len == 1;\n CachedClockPath cache_entry{};\n\n \/\/ Iterate trough the path found and translate timestamps onto the new clock\n \/\/ domain on each step, until the target domain is reached.\n ClockDomain* src_domain = GetClock(src_clock_id);\n int64_t ns = src_domain->ToNs(src_timestamp);\n for (uint32_t i = 0; i < path.len; ++i) {\n const ClockGraphEdge edge = path.at(i);\n ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n ClockDomain* next_clock = GetClock(std::get<1>(edge));\n const SnapshotHash hash = std::get<2>(edge);\n\n \/\/ Find the closest timestamp within the snapshots of the source clock.\n const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n const auto& ts_vec = cur_snap.timestamps_ns;\n auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n if (it != ts_vec.begin())\n --it;\n\n \/\/ Now lookup the snapshot id that matches the closest timestamp.\n size_t index = static_cast(std::distance(ts_vec.begin(), it));\n PERFETTO_DCHECK(index < ts_vec.size());\n PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n \/\/ And use that to retrieve the corresponding time in the next clock domain.\n \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n \/\/ either the hash logic or the pathfinding logic are bugged.\n \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n \/\/ of the snapshot.\n const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n \/\/ a binary search. std::find would do a linear scan.\n auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n next_snap.snapshot_ids.end(), snapshot_id);\n if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n continue;\n }\n size_t next_index = static_cast(\n std::distance(next_snap.snapshot_ids.begin(), next_it));\n PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n \/\/ The translated timestamp is the relative delta of the source timestamp\n \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n \/\/ the new clock domain for the same snapshot id.\n const int64_t adj = next_timestamp_ns - *it;\n ns += adj;\n\n \/\/ On the first iteration, keep track of the bounds for the cache entry.\n \/\/ This will allow future Convert() calls to skip the pathfinder logic\n \/\/ as long as the query stays within the bound.\n if (cacheable) {\n PERFETTO_DCHECK(i == 0);\n const int64_t kInt64Min = std::numeric_limits::min();\n const int64_t kInt64Max = std::numeric_limits::max();\n cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n auto ubound = it + 1;\n cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n cache_entry.translation_ns = adj;\n }\n\n \/\/ The last clock in the path must be the target clock.\n PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n }\n\n if (cacheable) {\n cache_entry.src = src_clock_id;\n cache_entry.src_domain = src_domain;\n cache_entry.target = target_clock_id;\n cache_[rnd_() % cache_.size()] = cache_entry;\n }\n\n return ns;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\nRemove log that spams tests\/*\n * Copyright (C) 2019 The Android Open Source Project\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 \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include \n\n#include \n#include \n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n : context_(ctx),\n trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector& clocks) {\n const auto snapshot_id = cur_snapshot_id_++;\n\n \/\/ Clear the cache\n cache_.fill({});\n\n \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n \/\/ used by the clock pathfinding logic.\n base::Hash hasher;\n for (const auto& clock : clocks)\n hasher.Update(clock.clock_id);\n const auto snapshot_hash = static_cast(hasher.digest());\n\n \/\/ Add a new entry in each clock's snapshot vector.\n for (const auto& clock : clocks) {\n ClockId clock_id = clock.clock_id;\n ClockDomain& domain = clocks_[clock_id];\n if (domain.snapshots.empty()) {\n if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n \" cannot use incremental encoding; this is only \"\n \"supported for sequence-scoped clocks.\",\n clock_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n domain.is_incremental = clock.is_incremental;\n } else if (PERFETTO_UNLIKELY(\n domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n domain.is_incremental != clock.is_incremental)) {\n PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n \" (unit=%\" PRIu64\n \", incremental=%d), was previously registered with \"\n \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n domain.unit_multiplier_ns, domain.is_incremental);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n const int64_t timestamp_ns =\n clock.absolute_timestamp * domain.unit_multiplier_ns;\n domain.last_timestamp_ns = timestamp_ns;\n\n ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n if (!vect.snapshot_ids.empty() &&\n PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n \" at snapshot %\" PRIu32 \".\",\n clock_id, snapshot_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n \/\/ this function.\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n \/\/ Snapshot IDs must be always monotonic.\n PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n vect.snapshot_ids.back() < snapshot_id);\n\n if (!vect.timestamps_ns.empty() &&\n timestamp_ns < vect.timestamps_ns.back()) {\n \/\/ Clock is not monotonic.\n\n if (clock_id == trace_time_clock_id_) {\n \/\/ The trace clock cannot be non-monotonic.\n PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n \" not >= %\" PRId64 \".\",\n clock_id, snapshot_id, timestamp_ns,\n vect.timestamps_ns.back());\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n \/\/ For the other clocks the best thing we can do is mark it as\n \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n \/\/ graph. We can still use it as a target clock, but not viceversa.\n \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n \/\/ daylight saving. We can still answer the question \"what was the\n \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n \/\/ same REALTIME instant because of the 1:many relationship.\n non_monotonic_clocks_.insert(clock_id);\n\n \/\/ Erase all edges from the graph that start from this clock (but keep the\n \/\/ ones that end on this clock).\n auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n graph_.erase(begin, end);\n }\n vect.snapshot_ids.emplace_back(snapshot_id);\n vect.timestamps_ns.emplace_back(timestamp_ns);\n }\n\n \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n \/\/ This is to store the information: Clock A is syncable to Clock B via the\n \/\/ snapshots of type (hash).\n \/\/ Clocks that were previously marked as non-monotonic won't be added as\n \/\/ valid sources.\n for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n auto it2 = it1;\n ++it2;\n for (; it2 != clocks.end(); ++it2) {\n if (!non_monotonic_clocks_.count(it1->clock_id))\n graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n if (!non_monotonic_clocks_.count(it2->clock_id))\n graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n }\n }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n \/\/ This is a classic breadth-first search. Each node in the queue holds also\n \/\/ the full path to reach that node.\n \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n \/\/ stop the search anyways.\n PERFETTO_CHECK(src != target);\n std::queue queue;\n queue.emplace(src);\n\n while (!queue.empty()) {\n ClockPath cur_path = queue.front();\n queue.pop();\n\n const ClockId cur_clock_id = cur_path.last;\n if (cur_clock_id == target)\n return cur_path;\n\n if (cur_path.len >= ClockPath::kMaxLen)\n continue;\n\n \/\/ Expore all the adjacent clocks.\n \/\/ The lower_bound() below returns an iterator to the first edge that starts\n \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n ClockGraphEdge(cur_clock_id, 0, 0));\n it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n ClockId next_clock_id = std::get<1>(*it);\n SnapshotHash hash = std::get<2>(*it);\n queue.push(ClockPath(cur_path, next_clock_id, hash));\n }\n }\n return ClockPath(); \/\/ invalid path.\n}\n\nbase::Optional ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n int64_t src_timestamp,\n ClockId target_clock_id) {\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n ClockPath path = FindPath(src_clock_id, target_clock_id);\n if (!path.valid()) {\n \/\/ Too many logs maybe emitted when path is invalid.\n static uint64_t dlog_count = 0;\n if (dlog_count++ < 10) {\n PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n \" at timestamp %\" PRId64,\n src_clock_id, target_clock_id, src_timestamp);\n }\n context_->storage->IncrementStats(stats::clock_sync_failure);\n return base::nullopt;\n }\n\n \/\/ We can cache only single-path resolutions between two clocks.\n \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n \/\/ too frequent these days, so we focus only on caching the more frequent\n \/\/ one-step resolutions (typically from any clock to the trace clock).\n const bool cacheable = path.len == 1;\n CachedClockPath cache_entry{};\n\n \/\/ Iterate trough the path found and translate timestamps onto the new clock\n \/\/ domain on each step, until the target domain is reached.\n ClockDomain* src_domain = GetClock(src_clock_id);\n int64_t ns = src_domain->ToNs(src_timestamp);\n for (uint32_t i = 0; i < path.len; ++i) {\n const ClockGraphEdge edge = path.at(i);\n ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n ClockDomain* next_clock = GetClock(std::get<1>(edge));\n const SnapshotHash hash = std::get<2>(edge);\n\n \/\/ Find the closest timestamp within the snapshots of the source clock.\n const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n const auto& ts_vec = cur_snap.timestamps_ns;\n auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n if (it != ts_vec.begin())\n --it;\n\n \/\/ Now lookup the snapshot id that matches the closest timestamp.\n size_t index = static_cast(std::distance(ts_vec.begin(), it));\n PERFETTO_DCHECK(index < ts_vec.size());\n PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n \/\/ And use that to retrieve the corresponding time in the next clock domain.\n \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n \/\/ either the hash logic or the pathfinding logic are bugged.\n \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n \/\/ of the snapshot.\n const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n \/\/ a binary search. std::find would do a linear scan.\n auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n next_snap.snapshot_ids.end(), snapshot_id);\n if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n continue;\n }\n size_t next_index = static_cast(\n std::distance(next_snap.snapshot_ids.begin(), next_it));\n PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n \/\/ The translated timestamp is the relative delta of the source timestamp\n \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n \/\/ the new clock domain for the same snapshot id.\n const int64_t adj = next_timestamp_ns - *it;\n ns += adj;\n\n \/\/ On the first iteration, keep track of the bounds for the cache entry.\n \/\/ This will allow future Convert() calls to skip the pathfinder logic\n \/\/ as long as the query stays within the bound.\n if (cacheable) {\n PERFETTO_DCHECK(i == 0);\n const int64_t kInt64Min = std::numeric_limits::min();\n const int64_t kInt64Max = std::numeric_limits::max();\n cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n auto ubound = it + 1;\n cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n cache_entry.translation_ns = adj;\n }\n\n \/\/ The last clock in the path must be the target clock.\n PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n }\n\n if (cacheable) {\n cache_entry.src = src_clock_id;\n cache_entry.src_domain = src_domain;\n cache_entry.target = target_clock_id;\n cache_[rnd_() % cache_.size()] = cache_entry;\n }\n\n return ns;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2017 Taras Kushnir \n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"spellchecksuggestionmodel.h\"\n#include \n#include \n#include \n#include \"spellsuggestionsitem.h\"\n#include \"..\/Models\/artworkmetadata.h\"\n#include \"spellcheckerservice.h\"\n#include \"..\/Commands\/commandmanager.h\"\n#include \"..\/Common\/flags.h\"\n#include \"..\/Common\/defines.h\"\n#include \"..\/Common\/basickeywordsmodel.h\"\n\nnamespace SpellCheck {\n\n std::vector > combineSuggestionRequests(const SuggestionsVector &items) {\n QHash dict;\n\n size_t size = items.size();\n for (size_t i = 0; i < size; ++i) {\n auto &item = items.at(i);\n const QString &word = item->getWord();\n if (!dict.contains(word)) {\n dict.insert(word, SuggestionsVector());\n }\n\n dict[word].emplace_back(item);\n }\n\n SuggestionsVector result;\n result.reserve(size);\n\n QHash::iterator i = dict.begin();\n QHash::iterator end = dict.end();\n for (; i != end; ++i) {\n SuggestionsVector &vector = i.value();\n\n if (vector.size() > 1) {\n result.emplace_back(new CombinedSpellSuggestions(i.key(), vector));\n } else {\n result.emplace_back(vector.front());\n }\n }\n\n return result;\n }\n\n QHash combinedFailedReplacements(const SuggestionsVector &failedReplacements) {\n QHash candidatesToRemove;\n size_t size = failedReplacements.size();\n candidatesToRemove.reserve((int)size);\n\n for (size_t i = 0; i < size; ++i) {\n auto &item = failedReplacements.at(i);\n std::shared_ptr keywordsItem = std::dynamic_pointer_cast(item);\n\n if (keywordsItem) {\n auto *item = keywordsItem->getMetadataOperator();\n\n if (keywordsItem->isPotentialDuplicate()) {\n if (!candidatesToRemove.contains(item)) {\n candidatesToRemove.insert(item, KeywordsSuggestionsVector());\n }\n\n candidatesToRemove[item].emplace_back(keywordsItem);\n }\n } else {\n std::shared_ptr combinedItem = std::dynamic_pointer_cast(item);\n if (combinedItem) {\n auto keywordsItems = combinedItem->getKeywordsDuplicateSuggestions();\n\n for (auto &keywordsCombinedItem: keywordsItems) {\n auto *item = keywordsCombinedItem->getMetadataOperator();\n\n if (!candidatesToRemove.contains(item)) {\n candidatesToRemove.insert(item, KeywordsSuggestionsVector());\n }\n\n candidatesToRemove[item].emplace_back(keywordsCombinedItem);\n }\n } else {\n LOG_WARNING << \"Unsupported failed suggestion type\";\n }\n }\n }\n\n return candidatesToRemove;\n }\n\n SpellCheckSuggestionModel::SpellCheckSuggestionModel():\n QAbstractListModel(),\n Common::BaseEntity()\n {\n }\n\n SpellCheckSuggestionModel::~SpellCheckSuggestionModel() {\n }\n\n QObject *SpellCheckSuggestionModel::getSuggestionItself(int index) const {\n SpellSuggestionsItem *item = NULL;\n\n if (0 <= index && index < (int)m_SuggestionsList.size()) {\n item = m_SuggestionsList.at(index).get();\n QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);\n }\n\n return item;\n }\n\n void SpellCheckSuggestionModel::clearModel() {\n beginResetModel();\n m_SuggestionsList.clear();\n m_ItemsPairs.clear();\n endResetModel();\n emit artworksCountChanged();\n }\n\n void SpellCheckSuggestionModel::submitCorrections() const {\n LOG_DEBUG << \"#\";\n bool anyChanged = false;\n\n SuggestionsVector failedItems;\n\n for (auto &item: m_SuggestionsList) {\n if (item->anyReplacementSelected()) {\n item->replaceToSuggested();\n\n if (!item->getReplacementSucceeded()) {\n failedItems.push_back(item);\n } else {\n anyChanged = true;\n }\n }\n }\n\n if (processFailedReplacements(failedItems)) {\n anyChanged = true;\n }\n\n if (anyChanged) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n item->afterReplaceCallback();\n m_CommandManager->submitItemForSpellCheck(item->getBasicKeywordsModel());\n }\n }\n\n updateItems();\n }\n\n void SpellCheckSuggestionModel::resetAllSuggestions() {\n LOG_DEBUG << \"#\";\n for (auto &item: m_SuggestionsList) {\n item->setReplacementIndex(-1);\n }\n }\n\n void SpellCheckSuggestionModel::setupModel(Common::IMetadataOperator *item, int index, Common::SuggestionFlags flags) {\n Q_ASSERT(item != NULL);\n LOG_DEBUG << \"#\";\n\n std::vector > items;\n items.emplace_back(item, index);\n this->setupModel(items, flags);\n }\n\n void SpellCheckSuggestionModel::setupModel(std::vector > &items, Common::SuggestionFlags flags) {\n LOG_INFO << \"flags =\" << (int)flags;\n m_ItemsPairs = std::move(items);\n\n auto requests = createSuggestionsRequests(flags);\n\n auto combinedRequests = combineSuggestionRequests(requests);\n LOG_INFO << combinedRequests.size() << \"combined request(s)\";\n\n auto executedRequests = setupSuggestions(combinedRequests);\n LOG_INFO << executedRequests.size() << \"executed request(s)\";\n\n#if defined(CORE_TESTS) || defined(INTEGRATION_TESTS)\n for (auto &executedItem: executedRequests) {\n LOG_INFO << executedItem->toDebugString();\n }\n#endif\n\n beginResetModel();\n m_SuggestionsList.clear();\n m_SuggestionsList = executedRequests;\n endResetModel();\n\n emit artworksCountChanged();\n }\n\n SuggestionsVector SpellCheckSuggestionModel::createSuggestionsRequests(Common::SuggestionFlags flags) {\n SuggestionsVector requests;\n\n using namespace Common;\n\n if (Common::HasFlag(flags, SuggestionFlags::Keywords)) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n auto subrequests = item->createKeywordsSuggestionsList();\n for (auto &req: subrequests) { req->setMetadataOperator(item); }\n requests.insert(requests.end(), subrequests.begin(), subrequests.end());\n LOG_DEBUG << subrequests.size() << \"keywords requests\";\n }\n }\n\n if (Common::HasFlag(flags, SuggestionFlags::Title)) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n auto subrequests = item->createTitleSuggestionsList();\n for (auto &req: subrequests) { req->setMetadataOperator(item); }\n requests.insert(requests.end(), subrequests.begin(), subrequests.end());\n LOG_DEBUG << subrequests.size() << \"title requests\";\n }\n }\n\n if (Common::HasFlag(flags, SuggestionFlags::Description)) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n auto subrequests = item->createDescriptionSuggestionsList();\n for (auto &req: subrequests) { req->setMetadataOperator(item); }\n requests.insert(requests.end(), subrequests.begin(), subrequests.end());\n LOG_DEBUG << subrequests.size() << \"description requests\";\n }\n }\n\n return requests;\n }\n\n bool SpellCheckSuggestionModel::processFailedReplacements(const SuggestionsVector &failedReplacements) const {\n LOG_INFO << failedReplacements.size() << \"failed items\";\n\n auto candidatesToRemove = combinedFailedReplacements(failedReplacements);\n\n auto it = candidatesToRemove.begin();\n auto itEnd = candidatesToRemove.end();\n\n bool anyReplaced = false;\n for (; it != itEnd; ++it) {\n auto *item = it.key();\n\n if (item->processFailedKeywordReplacements(it.value())) {\n anyReplaced = true;\n }\n }\n\n return anyReplaced;\n }\n\n SuggestionsVector SpellCheckSuggestionModel::setupSuggestions(const SuggestionsVector &items) {\n LOG_INFO << items.size() << \"item(s)\";\n SpellCheckerService *service = m_CommandManager->getSpellCheckerService();\n \/\/ another vector for requests with available suggestions\n SuggestionsVector executedRequests;\n executedRequests.reserve(items.size());\n\n for (auto &item: items) {\n QStringList suggestions = service->suggestCorrections(item->getWord());\n if (!suggestions.isEmpty()) {\n item->setSuggestions(suggestions);\n executedRequests.push_back(item);\n }\n }\n\n return executedRequests;\n }\n\n int SpellCheckSuggestionModel::rowCount(const QModelIndex &parent) const {\n Q_UNUSED(parent);\n return (int)m_SuggestionsList.size();\n }\n\n QVariant SpellCheckSuggestionModel::data(const QModelIndex &index, int role) const {\n int row = index.row();\n if (row < 0 || row >= (int)m_SuggestionsList.size()) { return QVariant(); }\n\n auto &item = m_SuggestionsList.at(row);\n\n switch (role) {\n case WordRole:\n return item->getWord();\n case ReplacementIndexRole:\n return item->getReplacementIndex();\n case ReplacementOriginRole:\n return item->getReplacementOrigin();\n default:\n return QVariant();\n }\n }\n\n QHash SpellCheckSuggestionModel::roleNames() const {\n QHash roles;\n roles[WordRole] = \"word\";\n roles[ReplacementIndexRole] = \"replacementindex\";\n roles[ReplacementOriginRole] = \"replacementorigin\";\n return roles;\n }\n\n void SpellCheckSuggestionModel::updateItems() const {\n QVector indices;\n indices.reserve((int)m_ItemsPairs.size());\n\n for (auto &pair: m_ItemsPairs) {\n int index = pair.second;\n if (index != -1) {\n indices.push_back(index);\n }\n }\n\n m_CommandManager->updateArtworksAtIndices(indices);\n }\n}\nFix for multireplace test\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2017 Taras Kushnir \n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"spellchecksuggestionmodel.h\"\n#include \n#include \n#include \n#include \"spellsuggestionsitem.h\"\n#include \"..\/Models\/artworkmetadata.h\"\n#include \"spellcheckerservice.h\"\n#include \"..\/Commands\/commandmanager.h\"\n#include \"..\/Common\/flags.h\"\n#include \"..\/Common\/defines.h\"\n#include \"..\/Common\/basickeywordsmodel.h\"\n\nnamespace SpellCheck {\n\n std::vector > combineSuggestionRequests(const SuggestionsVector &items) {\n QHash dict;\n\n size_t size = items.size();\n for (size_t i = 0; i < size; ++i) {\n auto &item = items.at(i);\n const QString &word = item->getWord();\n if (!dict.contains(word)) {\n dict.insert(word, SuggestionsVector());\n }\n\n dict[word].emplace_back(item);\n }\n\n SuggestionsVector result;\n result.reserve(size);\n\n QHash::iterator i = dict.begin();\n QHash::iterator end = dict.end();\n for (; i != end; ++i) {\n SuggestionsVector &vector = i.value();\n\n if (vector.size() > 1) {\n result.emplace_back(new CombinedSpellSuggestions(i.key(), vector));\n } else {\n result.emplace_back(vector.front());\n }\n }\n\n return result;\n }\n\n QHash combinedFailedReplacements(const SuggestionsVector &failedReplacements) {\n QHash candidatesToRemove;\n size_t size = failedReplacements.size();\n candidatesToRemove.reserve((int)size);\n\n for (size_t i = 0; i < size; ++i) {\n auto &item = failedReplacements.at(i);\n std::shared_ptr keywordsItem = std::dynamic_pointer_cast(item);\n\n if (keywordsItem) {\n auto *item = keywordsItem->getMetadataOperator();\n\n if (keywordsItem->isPotentialDuplicate()) {\n if (!candidatesToRemove.contains(item)) {\n candidatesToRemove.insert(item, KeywordsSuggestionsVector());\n }\n\n candidatesToRemove[item].emplace_back(keywordsItem);\n }\n } else {\n std::shared_ptr combinedItem = std::dynamic_pointer_cast(item);\n if (combinedItem) {\n auto keywordsItems = combinedItem->getKeywordsDuplicateSuggestions();\n\n for (auto &keywordsCombinedItem: keywordsItems) {\n auto *item = keywordsCombinedItem->getMetadataOperator();\n\n if (!candidatesToRemove.contains(item)) {\n candidatesToRemove.insert(item, KeywordsSuggestionsVector());\n }\n\n candidatesToRemove[item].emplace_back(keywordsCombinedItem);\n }\n } else {\n LOG_WARNING << \"Unsupported failed suggestion type\";\n }\n }\n }\n\n return candidatesToRemove;\n }\n\n SpellCheckSuggestionModel::SpellCheckSuggestionModel():\n QAbstractListModel(),\n Common::BaseEntity()\n {\n }\n\n SpellCheckSuggestionModel::~SpellCheckSuggestionModel() {\n }\n\n QObject *SpellCheckSuggestionModel::getSuggestionItself(int index) const {\n SpellSuggestionsItem *item = NULL;\n\n if (0 <= index && index < (int)m_SuggestionsList.size()) {\n item = m_SuggestionsList.at(index).get();\n QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);\n }\n\n return item;\n }\n\n void SpellCheckSuggestionModel::clearModel() {\n beginResetModel();\n m_SuggestionsList.clear();\n m_ItemsPairs.clear();\n endResetModel();\n emit artworksCountChanged();\n }\n\n void SpellCheckSuggestionModel::submitCorrections() const {\n LOG_DEBUG << \"#\";\n bool anyChanged = false;\n\n SuggestionsVector failedItems;\n\n for (auto &item: m_SuggestionsList) {\n if (item->anyReplacementSelected()) {\n item->replaceToSuggested();\n\n if (!item->getReplacementSucceeded()) {\n failedItems.push_back(item);\n } else {\n anyChanged = true;\n }\n }\n }\n\n if (processFailedReplacements(failedItems)) {\n anyChanged = true;\n }\n\n if (anyChanged) {\n QVector itemsToSubmit;\n itemsToSubmit.reserve((int)m_ItemsPairs.size());\n\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n item->afterReplaceCallback();\n itemsToSubmit.append(item->getBasicKeywordsModel());\n }\n\n m_CommandManager->submitForSpellCheck(itemsToSubmit);\n }\n\n updateItems();\n }\n\n void SpellCheckSuggestionModel::resetAllSuggestions() {\n LOG_DEBUG << \"#\";\n for (auto &item: m_SuggestionsList) {\n item->setReplacementIndex(-1);\n }\n }\n\n void SpellCheckSuggestionModel::setupModel(Common::IMetadataOperator *item, int index, Common::SuggestionFlags flags) {\n Q_ASSERT(item != NULL);\n LOG_DEBUG << \"#\";\n\n std::vector > items;\n items.emplace_back(item, index);\n this->setupModel(items, flags);\n }\n\n void SpellCheckSuggestionModel::setupModel(std::vector > &items, Common::SuggestionFlags flags) {\n LOG_INFO << \"flags =\" << (int)flags;\n m_ItemsPairs = std::move(items);\n\n auto requests = createSuggestionsRequests(flags);\n\n auto combinedRequests = combineSuggestionRequests(requests);\n LOG_INFO << combinedRequests.size() << \"combined request(s)\";\n\n auto executedRequests = setupSuggestions(combinedRequests);\n LOG_INFO << executedRequests.size() << \"executed request(s)\";\n\n#if defined(CORE_TESTS) || defined(INTEGRATION_TESTS)\n for (auto &executedItem: executedRequests) {\n LOG_INFO << executedItem->toDebugString();\n }\n#endif\n\n beginResetModel();\n m_SuggestionsList.clear();\n m_SuggestionsList = executedRequests;\n endResetModel();\n\n emit artworksCountChanged();\n }\n\n SuggestionsVector SpellCheckSuggestionModel::createSuggestionsRequests(Common::SuggestionFlags flags) {\n SuggestionsVector requests;\n\n using namespace Common;\n\n if (Common::HasFlag(flags, SuggestionFlags::Keywords)) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n auto subrequests = item->createKeywordsSuggestionsList();\n for (auto &req: subrequests) { req->setMetadataOperator(item); }\n requests.insert(requests.end(), subrequests.begin(), subrequests.end());\n LOG_DEBUG << subrequests.size() << \"keywords requests\";\n }\n }\n\n if (Common::HasFlag(flags, SuggestionFlags::Title)) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n auto subrequests = item->createTitleSuggestionsList();\n for (auto &req: subrequests) { req->setMetadataOperator(item); }\n requests.insert(requests.end(), subrequests.begin(), subrequests.end());\n LOG_DEBUG << subrequests.size() << \"title requests\";\n }\n }\n\n if (Common::HasFlag(flags, SuggestionFlags::Description)) {\n for (auto &pair: m_ItemsPairs) {\n auto *item = pair.first;\n auto subrequests = item->createDescriptionSuggestionsList();\n for (auto &req: subrequests) { req->setMetadataOperator(item); }\n requests.insert(requests.end(), subrequests.begin(), subrequests.end());\n LOG_DEBUG << subrequests.size() << \"description requests\";\n }\n }\n\n return requests;\n }\n\n bool SpellCheckSuggestionModel::processFailedReplacements(const SuggestionsVector &failedReplacements) const {\n LOG_INFO << failedReplacements.size() << \"failed items\";\n\n auto candidatesToRemove = combinedFailedReplacements(failedReplacements);\n\n auto it = candidatesToRemove.begin();\n auto itEnd = candidatesToRemove.end();\n\n bool anyReplaced = false;\n for (; it != itEnd; ++it) {\n auto *item = it.key();\n\n if (item->processFailedKeywordReplacements(it.value())) {\n anyReplaced = true;\n }\n }\n\n return anyReplaced;\n }\n\n SuggestionsVector SpellCheckSuggestionModel::setupSuggestions(const SuggestionsVector &items) {\n LOG_INFO << items.size() << \"item(s)\";\n SpellCheckerService *service = m_CommandManager->getSpellCheckerService();\n \/\/ another vector for requests with available suggestions\n SuggestionsVector executedRequests;\n executedRequests.reserve(items.size());\n\n for (auto &item: items) {\n QStringList suggestions = service->suggestCorrections(item->getWord());\n if (!suggestions.isEmpty()) {\n item->setSuggestions(suggestions);\n executedRequests.push_back(item);\n }\n }\n\n return executedRequests;\n }\n\n int SpellCheckSuggestionModel::rowCount(const QModelIndex &parent) const {\n Q_UNUSED(parent);\n return (int)m_SuggestionsList.size();\n }\n\n QVariant SpellCheckSuggestionModel::data(const QModelIndex &index, int role) const {\n int row = index.row();\n if (row < 0 || row >= (int)m_SuggestionsList.size()) { return QVariant(); }\n\n auto &item = m_SuggestionsList.at(row);\n\n switch (role) {\n case WordRole:\n return item->getWord();\n case ReplacementIndexRole:\n return item->getReplacementIndex();\n case ReplacementOriginRole:\n return item->getReplacementOrigin();\n default:\n return QVariant();\n }\n }\n\n QHash SpellCheckSuggestionModel::roleNames() const {\n QHash roles;\n roles[WordRole] = \"word\";\n roles[ReplacementIndexRole] = \"replacementindex\";\n roles[ReplacementOriginRole] = \"replacementorigin\";\n return roles;\n }\n\n void SpellCheckSuggestionModel::updateItems() const {\n QVector indices;\n indices.reserve((int)m_ItemsPairs.size());\n\n for (auto &pair: m_ItemsPairs) {\n int index = pair.second;\n if (index != -1) {\n indices.push_back(index);\n }\n }\n\n m_CommandManager->updateArtworksAtIndices(indices);\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014-2016 SSPA Sweden AB\n\n#pragma once\n\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"PysimTypes.hpp\"\n\nstruct Dptr;\n\nclass StoreHandler{\npublic:\n StoreHandler();\n virtual ~StoreHandler();\n\n void doStoreStep(double time);\n\n \/\/Store handling\n const std::vector& getStoreVector(char* name);\n void fillWithStore(char* name, double* p,int rows, int columns);\n void fillWithTime(double* p);\n int getStoreSize();\n int getStoreColumns(char* name);\n void setStoreInterval(double interval);\n std::vector getStoreNames();\n void store_scalar(char* name, double* pointer);\n void store_vector(char* name, pysim::vector* pointer);\n\nprotected:\n\nprivate:\n Dptr* d_ptr;\n\n};\n\nremoving unused imports\/\/ Copyright (c) 2014-2016 SSPA Sweden AB\n#pragma once\n\n#include \n#include \n#include \n\n#include \"PysimTypes.hpp\"\n\nstruct Dptr;\n\nclass StoreHandler{\npublic:\n StoreHandler();\n virtual ~StoreHandler();\n\n void doStoreStep(double time);\n\n \/\/Store handling\n const std::vector& getStoreVector(char* name);\n void fillWithStore(char* name, double* p,int rows, int columns);\n void fillWithTime(double* p);\n int getStoreSize();\n int getStoreColumns(char* name);\n void setStoreInterval(double interval);\n std::vector getStoreNames();\n void store_scalar(char* name, double* pointer);\n void store_vector(char* name, pysim::vector* pointer);\n\nprotected:\n\nprivate:\n Dptr* d_ptr;\n\n};\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n\n\n#include \"otbVectorImage.h\"\n#include \"itkMacro.h\"\n#include \n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbMultiChannelExtractROI.h\"\n\nint otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const std::string inputFilename = argv[1];\n const std::string outputFilename = argv[2];\n\n const unsigned int startx = atoi(argv[3]);\n const unsigned int starty = atoi(argv[4]);\n const unsigned int sizex = atoi(argv[5]);\n const unsigned int sizey = atoi(argv[6]);\n const std::string separator = \":\";\n\n typedef float InputPixelType;\n typedef float OutputPixelType;\n\n typedef otb::VectorImage InputImageType;\n\n typedef typename InputImageType::PixelType PixelType;\n\n typedef otb::MultiChannelExtractROI ExtractROIFilterType;\n\n typedef otb::ImageFileReader ReaderType;\n typedef otb::ImageFileWriter WriterType;\n\n typedef itk::ImageRegionIterator< InputImageType > IteratorType;\n typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;\n\n ReaderType::Pointer reader = ReaderType::New();\n ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(inputFilename);\n\n \/\/Build output filename with extended box\n std::ostringstream outputFilenameExtended;\n outputFilenameExtended\n << outputFilename\n << \"?&box=\" << startx << separator\n << starty << separator\n << sizex << separator\n << sizey\n ;\n\n std::cout << \"Output image with user defined path \" << outputFilenameExtended.str() << std::endl;\n\n writer->SetFileName(outputFilenameExtended.str());\n writer->SetInput(reader->GetOutput());\n\n extractROIFilter->SetStartX(startx);\n extractROIFilter->SetStartY(starty);\n extractROIFilter->SetSizeX(sizex);\n extractROIFilter->SetSizeY(sizey);\n extractROIFilter->SetInput(reader->GetOutput());\n\n writer->Update();\n extractROIFilter->Update();\n\n ReaderType::Pointer reader2 = ReaderType::New();\n reader2->SetFileName(outputFilename);\n\n reader2->Update();\n\n typename InputImageType::ConstPointer readImage = reader2->GetOutput();\n typename InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput();\n\n ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() );\n ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() );\n\n ritr.GoToBegin();\n extractitr.GoToBegin();\n\n std::cout << \"Comparing the pixel values.. :\" << std::endl;\n\n while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() )\n {\n if( ritr.Get() != extractitr.Get() )\n {\n std::cerr << \"Pixel comparison failed at index = \" << ritr.GetIndex() << std::endl;\n std::cerr << \"Expected pixel value \" << extractitr.Get() << std::endl;\n std::cerr << \"Read Image pixel value \" << ritr.Get() << std::endl;\n return EXIT_FAILURE;\n }\n ++extractitr;\n ++ritr;\n }\n\n std::cout << std::endl;\n std::cout << \"Test PASSED !\" << std::endl;\n\n return EXIT_SUCCESS;\n}\nSTYLE\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n\n\n#include \"otbVectorImage.h\"\n#include \"itkMacro.h\"\n#include \n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbMultiChannelExtractROI.h\"\n\nint otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const std::string inputFilename = argv[1];\n const std::string outputFilename = argv[2];\n\n const unsigned int startx = atoi(argv[3]);\n const unsigned int starty = atoi(argv[4]);\n const unsigned int sizex = atoi(argv[5]);\n const unsigned int sizey = atoi(argv[6]);\n const std::string separator = \":\";\n\n typedef float InputPixelType;\n typedef float OutputPixelType;\n\n typedef otb::VectorImage InputImageType;\n\n typedef typename InputImageType::PixelType PixelType;\n\n typedef otb::MultiChannelExtractROI ExtractROIFilterType;\n\n typedef otb::ImageFileReader ReaderType;\n typedef otb::ImageFileWriter WriterType;\n\n typedef itk::ImageRegionIterator< InputImageType > IteratorType;\n typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;\n\n ReaderType::Pointer reader = ReaderType::New();\n ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(inputFilename);\n\n \/\/Build output filename with extended box\n std::ostringstream outputFilenameExtended;\n outputFilenameExtended\n << outputFilename\n << \"?&box=\" << startx << separator\n << starty << separator\n << sizex << separator\n << sizey\n ;\n\n std::cout << \"Output image with user defined path \" << outputFilenameExtended.str() << std::endl;\n\n writer->SetFileName(outputFilenameExtended.str());\n writer->SetInput(reader->GetOutput());\n\n extractROIFilter->SetStartX(startx);\n extractROIFilter->SetStartY(starty);\n extractROIFilter->SetSizeX(sizex);\n extractROIFilter->SetSizeY(sizey);\n extractROIFilter->SetInput(reader->GetOutput());\n\n writer->Update();\n extractROIFilter->Update();\n\n ReaderType::Pointer reader2 = ReaderType::New();\n reader2->SetFileName(outputFilename);\n\n reader2->Update();\n\n typename InputImageType::ConstPointer readImage = reader2->GetOutput();\n typename InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput();\n\n ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() );\n ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() );\n\n ritr.GoToBegin();\n extractitr.GoToBegin();\n\n std::cout << \"Comparing the pixel values.. :\" << std::endl;\n\n while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() )\n {\n if( ritr.Get() != extractitr.Get() )\n {\n std::cerr << \"Pixel comparison failed at index = \" << ritr.GetIndex() << std::endl;\n std::cerr << \"Expected pixel value \" << extractitr.Get() << std::endl;\n std::cerr << \"Read Image pixel value \" << ritr.Get() << std::endl;\n return EXIT_FAILURE;\n }\n ++extractitr;\n ++ritr;\n }\n\n std::cout << std::endl;\n std::cout << \"Test PASSED !\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2015, Youssef Kashef\n\/\/ Copyright (c) 2015, ELM Library Project\n\/\/ 3-clause BSD License\n\/\/\n\/\/M*\/\n#include \"elm\/layers\/imagegradient.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include \n\n#include \"elm\/core\/exception.h\"\n#include \"elm\/core\/inputname.h\"\n#include \"elm\/core\/layerconfig.h\"\n#include \"elm\/core\/signal.h\"\n#include \"elm\/ts\/layer_assertions.h\"\n#include \"elm\/ts\/mat_assertions.h\"\n#include \"elm\/core\/debug_utils.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace elm;\n\nnamespace {\n\nELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(ImageGradient);\n\nconst std::string NAME_IN = \"in\";\nconst std::string NAME_GRAD = \"g\";\n\nclass ImageGradientTest : public ::testing::Test\n{\nprotected:\n virtual void SetUp() {\n\n to_.reset(new ImageGradient());\n\n config_ = LayerConfig();\n\n \/\/ params\n PTree params;\n config_.Params(params);\n\n \/\/ IO\n io_ = LayerIONames();\n io_.Input(ImageGradient::KEY_INPUT_STIMULUS, NAME_IN);\n io_.Output(ImageGradient::KEY_OUTPUT_RESPONSE, NAME_GRAD);\n\n to_.reset(new ImageGradient(config_));\n to_->IONames(io_);\n }\n\n shared_ptr to_; \/\/\/< test object\n LayerConfig config_; \/\/\/< default config for tests\n LayerIONames io_; \/\/\/< default I\/O for tests\n};\n\nTEST_F(ImageGradientTest, Reset_EmptyConfig)\n{\n EXPECT_NO_THROW(to_->Reset(LayerConfig())) << \"All params are optional, no?\";\n}\n\nTEST_F(ImageGradientTest, Response_exists)\n{\n Mat1f in(10, 10, 1.f);\n\n Signal sig;\n sig.Append(NAME_IN, in);\n\n to_->Activate(sig);\n\n EXPECT_FALSE(sig.Exists(NAME_GRAD));\n\n to_->Response(sig);\n\n EXPECT_TRUE(sig.Exists(NAME_GRAD));\n}\n\nTEST_F(ImageGradientTest, Response_dims)\n{\n const int R=10;\n const int C=10;\n\n for(int r=2; rActivate(sig);\n to_->Response(sig);\n\n Mat1f gradient = sig.MostRecentMat1f(NAME_GRAD);\n\n EXPECT_EQ(r, gradient.rows);\n EXPECT_EQ(c*2, gradient.cols);\n }\n }\n}\n\nTEST_F(ImageGradientTest, Invalid_input)\n{\n for(int r=0; r<2; r++) {\n\n for(int c=0; c<2; c++) {\n\n Mat1f in(r, c, 1.f);\n\n Signal sig;\n sig.Append(NAME_IN, in);\n\n EXPECT_THROW(to_->Activate(sig), ExceptionBadDims);\n }\n }\n}\n\n\n} \/\/ annonymous namespace for test cases and fixtures\n\ntest response for image gradient layer\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2015, Youssef Kashef\n\/\/ Copyright (c) 2015, ELM Library Project\n\/\/ 3-clause BSD License\n\/\/\n\/\/M*\/\n#include \"elm\/layers\/imagegradient.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include \n\n#include \"elm\/core\/exception.h\"\n#include \"elm\/core\/inputname.h\"\n#include \"elm\/core\/layerconfig.h\"\n#include \"elm\/core\/signal.h\"\n#include \"elm\/ts\/layer_assertions.h\"\n#include \"elm\/ts\/mat_assertions.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace elm;\n\nnamespace {\n\nELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(ImageGradient);\n\nconst std::string NAME_IN = \"in\";\nconst std::string NAME_GRAD = \"g\";\n\nclass ImageGradientTest : public ::testing::Test\n{\nprotected:\n virtual void SetUp() {\n\n to_.reset(new ImageGradient());\n\n config_ = LayerConfig();\n\n \/\/ params\n PTree params;\n config_.Params(params);\n\n \/\/ IO\n io_ = LayerIONames();\n io_.Input(ImageGradient::KEY_INPUT_STIMULUS, NAME_IN);\n io_.Output(ImageGradient::KEY_OUTPUT_RESPONSE, NAME_GRAD);\n\n to_.reset(new ImageGradient(config_));\n to_->IONames(io_);\n }\n\n shared_ptr to_; \/\/\/< test object\n LayerConfig config_; \/\/\/< default config for tests\n LayerIONames io_; \/\/\/< default I\/O for tests\n};\n\nTEST_F(ImageGradientTest, Reset_EmptyConfig)\n{\n EXPECT_NO_THROW(to_->Reset(LayerConfig())) << \"All params are optional, no?\";\n}\n\nTEST_F(ImageGradientTest, Response_exists)\n{\n Mat1f in(10, 10, 1.f);\n\n Signal sig;\n sig.Append(NAME_IN, in);\n\n to_->Activate(sig);\n\n EXPECT_FALSE(sig.Exists(NAME_GRAD));\n\n to_->Response(sig);\n\n EXPECT_TRUE(sig.Exists(NAME_GRAD));\n}\n\nTEST_F(ImageGradientTest, Response_dims)\n{\n const int R=10;\n const int C=10;\n\n for(int r=2; rActivate(sig);\n to_->Response(sig);\n\n Mat1f gradient = sig.MostRecentMat1f(NAME_GRAD);\n\n EXPECT_EQ(r, gradient.rows);\n EXPECT_EQ(c*2, gradient.cols);\n }\n }\n}\n\nTEST_F(ImageGradientTest, Invalid_input)\n{\n for(int r=0; r<2; r++) {\n\n for(int c=0; c<2; c++) {\n\n Mat1f in(r, c, 1.f);\n\n Signal sig;\n sig.Append(NAME_IN, in);\n\n EXPECT_THROW(to_->Activate(sig), ExceptionBadDims);\n }\n }\n}\n\nTEST_F(ImageGradientTest, Gradient)\n{\n const int ROWS=3;\n const int COLS=2;\n\n float data1[ROWS*COLS] = {1.1f, 1.2f,\n 2.3f, 2.2f,\n -3.1f, 0.f,\n };\n Mat1f in = Mat1f(ROWS, COLS, data1).clone();\n\n Signal sig;\n sig.Append(NAME_IN, in);\n\n to_->Activate(sig);\n to_->Response(sig);\n\n Mat2f gradient = static_cast(sig.MostRecentMat1f(NAME_GRAD));\n\n EXPECT_EQ(ROWS, gradient.rows);\n EXPECT_EQ(COLS, gradient.cols);\n\n VecMat1f components;\n cv::split(gradient, components);\n\n Mat1f grad_x = components[0];\n EXPECT_FLOAT_EQ(0.1f, grad_x(0, 0));\n EXPECT_NEAR(-0.1f, grad_x(1, 0), 1e-5);\n EXPECT_FLOAT_EQ(-in(2, 0), grad_x(2, 0));\n EXPECT_MAT_EQ(Mat1f::zeros(ROWS, 1), grad_x.col(COLS-1));\n\n Mat1f grad_y = components[1];\n EXPECT_FLOAT_EQ(1.2f, grad_y(0, 0));\n EXPECT_FLOAT_EQ(1.0f, grad_y(0, 1));\n EXPECT_FLOAT_EQ(-3.1f-2.3f, grad_y(1, 0));\n EXPECT_NEAR(-2.2f, grad_y(1, 1), 1e-5);\n EXPECT_MAT_EQ(Mat1f::zeros(1, COLS), grad_y.row(ROWS-1));\n}\n\nTEST_F(ImageGradientTest, Gradient_nan)\n{\n const int ROWS=3;\n const int COLS=2;\n\n const float NAN_VALUE=std::numeric_limits::quiet_NaN();\n\n float data1[ROWS*COLS] = {1.1f, NAN_VALUE,\n 2.3f, NAN_VALUE,\n -3.1f, 0.f,\n };\n Mat1f in = Mat1f(ROWS, COLS, data1).clone();\n\n Signal sig;\n sig.Append(NAME_IN, in);\n\n to_->Activate(sig);\n to_->Response(sig);\n\n Mat2f gradient = static_cast(sig.MostRecentMat1f(NAME_GRAD));\n\n EXPECT_EQ(ROWS, gradient.rows);\n EXPECT_EQ(COLS, gradient.cols);\n\n VecMat1f components;\n cv::split(gradient, components);\n\n Mat1f grad_x = components[0];\n\n EXPECT_NE(grad_x(0, 0), grad_x(0, 0));\n EXPECT_NE(grad_x(1, 0), grad_x(1, 0));\n EXPECT_FLOAT_EQ(-in(2, 0), grad_x(2, 0));\n EXPECT_MAT_EQ(Mat1f::zeros(ROWS, 1), grad_x.col(COLS-1));\n\n Mat1f grad_y = components[1];\n\n EXPECT_FLOAT_EQ(1.2f, grad_y(0, 0));\n EXPECT_NE(grad_y(0, 1), grad_y(0, 1));\n EXPECT_FLOAT_EQ(-3.1f-2.3f, grad_y(1, 0));\n EXPECT_NE(-grad_y(1, 1), grad_y(1, 1));\n EXPECT_MAT_EQ(Mat1f::zeros(1, COLS), grad_y.row(ROWS-1));\n}\n\n} \/\/ annonymous namespace for test cases and fixtures\n\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"progressiveframerenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/kernel\/rendering\/progressive\/samplecounter.h\"\n#include \"renderer\/kernel\/rendering\/progressive\/samplegeneratorjob.h\"\n#include \"renderer\/kernel\/rendering\/accumulationframebuffer.h\"\n#include \"renderer\/kernel\/rendering\/framerendererbase.h\"\n#include \"renderer\/kernel\/rendering\/isamplegenerator.h\"\n#include \"renderer\/kernel\/rendering\/itilecallback.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n#include \"renderer\/modeling\/project\/project.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/analysis.h\"\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/genericimagefilereader.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/math\/fixedsizehistory.h\"\n#include \"foundation\/platform\/thread.h\"\n#include \"foundation\/platform\/timer.h\"\n#include \"foundation\/utility\/foreach.h\"\n#include \"foundation\/utility\/job.h\"\n#include \"foundation\/utility\/maplefile.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n#include \"foundation\/utility\/string.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace boost;\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n typedef vector SampleGeneratorVector;\n typedef vector TileCallbackVector;\n\n\n \/\/\n \/\/ Progressive frame renderer.\n \/\/\n\n class ProgressiveFrameRenderer\n : public FrameRendererBase\n {\n public:\n ProgressiveFrameRenderer(\n const Project& project,\n ISampleGeneratorFactory* generator_factory,\n ITileCallbackFactory* callback_factory,\n const ParamArray& params)\n : m_frame(*project.get_frame())\n , m_params(params)\n , m_sample_counter(m_params.m_max_sample_count)\n , m_ref_image_avg_lum(0.0)\n {\n \/\/ We must have a generator factory, but it's OK not to have a callback factory.\n assert(generator_factory);\n\n \/\/ Create an accumulation framebuffer.\n const CanvasProperties& props = m_frame.image().properties();\n m_framebuffer.reset(\n generator_factory->create_accumulation_framebuffer(\n props.m_canvas_width,\n props.m_canvas_height));\n\n \/\/ Create and initialize the job manager.\n m_job_manager.reset(\n new JobManager(\n global_logger(),\n m_job_queue,\n m_params.m_thread_count,\n JobManager::KeepRunningOnEmptyQueue));\n\n \/\/ Instantiate sample generators, one per rendering thread.\n for (size_t i = 0; i < m_params.m_thread_count; ++i)\n {\n m_sample_generators.push_back(\n generator_factory->create(i, m_params.m_thread_count));\n }\n\n \/\/ Instantiate tile callbacks, one per rendering thread.\n if (callback_factory)\n {\n for (size_t i = 0; i < m_params.m_thread_count; ++i)\n m_tile_callbacks.push_back(callback_factory->create());\n }\n\n \/\/ Load the reference image if one is specified.\n if (!m_params.m_ref_image_path.empty())\n {\n const string ref_image_path =\n project.get_search_paths().qualify(m_params.m_ref_image_path);\n\n RENDERER_LOG_DEBUG(\"loading reference image %s...\", ref_image_path.c_str());\n\n GenericImageFileReader reader;\n m_ref_image.reset(reader.read(ref_image_path.c_str()));\n\n m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get());\n\n RENDERER_LOG_DEBUG(\n \"reference image average luminance is %s.\",\n pretty_scalar(m_ref_image_avg_lum, 6).c_str());\n }\n\n print_rendering_thread_count(m_params.m_thread_count);\n }\n\n virtual ~ProgressiveFrameRenderer()\n {\n \/\/ Tell the statistics printing thread to stop.\n m_abort_switch.abort();\n\n \/\/ Wait until the statistics printing thread is terminated.\n m_statistics_thread->join();\n\n \/\/ Delete tile callbacks.\n for (const_each i = m_tile_callbacks; i; ++i)\n (*i)->release();\n\n \/\/ Delete sample generators.\n for (const_each i = m_sample_generators; i; ++i)\n (*i)->release();\n }\n\n virtual void release()\n {\n delete this;\n }\n\n virtual void render()\n {\n start_rendering();\n m_job_queue.wait_until_completion();\n }\n\n virtual void start_rendering()\n {\n assert(!is_rendering());\n assert(!m_job_queue.has_scheduled_or_running_jobs());\n\n m_abort_switch.clear();\n m_framebuffer->clear();\n m_sample_counter.clear();\n\n \/\/ Reset sample generators.\n for (size_t i = 0; i < m_params.m_thread_count; ++i)\n m_sample_generators[i]->reset();\n\n \/\/ Schedule the first batch of jobs.\n for (size_t i = 0; i < m_params.m_thread_count; ++i)\n {\n m_job_queue.schedule(\n new SampleGeneratorJob(\n m_frame,\n *m_framebuffer.get(),\n m_sample_generators[i],\n m_sample_counter,\n m_tile_callbacks[i],\n m_job_queue,\n i, \/\/ job index\n m_params.m_thread_count, \/\/ job count\n 0, \/\/ pass number\n m_abort_switch));\n }\n\n \/\/ Start job execution.\n m_job_manager->start();\n\n \/\/ Create and start the statistics printing thread.\n m_statistics_func.reset(\n new StatisticsFunc(\n m_frame,\n *m_framebuffer.get(),\n m_params.m_print_luminance_stats,\n m_ref_image.get(),\n m_ref_image_avg_lum,\n m_abort_switch));\n ThreadFunctionWrapper wrapper(m_statistics_func.get());\n m_statistics_thread.reset(new thread(wrapper));\n }\n\n virtual void stop_rendering()\n {\n \/\/ Tell rendering jobs and the statistics printing thread to stop.\n m_abort_switch.abort();\n\n \/\/ Stop job execution.\n m_job_manager->stop();\n\n \/\/ Delete all non-executed jobs.\n m_job_queue.clear_scheduled_jobs();\n\n \/\/ Wait until the statistics printing thread is terminated.\n m_statistics_thread->join();\n }\n\n virtual void terminate_rendering()\n {\n stop_rendering();\n\n m_statistics_func->write_rms_deviation_file();\n }\n\n virtual bool is_rendering() const\n {\n return m_job_queue.has_scheduled_or_running_jobs();\n }\n\n private:\n struct Parameters\n {\n const size_t m_thread_count; \/\/ number of rendering threads\n const uint64 m_max_sample_count; \/\/ maximum total number of samples to store in the framebuffer\n const bool m_print_luminance_stats; \/\/ compute and print luminance statistics?\n const string m_ref_image_path; \/\/ path to the reference image\n\n \/\/ Constructor, extract parameters.\n explicit Parameters(const ParamArray& params)\n : m_thread_count(FrameRendererBase::get_rendering_thread_count(params))\n , m_max_sample_count(params.get_optional(\"max_samples\", numeric_limits::max()))\n , m_print_luminance_stats(params.get_optional(\"print_luminance_statistics\", false))\n , m_ref_image_path(params.get_optional(\"reference_image\", \"\"))\n {\n }\n };\n\n Frame& m_frame;\n const Parameters m_params;\n SampleCounter m_sample_counter;\n\n auto_ptr m_framebuffer;\n\n JobQueue m_job_queue;\n auto_ptr m_job_manager;\n AbortSwitch m_abort_switch;\n\n SampleGeneratorVector m_sample_generators;\n TileCallbackVector m_tile_callbacks;\n\n auto_ptr m_ref_image;\n double m_ref_image_avg_lum;\n\n class StatisticsFunc\n : public NonCopyable\n {\n public:\n StatisticsFunc(\n Frame& frame,\n AccumulationFramebuffer& framebuffer,\n const bool print_luminance_stats,\n const Image* ref_image,\n const double ref_image_avg_lum,\n AbortSwitch& abort_switch)\n : m_frame(frame)\n , m_framebuffer(framebuffer)\n , m_print_luminance_stats(print_luminance_stats)\n , m_ref_image(ref_image)\n , m_ref_image_avg_lum(ref_image_avg_lum)\n , m_abort_switch(abort_switch)\n , m_timer_frequency(m_timer.frequency())\n , m_last_time(m_timer.read())\n , m_last_sample_count(0)\n {\n }\n\n void operator()()\n {\n while (!m_abort_switch.is_aborted())\n {\n const uint64 time = m_timer.read();\n const uint64 elapsed_ticks = time - m_last_time;\n const double elapsed_seconds = static_cast(elapsed_ticks) \/ m_timer_frequency;\n\n if (elapsed_seconds >= 1.0)\n {\n print_and_record_statistics(elapsed_seconds);\n m_last_time = time;\n }\n\n foundation::sleep(5); \/\/ needs full qualification\n }\n }\n\n void write_rms_deviation_file() const\n {\n if (!m_spp_count_history.empty())\n {\n MapleFile file(\"RMS Deviation.mpl\");\n file.define(\"rmsd\", m_spp_count_history, m_rmsd_history);\n file.plot(\"rmsd\", \"RMS Deviation\");\n }\n }\n\n private:\n Frame& m_frame;\n AccumulationFramebuffer& m_framebuffer;\n const bool m_print_luminance_stats;\n const Image* m_ref_image;\n const double m_ref_image_avg_lum;\n AbortSwitch& m_abort_switch;\n\n DefaultWallclockTimer m_timer;\n uint64 m_timer_frequency;\n uint64 m_last_time;\n\n uint64 m_last_sample_count;\n FixedSizeHistory m_sps_count_history; \/\/ samples per second history\n vector m_spp_count_history; \/\/ samples per pixel history\n vector m_rmsd_history; \/\/ RMS deviation history\n\n void print_and_record_statistics(const double elapsed_seconds)\n {\n print_performance_statistics(elapsed_seconds);\n\n if (m_print_luminance_stats || m_ref_image)\n print_and_record_convergence_statistics();\n }\n\n void print_performance_statistics(const double elapsed_seconds)\n {\n const uint64 new_sample_count = m_framebuffer.get_sample_count();\n const uint64 pixel_count = static_cast(m_frame.image().properties().m_pixel_count);\n const double spp_count = static_cast(new_sample_count) \/ pixel_count;\n const double sps_count = static_cast(new_sample_count - m_last_sample_count) \/ elapsed_seconds;\n\n m_sps_count_history.insert(sps_count);\n\n const uint64 avg_sps_count = truncate(m_sps_count_history.compute_average());\n\n RENDERER_LOG_INFO(\n \"%s samples, %s samples\/pixel, %s samples\/second\",\n pretty_uint(new_sample_count).c_str(),\n pretty_scalar(spp_count).c_str(),\n pretty_uint(avg_sps_count).c_str());\n\n m_last_sample_count = new_sample_count;\n }\n\n void print_and_record_convergence_statistics()\n {\n assert(m_print_luminance_stats || m_ref_image);\n\n string output;\n\n Image current_image(m_frame.image());\n m_frame.transform_to_output_color_space(current_image);\n\n if (m_print_luminance_stats)\n {\n const double avg_lum = compute_average_luminance(current_image);\n output += \"average luminance \" + pretty_scalar(avg_lum, 6);\n\n if (m_ref_image)\n {\n const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum);\n output += \" (\";\n output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3);\n output += \" error)\";\n }\n }\n\n if (m_ref_image)\n {\n if (m_print_luminance_stats)\n output += \", \";\n\n const double spp_count =\n static_cast(m_framebuffer.get_sample_count())\n \/ m_frame.image().properties().m_pixel_count;\n\n const double rmsd = compute_rms_deviation(current_image, *m_ref_image);\n\n output += \"rms deviation \" + pretty_scalar(rmsd, 6);\n\n m_spp_count_history.push_back(spp_count);\n m_rmsd_history.push_back(rmsd);\n }\n\n RENDERER_LOG_DEBUG(\"%s\", output.c_str());\n }\n };\n\n auto_ptr m_statistics_func;\n auto_ptr m_statistics_thread;\n };\n}\n\n\n\/\/\n\/\/ ProgressiveFrameRendererFactory class implementation.\n\/\/\n\nProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory(\n const Project& project,\n ISampleGeneratorFactory* generator_factory,\n ITileCallbackFactory* callback_factory,\n const ParamArray& params)\n : m_project(project)\n , m_generator_factory(generator_factory) \n , m_callback_factory(callback_factory)\n , m_params(params)\n{\n}\n\nvoid ProgressiveFrameRendererFactory::release()\n{\n delete this;\n}\n\nIFrameRenderer* ProgressiveFrameRendererFactory::create()\n{\n return\n new ProgressiveFrameRenderer(\n m_project,\n m_generator_factory,\n m_callback_factory,\n m_params);\n}\n\nIFrameRenderer* ProgressiveFrameRendererFactory::create(\n const Project& project,\n ISampleGeneratorFactory* generator_factory,\n ITileCallbackFactory* callback_factory,\n const ParamArray& params)\n{\n return\n new ProgressiveFrameRenderer(\n project,\n generator_factory,\n callback_factory,\n params);\n}\n\n} \/\/ namespace renderer\nminor code tweaks.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"progressiveframerenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/kernel\/rendering\/progressive\/samplecounter.h\"\n#include \"renderer\/kernel\/rendering\/progressive\/samplegeneratorjob.h\"\n#include \"renderer\/kernel\/rendering\/accumulationframebuffer.h\"\n#include \"renderer\/kernel\/rendering\/framerendererbase.h\"\n#include \"renderer\/kernel\/rendering\/isamplegenerator.h\"\n#include \"renderer\/kernel\/rendering\/itilecallback.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n#include \"renderer\/modeling\/project\/project.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/analysis.h\"\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/genericimagefilereader.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/math\/fixedsizehistory.h\"\n#include \"foundation\/platform\/thread.h\"\n#include \"foundation\/platform\/timer.h\"\n#include \"foundation\/utility\/foreach.h\"\n#include \"foundation\/utility\/job.h\"\n#include \"foundation\/utility\/maplefile.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n#include \"foundation\/utility\/string.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace boost;\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n typedef vector SampleGeneratorVector;\n typedef vector TileCallbackVector;\n\n\n \/\/\n \/\/ Progressive frame renderer.\n \/\/\n\n class ProgressiveFrameRenderer\n : public FrameRendererBase\n {\n public:\n ProgressiveFrameRenderer(\n const Project& project,\n ISampleGeneratorFactory* generator_factory,\n ITileCallbackFactory* callback_factory,\n const ParamArray& params)\n : m_frame(*project.get_frame())\n , m_params(params)\n , m_sample_counter(m_params.m_max_sample_count)\n , m_ref_image_avg_lum(0.0)\n {\n \/\/ We must have a generator factory, but it's OK not to have a callback factory.\n assert(generator_factory);\n\n \/\/ Create an accumulation framebuffer.\n const CanvasProperties& props = m_frame.image().properties();\n m_framebuffer.reset(\n generator_factory->create_accumulation_framebuffer(\n props.m_canvas_width,\n props.m_canvas_height));\n\n \/\/ Create and initialize the job manager.\n m_job_manager.reset(\n new JobManager(\n global_logger(),\n m_job_queue,\n m_params.m_thread_count,\n JobManager::KeepRunningOnEmptyQueue));\n\n \/\/ Instantiate sample generators, one per rendering thread.\n for (size_t i = 0; i < m_params.m_thread_count; ++i)\n {\n m_sample_generators.push_back(\n generator_factory->create(i, m_params.m_thread_count));\n }\n\n \/\/ Instantiate tile callbacks, one per rendering thread.\n if (callback_factory)\n {\n for (size_t i = 0; i < m_params.m_thread_count; ++i)\n m_tile_callbacks.push_back(callback_factory->create());\n }\n\n \/\/ Load the reference image if one is specified.\n if (!m_params.m_ref_image_path.empty())\n {\n const string ref_image_path =\n project.get_search_paths().qualify(m_params.m_ref_image_path);\n\n RENDERER_LOG_DEBUG(\"loading reference image %s...\", ref_image_path.c_str());\n\n GenericImageFileReader reader;\n m_ref_image.reset(reader.read(ref_image_path.c_str()));\n\n m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get());\n\n RENDERER_LOG_DEBUG(\n \"reference image average luminance is %s.\",\n pretty_scalar(m_ref_image_avg_lum, 6).c_str());\n }\n\n print_rendering_thread_count(m_params.m_thread_count);\n }\n\n virtual ~ProgressiveFrameRenderer()\n {\n \/\/ Tell the statistics printing thread to stop.\n m_abort_switch.abort();\n\n \/\/ Wait until the statistics printing thread is terminated.\n m_statistics_thread->join();\n\n \/\/ Delete tile callbacks.\n for (const_each i = m_tile_callbacks; i; ++i)\n (*i)->release();\n\n \/\/ Delete sample generators.\n for (const_each i = m_sample_generators; i; ++i)\n (*i)->release();\n }\n\n virtual void release()\n {\n delete this;\n }\n\n virtual void render()\n {\n start_rendering();\n m_job_queue.wait_until_completion();\n }\n\n virtual void start_rendering()\n {\n assert(!is_rendering());\n assert(!m_job_queue.has_scheduled_or_running_jobs());\n\n m_abort_switch.clear();\n m_framebuffer->clear();\n m_sample_counter.clear();\n\n \/\/ Reset sample generators.\n for (size_t i = 0; i < m_sample_generators.size(); ++i)\n m_sample_generators[i]->reset();\n\n \/\/ Schedule the first batch of jobs.\n for (size_t i = 0; i < m_sample_generators.size(); ++i)\n {\n m_job_queue.schedule(\n new SampleGeneratorJob(\n m_frame,\n *m_framebuffer.get(),\n m_sample_generators[i],\n m_sample_counter,\n m_tile_callbacks[i],\n m_job_queue,\n i, \/\/ job index\n m_sample_generators.size(), \/\/ job count\n 0, \/\/ pass number\n m_abort_switch));\n }\n\n \/\/ Start job execution.\n m_job_manager->start();\n\n \/\/ Create and start the statistics printing thread.\n m_statistics_func.reset(\n new StatisticsFunc(\n m_frame,\n *m_framebuffer.get(),\n m_params.m_print_luminance_stats,\n m_ref_image.get(),\n m_ref_image_avg_lum,\n m_abort_switch));\n ThreadFunctionWrapper wrapper(m_statistics_func.get());\n m_statistics_thread.reset(new thread(wrapper));\n }\n\n virtual void stop_rendering()\n {\n \/\/ Tell rendering jobs and the statistics printing thread to stop.\n m_abort_switch.abort();\n\n \/\/ Stop job execution.\n m_job_manager->stop();\n\n \/\/ Delete all non-executed jobs.\n m_job_queue.clear_scheduled_jobs();\n\n \/\/ Wait until the statistics printing thread is terminated.\n m_statistics_thread->join();\n }\n\n virtual void terminate_rendering()\n {\n stop_rendering();\n\n m_statistics_func->write_rms_deviation_file();\n }\n\n virtual bool is_rendering() const\n {\n return m_job_queue.has_scheduled_or_running_jobs();\n }\n\n private:\n struct Parameters\n {\n const size_t m_thread_count; \/\/ number of rendering threads\n const uint64 m_max_sample_count; \/\/ maximum total number of samples to store in the framebuffer\n const bool m_print_luminance_stats; \/\/ compute and print luminance statistics?\n const string m_ref_image_path; \/\/ path to the reference image\n\n \/\/ Constructor, extract parameters.\n explicit Parameters(const ParamArray& params)\n : m_thread_count(FrameRendererBase::get_rendering_thread_count(params))\n , m_max_sample_count(params.get_optional(\"max_samples\", numeric_limits::max()))\n , m_print_luminance_stats(params.get_optional(\"print_luminance_statistics\", false))\n , m_ref_image_path(params.get_optional(\"reference_image\", \"\"))\n {\n }\n };\n\n Frame& m_frame;\n const Parameters m_params;\n SampleCounter m_sample_counter;\n\n auto_ptr m_framebuffer;\n\n JobQueue m_job_queue;\n auto_ptr m_job_manager;\n AbortSwitch m_abort_switch;\n\n SampleGeneratorVector m_sample_generators;\n TileCallbackVector m_tile_callbacks;\n\n auto_ptr m_ref_image;\n double m_ref_image_avg_lum;\n\n class StatisticsFunc\n : public NonCopyable\n {\n public:\n StatisticsFunc(\n Frame& frame,\n AccumulationFramebuffer& framebuffer,\n const bool print_luminance_stats,\n const Image* ref_image,\n const double ref_image_avg_lum,\n AbortSwitch& abort_switch)\n : m_frame(frame)\n , m_framebuffer(framebuffer)\n , m_print_luminance_stats(print_luminance_stats)\n , m_ref_image(ref_image)\n , m_ref_image_avg_lum(ref_image_avg_lum)\n , m_abort_switch(abort_switch)\n , m_timer_frequency(m_timer.frequency())\n , m_last_time(m_timer.read())\n , m_last_sample_count(0)\n {\n }\n\n void operator()()\n {\n while (!m_abort_switch.is_aborted())\n {\n const uint64 time = m_timer.read();\n const uint64 elapsed_ticks = time - m_last_time;\n const double elapsed_seconds = static_cast(elapsed_ticks) \/ m_timer_frequency;\n\n if (elapsed_seconds >= 1.0)\n {\n print_and_record_statistics(elapsed_seconds);\n m_last_time = time;\n }\n\n foundation::sleep(5); \/\/ needs full qualification\n }\n }\n\n void write_rms_deviation_file() const\n {\n if (!m_spp_count_history.empty())\n {\n MapleFile file(\"RMS Deviation.mpl\");\n file.define(\"rmsd\", m_spp_count_history, m_rmsd_history);\n file.plot(\"rmsd\", \"RMS Deviation\");\n }\n }\n\n private:\n Frame& m_frame;\n AccumulationFramebuffer& m_framebuffer;\n const bool m_print_luminance_stats;\n const Image* m_ref_image;\n const double m_ref_image_avg_lum;\n AbortSwitch& m_abort_switch;\n\n DefaultWallclockTimer m_timer;\n uint64 m_timer_frequency;\n uint64 m_last_time;\n\n uint64 m_last_sample_count;\n FixedSizeHistory m_sps_count_history; \/\/ samples per second history\n vector m_spp_count_history; \/\/ samples per pixel history\n vector m_rmsd_history; \/\/ RMS deviation history\n\n void print_and_record_statistics(const double elapsed_seconds)\n {\n print_performance_statistics(elapsed_seconds);\n\n if (m_print_luminance_stats || m_ref_image)\n print_and_record_convergence_statistics();\n }\n\n void print_performance_statistics(const double elapsed_seconds)\n {\n const uint64 new_sample_count = m_framebuffer.get_sample_count();\n const uint64 pixel_count = static_cast(m_frame.image().properties().m_pixel_count);\n const double spp_count = static_cast(new_sample_count) \/ pixel_count;\n const double sps_count = static_cast(new_sample_count - m_last_sample_count) \/ elapsed_seconds;\n\n m_sps_count_history.insert(sps_count);\n\n const uint64 avg_sps_count = truncate(m_sps_count_history.compute_average());\n\n RENDERER_LOG_INFO(\n \"%s samples, %s samples\/pixel, %s samples\/second\",\n pretty_uint(new_sample_count).c_str(),\n pretty_scalar(spp_count).c_str(),\n pretty_uint(avg_sps_count).c_str());\n\n m_last_sample_count = new_sample_count;\n }\n\n void print_and_record_convergence_statistics()\n {\n assert(m_print_luminance_stats || m_ref_image);\n\n string output;\n\n Image current_image(m_frame.image());\n m_frame.transform_to_output_color_space(current_image);\n\n if (m_print_luminance_stats)\n {\n const double avg_lum = compute_average_luminance(current_image);\n output += \"average luminance \" + pretty_scalar(avg_lum, 6);\n\n if (m_ref_image)\n {\n const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum);\n output += \" (\";\n output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3);\n output += \" error)\";\n }\n }\n\n if (m_ref_image)\n {\n if (m_print_luminance_stats)\n output += \", \";\n\n const double spp_count =\n static_cast(m_framebuffer.get_sample_count())\n \/ m_frame.image().properties().m_pixel_count;\n\n const double rmsd = compute_rms_deviation(current_image, *m_ref_image);\n\n output += \"rms deviation \" + pretty_scalar(rmsd, 6);\n\n m_spp_count_history.push_back(spp_count);\n m_rmsd_history.push_back(rmsd);\n }\n\n RENDERER_LOG_DEBUG(\"%s\", output.c_str());\n }\n };\n\n auto_ptr m_statistics_func;\n auto_ptr m_statistics_thread;\n };\n}\n\n\n\/\/\n\/\/ ProgressiveFrameRendererFactory class implementation.\n\/\/\n\nProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory(\n const Project& project,\n ISampleGeneratorFactory* generator_factory,\n ITileCallbackFactory* callback_factory,\n const ParamArray& params)\n : m_project(project)\n , m_generator_factory(generator_factory) \n , m_callback_factory(callback_factory)\n , m_params(params)\n{\n}\n\nvoid ProgressiveFrameRendererFactory::release()\n{\n delete this;\n}\n\nIFrameRenderer* ProgressiveFrameRendererFactory::create()\n{\n return\n new ProgressiveFrameRenderer(\n m_project,\n m_generator_factory,\n m_callback_factory,\n m_params);\n}\n\nIFrameRenderer* ProgressiveFrameRendererFactory::create(\n const Project& project,\n ISampleGeneratorFactory* generator_factory,\n ITileCallbackFactory* callback_factory,\n const ParamArray& params)\n{\n return\n new ProgressiveFrameRenderer(\n project,\n generator_factory,\n callback_factory,\n params);\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/platform\/hadoop\/hadoop_file_system.h\"\n\n#include \n\n#include \"tensorflow\/core\/lib\/core\/status.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/file_system.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/posix\/error.h\"\n#include \"third_party\/hadoop\/hdfs.h\"\n\nnamespace tensorflow {\n\ntemplate \nStatus BindFunc(void* handle, const char* name,\n std::function* func) {\n void* symbol_ptr = nullptr;\n TF_RETURN_IF_ERROR(\n Env::Default()->GetSymbolFromLibrary(handle, name, &symbol_ptr));\n *func = reinterpret_cast(symbol_ptr);\n return Status::OK();\n}\n\nclass LibHDFS {\n public:\n static LibHDFS* Load() {\n static LibHDFS* lib = []() -> LibHDFS* {\n LibHDFS* lib = new LibHDFS;\n lib->LoadAndBind();\n return lib;\n }();\n\n return lib;\n }\n\n \/\/ The status, if any, from failure to load.\n Status status() { return status_; }\n\n std::function hdfsBuilderConnect;\n std::function hdfsNewBuilder;\n std::function hdfsBuilderSetNameNode;\n std::function hdfsCloseFile;\n std::function hdfsPread;\n std::function hdfsWrite;\n std::function hdfsFlush;\n std::function hdfsHSync;\n std::function\n hdfsOpenFile;\n std::function hdfsExists;\n std::function hdfsListDirectory;\n std::function hdfsFreeFileInfo;\n std::function hdfsDelete;\n std::function hdfsCreateDirectory;\n std::function hdfsGetPathInfo;\n std::function hdfsRename;\n\n private:\n void LoadAndBind() {\n auto TryLoadAndBind = [this](const char* name, void** handle) -> Status {\n TF_RETURN_IF_ERROR(Env::Default()->LoadLibrary(name, handle));\n#define BIND_HDFS_FUNC(function) \\\n TF_RETURN_IF_ERROR(BindFunc(*handle, #function, &function));\n\n BIND_HDFS_FUNC(hdfsBuilderConnect);\n BIND_HDFS_FUNC(hdfsNewBuilder);\n BIND_HDFS_FUNC(hdfsBuilderSetNameNode);\n BIND_HDFS_FUNC(hdfsCloseFile);\n BIND_HDFS_FUNC(hdfsPread);\n BIND_HDFS_FUNC(hdfsWrite);\n BIND_HDFS_FUNC(hdfsFlush);\n BIND_HDFS_FUNC(hdfsHSync);\n BIND_HDFS_FUNC(hdfsOpenFile);\n BIND_HDFS_FUNC(hdfsExists);\n BIND_HDFS_FUNC(hdfsListDirectory);\n BIND_HDFS_FUNC(hdfsFreeFileInfo);\n BIND_HDFS_FUNC(hdfsDelete);\n BIND_HDFS_FUNC(hdfsCreateDirectory);\n BIND_HDFS_FUNC(hdfsGetPathInfo);\n BIND_HDFS_FUNC(hdfsRename);\n#undef BIND_HDFS_FUNC\n return Status::OK();\n };\n\n \/\/ libhdfs.so won't be in the standard locations. Use the path as specified\n \/\/ in the libhdfs documentation.\n char* hdfs_home = getenv(\"HADOOP_HDFS_HOME\");\n if (hdfs_home == nullptr) {\n status_ = errors::FailedPrecondition(\n \"Environment variable HADOOP_HDFS_HOME not set\");\n return;\n }\n string path = io::JoinPath(hdfs_home, \"lib\", \"native\", \"libhdfs.so\");\n status_ = TryLoadAndBind(path.c_str(), &handle_);\n return;\n }\n\n Status status_;\n void* handle_ = nullptr;\n};\n\nHadoopFileSystem::HadoopFileSystem() : hdfs_(LibHDFS::Load()) {}\n\nHadoopFileSystem::~HadoopFileSystem() {}\n\n\/\/ We rely on HDFS connection caching here. The HDFS client calls\n\/\/ org.apache.hadoop.fs.FileSystem.get(), which caches the connection\n\/\/ internally.\nStatus HadoopFileSystem::Connect(StringPiece fname, hdfsFS* fs) {\n TF_RETURN_IF_ERROR(hdfs_->status());\n\n StringPiece scheme, namenode, path;\n ParseURI(fname, &scheme, &namenode, &path);\n\n hdfsBuilder* builder = hdfs_->hdfsNewBuilder();\n if (scheme == \"file\") {\n hdfs_->hdfsBuilderSetNameNode(builder, nullptr);\n } else {\n hdfs_->hdfsBuilderSetNameNode(builder, namenode.ToString().c_str());\n }\n *fs = hdfs_->hdfsBuilderConnect(builder);\n if (*fs == nullptr) {\n return errors::NotFound(strerror(errno));\n }\n return Status::OK();\n}\n\nstring HadoopFileSystem::TranslateName(const string& name) const {\n StringPiece scheme, namenode, path;\n ParseURI(name, &scheme, &namenode, &path);\n return path.ToString();\n}\n\nclass HDFSRandomAccessFile : public RandomAccessFile {\n public:\n HDFSRandomAccessFile(const string& fname, LibHDFS* hdfs, hdfsFS fs,\n hdfsFile file)\n : filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}\n\n ~HDFSRandomAccessFile() override { hdfs_->hdfsCloseFile(fs_, file_); }\n\n Status Read(uint64 offset, size_t n, StringPiece* result,\n char* scratch) const override {\n Status s;\n char* dst = scratch;\n while (n > 0 && s.ok()) {\n tSize r = hdfs_->hdfsPread(fs_, file_, static_cast(offset), dst,\n static_cast(n));\n if (r > 0) {\n dst += r;\n n -= r;\n offset += r;\n } else if (r == 0) {\n s = Status(error::OUT_OF_RANGE, \"Read less bytes than requested\");\n } else if (errno == EINTR || errno == EAGAIN) {\n \/\/ hdfsPread may return EINTR too. Just retry.\n } else {\n s = IOError(filename_, errno);\n }\n }\n *result = StringPiece(scratch, dst - scratch);\n return s;\n }\n\n private:\n string filename_;\n LibHDFS* hdfs_;\n hdfsFS fs_;\n hdfsFile file_;\n};\n\nStatus HadoopFileSystem::NewRandomAccessFile(\n const string& fname, std::unique_ptr* result) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFile file =\n hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_RDONLY, 0, 0, 0);\n if (file == nullptr) {\n return IOError(fname, errno);\n }\n result->reset(new HDFSRandomAccessFile(fname, hdfs_, fs, file));\n return Status::OK();\n}\n\nclass HDFSWritableFile : public WritableFile {\n public:\n HDFSWritableFile(const string& fname, LibHDFS* hdfs, hdfsFS fs, hdfsFile file)\n : filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}\n\n ~HDFSWritableFile() override {\n if (file_ != nullptr) {\n Close();\n }\n }\n\n Status Append(const StringPiece& data) override {\n if (hdfs_->hdfsWrite(fs_, file_, data.data(),\n static_cast(data.size())) == -1) {\n return IOError(filename_, errno);\n }\n return Status::OK();\n }\n\n Status Close() override {\n Status result;\n if (hdfs_->hdfsCloseFile(fs_, file_) != 0) {\n result = IOError(filename_, errno);\n }\n hdfs_ = nullptr;\n fs_ = nullptr;\n file_ = nullptr;\n return result;\n }\n\n Status Flush() override {\n if (hdfs_->hdfsFlush(fs_, file_) != 0) {\n return IOError(filename_, errno);\n }\n return Status::OK();\n }\n\n Status Sync() override {\n if (hdfs_->hdfsHSync(fs_, file_) != 0) {\n return IOError(filename_, errno);\n }\n return Status::OK();\n }\n\n private:\n string filename_;\n LibHDFS* hdfs_;\n hdfsFS fs_;\n hdfsFile file_;\n};\n\nStatus HadoopFileSystem::NewWritableFile(\n const string& fname, std::unique_ptr* result) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFile file =\n hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_WRONLY, 0, 0, 0);\n if (file == nullptr) {\n return IOError(fname, errno);\n }\n result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));\n return Status::OK();\n}\n\nStatus HadoopFileSystem::NewAppendableFile(\n const string& fname, std::unique_ptr* result) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFile file = hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(),\n O_WRONLY | O_APPEND, 0, 0, 0);\n if (file == nullptr) {\n return IOError(fname, errno);\n }\n result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));\n return Status::OK();\n}\n\nStatus HadoopFileSystem::NewReadOnlyMemoryRegionFromFile(\n const string& fname, std::unique_ptr* result) {\n \/\/ hadoopReadZero() technically supports this call with the following\n \/\/ caveats:\n \/\/ - It only works up to 2 GB. We'd have to Stat() the file to ensure that\n \/\/ it fits.\n \/\/ - If not on the local filesystem, the entire file will be read, making\n \/\/ it inefficient for callers that assume typical mmap() behavior.\n return errors::Unimplemented(\"HDFS does not support ReadOnlyMemoryRegion\");\n}\n\nbool HadoopFileSystem::FileExists(const string& fname) {\n hdfsFS fs = nullptr;\n Status status = Connect(fname, &fs);\n if (!status.ok()) {\n LOG(ERROR) << \"Connect failed: \" << status.error_message();\n return false;\n }\n\n return hdfs_->hdfsExists(fs, TranslateName(fname).c_str()) == 0;\n}\n\nStatus HadoopFileSystem::GetChildren(const string& dir,\n std::vector* result) {\n result->clear();\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(dir, &fs));\n\n \/\/ hdfsListDirectory returns nullptr if the directory is empty. Do a separate\n \/\/ check to verify the directory exists first.\n FileStatistics stat;\n TF_RETURN_IF_ERROR(Stat(dir, &stat));\n\n int entries = 0;\n hdfsFileInfo* info =\n hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);\n if (info == nullptr) {\n if (stat.is_directory) {\n \/\/ Assume it's an empty directory.\n return Status::OK();\n }\n return IOError(dir, errno);\n }\n for (int i = 0; i < entries; i++) {\n result->push_back(io::Basename(info[i].mName).ToString());\n }\n hdfs_->hdfsFreeFileInfo(info, entries);\n return Status::OK();\n}\n\nStatus HadoopFileSystem::DeleteFile(const string& fname) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n if (hdfs_->hdfsDelete(fs, TranslateName(fname).c_str(),\n \/*recursive=*\/0) != 0) {\n return IOError(fname, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::CreateDir(const string& dir) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(dir, &fs));\n\n if (hdfs_->hdfsCreateDirectory(fs, TranslateName(dir).c_str()) != 0) {\n return IOError(dir, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::DeleteDir(const string& dir) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(dir, &fs));\n\n \/\/ Count the number of entries in the directory, and only delete if it's\n \/\/ non-empty. This is consistent with the interface, but note that there's\n \/\/ a race condition where a file may be added after this check, in which\n \/\/ case the directory will still be deleted.\n int entries = 0;\n hdfsFileInfo* info =\n hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);\n if (info != nullptr) {\n return IOError(dir, errno);\n }\n hdfs_->hdfsFreeFileInfo(info, entries);\n\n if (entries > 0) {\n return errors::FailedPrecondition(\"Cannot delete a non-empty directory.\");\n }\n if (hdfs_->hdfsDelete(fs, TranslateName(dir).c_str(),\n \/*recursive=*\/1) != 0) {\n return IOError(dir, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::GetFileSize(const string& fname, uint64* size) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());\n if (info == nullptr) {\n return IOError(fname, errno);\n }\n *size = static_cast(info->mSize);\n hdfs_->hdfsFreeFileInfo(info, 1);\n return Status::OK();\n}\n\nStatus HadoopFileSystem::RenameFile(const string& src, const string& target) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(src, &fs));\n\n if (hdfs_->hdfsRename(fs, TranslateName(src).c_str(),\n TranslateName(target).c_str()) != 0) {\n return IOError(src, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::Stat(const string& fname, FileStatistics* stats) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());\n if (info == nullptr) {\n return IOError(fname, errno);\n }\n stats->length = static_cast(info->mSize);\n stats->mtime_nsec = static_cast(info->mLastMod) * 1e9;\n stats->is_directory = info->mKind == kObjectKindDirectory;\n hdfs_->hdfsFreeFileInfo(info, 1);\n return Status::OK();\n}\n\nREGISTER_FILE_SYSTEM(\"hdfs\", HadoopFileSystem);\n\n} \/\/ namespace tensorflow\nFix usage of a temporary when passing the namenode as a c_str(). Change: 134095364\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/platform\/hadoop\/hadoop_file_system.h\"\n\n#include \n\n#include \"tensorflow\/core\/lib\/core\/status.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/file_system.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/posix\/error.h\"\n#include \"third_party\/hadoop\/hdfs.h\"\n\nnamespace tensorflow {\n\ntemplate \nStatus BindFunc(void* handle, const char* name,\n std::function* func) {\n void* symbol_ptr = nullptr;\n TF_RETURN_IF_ERROR(\n Env::Default()->GetSymbolFromLibrary(handle, name, &symbol_ptr));\n *func = reinterpret_cast(symbol_ptr);\n return Status::OK();\n}\n\nclass LibHDFS {\n public:\n static LibHDFS* Load() {\n static LibHDFS* lib = []() -> LibHDFS* {\n LibHDFS* lib = new LibHDFS;\n lib->LoadAndBind();\n return lib;\n }();\n\n return lib;\n }\n\n \/\/ The status, if any, from failure to load.\n Status status() { return status_; }\n\n std::function hdfsBuilderConnect;\n std::function hdfsNewBuilder;\n std::function hdfsBuilderSetNameNode;\n std::function hdfsCloseFile;\n std::function hdfsPread;\n std::function hdfsWrite;\n std::function hdfsFlush;\n std::function hdfsHSync;\n std::function\n hdfsOpenFile;\n std::function hdfsExists;\n std::function hdfsListDirectory;\n std::function hdfsFreeFileInfo;\n std::function hdfsDelete;\n std::function hdfsCreateDirectory;\n std::function hdfsGetPathInfo;\n std::function hdfsRename;\n\n private:\n void LoadAndBind() {\n auto TryLoadAndBind = [this](const char* name, void** handle) -> Status {\n TF_RETURN_IF_ERROR(Env::Default()->LoadLibrary(name, handle));\n#define BIND_HDFS_FUNC(function) \\\n TF_RETURN_IF_ERROR(BindFunc(*handle, #function, &function));\n\n BIND_HDFS_FUNC(hdfsBuilderConnect);\n BIND_HDFS_FUNC(hdfsNewBuilder);\n BIND_HDFS_FUNC(hdfsBuilderSetNameNode);\n BIND_HDFS_FUNC(hdfsCloseFile);\n BIND_HDFS_FUNC(hdfsPread);\n BIND_HDFS_FUNC(hdfsWrite);\n BIND_HDFS_FUNC(hdfsFlush);\n BIND_HDFS_FUNC(hdfsHSync);\n BIND_HDFS_FUNC(hdfsOpenFile);\n BIND_HDFS_FUNC(hdfsExists);\n BIND_HDFS_FUNC(hdfsListDirectory);\n BIND_HDFS_FUNC(hdfsFreeFileInfo);\n BIND_HDFS_FUNC(hdfsDelete);\n BIND_HDFS_FUNC(hdfsCreateDirectory);\n BIND_HDFS_FUNC(hdfsGetPathInfo);\n BIND_HDFS_FUNC(hdfsRename);\n#undef BIND_HDFS_FUNC\n return Status::OK();\n };\n\n \/\/ libhdfs.so won't be in the standard locations. Use the path as specified\n \/\/ in the libhdfs documentation.\n char* hdfs_home = getenv(\"HADOOP_HDFS_HOME\");\n if (hdfs_home == nullptr) {\n status_ = errors::FailedPrecondition(\n \"Environment variable HADOOP_HDFS_HOME not set\");\n return;\n }\n string path = io::JoinPath(hdfs_home, \"lib\", \"native\", \"libhdfs.so\");\n status_ = TryLoadAndBind(path.c_str(), &handle_);\n return;\n }\n\n Status status_;\n void* handle_ = nullptr;\n};\n\nHadoopFileSystem::HadoopFileSystem() : hdfs_(LibHDFS::Load()) {}\n\nHadoopFileSystem::~HadoopFileSystem() {}\n\n\/\/ We rely on HDFS connection caching here. The HDFS client calls\n\/\/ org.apache.hadoop.fs.FileSystem.get(), which caches the connection\n\/\/ internally.\nStatus HadoopFileSystem::Connect(StringPiece fname, hdfsFS* fs) {\n TF_RETURN_IF_ERROR(hdfs_->status());\n\n StringPiece scheme, namenode, path;\n ParseURI(fname, &scheme, &namenode, &path);\n const string nn = namenode.ToString();\n\n hdfsBuilder* builder = hdfs_->hdfsNewBuilder();\n if (scheme == \"file\") {\n hdfs_->hdfsBuilderSetNameNode(builder, nullptr);\n } else {\n hdfs_->hdfsBuilderSetNameNode(builder, nn.c_str());\n }\n *fs = hdfs_->hdfsBuilderConnect(builder);\n if (*fs == nullptr) {\n return errors::NotFound(strerror(errno));\n }\n return Status::OK();\n}\n\nstring HadoopFileSystem::TranslateName(const string& name) const {\n StringPiece scheme, namenode, path;\n ParseURI(name, &scheme, &namenode, &path);\n return path.ToString();\n}\n\nclass HDFSRandomAccessFile : public RandomAccessFile {\n public:\n HDFSRandomAccessFile(const string& fname, LibHDFS* hdfs, hdfsFS fs,\n hdfsFile file)\n : filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}\n\n ~HDFSRandomAccessFile() override { hdfs_->hdfsCloseFile(fs_, file_); }\n\n Status Read(uint64 offset, size_t n, StringPiece* result,\n char* scratch) const override {\n Status s;\n char* dst = scratch;\n while (n > 0 && s.ok()) {\n tSize r = hdfs_->hdfsPread(fs_, file_, static_cast(offset), dst,\n static_cast(n));\n if (r > 0) {\n dst += r;\n n -= r;\n offset += r;\n } else if (r == 0) {\n s = Status(error::OUT_OF_RANGE, \"Read less bytes than requested\");\n } else if (errno == EINTR || errno == EAGAIN) {\n \/\/ hdfsPread may return EINTR too. Just retry.\n } else {\n s = IOError(filename_, errno);\n }\n }\n *result = StringPiece(scratch, dst - scratch);\n return s;\n }\n\n private:\n string filename_;\n LibHDFS* hdfs_;\n hdfsFS fs_;\n hdfsFile file_;\n};\n\nStatus HadoopFileSystem::NewRandomAccessFile(\n const string& fname, std::unique_ptr* result) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFile file =\n hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_RDONLY, 0, 0, 0);\n if (file == nullptr) {\n return IOError(fname, errno);\n }\n result->reset(new HDFSRandomAccessFile(fname, hdfs_, fs, file));\n return Status::OK();\n}\n\nclass HDFSWritableFile : public WritableFile {\n public:\n HDFSWritableFile(const string& fname, LibHDFS* hdfs, hdfsFS fs, hdfsFile file)\n : filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}\n\n ~HDFSWritableFile() override {\n if (file_ != nullptr) {\n Close();\n }\n }\n\n Status Append(const StringPiece& data) override {\n if (hdfs_->hdfsWrite(fs_, file_, data.data(),\n static_cast(data.size())) == -1) {\n return IOError(filename_, errno);\n }\n return Status::OK();\n }\n\n Status Close() override {\n Status result;\n if (hdfs_->hdfsCloseFile(fs_, file_) != 0) {\n result = IOError(filename_, errno);\n }\n hdfs_ = nullptr;\n fs_ = nullptr;\n file_ = nullptr;\n return result;\n }\n\n Status Flush() override {\n if (hdfs_->hdfsFlush(fs_, file_) != 0) {\n return IOError(filename_, errno);\n }\n return Status::OK();\n }\n\n Status Sync() override {\n if (hdfs_->hdfsHSync(fs_, file_) != 0) {\n return IOError(filename_, errno);\n }\n return Status::OK();\n }\n\n private:\n string filename_;\n LibHDFS* hdfs_;\n hdfsFS fs_;\n hdfsFile file_;\n};\n\nStatus HadoopFileSystem::NewWritableFile(\n const string& fname, std::unique_ptr* result) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFile file =\n hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_WRONLY, 0, 0, 0);\n if (file == nullptr) {\n return IOError(fname, errno);\n }\n result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));\n return Status::OK();\n}\n\nStatus HadoopFileSystem::NewAppendableFile(\n const string& fname, std::unique_ptr* result) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFile file = hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(),\n O_WRONLY | O_APPEND, 0, 0, 0);\n if (file == nullptr) {\n return IOError(fname, errno);\n }\n result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));\n return Status::OK();\n}\n\nStatus HadoopFileSystem::NewReadOnlyMemoryRegionFromFile(\n const string& fname, std::unique_ptr* result) {\n \/\/ hadoopReadZero() technically supports this call with the following\n \/\/ caveats:\n \/\/ - It only works up to 2 GB. We'd have to Stat() the file to ensure that\n \/\/ it fits.\n \/\/ - If not on the local filesystem, the entire file will be read, making\n \/\/ it inefficient for callers that assume typical mmap() behavior.\n return errors::Unimplemented(\"HDFS does not support ReadOnlyMemoryRegion\");\n}\n\nbool HadoopFileSystem::FileExists(const string& fname) {\n hdfsFS fs = nullptr;\n Status status = Connect(fname, &fs);\n if (!status.ok()) {\n LOG(ERROR) << \"Connect failed: \" << status.error_message();\n return false;\n }\n\n return hdfs_->hdfsExists(fs, TranslateName(fname).c_str()) == 0;\n}\n\nStatus HadoopFileSystem::GetChildren(const string& dir,\n std::vector* result) {\n result->clear();\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(dir, &fs));\n\n \/\/ hdfsListDirectory returns nullptr if the directory is empty. Do a separate\n \/\/ check to verify the directory exists first.\n FileStatistics stat;\n TF_RETURN_IF_ERROR(Stat(dir, &stat));\n\n int entries = 0;\n hdfsFileInfo* info =\n hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);\n if (info == nullptr) {\n if (stat.is_directory) {\n \/\/ Assume it's an empty directory.\n return Status::OK();\n }\n return IOError(dir, errno);\n }\n for (int i = 0; i < entries; i++) {\n result->push_back(io::Basename(info[i].mName).ToString());\n }\n hdfs_->hdfsFreeFileInfo(info, entries);\n return Status::OK();\n}\n\nStatus HadoopFileSystem::DeleteFile(const string& fname) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n if (hdfs_->hdfsDelete(fs, TranslateName(fname).c_str(),\n \/*recursive=*\/0) != 0) {\n return IOError(fname, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::CreateDir(const string& dir) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(dir, &fs));\n\n if (hdfs_->hdfsCreateDirectory(fs, TranslateName(dir).c_str()) != 0) {\n return IOError(dir, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::DeleteDir(const string& dir) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(dir, &fs));\n\n \/\/ Count the number of entries in the directory, and only delete if it's\n \/\/ non-empty. This is consistent with the interface, but note that there's\n \/\/ a race condition where a file may be added after this check, in which\n \/\/ case the directory will still be deleted.\n int entries = 0;\n hdfsFileInfo* info =\n hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);\n if (info != nullptr) {\n return IOError(dir, errno);\n }\n hdfs_->hdfsFreeFileInfo(info, entries);\n\n if (entries > 0) {\n return errors::FailedPrecondition(\"Cannot delete a non-empty directory.\");\n }\n if (hdfs_->hdfsDelete(fs, TranslateName(dir).c_str(),\n \/*recursive=*\/1) != 0) {\n return IOError(dir, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::GetFileSize(const string& fname, uint64* size) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());\n if (info == nullptr) {\n return IOError(fname, errno);\n }\n *size = static_cast(info->mSize);\n hdfs_->hdfsFreeFileInfo(info, 1);\n return Status::OK();\n}\n\nStatus HadoopFileSystem::RenameFile(const string& src, const string& target) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(src, &fs));\n\n if (hdfs_->hdfsRename(fs, TranslateName(src).c_str(),\n TranslateName(target).c_str()) != 0) {\n return IOError(src, errno);\n }\n return Status::OK();\n}\n\nStatus HadoopFileSystem::Stat(const string& fname, FileStatistics* stats) {\n hdfsFS fs = nullptr;\n TF_RETURN_IF_ERROR(Connect(fname, &fs));\n\n hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());\n if (info == nullptr) {\n return IOError(fname, errno);\n }\n stats->length = static_cast(info->mSize);\n stats->mtime_nsec = static_cast(info->mLastMod) * 1e9;\n stats->is_directory = info->mKind == kObjectKindDirectory;\n hdfs_->hdfsFreeFileInfo(info, 1);\n return Status::OK();\n}\n\nREGISTER_FILE_SYSTEM(\"hdfs\", HadoopFileSystem);\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/micro\/benchmarks\/keyword_scrambled_model_data.h\"\n#include \"tensorflow\/lite\/micro\/benchmarks\/micro_benchmark.h\"\n#include \"tensorflow\/lite\/micro\/kernels\/fully_connected.h\"\n#include \"tensorflow\/lite\/micro\/kernels\/softmax.h\"\n#include \"tensorflow\/lite\/micro\/micro_error_reporter.h\"\n#include \"tensorflow\/lite\/micro\/micro_mutable_op_resolver.h\"\n#include \"tensorflow\/lite\/micro\/micro_profiler.h\"\n#include \"tensorflow\/lite\/micro\/system_setup.h\"\n\n\/*\n * Keyword Spotting Benchmark for performance optimizations. The model used in\n * this benchmark only serves as a reference. The values assigned to the model\n * weights and parameters are not representative of the original model.\n *\/\n\nnamespace tflite {\n\nusing KeywordBenchmarkRunner = MicroBenchmarkRunner;\nusing KeywordOpResolver = MicroMutableOpResolver<6>;\n\n#if defined(HEXAGON)\n\/\/ TODO(b\/174781826): reduce arena usage for optimized Hexagon kernels.\nconstexpr int kOptimizedKernelArenaIncrement = 21000;\n#else\nconstexpr int kOptimizedKernelArenaIncrement = 0;\n#endif\n\n\/\/ Create an area of memory to use for input, output, and intermediate arrays.\n\/\/ Align arena to 16 bytes to avoid alignment warnings on certain platforms.\nconstexpr int kTensorArenaSize = 21 * 1024 + kOptimizedKernelArenaIncrement;\nalignas(16) uint8_t tensor_arena[kTensorArenaSize];\n\nuint8_t benchmark_runner_buffer[sizeof(KeywordBenchmarkRunner)];\nuint8_t op_resolver_buffer[sizeof(KeywordOpResolver)];\n\n\/\/ Initialize benchmark runner instance explicitly to avoid global init order\n\/\/ issues on Sparkfun. Use new since static variables within a method\n\/\/ are automatically surrounded by locking, which breaks bluepill and stm32f4.\nKeywordBenchmarkRunner* CreateBenchmarkRunner(MicroProfiler* profiler) {\n \/\/ We allocate the KeywordOpResolver from a global buffer because the object's\n \/\/ lifetime must exceed that of the KeywordBenchmarkRunner object.\n KeywordOpResolver* op_resolver = new (op_resolver_buffer) KeywordOpResolver();\n op_resolver->AddFullyConnected(tflite::Register_FULLY_CONNECTED_INT8());\n op_resolver->AddQuantize();\n op_resolver->AddSoftmax(tflite::Register_SOFTMAX_INT8_INT16());\n op_resolver->AddSvdf();\n\n return new (benchmark_runner_buffer)\n KeywordBenchmarkRunner(g_keyword_scrambled_model_data, op_resolver,\n tensor_arena, kTensorArenaSize, profiler);\n}\n\nvoid KeywordRunNIerations(int iterations, const char* tag,\n KeywordBenchmarkRunner& benchmark_runner,\n MicroProfiler& profiler) {\n int32_t ticks = 0;\n for (int i = 0; i < iterations; ++i) {\n benchmark_runner.SetRandomInput(i);\n profiler.ClearEvents();\n benchmark_runner.RunSingleIteration();\n ticks += profiler.GetTotalTicks();\n }\n MicroPrintf(\"%s took %d ticks (%d ms)\", tag, ticks, TicksToMs(ticks));\n}\n\n} \/\/ namespace tflite\n\nint main(int argc, char** argv) {\n tflite::InitializeTarget();\n tflite::MicroProfiler profiler;\n\n uint32_t event_handle = profiler.BeginEvent(\"InitializeKeywordRunner\");\n tflite::KeywordBenchmarkRunner* benchmark_runner =\n CreateBenchmarkRunner(&profiler);\n profiler.EndEvent(event_handle);\n profiler.Log();\n MicroPrintf(\"\"); \/\/ null MicroPrintf serves as a newline.\n\n tflite::KeywordRunNIerations(1, \"KeywordRunNIerations(1)\", *benchmark_runner,\n profiler);\n profiler.Log();\n MicroPrintf(\"\"); \/\/ null MicroPrintf serves as a newline.\n\n tflite::KeywordRunNIerations(10, \"KeywordRunNIerations(10)\",\n *benchmark_runner, profiler);\n MicroPrintf(\"\"); \/\/ null MicroPrintf serves as a newline.\n\n benchmark_runner->PrintAllocations();\n}\nUpdated QC implementation no longer needs additional arena for keyword_benchmark. (#221)\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/micro\/benchmarks\/keyword_scrambled_model_data.h\"\n#include \"tensorflow\/lite\/micro\/benchmarks\/micro_benchmark.h\"\n#include \"tensorflow\/lite\/micro\/kernels\/fully_connected.h\"\n#include \"tensorflow\/lite\/micro\/kernels\/softmax.h\"\n#include \"tensorflow\/lite\/micro\/micro_error_reporter.h\"\n#include \"tensorflow\/lite\/micro\/micro_mutable_op_resolver.h\"\n#include \"tensorflow\/lite\/micro\/micro_profiler.h\"\n#include \"tensorflow\/lite\/micro\/system_setup.h\"\n\n\/*\n * Keyword Spotting Benchmark for performance optimizations. The model used in\n * this benchmark only serves as a reference. The values assigned to the model\n * weights and parameters are not representative of the original model.\n *\/\n\nnamespace tflite {\n\nusing KeywordBenchmarkRunner = MicroBenchmarkRunner;\nusing KeywordOpResolver = MicroMutableOpResolver<6>;\n\n\/\/ Create an area of memory to use for input, output, and intermediate arrays.\n\/\/ Align arena to 16 bytes to avoid alignment warnings on certain platforms.\nconstexpr int kTensorArenaSize = 21 * 1024;\nalignas(16) uint8_t tensor_arena[kTensorArenaSize];\n\nuint8_t benchmark_runner_buffer[sizeof(KeywordBenchmarkRunner)];\nuint8_t op_resolver_buffer[sizeof(KeywordOpResolver)];\n\n\/\/ Initialize benchmark runner instance explicitly to avoid global init order\n\/\/ issues on Sparkfun. Use new since static variables within a method\n\/\/ are automatically surrounded by locking, which breaks bluepill and stm32f4.\nKeywordBenchmarkRunner* CreateBenchmarkRunner(MicroProfiler* profiler) {\n \/\/ We allocate the KeywordOpResolver from a global buffer because the object's\n \/\/ lifetime must exceed that of the KeywordBenchmarkRunner object.\n KeywordOpResolver* op_resolver = new (op_resolver_buffer) KeywordOpResolver();\n op_resolver->AddFullyConnected(tflite::Register_FULLY_CONNECTED_INT8());\n op_resolver->AddQuantize();\n op_resolver->AddSoftmax(tflite::Register_SOFTMAX_INT8_INT16());\n op_resolver->AddSvdf();\n\n return new (benchmark_runner_buffer)\n KeywordBenchmarkRunner(g_keyword_scrambled_model_data, op_resolver,\n tensor_arena, kTensorArenaSize, profiler);\n}\n\nvoid KeywordRunNIerations(int iterations, const char* tag,\n KeywordBenchmarkRunner& benchmark_runner,\n MicroProfiler& profiler) {\n int32_t ticks = 0;\n for (int i = 0; i < iterations; ++i) {\n benchmark_runner.SetRandomInput(i);\n profiler.ClearEvents();\n benchmark_runner.RunSingleIteration();\n ticks += profiler.GetTotalTicks();\n }\n MicroPrintf(\"%s took %d ticks (%d ms)\", tag, ticks, TicksToMs(ticks));\n}\n\n} \/\/ namespace tflite\n\nint main(int argc, char** argv) {\n tflite::InitializeTarget();\n tflite::MicroProfiler profiler;\n\n uint32_t event_handle = profiler.BeginEvent(\"InitializeKeywordRunner\");\n tflite::KeywordBenchmarkRunner* benchmark_runner =\n CreateBenchmarkRunner(&profiler);\n profiler.EndEvent(event_handle);\n profiler.Log();\n MicroPrintf(\"\"); \/\/ null MicroPrintf serves as a newline.\n\n tflite::KeywordRunNIerations(1, \"KeywordRunNIerations(1)\", *benchmark_runner,\n profiler);\n profiler.Log();\n MicroPrintf(\"\"); \/\/ null MicroPrintf serves as a newline.\n\n tflite::KeywordRunNIerations(10, \"KeywordRunNIerations(10)\",\n *benchmark_runner, profiler);\n MicroPrintf(\"\"); \/\/ null MicroPrintf serves as a newline.\n\n benchmark_runner->PrintAllocations();\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \"constants.hpp\"\n#include \"local_datagram_client.hpp\"\n#include \"userspace_defs.h\"\n\nclass grabber_client final {\npublic:\n grabber_client(void) : client_(constants::get_grabber_socket_file_path()) {}\n\n void connect(void) {\n krbn_operation_type_connect data;\n data.console_user_server_pid = getpid();\n client_.send_to(reinterpret_cast(&data), sizeof(data));\n }\n\nprivate:\n local_datagram_client client_;\n};\nset operation_type manually#pragma once\n\n#include \n\n#include \"constants.hpp\"\n#include \"local_datagram_client.hpp\"\n#include \"userspace_defs.h\"\n\nclass grabber_client final {\npublic:\n grabber_client(void) : client_(constants::get_grabber_socket_file_path()) {}\n\n void connect(void) {\n krbn_operation_type_connect data;\n data.operation_type = KRBN_OPERATION_TYPE_CONNECT;\n data.console_user_server_pid = getpid();\n client_.send_to(reinterpret_cast(&data), sizeof(data));\n }\n\nprivate:\n local_datagram_client client_;\n};\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"SnoopTest.h\"\n\nclass UpBroadcastListener:\n public virtual EventReceiver\n{\npublic:\n virtual void SimpleCall(void) {}\n};\n\nclass SnoopTestBase:\n public UpBroadcastListener\n{\npublic:\n SnoopTestBase(void):\n m_simpleCall(false)\n {}\n\n bool m_simpleCall;\n\n void SimpleCall(void) override {\n m_simpleCall = true;\n }\n};\n\nclass Firer:\n public EventSender\n{\npublic:\n void DoFire(void) {\n Fire(&UpBroadcastListener::SimpleCall)();\n };\n};\n\nclass ChildMember:\n public SnoopTestBase\n{};\n\nclass ParentMember:\n public SnoopTestBase\n{\n};\n\nclass IgnoredParentMember:\n public SnoopTestBase\n{\n};\n\nclass Disallowed:\n public ContextMember,\n public UpBroadcastListener\n{\n};\n\nclass DisallowedGeneric:\n public UpBroadcastListener\n{\n};\n\nTEST_F(SnoopTest, VerifySimpleSnoop) {\n \/\/ Create the parent listener:\n AutoRequired parentMember;\n\n \/\/ This listener instance shouldn't get any messages:\n AutoRequired ignored;\n\n {\n \/\/ Create the child context and insert the child member:\n AutoCreateContext child;\n CurrentContextPusher pshr(child);\n AutoRequired childMember;\n\n \/\/ Snoop\n child->Snoop(parentMember);\n\n \/\/ Now fire an event from the child:\n AutoRequired firer;\n firer->DoFire();\n\n \/\/ Verify that the child itself got the message:\n EXPECT_TRUE(childMember->m_simpleCall) << \"Message not received by another member of the same context\";\n }\n\n \/\/ Verify that the parent got the message:\n EXPECT_TRUE(parentMember->m_simpleCall) << \"Parent context snooper didn't receive a message broadcast by the child context\";\n\n \/\/ Verify that the OTHER member got nothing:\n EXPECT_FALSE(ignored->m_simpleCall) << \"A member in a parent context received a child-context message even though it didn't request to snoop that context\";\n}\n\nTEST_F(SnoopTest, DetectDisallowedContextMember) {\n \/\/ Create two child contexts:\n AutoCreateContext sibling1;\n AutoCreateContext sibling2;\n\n \/\/ Create a member of the first context, and try to use it to snoop the second context:\n {\n CurrentContextPusher pshr(sibling1);\n AutoRequired disallow;\n\n EXPECT_THROW(sibling2->Snoop(disallow), std::runtime_error);\n }\n}\n\nTEST_F(SnoopTest, DetectDisallowedGeneralType) {\n \/\/ Create two child contexts:\n AutoCreateContext sibling1;\n AutoCreateContext sibling2;\n \n \/\/ Create a member again, but this time, use the generic type so we can't use a context membership check\n {\n CurrentContextPusher pshr(sibling1);\n AutoRequired disallowGeneric;\n\n EXPECT_THROW(sibling2->Snoop(disallowGeneric), std::runtime_error);\n }\n}Adding a unit test for Unsnoop#include \"stdafx.h\"\n#include \"SnoopTest.h\"\n\nclass UpBroadcastListener:\n public virtual EventReceiver\n{\npublic:\n virtual void SimpleCall(void) {}\n};\n\nclass SnoopTestBase:\n public UpBroadcastListener\n{\npublic:\n SnoopTestBase(void):\n m_simpleCall(false)\n {}\n\n bool m_simpleCall;\n\n void SimpleCall(void) override {\n m_simpleCall = true;\n }\n};\n\nclass Firer:\n public EventSender\n{\npublic:\n void DoFire(void) {\n Fire(&UpBroadcastListener::SimpleCall)();\n };\n};\n\nclass ChildMember:\n public SnoopTestBase\n{};\n\nclass ParentMember:\n public SnoopTestBase\n{\n};\n\nclass IgnoredParentMember:\n public SnoopTestBase\n{\n};\n\nclass Disallowed:\n public ContextMember,\n public UpBroadcastListener\n{\n};\n\nclass DisallowedGeneric:\n public UpBroadcastListener\n{\n};\n\nTEST_F(SnoopTest, VerifySimpleSnoop) {\n \/\/ Create the parent listener:\n AutoRequired parentMember;\n\n \/\/ This listener instance shouldn't get any messages:\n AutoRequired ignored;\n\n {\n \/\/ Create the child context and insert the child member:\n AutoCreateContext child;\n CurrentContextPusher pshr(child);\n AutoRequired childMember;\n\n \/\/ Snoop\n child->Snoop(parentMember);\n\n \/\/ Now fire an event from the child:\n AutoRequired firer;\n firer->DoFire();\n\n \/\/ Verify that the child itself got the message:\n EXPECT_TRUE(childMember->m_simpleCall) << \"Message not received by another member of the same context\";\n }\n\n \/\/ Verify that the parent got the message:\n EXPECT_TRUE(parentMember->m_simpleCall) << \"Parent context snooper didn't receive a message broadcast by the child context\";\n\n \/\/ Verify that the OTHER member got nothing:\n EXPECT_FALSE(ignored->m_simpleCall) << \"A member in a parent context received a child-context message even though it didn't request to snoop that context\";\n}\n\nTEST_F(SnoopTest, VerifyUnsnoop) {\n \/\/ Create a child context to snoop:\n AutoCreateContext snoopy;\n AutoRequired parentMember;\n\n \/\/ Add a member to be snooped:\n {\n CurrentContextPusher pshr(snoopy);\n AutoRequired childMember;\n\n \/\/ Snoop, unsnoop:\n snoopy->Snoop(parentMember);\n snoopy->Unsnoop(parentMember);\n\n \/\/ Fire one event:\n AutoRequired firer;\n firer->DoFire();\n\n \/\/ The local listener should have gotten something\n EXPECT_TRUE(childMember->m_simpleCall) << \"Message not received by a local listener after Unsnoop call\";\n }\n\n EXPECT_FALSE(parentMember->m_simpleCall) << \"ParentMember snooper received an event, even after an Unsnoop call was made\";\n}\n\nTEST_F(SnoopTest, DetectDisallowedContextMember) {\n \/\/ Create two child contexts:\n AutoCreateContext sibling1;\n AutoCreateContext sibling2;\n\n \/\/ Create a member of the first context, and try to use it to snoop the second context:\n {\n CurrentContextPusher pshr(sibling1);\n AutoRequired disallow;\n\n EXPECT_THROW(sibling2->Snoop(disallow), std::runtime_error);\n }\n}\n\nTEST_F(SnoopTest, DetectDisallowedGeneralType) {\n \/\/ Create two child contexts:\n AutoCreateContext sibling1;\n AutoCreateContext sibling2;\n \n \/\/ Create a member again, but this time, use the generic type so we can't use a context membership check\n {\n CurrentContextPusher pshr(sibling1);\n AutoRequired disallowGeneric;\n\n EXPECT_THROW(sibling2->Snoop(disallowGeneric), std::runtime_error);\n }\n}<|endoftext|>"} {"text":"#include \n#include \n\n#ifdef STAN_OPENCL\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n for (int i = 0; i < A.size(); i++) \\\n EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(MathMatrix, mdivide_left_tri_val) {\n using stan::math::mdivide_left_tri;\n stan::math::matrix_d Ad(2, 2);\n stan::math::matrix_d Ad_inv(2, 2);\n stan::math::matrix_d I;\n\n Ad << 2.0, 0.0, 5.0, 7.0;\n\n I = mdivide_left_tri(Ad, Ad);\n EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n\n Ad_inv = mdivide_left_tri(Ad);\n I = Ad * Ad_inv;\n EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n\n Ad << 2.0, 3.0, 0.0, 7.0;\n\n I = mdivide_left_tri(Ad, Ad);\n EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n}\n\n#ifdef STAN_OPENCL\nvoid mdivide_left_tri_lower_cl_test(int size) {\n boost::random::mt19937 rng;\n auto m1 = stan::math::matrix_d(size, size);\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < i; j++) {\n m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n }\n m1(i, i) = 20.0;\n for (int j = i + 1; j < size; j++) {\n m1(i, j) = 0.0;\n }\n }\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = size * 2;\n\n auto m1_cpu = stan::math::mdivide_left_tri(m1);\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = 0;\n\n auto m1_cl = stan::math::mdivide_left_tri(m1);\n\n EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mvidide_left_tri_lower_cl_small) {\n mvidive_left_tri_lower_cl_test(3);\n}\nTEST(MathMatrixCL, mvidide_left_tri_lower_cl_mid) {\n mvidive_left_tri_lower_cl_test(100);\n}\nTEST(MathMatrixCL, mvidide_left_tri_lower_cl_big) {\n mvidive_left_tri_lower_cl_test(500);\n}\n\nvoid mvidive_left_tri_upper_cl_test(int size) {\n boost::random::mt19937 rng;\n auto m1 = stan::math::matrix_d(size, size);\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < i; j++) {\n m1(i, j) = 0.0;\n }\n m1(i, i) = 20.0;\n for (int j = i + 1; j < size; j++) {\n m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n }\n }\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = size * 2;\n\n auto m1_cpu = stan::math::mdivide_left_tri(m1);\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = 0;\n\n auto m1_cl = stan::math::mdivide_left_tri(m1);\n\n EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mvidide_left_tri_upper_cl_small) {\n mvidive_left_tri_upper_cl_test(3);\n}\nTEST(MathMatrixCL, mvidide_left_tri_upper_cl_mid) {\n mvidive_left_tri_upper_cl_test(100);\n}\nTEST(MathMatrixCL, mvidide_left_tri_upper_cl_big) {\n mvidive_left_tri_upper_cl_test(500);\n}\n\nvoid mvidive_left_tri_cl_test(int size) {\n boost::random::mt19937 rng;\n auto m1 = stan::math::matrix_d(size, size);\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < i; j++) {\n m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n }\n m1(i, i) = 20.0;\n for (int j = i + 1; j < size; j++) {\n m1(i, j) = 0.0;\n }\n }\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = size * 2;\n\n auto m1_cpu = stan::math::mdivide_left_tri(m1, m1);\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = 0;\n\n auto m1_cl = stan::math::mdivide_left_tri(m1, m1);\n\n EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mvidide_left_tri_cl_small) { mvidive_left_tri_cl_test(3); }\nTEST(MathMatrixCL, mvidide_left_tri_cl_mid) { mvidive_left_tri_cl_test(100); }\nTEST(MathMatrixCL, mvidide_left_tri_cl_big) { mvidive_left_tri_cl_test(500); }\n\n#endif\nfixed mdivide typo#include \n#include \n\n#ifdef STAN_OPENCL\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n for (int i = 0; i < A.size(); i++) \\\n EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(MathMatrix, mdivide_left_tri_val) {\n using stan::math::mdivide_left_tri;\n stan::math::matrix_d Ad(2, 2);\n stan::math::matrix_d Ad_inv(2, 2);\n stan::math::matrix_d I;\n\n Ad << 2.0, 0.0, 5.0, 7.0;\n\n I = mdivide_left_tri(Ad, Ad);\n EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n\n Ad_inv = mdivide_left_tri(Ad);\n I = Ad * Ad_inv;\n EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n\n Ad << 2.0, 3.0, 0.0, 7.0;\n\n I = mdivide_left_tri(Ad, Ad);\n EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n}\n\n#ifdef STAN_OPENCL\nvoid mdivide_left_tri_lower_cl_test(int size) {\n boost::random::mt19937 rng;\n auto m1 = stan::math::matrix_d(size, size);\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < i; j++) {\n m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n }\n m1(i, i) = 20.0;\n for (int j = i + 1; j < size; j++) {\n m1(i, j) = 0.0;\n }\n }\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = size * 2;\n\n auto m1_cpu = stan::math::mdivide_left_tri(m1);\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = 0;\n\n auto m1_cl = stan::math::mdivide_left_tri(m1);\n\n EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_left_tri_lower_cl_small) {\n mdivide_left_tri_lower_cl_test(3);\n}\nTEST(MathMatrixCL, mdivide_left_tri_lower_cl_mid) {\n mdivide_left_tri_lower_cl_test(100);\n}\nTEST(MathMatrixCL, mdivide_left_tri_lower_cl_big) {\n mdivide_left_tri_lower_cl_test(500);\n}\n\nvoid mdivide_left_tri_upper_cl_test(int size) {\n boost::random::mt19937 rng;\n auto m1 = stan::math::matrix_d(size, size);\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < i; j++) {\n m1(i, j) = 0.0;\n }\n m1(i, i) = 20.0;\n for (int j = i + 1; j < size; j++) {\n m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n }\n }\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = size * 2;\n\n auto m1_cpu = stan::math::mdivide_left_tri(m1);\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = 0;\n\n auto m1_cl = stan::math::mdivide_left_tri(m1);\n\n EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_left_tri_upper_cl_small) {\n mdivide_left_tri_upper_cl_test(3);\n}\nTEST(MathMatrixCL, mdivide_left_tri_upper_cl_mid) {\n mdivide_left_tri_upper_cl_test(100);\n}\nTEST(MathMatrixCL, mdivide_left_tri_upper_cl_big) {\n mdivide_left_tri_upper_cl_test(500);\n}\n\nvoid mdivide_left_tri_cl_test(int size) {\n boost::random::mt19937 rng;\n auto m1 = stan::math::matrix_d(size, size);\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < i; j++) {\n m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n }\n m1(i, i) = 20.0;\n for (int j = i + 1; j < size; j++) {\n m1(i, j) = 0.0;\n }\n }\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = size * 2;\n\n auto m1_cpu = stan::math::mdivide_left_tri(m1, m1);\n\n stan::math::opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer\n = 0;\n\n auto m1_cl = stan::math::mdivide_left_tri(m1, m1);\n\n EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_left_tri_cl_small) { mdivide_left_tri_cl_test(3); }\nTEST(MathMatrixCL, mdivide_left_tri_cl_mid) { mdivide_left_tri_cl_test(100); }\nTEST(MathMatrixCL, mdivide_left_tri_cl_big) { mdivide_left_tri_cl_test(500); }\n#endif\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"Game.h\"\n\nint Game::MainLoop()\n{\n\tHRESULT hRes = 0;\n\tint res = 0;\n\n\tRECT rect;\n\tSetRect(&rect, 10, 10, 200, 50);\n\n\tint fps = 0;\n\tint frameCount = 0;\n\n\tdouble dt = 0;\n\tdouble dtAcc = 0;\n\n\tLARGE_INTEGER accTimePrecStart;\n\tLARGE_INTEGER accTimePrecEnd;\n\tLARGE_INTEGER accTimePrecFreq;\n\tQueryPerformanceFrequency(&accTimePrecFreq);\n\n\twhile (true)\n\t{\n\t\tQueryPerformanceCounter(&accTimePrecStart);\n\n\t\tif (PeekMessage(&RenderDeviceManager::msg, NULL, 0, 0, PM_REMOVE))\n\t\t{\n\t\t\tif (RenderDeviceManager::msg.message == WM_QUIT)\n\t\t\t\tbreak;\n\t\t\tTranslateMessage(&RenderDeviceManager::msg);\n\t\t\tDispatchMessage(&RenderDeviceManager::msg);\n\t\t}\n\n\t\t\/\/ Check render device\n\t\tif (!RenderDeviceManager::Created)\n\t\t{\n\t\t\tif (!OnNullRenderDevice())\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Check input device\n\t\tif (!InputDeviceManager::created)\n\t\t{\n\t\t\tInputDeviceManager::CreateInputDevices();\n\t\t\tif (!InputDeviceManager::created)\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Check inputs\n\t\tInputDeviceManager::CheckDevices();\n\t\tHandleKeyboard();\n\t\tHandleMouse();\n\n\t\t\/\/ Start scene drawing\n\t\tEnterCriticalSection(&worldLocker);\n\t\tRenderDeviceManager::RenderDevice->SetRenderTarget(0, RenderDeviceManager::DefaultRenderTarget);\n\t\thRes = RenderDeviceManager::RenderDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(255, 0, 0, 0), 1.0f, 0);\n\t\thRes = RenderDeviceManager::RenderDevice->BeginScene();\n\n\t\tif (WORLD != nullptr)\n\t\t\tDrawer::DrawWorld();\n\n\t\t\/\/ End scene drawing\n\t\thRes = RenderDeviceManager::RenderDevice->EndScene();\n\t\thRes = RenderDeviceManager::RenderDevice->Present(NULL, NULL, NULL, NULL);\n\t\tLeaveCriticalSection(&worldLocker);\n\n\t\tQueryPerformanceCounter(&accTimePrecEnd);\n\t\tdt = (double)(accTimePrecEnd.QuadPart - accTimePrecStart.QuadPart);\n\t\tdt \/= accTimePrecFreq.QuadPart;\n\n\t\tframeCount++;\n\t\tdtAcc += dt;\n\t\tif (dtAcc > 1)\n\t\t{\n\t\t\tfps = frameCount;\n\t\t\tdtAcc -= 1;\n\t\t\tframeCount = 0;\n\t\t}\n\t}\n\n\treturn RenderDeviceManager::msg.wParam;\n}\n- nothing meaningful#include \"stdafx.h\"\n#include \"Game.h\"\n\nint Game::MainLoop()\n{\n\tHRESULT hRes = 0;\n\tint res = 0;\n\n\tint fps = 0;\n\tint frameCount = 0;\n\n\tdouble dt = 0;\n\tdouble dtAcc = 0;\n\n\tLARGE_INTEGER accTimePrecStart;\n\tLARGE_INTEGER accTimePrecEnd;\n\tLARGE_INTEGER accTimePrecFreq;\n\tQueryPerformanceFrequency(&accTimePrecFreq);\n\n\twhile (true)\n\t{\n\t\tQueryPerformanceCounter(&accTimePrecStart);\n\n\t\tif (PeekMessage(&RenderDeviceManager::msg, NULL, 0, 0, PM_REMOVE))\n\t\t{\n\t\t\tif (RenderDeviceManager::msg.message == WM_QUIT)\n\t\t\t\tbreak;\n\t\t\tTranslateMessage(&RenderDeviceManager::msg);\n\t\t\tDispatchMessage(&RenderDeviceManager::msg);\n\t\t}\n\n\t\t\/\/ Check render device\n\t\tif (!RenderDeviceManager::Created)\n\t\t{\n\t\t\tif (!OnNullRenderDevice())\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Check input device\n\t\tif (!InputDeviceManager::created)\n\t\t{\n\t\t\tInputDeviceManager::CreateInputDevices();\n\t\t\tif (!InputDeviceManager::created)\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Check inputs\n\t\tInputDeviceManager::CheckDevices();\n\t\tHandleKeyboard();\n\t\tHandleMouse();\n\n\t\t\/\/ Start scene drawing\n\t\tEnterCriticalSection(&worldLocker);\n\t\tRenderDeviceManager::RenderDevice->SetRenderTarget(0, RenderDeviceManager::DefaultRenderTarget);\n\t\thRes = RenderDeviceManager::RenderDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(255, 0, 0, 0), 1.0f, 0);\n\t\thRes = RenderDeviceManager::RenderDevice->BeginScene();\n\n\t\tif (WORLD != nullptr)\n\t\t\tDrawer::DrawWorld();\n\n\t\t\/\/ End scene drawing\n\t\thRes = RenderDeviceManager::RenderDevice->EndScene();\n\t\thRes = RenderDeviceManager::RenderDevice->Present(NULL, NULL, NULL, NULL);\n\t\tLeaveCriticalSection(&worldLocker);\n\n\t\tQueryPerformanceCounter(&accTimePrecEnd);\n\t\tdt = (double)(accTimePrecEnd.QuadPart - accTimePrecStart.QuadPart);\n\t\tdt \/= accTimePrecFreq.QuadPart;\n\n\t\tframeCount++;\n\t\tdtAcc += dt;\n\t\tif (dtAcc > 1)\n\t\t{\n\t\t\tfps = frameCount;\n\t\t\tdtAcc -= 1;\n\t\t\tframeCount = 0;\n\t\t}\n\t}\n\n\treturn RenderDeviceManager::msg.wParam;\n}\n<|endoftext|>"} {"text":"#include \"GameBoardLayer.h\"\n#include \"GameManager.h\"\n#include \"CMO_tile.h\"\n#include \"CMO_dot.h\"\n#include \"CMO_line.h\"\n#include \"CMO_item.h\"\n\nUSING_NS_CC;\n\nbool CGameBoardLayer::init()\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ 1. super init first\n\tif ( !CCLayer::init() )\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ 2. add resources\n\tm_VisibleSize = CCDirector::sharedDirector()->getVisibleSize();\n\n\tint rowNum = 0;\n\tint columnNum = 0;\n\n\tswitch (CGameManager::GetInstance()->GetSelectedMapSize() )\n\t{\n\tcase MS_5X5:\n\t\trowNum = 5;\n\t\tcolumnNum = 5;\n\t\tbreak;\n\tcase MS_7X7:\n\t\trowNum = 7;\n\t\tcolumnNum = 7;\n\t\tbreak;\n\tcase MS_8X8:\n\t\trowNum = 8;\n\t\tcolumnNum = 8;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tm_Board = CCSprite::create(\n\t\tPLAYSCENE_BOARD.c_str(), \n\t\tCCRect(0, 0, columnNum * DEFAULT_TILE_WIDTH, rowNum * DEFAULT_TILE_HEIGHT)\n\t\t);\n\tm_Board->setAnchorPoint(ccp(0.5f, 0.5f));\n\tm_Board->setPosition(ccp(m_VisibleSize.width \/ 2, m_VisibleSize.height \/ 2) );\n\tthis->addChild(m_Board);\n\n\tm_BoardOrigin.x = m_VisibleSize.width\/2 - (float(columnNum)\/2 * DEFAULT_TILE_WIDTH);\n\tm_BoardOrigin.y = m_VisibleSize.height\/2;\t\n\n\tfloat m_OriginX = 0.0f;\n\tfloat m_OriginY = m_Board->getContentSize().height\/2;\n\n\tfloat m_LineOriginX = m_OriginX;\n\tfloat m_LineOriginY = m_OriginY;\n\n\tfloat m_DeltaX = DEFAULT_TILE_WIDTH\/2;\n\tfloat m_DeltaY = DEFAULT_TILE_HEIGHT\/2;\n\n\tfor (int i = 1; i < rowNum * 2 + 2; ++i)\n\t{\n\t\tfor (int j = 1; j < columnNum * 2 + 2; ++j)\n\t\t{\n\t\t\tIndexedPosition pos;\n\t\t\tpos.m_PosI = i;\n\t\t\tpos.m_PosJ = j;\n\n\t\t\t\/\/«‡, ø≠ ∏µŒ ¬¶ºˆ ¿œ ∞ÊøÏ ≈∏¿œ¿ª ±◊∏∞¥Ÿ.\n\t\t\tif ( i % 2 == 0 && j % 2 == 0)\n\t\t\t{\n\t\t\t\tCMO_tile* pTile = CMO_tile::create();\n\t\t\t\tpTile->setImage(pos);\n\t\t\t\tpTile->setPosition(ccp(m_OriginX+m_DeltaX*(j\/2-1),m_OriginY+m_DeltaY*(j\/2-1)));\n\n\t\t\t\tm_Board->addChild(pTile, 0);\n \n \/\/add item\n if (CGameManager::GetInstance()->GetItem(IndexedPosition(i,j))!= ITEM_NOTHING)\n {\n CMO_item* pItem = CMO_item::create();\n pItem->setImage(IndexedPosition(i,j));\n pItem->setPosition( ccp(m_OriginX+m_DeltaX*(j\/2-1),m_OriginY+m_DeltaY*(j\/2-1)) );\n m_Board->addChild(pItem, 4);\n }\n \n\t\t\t}\n\t\t\t\/\/ «‡, ø≠ ∏µŒ »¶ºˆ¿œ ∞ÊøÏ ¥Â¿ª ±◊∏∞¥Ÿ.\n\t\t\telse if ( i % 2 == 1 && j % 2 == 1)\n\t\t\t{\n\t\t\t\tCMO_dot* pDot = CMO_dot::Create();\n\t\t\t\tpDot->setPosition( ccp( m_OriginX+m_DeltaX*(j\/2),m_OriginY+m_DeltaY*(j\/2) ) );\n\n\t\t\t\tm_Board->addChild(pDot, 2);\n\t\t\t}\n\t\t\t\n\t\t\t\/\/±◊ ø‹ø°¥¬ º±¿Ã¥Ÿ.(i¬¶ºˆ\/j»¶ºˆ ∂«¥¬ i»¶ºˆ\/j¬¶ºˆ)\n\t\t\telse\n\t\t\t{\n\t\t\t\tCMO_line* pLine = CMO_line::create();\n\t\t\t\tpLine->setImage(pos);\n\n\t\t\t\tif (j%2 == 0)\n\t\t\t\t\tpLine->setPosition( ccp( m_LineOriginX+m_DeltaX*(j\/2-1),m_LineOriginY+m_DeltaY*(j\/2-1) ) );\n\t\t\t\telse\n\t\t\t\t\tpLine->setPosition( ccp( m_LineOriginX+m_DeltaX*(j\/2),m_LineOriginY+m_DeltaY*(j\/2) ) );\n\n\t\t\t\tm_Board->addChild(pLine, 1);\n\n\t\t\t}\n\n\t\t}\t\n\t\tif (i%2==0)\n\t\t{\n\t\t\tm_OriginX += m_DeltaX;\n\t\t\tm_OriginY -= m_DeltaY;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_LineOriginX += m_DeltaX;\n\t\t\tm_LineOriginY -= m_DeltaY;\n\t\t}\n\t\t}\n\t\n\n\tthis->setTouchEnabled(true);\n\t\n return true;\n}\n\nvoid CGameBoardLayer::DrawMapObjects()\n{\n\t\n}\n\nvoid CGameBoardLayer::ccTouchesBegan( CCSet* pTouches, CCEvent* pEvent )\n{\n\tCCTouch *pTouch = (CCTouch*)pTouches->anyObject();\n\n\tm_StartPoint = pTouch->getLocationInView();\n Highlight(m_StartPoint, 1);\n\tCCLog(\"Start point = %f, %f\", m_StartPoint.x,m_StartPoint.y);\n\n}\n\nvoid CGameBoardLayer::ccTouchesMoved(CCSet* pTouches, cocos2d::CCEvent* pEvent)\n{\n CCTouch *pTouch = (CCTouch*)pTouches->anyObject();\n m_middlePoint = pTouch->getLocationInView();\n Highlight(m_middlePoint, 0);\n}\n\nvoid CGameBoardLayer::ccTouchesEnded( CCSet *pTouches, CCEvent *pEvent )\n{\n\tCCTouch *pTouch = (CCTouch*)pTouches->anyObject();\n\n\tm_EndPoint = pTouch->getLocationInView();\n\tCCLog(\"End point = %f, %f\", m_EndPoint.x,m_EndPoint.y);\n removeChildByTag(0);\n removeChildByTag(1);\n\tDrawLine();\n}\n\nvoid CGameBoardLayer::DrawLine()\n{\n\tIndexedPosition startIndex = ConvertCoordinate(m_StartPoint);\n\tIndexedPosition endIndex = ConvertCoordinate(m_EndPoint);\n\t\n\tif (startIndex.m_PosI == endIndex.m_PosI)\n\t{\n\t\tif (endIndex.m_PosJ - startIndex.m_PosJ == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(startIndex.m_PosI, endIndex.m_PosJ - 1) );\n\t\t\tm_LineDirection = DI_UP;\n\t\t}\n\t\telse if (startIndex.m_PosJ - endIndex.m_PosJ == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(startIndex.m_PosI, startIndex.m_PosJ - 1) );\n\t\t\tm_LineDirection = DI_DOWN;\n\t\t}\n\t}\n\telse if (startIndex.m_PosJ == endIndex.m_PosJ)\n\t{\n\t\tif (endIndex.m_PosI - startIndex.m_PosI == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(endIndex.m_PosI - 1, startIndex.m_PosJ) );\n\t\t\tm_LineDirection = DI_DOWN;\n\t\t}\n\t\telse if (startIndex.m_PosI - endIndex.m_PosI == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(startIndex.m_PosI - 1, startIndex.m_PosJ) );\n\t\t\tm_LineDirection = DI_UP;\n\t\t}\n\t}\n}\n\nIndexedPosition CGameBoardLayer::ConvertCoordinate(CCPoint point)\n{\n\t\/\/새로운 변환 함수 작성\n\t\/\/각 행마다 기울기는 y = (DeltaY\/DeltaX) x 로 동일하지만, y절편이 -deltaY\/2만큼씩 감소한다.\n\t\/\/따라서 마우스 좌표값으로 해당 행을 구한 뒤, x값을 계산하여 열을 구해낼 수 있다.\n \n\t\/\/ (0,0)을 씬의 왼쪽 아래로 옮겨온다.\n\tpoint.y = m_VisibleSize.height - point.y - m_BoardOrigin.y;\n\tpoint.x -= m_BoardOrigin.x;\n\n\t\/\/이제 인덱스로 바꾼다.\n\tIndexedPosition indexedPosition;\n\n\t\/\/먼저, 범위를 벗어났는지 확인한다.\n\tif ( point.x > m_Board->getContentSize().width + TOUCH_AREA ||\n\t\tpoint.x< - TOUCH_AREA||\n\t\tpoint.y > m_Board->getContentSize().height\/2 + TOUCH_AREA ||\n\t\tpoint.y < -m_Board->getContentSize().height\/2- TOUCH_AREA)\n\t{\n\t\tindexedPosition.m_PosI = 0;\n\t\tindexedPosition.m_PosJ = 0;\n\t\treturn indexedPosition;\n\t}\n\n\tfloat deltaX = DEFAULT_TILE_WIDTH\/2;\n\tfloat deltaY = DEFAULT_TILE_HEIGHT\/2;\n\tfloat interceptY = 0.0f;\n\n\tfloat remainderX = static_cast(point.x) % static_cast(deltaX);\n\tfloat remainderY = static_cast(point.y) % static_cast(deltaY) ;\n\n\t\/\/일단 이 아이를 다듬어야 해.\n\n\tif ( remainderX < TOUCH_AREA)\n\t{\n\t\tpoint.x -= remainderX;\n\t}\n\telse if (remainderX > deltaX - TOUCH_AREA)\n\t{\n\t\tpoint.x +=(deltaX - remainderX);\n\t}\n\n\tif ( abs(remainderY) < TOUCH_AREA)\n\t{\n\t\tif (remainderY>=0)\n\t\t\tpoint.y -= remainderY;\n\t\telse\n\t\t\tpoint.y += remainderY;\n\t}\n\telse if (abs(remainderY) > deltaY - TOUCH_AREA)\n\t{\n\t\tif (remainderY>=0)\n\t\t\tpoint.y +=(deltaY - remainderY);\n\t\telse\n\t\t\tpoint.y -=(deltaY + remainderY);\n\t}\n\n\t\/\/y절편을 계산한다.\n\tinterceptY = point.y - (deltaY\/deltaX)*point.x;\n\n\t\/\/행을 계산한다.\n\tindexedPosition.m_PosI = static_cast(interceptY\/-DEFAULT_TILE_HEIGHT);\n\n\t\/\/열을 계산한다.\n\tindexedPosition.m_PosJ = static_cast(point.x - deltaX*indexedPosition.m_PosI)\/deltaX;\n\n\t\/\/점에 해당하도록 계산한다.\n\tindexedPosition.m_PosI = indexedPosition.m_PosI*2+1;\n\tindexedPosition.m_PosJ = indexedPosition.m_PosJ*2+1;\n\n\tCCLog(\"CONVERTED : %d, %d\",indexedPosition.m_PosI, indexedPosition.m_PosJ);\n\n\treturn indexedPosition;\n}\n\nvoid CGameBoardLayer::Highlight(cocos2d::CCPoint point,int isClicked)\n{\n if(getChildByTag(0)!=nullptr)\n {\n removeChildByTag(0);\n }\n \n \n \n \/\/Dot에 해당하는지 검사.\n \/\/마우스 오버시 무조건 highlight, 클릭된 것은 클릭이 끝날 때 까지 highlight 유지.\n \n IndexedPosition indexedPosition = ConvertCoordinate(point);\n point.y = m_VisibleSize.height - point.y - m_BoardOrigin.y;\n\tpoint.x -= m_BoardOrigin.x;\n \n \/\/범위를 벗어날 경우. 그냥 종료.\n\tif ( point.x > m_Board->getContentSize().width + TOUCH_AREA ||\n\t\tpoint.x< - TOUCH_AREA||\n\t\tpoint.y > m_Board->getContentSize().height\/2 + TOUCH_AREA ||\n\t\tpoint.y < -m_Board->getContentSize().height\/2- TOUCH_AREA)\n\t{\n\t\treturn;\n\t}\n \n float deltaX = DEFAULT_TILE_WIDTH\/2;\n\tfloat deltaY = DEFAULT_TILE_HEIGHT\/2;\n\t\n \/\/2. converted IndexPosition이 Dot에 해당하는지 검사.\n if(indexedPosition.m_PosI%2==1 && indexedPosition.m_PosJ%2 ==1)\n {\n \/\/고쳐라.\n if(isClicked == 0 && (abs(indexedPosition.m_PosI-ConvertCoordinate(m_StartPoint).m_PosI)+abs(indexedPosition.m_PosJ-ConvertCoordinate(m_StartPoint).m_PosJ))>2 )\n {\n return;\n }\n \n CCPoint tempP;\n \/\/시작점\n tempP.x = m_BoardOrigin.x + (indexedPosition.m_PosI\/2) * deltaX;\n tempP.y = m_BoardOrigin.y - (indexedPosition.m_PosI\/2) * deltaY;\n \n tempP.x += deltaX * (indexedPosition.m_PosJ\/2) ;\n tempP.y += deltaY * (indexedPosition.m_PosJ\/2) ;\n \n \n CCSprite* pHighlight = CCSprite::create(\"image\/playscene_dot_highlight.png\");\n \n pHighlight->setPosition(tempP);\n pHighlight->setTag(isClicked);\n addChild(pHighlight,3);\n \n \/\/line\n if (isClicked!=3)\n {\n removeChildByTag(3);\n CCSprite * lineHighlight = CCSprite::create();\n float wide = sqrtf(powf(m_middlePoint.x-tempP.x, 2)+powf(m_middlePoint.y-tempP.y,2));\n lineHighlight->setTextureRect(CCRectMake(0, 0, wide, 100));\n lineHighlight->setColor(ccc3(192,41,20));\n lineHighlight->setPosition(ccp(500,500));\n lineHighlight->setTag(3);\n addChild(lineHighlight,5);\n }\n }\n return;\n\t\n}\n\nvoid CGameBoardLayer::update(float dt)\n{\n\t\/\/ø©±‚º≠ childµÈ¿ª 昵•¿Ã∆Æ «ÿæfl «’¥œ¥Ÿ.\n\t\/\/CCLog(\"1111 Board layer updated\");\n\tCCArray* mapObjects = m_Board->getChildren();\n\n\tunsigned int objectNum = mapObjects->count();\n\tfor (unsigned int i = 0; i < objectNum; ++i)\n\t{\n\t\tmapObjects->objectAtIndex(i)->update(dt);\n\t}\n\t\n}불완전한 라인 터치감 진행중 !! 수정해야해#include \"GameBoardLayer.h\"\n#include \"GameManager.h\"\n#include \"CMO_tile.h\"\n#include \"CMO_dot.h\"\n#include \"CMO_line.h\"\n#include \"CMO_item.h\"\n\nUSING_NS_CC;\n\nbool CGameBoardLayer::init()\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ 1. super init first\n\tif ( !CCLayer::init() )\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ 2. add resources\n\tm_VisibleSize = CCDirector::sharedDirector()->getVisibleSize();\n\n\tint rowNum = 0;\n\tint columnNum = 0;\n\n\tswitch (CGameManager::GetInstance()->GetSelectedMapSize() )\n\t{\n\tcase MS_5X5:\n\t\trowNum = 5;\n\t\tcolumnNum = 5;\n\t\tbreak;\n\tcase MS_7X7:\n\t\trowNum = 7;\n\t\tcolumnNum = 7;\n\t\tbreak;\n\tcase MS_8X8:\n\t\trowNum = 8;\n\t\tcolumnNum = 8;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tm_Board = CCSprite::create(\n\t\tPLAYSCENE_BOARD.c_str(), \n\t\tCCRect(0, 0, columnNum * DEFAULT_TILE_WIDTH, rowNum * DEFAULT_TILE_HEIGHT)\n\t\t);\n\tm_Board->setAnchorPoint(ccp(0.5f, 0.5f));\n\tm_Board->setPosition(ccp(m_VisibleSize.width \/ 2, m_VisibleSize.height \/ 2) );\n\tthis->addChild(m_Board);\n\n\tm_BoardOrigin.x = m_VisibleSize.width\/2 - (float(columnNum)\/2 * DEFAULT_TILE_WIDTH);\n\tm_BoardOrigin.y = m_VisibleSize.height\/2;\t\n\n\tfloat m_OriginX = 0.0f;\n\tfloat m_OriginY = m_Board->getContentSize().height\/2;\n\n\tfloat m_LineOriginX = m_OriginX;\n\tfloat m_LineOriginY = m_OriginY;\n\n\tfloat m_DeltaX = DEFAULT_TILE_WIDTH\/2;\n\tfloat m_DeltaY = DEFAULT_TILE_HEIGHT\/2;\n\n\tfor (int i = 1; i < rowNum * 2 + 2; ++i)\n\t{\n\t\tfor (int j = 1; j < columnNum * 2 + 2; ++j)\n\t\t{\n\t\t\tIndexedPosition pos;\n\t\t\tpos.m_PosI = i;\n\t\t\tpos.m_PosJ = j;\n\n\t\t\t\/\/«‡, ø≠ ∏µŒ ¬¶ºˆ ¿œ ∞ÊøÏ ≈∏¿œ¿ª ±◊∏∞¥Ÿ.\n\t\t\tif ( i % 2 == 0 && j % 2 == 0)\n\t\t\t{\n\t\t\t\tCMO_tile* pTile = CMO_tile::create();\n\t\t\t\tpTile->setImage(pos);\n\t\t\t\tpTile->setPosition(ccp(m_OriginX+m_DeltaX*(j\/2-1),m_OriginY+m_DeltaY*(j\/2-1)));\n\n\t\t\t\tm_Board->addChild(pTile, 0);\n \n \/\/add item\n if (CGameManager::GetInstance()->GetItem(IndexedPosition(i,j))!= ITEM_NOTHING)\n {\n CMO_item* pItem = CMO_item::create();\n pItem->setImage(IndexedPosition(i,j));\n pItem->setPosition( ccp(m_OriginX+m_DeltaX*(j\/2-1),m_OriginY+m_DeltaY*(j\/2-1)) );\n m_Board->addChild(pItem, 5);\n }\n \n\t\t\t}\n\t\t\t\/\/ «‡, ø≠ ∏µŒ »¶ºˆ¿œ ∞ÊøÏ ¥Â¿ª ±◊∏∞¥Ÿ.\n\t\t\telse if ( i % 2 == 1 && j % 2 == 1)\n\t\t\t{\n\t\t\t\tCMO_dot* pDot = CMO_dot::Create();\n\t\t\t\tpDot->setPosition( ccp( m_OriginX+m_DeltaX*(j\/2),m_OriginY+m_DeltaY*(j\/2) ) );\n\n\t\t\t\tm_Board->addChild(pDot, 2);\n\t\t\t}\n\t\t\t\n\t\t\t\/\/±◊ ø‹ø°¥¬ º±¿Ã¥Ÿ.(i¬¶ºˆ\/j»¶ºˆ ∂«¥¬ i»¶ºˆ\/j¬¶ºˆ)\n\t\t\telse\n\t\t\t{\n\t\t\t\tCMO_line* pLine = CMO_line::create();\n\t\t\t\tpLine->setImage(pos);\n\n\t\t\t\tif (j%2 == 0)\n\t\t\t\t\tpLine->setPosition( ccp( m_LineOriginX+m_DeltaX*(j\/2-1),m_LineOriginY+m_DeltaY*(j\/2-1) ) );\n\t\t\t\telse\n\t\t\t\t\tpLine->setPosition( ccp( m_LineOriginX+m_DeltaX*(j\/2),m_LineOriginY+m_DeltaY*(j\/2) ) );\n\n\t\t\t\tm_Board->addChild(pLine, 1);\n\n\t\t\t}\n\n\t\t}\t\n\t\tif (i%2==0)\n\t\t{\n\t\t\tm_OriginX += m_DeltaX;\n\t\t\tm_OriginY -= m_DeltaY;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_LineOriginX += m_DeltaX;\n\t\t\tm_LineOriginY -= m_DeltaY;\n\t\t}\n\t\t}\n\t\n\n\tthis->setTouchEnabled(true);\n\t\n return true;\n}\n\nvoid CGameBoardLayer::DrawMapObjects()\n{\n\t\n}\n\nvoid CGameBoardLayer::ccTouchesBegan( CCSet* pTouches, CCEvent* pEvent )\n{\n\tCCTouch *pTouch = (CCTouch*)pTouches->anyObject();\n\n\tm_StartPoint = pTouch->getLocationInView();\n Highlight(m_StartPoint, 1);\n\tCCLog(\"Start point = %f, %f\", m_StartPoint.x,m_StartPoint.y);\n\n}\n\nvoid CGameBoardLayer::ccTouchesMoved(CCSet* pTouches, cocos2d::CCEvent* pEvent)\n{\n CCTouch *pTouch = (CCTouch*)pTouches->anyObject();\n m_middlePoint = pTouch->getLocationInView();\n Highlight(m_middlePoint, 0);\n}\n\nvoid CGameBoardLayer::ccTouchesEnded( CCSet *pTouches, CCEvent *pEvent )\n{\n\tCCTouch *pTouch = (CCTouch*)pTouches->anyObject();\n\n\tm_EndPoint = pTouch->getLocationInView();\n\tCCLog(\"End point = %f, %f\", m_EndPoint.x,m_EndPoint.y);\n removeChildByTag(0);\n removeChildByTag(1);\n\tDrawLine();\n}\n\nvoid CGameBoardLayer::DrawLine()\n{\n\tIndexedPosition startIndex = ConvertCoordinate(m_StartPoint);\n\tIndexedPosition endIndex = ConvertCoordinate(m_EndPoint);\n\t\n\tif (startIndex.m_PosI == endIndex.m_PosI)\n\t{\n\t\tif (endIndex.m_PosJ - startIndex.m_PosJ == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(startIndex.m_PosI, endIndex.m_PosJ - 1) );\n\t\t\tm_LineDirection = DI_UP;\n\t\t}\n\t\telse if (startIndex.m_PosJ - endIndex.m_PosJ == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(startIndex.m_PosI, startIndex.m_PosJ - 1) );\n\t\t\tm_LineDirection = DI_DOWN;\n\t\t}\n\t}\n\telse if (startIndex.m_PosJ == endIndex.m_PosJ)\n\t{\n\t\tif (endIndex.m_PosI - startIndex.m_PosI == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(endIndex.m_PosI - 1, startIndex.m_PosJ) );\n\t\t\tm_LineDirection = DI_DOWN;\n\t\t}\n\t\telse if (startIndex.m_PosI - endIndex.m_PosI == 2)\n\t\t{\n\t\t\tCGameManager::GetInstance()->DrawLine( IndexedPosition(startIndex.m_PosI - 1, startIndex.m_PosJ) );\n\t\t\tm_LineDirection = DI_UP;\n\t\t}\n\t}\n}\n\nIndexedPosition CGameBoardLayer::ConvertCoordinate(CCPoint point)\n{\n\t\/\/새로운 변환 함수 작성\n\t\/\/각 행마다 기울기는 y = (DeltaY\/DeltaX) x 로 동일하지만, y절편이 -deltaY\/2만큼씩 감소한다.\n\t\/\/따라서 마우스 좌표값으로 해당 행을 구한 뒤, x값을 계산하여 열을 구해낼 수 있다.\n \n\t\/\/ (0,0)을 씬의 왼쪽 아래로 옮겨온다.\n\tpoint.y = m_VisibleSize.height - point.y - m_BoardOrigin.y;\n\tpoint.x -= m_BoardOrigin.x;\n\n\t\/\/이제 인덱스로 바꾼다.\n\tIndexedPosition indexedPosition;\n\n\t\/\/먼저, 범위를 벗어났는지 확인한다.\n\tif ( point.x > m_Board->getContentSize().width + TOUCH_AREA ||\n\t\tpoint.x< - TOUCH_AREA||\n\t\tpoint.y > m_Board->getContentSize().height\/2 + TOUCH_AREA ||\n\t\tpoint.y < -m_Board->getContentSize().height\/2- TOUCH_AREA)\n\t{\n\t\tindexedPosition.m_PosI = 0;\n\t\tindexedPosition.m_PosJ = 0;\n\t\treturn indexedPosition;\n\t}\n\n\tfloat deltaX = DEFAULT_TILE_WIDTH\/2;\n\tfloat deltaY = DEFAULT_TILE_HEIGHT\/2;\n\tfloat interceptY = 0.0f;\n\n\tfloat remainderX = static_cast(point.x) % static_cast(deltaX);\n\tfloat remainderY = static_cast(point.y) % static_cast(deltaY) ;\n\n\t\/\/일단 이 아이를 다듬어야 해.\n\n\tif ( remainderX < TOUCH_AREA)\n\t{\n\t\tpoint.x -= remainderX;\n\t}\n\telse if (remainderX > deltaX - TOUCH_AREA)\n\t{\n\t\tpoint.x +=(deltaX - remainderX);\n\t}\n\n\tif ( abs(remainderY) < TOUCH_AREA)\n\t{\n\t\tif (remainderY>=0)\n\t\t\tpoint.y -= remainderY;\n\t\telse\n\t\t\tpoint.y += remainderY;\n\t}\n\telse if (abs(remainderY) > deltaY - TOUCH_AREA)\n\t{\n\t\tif (remainderY>=0)\n\t\t\tpoint.y +=(deltaY - remainderY);\n\t\telse\n\t\t\tpoint.y -=(deltaY + remainderY);\n\t}\n\n\t\/\/y절편을 계산한다.\n\tinterceptY = point.y - (deltaY\/deltaX)*point.x;\n\n\t\/\/행을 계산한다.\n\tindexedPosition.m_PosI = static_cast(interceptY\/-DEFAULT_TILE_HEIGHT);\n\n\t\/\/열을 계산한다.\n\tindexedPosition.m_PosJ = static_cast(point.x - deltaX*indexedPosition.m_PosI)\/deltaX;\n\n\t\/\/점에 해당하도록 계산한다.\n\tindexedPosition.m_PosI = indexedPosition.m_PosI*2+1;\n\tindexedPosition.m_PosJ = indexedPosition.m_PosJ*2+1;\n\n\tCCLog(\"CONVERTED : %d, %d\",indexedPosition.m_PosI, indexedPosition.m_PosJ);\n\n\treturn indexedPosition;\n}\n\nvoid CGameBoardLayer::Highlight(cocos2d::CCPoint point,int isClicked)\n{\n \/\/Dot에 해당하는지 검사.\n \/\/마우스 오버시 무조건 highlight, 클릭된 것은 클릭이 끝날 때 까지 highlight 유지.\n \n IndexedPosition indexedPosition = ConvertCoordinate(point);\n point.y = m_VisibleSize.height - point.y - m_BoardOrigin.y;\n\tpoint.x -= m_BoardOrigin.x;\n \n \/\/범위를 벗어날 경우. 그냥 종료.\n\tif ( point.x > m_Board->getContentSize().width + TOUCH_AREA ||\n\t\tpoint.x< - TOUCH_AREA||\n\t\tpoint.y > m_Board->getContentSize().height\/2 + TOUCH_AREA ||\n\t\tpoint.y < -m_Board->getContentSize().height\/2- TOUCH_AREA)\n\t{\n\t\treturn;\n\t}\n \/\/\/\n \n if(getChildByTag(0)!=nullptr)\n {\n removeChildByTag(0);\n }\n \n \/\/line\n if(isClicked==0)\n {\n if(getChildByTag(3)!=nullptr)\n {\n \/\/removeChildByTag(3);\n }\n getChildByTag(3)->setScaleX(sqrt(powf(m_middlePoint.x-m_StartPoint.x,2)+powf(m_middlePoint.y-m_StartPoint.y,2)));\n \n \/\/angle direction\n IndexedPosition startIdx = ConvertCoordinate(m_StartPoint);\n if(indexedPosition.m_PosI-startIdx.m_PosI==2)\n {\n getChildByTag(3)->setRotation(33.0f);\n }\n else if(indexedPosition.m_PosI-startIdx.m_PosI==-2)\n {\n getChildByTag(3)->setRotation(213.0f);\n }\n else if(indexedPosition.m_PosJ-startIdx.m_PosJ==-2)\n {\n getChildByTag(3)->setRotation(147.0f);\n }\n else if(indexedPosition.m_PosJ-startIdx.m_PosJ==2)\n {\n getChildByTag(3)->setRotation(327.0f);\n }\n \n }\n \n \/\/\/\n \n float deltaX = DEFAULT_TILE_WIDTH\/2;\n\tfloat deltaY = DEFAULT_TILE_HEIGHT\/2;\n\t\n \/\/2. converted IndexPosition이 Dot에 해당하는지 검사.\n if(indexedPosition.m_PosI%2==1 && indexedPosition.m_PosJ%2 ==1)\n {\n \/\/고쳐라.\n if(isClicked == 0 && (abs(indexedPosition.m_PosI-ConvertCoordinate(m_StartPoint).m_PosI)+abs(indexedPosition.m_PosJ-ConvertCoordinate(m_StartPoint).m_PosJ))>2 )\n {\n return;\n }\n \n CCPoint tempP;\n \/\/시작점\n tempP.x = m_BoardOrigin.x + (indexedPosition.m_PosI\/2) * deltaX;\n tempP.y = m_BoardOrigin.y - (indexedPosition.m_PosI\/2) * deltaY;\n \n tempP.x += deltaX * (indexedPosition.m_PosJ\/2) ;\n tempP.y += deltaY * (indexedPosition.m_PosJ\/2) ;\n \n \n CCSprite* pHighlight = CCSprite::create(\"image\/playscene_dot_highlight.png\");\n \n pHighlight->setPosition(tempP);\n pHighlight->setTag(isClicked);\n addChild(pHighlight,4);\n \n \/\/line\n if (isClicked==1)\n {\n removeChildByTag(3);\n CCSprite * lineHighlight = CCSprite::create();\n lineHighlight->setTextureRect(CCRectMake(0, 0, 1, 25));\n lineHighlight->setColor(ccc3(192,41,20));\n lineHighlight->setPosition(tempP);\n lineHighlight->setAnchorPoint(ccp(0,0.5));\n lineHighlight->setTag(3);\n addChild(lineHighlight,3);\n }\n\n }\n return;\n\t\n}\n\nvoid CGameBoardLayer::update(float dt)\n{\n\t\/\/ø©±‚º≠ childµÈ¿ª 昵•¿Ã∆Æ «ÿæfl «’¥œ¥Ÿ.\n\t\/\/CCLog(\"1111 Board layer updated\");\n\tCCArray* mapObjects = m_Board->getChildren();\n\n\tunsigned int objectNum = mapObjects->count();\n\tfor (unsigned int i = 0; i < objectNum; ++i)\n\t{\n\t\tmapObjects->objectAtIndex(i)->update(dt);\n\t}\n\t\n}<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2014 Greg Landrum and Rational Discovery LLC\n\/\/\n\/\/ @@ All Rights Reserved @@\n\/\/ This file is part of the RDKit.\n\/\/ The contents are covered by the terms of the BSD license\n\/\/ which is included in the file license.txt, found at the root\n\/\/ of the RDKit source tree.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/#include \n\n#include \nusing namespace std;\nusing namespace RDKit;\n\n\nvoid testBasics()\n{\n BOOST_LOG(rdInfoLog) << \"-----------------------\\n Basic Allocations\" << std::endl;\n Atom *a1 = new Atom(6);\n Bond *b1 = new Bond();\n ROMol *m1 = new ROMol();\n\n a1 = NULL; \/\/ intentional leak\n BOOST_LOG(rdInfoLog) << \"Finished\" << std::endl;\n}\n\nvoid testSMILES()\n{\n BOOST_LOG(rdInfoLog) << \"-----------------------\\n SMILES Read\" << std::endl;\n string smi=\"CCOC\";\n ROMol *m = SmilesToMol(smi);\n smi=\"C1COC1\";\n ROMol *m2 = SmilesToMol(smi);\n\n BOOST_LOG(rdInfoLog) << \"Finished\" << std::endl;\n}\n\nvoid testMol()\n{\n RWMol *m1 = new RWMol();\n m1->addAtom(new Atom(6),true,true);\n m1->addAtom(new Atom(6),true,true);\n m1->addAtom(new Atom(7),true,true);\n m1->addAtom(new Atom(6),true,true);\n m1->addBond(0,1,Bond::SINGLE);\n m1->addBond(1,2,Bond::SINGLE);\n m1->addBond(2,3,Bond::SINGLE);\n MolOps::sanitizeMol(*m1);\n}\n\n\/\/ -------------------------------------------------------------------\nint main()\n{\n RDLog::InitLogs();\n \/\/boost::logging::enable_logs(\"rdApp.info\");\n \/\/ test1(); \/\/ <- this doesn't seem to actually do anything\n#if 1\n \/\/testBasics();\n testSMILES();\n testMol();\n#endif\n\n return 0;\n}\nadd a larger smiles test\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2014 Greg Landrum and Rational Discovery LLC\n\/\/\n\/\/ @@ All Rights Reserved @@\n\/\/ This file is part of the RDKit.\n\/\/ The contents are covered by the terms of the BSD license\n\/\/ which is included in the file license.txt, found at the root\n\/\/ of the RDKit source tree.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/#include \n\n#include \nusing namespace std;\nusing namespace RDKit;\n\n\nvoid testBasics()\n{\n BOOST_LOG(rdInfoLog) << \"-----------------------\\n Basic Allocations\" << std::endl;\n Atom *a1 = new Atom(6);\n Bond *b1 = new Bond();\n ROMol *m1 = new ROMol();\n\n a1 = NULL; \/\/ intentional leak\n BOOST_LOG(rdInfoLog) << \"Finished\" << std::endl;\n}\n\nvoid testSMILES()\n{\n BOOST_LOG(rdInfoLog) << \"-----------------------\\n SMILES Read\" << std::endl;\n string smi=\"CCOC\";\n ROMol *m = SmilesToMol(smi);\n smi=\"C1COC1\";\n ROMol *m2 = SmilesToMol(smi);\n\n BOOST_LOG(rdInfoLog) << \"Finished\" << std::endl;\n}\n\nvoid testMol()\n{\n RWMol *m1 = new RWMol();\n m1->addAtom(new Atom(6),true,true);\n m1->addAtom(new Atom(6),true,true);\n m1->addAtom(new Atom(7),true,true);\n m1->addAtom(new Atom(6),true,true);\n m1->addBond(0,1,Bond::SINGLE);\n m1->addBond(1,2,Bond::SINGLE);\n m1->addBond(2,3,Bond::SINGLE);\n MolOps::sanitizeMol(*m1);\n}\n\nvoid testMols()\n{\n std::string smis[] = {\n \"CN1CCC[C@H]1c2cccnc2\",\n \"CC1(C)[C@@H](N2[C@@H](CC2=O)S1(=O)=O)C(=O)O\",\n \"C[C@]1(Cn2ccnn2)[C@@H](N3[C@@H](CC3=O)S1(=O)=O)C(=O)O\",\n \"CCN(CC)C(=O)[C@@H]1CN(C)[C@H]2Cc3c[nH]c4cccc(C2=C1)c34\",\n \"CCCN(CCC)[C@H]1CCc2c(O)cccc2C1\",\n \"CC(=O)NC[C@H]1CN(C(=O)O1)c2ccc(cc2)C(=O)C\",\n \"CC1(C)Oc2ccc3C=CC(=O)Oc3c2[C@@H](OC(=O)C45CCC(C)(C(=O)O4)C5(C)C)[C@H]1OC(=O)C67CCC(C)(C(=O)O6)C7(C)C\",\n \"CCC(C)(C)C(=O)C(=O)N1CCC[C@H]1C(=O)OCCCc2cccnc2\",\n \"CN1N=C(S\/C\/1=N\/C(=O)C)S(=O)(=O)N\",\n \"COc1ccc(cc1)[C@@H]2Sc3ccccc3N(CCN(C)C)C(=O)[C@@H]2OC(=O)C\",\n \"EOS\"\n };\n for(int i=0;smis[i]!=\"EOS\";++i){\n RWMol *m=SmilesToMol(smis[i]);\n }\n}\n\n\/\/ -------------------------------------------------------------------\nint main()\n{\n RDLog::InitLogs();\n \/\/boost::logging::enable_logs(\"rdApp.info\");\n \/\/ test1(); \/\/ <- this doesn't seem to actually do anything\n#if 1\n \/\/testBasics();\n \/\/testSMILES();\n \/\/testMol();\n testMols();\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2018-7-14 22:46:09\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \n#include \/\/ auto rd = bind(uniform_int_distribution(0, 9), mt19937(19920725));\n#include \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast(end_time-start_time).count();\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nconst long long MOD = 1000000007;\n\nlong long power(long long x, long long n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n % 2 == 1)\n {\n return (x * power(x, n - 1)) % MOD;\n }\n else\n {\n long long half = power(x, n \/ 2);\n return (half * half) % MOD;\n }\n}\n\nint N;\nll h[1010];\nll DP[2][1010];\n\nint main()\n{\n cin >> N;\n h[0] = 0;\n for (auto i = 1; i <= N; i++)\n {\n cin >> h[i];\n cerr << \"h[\" << i << \"] = \" << h[i] << endl;\n }\n DP[0][0] = 0;\n DP[0][1] = 1;\n for (auto i = 0; i < N; i++)\n {\n if (h[i] < h[i + 1])\n {\n if (h[i] >= 2)\n {\n ll t = h[i + 1] - h[i];\n ll p = power(2, t);\n DP[i + 1][1] = (((2 * DP[i][1]) % MOD) * p) % MOD;\n DP[i + 1][0] = (DP[i][0] * p) % MOD;\n }\n else if (h[i] == 1)\n {\n ll t = h[i + 1] - 2;\n ll p = power(2, t);\n DP[i + 1][1] = (((2 * DP[i][1]) % MOD) * p) % MOD;\n DP[i + 1][0] = DP[i + 1][1];\n }\n else\n {\n if (h[i + 1] >= 2)\n {\n ll t = h[i + 1] - 2;\n ll p = power(2, t);\n DP[i + 1][1] = (((2 * DP[i][1]) % MOD) * p) % MOD;\n DP[i + 1][0] = DP[i + 1][1];\n }\n else if (h[i + 1] == 1)\n {\n DP[i + 1][1] = (((DP[i][1] + DP[i][0]) % MOD) * 2) % MOD;\n DP[i + 1][0] = 0;\n }\n else\n {\n DP[i + 1][1] = (DP[i][1] + DP[i][0]) % MOD;\n DP[i + 1][0] = 0;\n }\n }\n }\n else if (h[i + 1] >= 2)\n {\n DP[i + 1][1] = (2 * DP[i][1]) % MOD;\n DP[i + 1][0] = DP[i][0];\n }\n else if (h[i + 1] == 1)\n {\n DP[i + 1][1] = (((DP[i][1] + DP[i][0]) % MOD) * 2) % MOD;\n DP[i + 1][0] = 0;\n }\n else\n {\n DP[i + 1][1] = (DP[i][1] + DP[i][0]) % MOD;\n DP[i + 1][0] = 0;\n }\n cerr << \"DP[\" << i + 1 << \"] = \" << DP[i + 1][0] << \" \" << DP[i + 1][1] << endl;\n }\n cout << (DP[N][1] + DP[N][0]) % MOD << endl;\n}tried D.cpp to 'D'\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2018-7-14 22:46:09\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \n#include \/\/ auto rd = bind(uniform_int_distribution(0, 9), mt19937(19920725));\n#include \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast(end_time-start_time).count();\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nconst long long MOD = 1000000007;\n\nlong long power(long long x, long long n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n % 2 == 1)\n {\n return (x * power(x, n - 1)) % MOD;\n }\n else\n {\n long long half = power(x, n \/ 2);\n return (half * half) % MOD;\n }\n}\n\nint N;\nll h[1010];\nll DP[2][1010];\n\nint main()\n{\n cin >> N;\n h[0] = 0;\n for (auto i = 1; i <= N; i++)\n {\n cin >> h[i];\n \/\/ cerr << \"h[\" << i << \"] = \" << h[i] << endl;\n }\n DP[0][0] = 0;\n DP[0][1] = 1;\n for (auto i = 0; i < N; i++)\n {\n cerr << \"i = \" << i << endl;\n if (h[i] < h[i + 1])\n {\n if (h[i] >= 2)\n {\n ll t = h[i + 1] - h[i];\n ll p = power(2, t);\n DP[i + 1][1] = (((2 * DP[i][1]) % MOD) * p) % MOD;\n DP[i + 1][0] = (DP[i][0] * p) % MOD;\n }\n else if (h[i] == 1)\n {\n ll t = h[i + 1] - 2;\n ll p = power(2, t);\n DP[i + 1][1] = (((2 * DP[i][1]) % MOD) * p) % MOD;\n DP[i + 1][0] = DP[i + 1][1];\n }\n else\n {\n if (h[i + 1] >= 2)\n {\n ll t = h[i + 1] - 2;\n ll p = power(2, t);\n DP[i + 1][1] = (((2 * DP[i][1]) % MOD) * p) % MOD;\n DP[i + 1][0] = DP[i + 1][1];\n }\n else if (h[i + 1] == 1)\n {\n DP[i + 1][1] = (((DP[i][1] + DP[i][0]) % MOD) * 2) % MOD;\n DP[i + 1][0] = 0;\n }\n else\n {\n DP[i + 1][1] = (DP[i][1] + DP[i][0]) % MOD;\n DP[i + 1][0] = 0;\n }\n }\n }\n else if (h[i + 1] >= 2)\n {\n DP[i + 1][1] = (2 * DP[i][1]) % MOD;\n DP[i + 1][0] = DP[i][0];\n }\n else if (h[i + 1] == 1)\n {\n DP[i + 1][1] = (((DP[i][1] + DP[i][0]) % MOD) * 2) % MOD;\n DP[i + 1][0] = 0;\n }\n else\n {\n DP[i + 1][1] = (DP[i][1] + DP[i][0]) % MOD;\n DP[i + 1][0] = 0;\n }\n cerr << \"DP[\" << i + 1 << \"] = \" << DP[i + 1][0] << \" \" << DP[i + 1][1] << endl;\n }\n cout << (DP[N][1] + DP[N][0]) % MOD << endl;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 5\/16\/2020, 9:50:51 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n ll A{0}, B{0};\n min_heap R;\n max_heap L;\n int Q;\n cin >> Q;\n for (auto q = 0; q < Q; ++q)\n {\n int c;\n cin >> c;\n if (c == 1)\n {\n ll a, b;\n cin >> a >> b;\n B += b;\n R.push(a);\n L.push(a);\n auto r{R.top()};\n auto l{L.top()};\n A += abs(r - l);\n if (r < l)\n {\n R.pop();\n L.pop();\n R.push(l);\n L.push(r);\n }\n }\n else\n {\n cout << A + B << endl;\n }\n }\n}\ntried F.cpp to 'F'#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 5\/16\/2020, 9:50:51 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n ll A{0}, B{0};\n min_heap R;\n max_heap L;\n int Q;\n cin >> Q;\n for (auto q = 0; q < Q; ++q)\n {\n int c;\n cin >> c;\n if (c == 1)\n {\n ll a, b;\n cin >> a >> b;\n B += b;\n R.push(a);\n L.push(a);\n auto r{R.top()};\n auto l{L.top()};\n A += abs(r - l);\n if (r < l)\n {\n R.pop();\n L.pop();\n R.push(l);\n L.push(r);\n }\n }\n else\n {\n cout << R.top() << \" \" << A + B << endl;\n }\n }\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 6\/9\/2019, 9:09:02 PM\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\n\/*\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\n\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n*\/\n\n\/*\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n*\/\n\n\/\/ const ll MOD = 1000000007;\n\nint H, W;\nstring S[2010];\nbool X[2010][2010];\nll A[2010][2010];\nll B[2010][2010];\n\nll solve()\n{\n for (auto i = 0; i < H; i++)\n {\n ll t = 0;\n for (auto j = 0; j < W; j++)\n {\n if (X[i][j])\n {\n t++;\n }\n else\n {\n for (auto k = j; k > j - t; k--)\n {\n A[i][k] = t;\n }\n t = 0;\n }\n }\n for (auto k = W - 1; k > W - 1 - t; k--)\n {\n A[i][k] = t;\n }\n }\n for (auto j = 0; j < W; j++)\n {\n ll t = 0;\n for (auto i = 0; i < H; i++)\n {\n if (X[i][j])\n {\n t++;\n }\n else\n {\n for (auto k = i; k > i - t; k--)\n {\n B[k][j] = t;\n }\n t = 0;\n }\n }\n for (auto k = H - 1; k > H - 1 - t; k--)\n {\n B[k][j] = t;\n }\n }\n ll ans = 0;\n for (auto i = 0; i < H; i++)\n {\n for (auto j = 0; j < W; j++)\n {\n ans = max(ans, A[i][j] + B[i][j]);\n }\n }\n return ans;\n}\n\nint main()\n{\n cin >> H >> W;\n for (auto i = 0; i < H; i++)\n {\n cin >> S[i];\n }\n for (auto i = 0; i < H; i++)\n {\n for (auto j = 0; j < W; j++)\n {\n X[i][j] = (S[i][j] == '.');\n }\n }\n cout << solve() - 1 << endl;\n}tried D.cpp to 'D'#define DEBUG 1\n\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 6\/9\/2019, 9:09:02 PM\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\n\/*\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\n\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n*\/\n\n\/*\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n*\/\n\n\/\/ const ll MOD = 1000000007;\n\nint H, W;\nstring S[2010];\nbool X[2010][2010];\nll A[2010][2010];\nll B[2010][2010];\n\nll solve()\n{\n for (auto i = 0; i < H; i++)\n {\n ll t = 0;\n for (auto j = 0; j < W; j++)\n {\n if (X[i][j])\n {\n t++;\n }\n else\n {\n for (auto k = j; k > j - t; k--)\n {\n A[i][k] = t;\n }\n t = 0;\n }\n }\n for (auto k = W - 1; k > W - 1 - t; k--)\n {\n A[i][k] = t;\n }\n }\n for (auto j = 0; j < W; j++)\n {\n ll t = 0;\n for (auto i = 0; i < H; i++)\n {\n if (X[i][j])\n {\n t++;\n }\n else\n {\n for (auto k = i; k > i - t; k--)\n {\n B[k][j] = t;\n }\n t = 0;\n }\n }\n for (auto k = H - 1; k > H - 1 - t; k--)\n {\n B[k][j] = t;\n }\n }\n ll ans = 0;\n for (auto i = 0; i < H; i++)\n {\n for (auto j = 0; j < W; j++)\n {\n ans = max(ans, A[i][j] + B[i][j]);\n }\n }\n return ans;\n}\n\nint main()\n{\n cin >> H >> W;\n for (auto i = 0; i < H; i++)\n {\n cin >> S[i];\n }\n for (auto i = 0; i < H; i++)\n {\n for (auto j = 0; j < W; j++)\n {\n X[i][j] = (S[i][j] == '.');\n }\n }\n solve();\n#if DEBUG == 1\n cerr << \"A\" << endl;\n for (auto i = 0; i < H; i++)\n {\n for (auto j = 0; j < W; j++)\n {\n cerr << A[i][j];\n }\n cerr << endl;\n }\n cerr << \"B\" << endl;\n for (auto i = 0; i < H; i++)\n {\n for (auto j = 0; j < W; j++)\n {\n cerr << B[i][j];\n }\n cerr << endl;\n }\n#endif\n \/\/ cout << solve() - 1 << endl;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 7\/7\/2019, 9:44:50 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n#define maxs(x, y) (x = max(x, y))\n#define mins(x, y) (x = min(x, y))\nusing ll = long long;\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\nconst int MAX_SIZE = 1000010;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a) { return (*this *= power(MOD - 2)); }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nmint inv[MAX_SIZE];\nmint fact[MAX_SIZE];\nmint factinv[MAX_SIZE];\nvoid init()\n{\n inv[1] = 1;\n for (int i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (int i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n}\nmint choose(int n, int k)\n{\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n}\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ const double epsilon = 1e-10;\n\/\/ const ll infty = 1000000000000000LL;\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\nll N, K;\nvector V[100010];\nvector children[100010];\nbool visited[100010];\n\nvoid dfs(int n)\n{\n if (!visited[n])\n {\n visited[n] = true;\n for (auto x : V[n])\n {\n if (!visited[x])\n {\n children[n].push_back(x);\n dfs(x);\n }\n }\n }\n}\n\nint main()\n{\n init();\n cin >> N >> K;\n for (auto i = 0; i < N; i++)\n {\n int a, b;\n cin >> a >> b;\n a--;\n b--;\n V[a].push_back(b);\n V[b].push_back(a);\n }\n dfs(0);\n queue Q;\n Q.push(0);\n mint ans = 1;\n while (!Q.empty())\n {\n int n = Q.front();\n Q.pop();\n ll child = children[n].size();\n ll D = K - 1;\n if (n != 0)\n {\n D--;\n }\n ans *= choose(D, child);\n for (auto x : children[n])\n {\n Q.push(x);\n }\n }\n cout << ans << endl;\n}tried E.cpp to 'E'#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 7\/7\/2019, 9:44:50 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n#define maxs(x, y) (x = max(x, y))\n#define mins(x, y) (x = min(x, y))\nusing ll = long long;\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\nconst int MAX_SIZE = 1000010;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a) { return (*this *= power(MOD - 2)); }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nmint inv[MAX_SIZE];\nmint fact[MAX_SIZE];\nmint factinv[MAX_SIZE];\nvoid init()\n{\n inv[1] = 1;\n for (int i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (int i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n}\nmint choose(int n, int k)\n{\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n}\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ const double epsilon = 1e-10;\n\/\/ const ll infty = 1000000000000000LL;\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\nll N, K;\nvector V[100010];\nvector children[100010];\nbool visited[100010];\n\nvoid dfs(int n)\n{\n if (!visited[n])\n {\n visited[n] = true;\n for (auto x : V[n])\n {\n if (!visited[x])\n {\n children[n].push_back(x);\n dfs(x);\n }\n }\n }\n}\n\nint main()\n{\n init();\n cin >> N >> K;\n for (auto i = 0; i < N; i++)\n {\n int a, b;\n cin >> a >> b;\n a--;\n b--;\n V[a].push_back(b);\n V[b].push_back(a);\n }\n dfs(0);\n queue Q;\n Q.push(0);\n mint ans = 1;\n#if DEBUG == 1\n cerr << \"Here\" << endl;\n#endif\n while (!Q.empty())\n {\n int n = Q.front();\n Q.pop();\n ll child = children[n].size();\n ll D = K - 1;\n if (n != 0)\n {\n D--;\n }\n ans *= choose(D, child);\n for (auto x : children[n])\n {\n Q.push(x);\n }\n }\n cout << ans << endl;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 8\/12\/2019, 7:02:46 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n#define maxs(x, y) (x = max(x, y))\n#define mins(x, y) (x = min(x, y))\nusing ll = long long;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a)\n {\n mint b{a};\n return *this *= b.power(MOD - 2);\n }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nclass combination\n{\npublic:\n vector inv, fact, factinv;\n static int MAX_SIZE;\n combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n};\nint combination::MAX_SIZE = 3000010;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon = 1e-10;\n\/\/ constexpr ll infty = 1000000000000000LL;\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\nvector count(string const &S)\n{\n vector cnt(3, 0);\n for (auto x : S)\n {\n cnt[x - 'A']++;\n }\n return cnt;\n}\n\nstring reduce(string const &S)\n{\n stringstream res{};\n char c{'x'};\n for (auto x : S)\n {\n if (x == c)\n {\n continue;\n }\n else\n {\n res << x;\n c = x;\n }\n }\n return res.str();\n}\n\nmap make_map(string const &S)\n{\n vector cnt = count(S);\n vector> V;\n for (auto i = 0; i < 3; i++)\n {\n V.emplace_back(cnt[i], 'A' + i);\n }\n sort(V.begin(), V.end());\n map res;\n for (auto i = 0; i < 3; i++)\n {\n res[get<1>(V[i])] = 'A' + i;\n }\n return res;\n}\n\nmap make_rev(map const &M)\n{\n map res;\n for (auto x : M)\n {\n res[x.second] = x.first;\n }\n return res;\n}\n\nstring convert(string const &S, map const &M)\n{\n stringstream SS{};\n for (auto x : S)\n {\n SS << M.at(x);\n }\n return SS.str();\n}\n\nvector split(string const &S, char c)\n{\n vector res;\n stringstream SS{};\n for (auto x : S)\n {\n if (x == c)\n {\n res.push_back(SS.str());\n SS.clear();\n }\n else\n {\n SS << x;\n }\n }\n return res;\n}\n\nstring make_ans(string const &S)\n{\n vector cnt = count(S);\n assert(cnt[0] <= cnt[1] && cnt[1] == cnt[2]);\n vector V = split(S, 'A');\n vector now(3, 0);\n vector> used(V.size());\n for (auto i = 0u; i < V.size(); i++)\n {\n used[i] = vector(V[i].size(), false);\n }\n \/\/ 1st step\n for (auto i = 0u; i < V.size(); i++)\n {\n if (V[i].size() % 2 == 1)\n {\n used[i][0] = true;\n now[V[i][0] - 'A']++;\n }\n }\n assert(now[0] == 0 && now[1] == now[2]);\n \/\/ 2nd step\n for (auto i = 1u; i < V.size() - 1; i++)\n {\n if (V[i].size() % 2 == 0)\n {\n used[i][0] = used[i][1] = true;\n now[V[i][0] - 'A']++;\n now[V[i][1] - 'A']++;\n }\n }\n assert(now[0] == 0 && now[1] == now[2]);\n \/\/ 3rd step\n if (now[1] < cnt[0])\n {\n for (auto i = 0u; i < V.size(); i++)\n {\n int num = V[i].size() - 1;\n while (num >= 1 && !used[i][num] && !used[i][num - 1])\n {\n used[i][num] = used[i][num - 1] = true;\n now[V[i][num] - 'A']++;\n now[V[i][num - 1] - 'A']++;\n num -= 2;\n if (now[1] == cnt[0])\n {\n break;\n }\n }\n if (now[1] == cnt[0])\n {\n break;\n }\n }\n }\n assert(now[0] == 0 && now[1] == now[2] && cnt[0] == now[1]);\n \/\/ make ans\n stringstream SS{};\n for (auto i = 0u; i < V.size(); i++)\n {\n for (auto j = 0u; j < V[i].size(); j++)\n {\n if (used[i][j])\n {\n SS << V[i][j];\n }\n }\n if (i < V.size() - 1)\n {\n SS << 'A';\n }\n }\n return SS.str();\n}\n\nstring erase_C(string const &S)\n{\n vector cnt = count(S);\n stringstream SS{};\n for (auto i = 0u; i < S.size(); i++)\n {\n if (cnt[2] > cnt[1])\n {\n if (S[i] == 'C')\n {\n if (i - 1 >= 0 && i + 1 < S.size())\n {\n if ((S[i - 1] == 'A' && S[i + 1] == 'B') || (S[i - 1] == 'B' && S[i + 1] == 'A'))\n {\n cnt[2]--;\n continue;\n }\n }\n else\n {\n cnt[2]--;\n continue;\n }\n }\n }\n SS << S[i];\n }\n return SS.str();\n}\n\nstring erase_AC(string const &S)\n{\n vector cnt = count(S);\n assert(cnt[0] <= cnt[1] && cnt[1] < cnt[2]);\n stringstream res{};\n for (auto i = 0u; i < S.size(); i++)\n {\n if (cnt[1] < cnt[2] && i < S.size() - 1 && S[i] == 'A' && S[i + 1] == 'C')\n {\n ++i;\n cnt[0]--;\n cnt[2]--;\n }\n else\n {\n res << S[i];\n }\n }\n return res.str();\n}\n\nint main()\n{\n string S;\n cin >> S;\n S = reduce(S);\n map M, R;\n M = make_map(S);\n R = make_rev(M);\n S = convert(S, M);\n vector cnt = count(S);\n if (cnt[1] < cnt[2])\n {\n S = erase_C(S);\n cnt = count(S);\n if (cnt[1] < cnt[2])\n {\n S = erase_AC(S);\n }\n }\n string ans{make_ans(S)};\n ans = convert(ans, R);\n cout << ans << endl;\n}tried E.cpp to 'E'#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 8\/12\/2019, 7:02:46 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n#define maxs(x, y) (x = max(x, y))\n#define mins(x, y) (x = min(x, y))\nusing ll = long long;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a)\n {\n mint b{a};\n return *this *= b.power(MOD - 2);\n }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nclass combination\n{\npublic:\n vector inv, fact, factinv;\n static int MAX_SIZE;\n combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n};\nint combination::MAX_SIZE = 3000010;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon = 1e-10;\n\/\/ constexpr ll infty = 1000000000000000LL;\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\nvector count(string const &S)\n{\n vector cnt(3, 0);\n for (auto x : S)\n {\n cnt[x - 'A']++;\n }\n return cnt;\n}\n\nstring reduce(string const &S)\n{\n stringstream res{};\n char c{'x'};\n for (auto x : S)\n {\n if (x == c)\n {\n continue;\n }\n else\n {\n res << x;\n c = x;\n }\n }\n return res.str();\n}\n\nmap make_map(string const &S)\n{\n vector cnt = count(S);\n vector> V;\n for (auto i = 0; i < 3; i++)\n {\n V.emplace_back(cnt[i], 'A' + i);\n }\n sort(V.begin(), V.end());\n map res;\n for (auto i = 0; i < 3; i++)\n {\n res[get<1>(V[i])] = 'A' + i;\n }\n return res;\n}\n\nmap make_rev(map const &M)\n{\n map res;\n for (auto x : M)\n {\n res[x.second] = x.first;\n }\n return res;\n}\n\nstring convert(string const &S, map const &M)\n{\n stringstream SS{};\n for (auto x : S)\n {\n SS << M.at(x);\n }\n return SS.str();\n}\n\nvector split(string const &S, char c)\n{\n vector res;\n stringstream SS{};\n for (auto x : S)\n {\n if (x == c)\n {\n res.push_back(SS.str());\n SS.clear();\n }\n else\n {\n SS << x;\n }\n }\n return res;\n}\n\nstring make_ans(string const &S)\n{\n vector cnt = count(S);\n assert(cnt[0] <= cnt[1] && cnt[1] == cnt[2]);\n vector V = split(S, 'A');\n vector now(3, 0);\n vector> used(V.size());\n for (auto i = 0u; i < V.size(); i++)\n {\n used[i] = vector(V[i].size(), false);\n }\n \/\/ 1st step\n for (auto i = 0u; i < V.size(); i++)\n {\n if (V[i].size() % 2 == 1)\n {\n used[i][0] = true;\n now[V[i][0] - 'A']++;\n }\n }\n assert(now[0] == 0 && now[1] == now[2]);\n \/\/ 2nd step\n for (auto i = 1u; i < V.size() - 1; i++)\n {\n if (V[i].size() % 2 == 0)\n {\n used[i][0] = used[i][1] = true;\n now[V[i][0] - 'A']++;\n now[V[i][1] - 'A']++;\n }\n }\n assert(now[0] == 0 && now[1] == now[2]);\n \/\/ 3rd step\n if (now[1] < cnt[0])\n {\n for (auto i = 0u; i < V.size(); i++)\n {\n int num = V[i].size() - 1;\n while (num >= 1 && !used[i][num] && !used[i][num - 1])\n {\n used[i][num] = used[i][num - 1] = true;\n now[V[i][num] - 'A']++;\n now[V[i][num - 1] - 'A']++;\n num -= 2;\n if (now[1] == cnt[0])\n {\n break;\n }\n }\n if (now[1] == cnt[0])\n {\n break;\n }\n }\n }\n assert(now[0] == 0 && now[1] == now[2] && cnt[0] == now[1]);\n \/\/ make ans\n stringstream SS{};\n for (auto i = 0u; i < V.size(); i++)\n {\n for (auto j = 0u; j < V[i].size(); j++)\n {\n if (used[i][j])\n {\n SS << V[i][j];\n }\n }\n if (i < V.size() - 1)\n {\n SS << 'A';\n }\n }\n return SS.str();\n}\n\nstring erase_C(string const &S)\n{\n vector cnt = count(S);\n stringstream SS{};\n for (auto i = 0u; i < S.size(); i++)\n {\n if (cnt[2] > cnt[1])\n {\n if (S[i] == 'C')\n {\n if (i - 1 >= 0 && i + 1 < S.size())\n {\n if ((S[i - 1] == 'A' && S[i + 1] == 'B') || (S[i - 1] == 'B' && S[i + 1] == 'A'))\n {\n cnt[2]--;\n continue;\n }\n }\n else\n {\n cnt[2]--;\n continue;\n }\n }\n }\n SS << S[i];\n }\n return SS.str();\n}\n\nstring erase_AC(string const &S)\n{\n vector cnt = count(S);\n assert(cnt[0] <= cnt[1] && cnt[1] < cnt[2]);\n stringstream res{};\n for (auto i = 0u; i < S.size(); i++)\n {\n if (cnt[1] < cnt[2] && i < S.size() - 1 && S[i] == 'A' && S[i + 1] == 'C')\n {\n ++i;\n cnt[0]--;\n cnt[2]--;\n }\n else\n {\n res << S[i];\n }\n }\n return res.str();\n}\n\nint main()\n{\n string S;\n cin >> S;\n S = reduce(S);\n map M, R;\n M = make_map(S);\n R = make_rev(M);\n S = convert(S, M);\n#if DEBUG == 1\n cerr << \"S = \" << S << endl;\n#endif\n vector cnt = count(S);\n if (cnt[1] < cnt[2])\n {\n S = erase_C(S);\n#if DEBUG == 1\n cerr << \"S = \" << S << endl;\n#endif\n cnt = count(S);\n if (cnt[1] < cnt[2])\n {\n S = erase_AC(S);\n#if DEBUG == 1\n cerr << \"S = \" << S << endl;\n#endif\n }\n }\n string ans{make_ans(S)};\n ans = convert(ans, R);\n cout << ans << endl;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 11\/18\/2019, 8:58:07 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{3000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nvoid add_edge(map &m, int h, int d)\n{\n if (m.find(h) == m.end())\n {\n m[h] = d;\n }\n else\n {\n ch_min(m[h], d);\n }\n}\n\nvoid calc_high(vector const &A, vector> &M, int i, int h, int d)\n{\n add_edge(M[i + 1], A[i + 1] - (A[i] - h), d);\n add_edge(M[i + 1], h, d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid calc_low(vector const &A, vector> &M, int i, int h, int d)\n{\n if (h <= A[i + 1])\n {\n add_edge(M[i + 1], h, d);\n }\n add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid eliminate(map &m)\n{\n int now{m[0]};\n auto k{make_unique>()};\n for (auto x : m)\n {\n if (x.second == now)\n {\n k->insert(x);\n --now;\n }\n }\n swap(m, *k);\n}\n\nvoid calc(vector const &A, vector> &M, int i, pair const &x)\n{\n int h{x.first};\n int d{x.second};\n if (A[i] <= A[i + 1])\n {\n calc_high(A, M, i, h, d);\n }\n else\n {\n calc_low(A, M, i, h, d);\n }\n eliminate(M[i + 1]);\n#if DEBUG == 1\n for (auto const &x : M[i + 1])\n {\n cerr << \"M[\" << i + 1 << \"][\" << x.first << \"] = \" << x.second << endl;\n }\n#endif\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector A(N + 2, 0);\n for (auto i = 1; i <= N; i++)\n {\n cin >> A[i];\n }\n vector> M(N + 2);\n M[0][0] = 0;\n for (auto i = 0; i <= N; i++)\n {\n for (auto const &x : M[i])\n {\n calc(A, M, i, x);\n }\n }\n cout << M[N + 1].end()->second << endl;\n}\ntried E.cpp to 'E'#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 11\/18\/2019, 8:58:07 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{3000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nvoid add_edge(map &m, int h, int d)\n{\n if (m.find(h) == m.end())\n {\n m[h] = d;\n }\n else\n {\n ch_min(m[h], d);\n }\n}\n\nvoid calc_high(vector const &A, vector> &M, int i, int h, int d)\n{\n add_edge(M[i + 1], A[i + 1] - (A[i] - h), d);\n add_edge(M[i + 1], h, d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid calc_low(vector const &A, vector> &M, int i, int h, int d)\n{\n if (h <= A[i + 1])\n {\n add_edge(M[i + 1], h, d);\n }\n add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid eliminate(map &m)\n{\n int now{m[0]};\n auto k{make_unique>()};\n for (auto const &x : m)\n {\n if (x.second == now)\n {\n k->insert(x);\n --now;\n }\n }\n swap(m, *k);\n}\n\nvoid calc(vector const &A, vector> &M, int i, pair const &x)\n{\n int h{x.first};\n int d{x.second};\n if (A[i] <= A[i + 1])\n {\n calc_high(A, M, i, h, d);\n }\n else\n {\n calc_low(A, M, i, h, d);\n }\n#if DEBUG == 1\n for (auto const &x : M[i + 1])\n {\n cerr << \"M[\" << i + 1 << \"][\" << x.first << \"] = \" << x.second << endl;\n }\n#endif\n eliminate(M[i + 1]);\n#if DEBUG == 1\n for (auto const &x : M[i + 1])\n {\n cerr << \"M[\" << i + 1 << \"][\" << x.first << \"] = \" << x.second << endl;\n }\n#endif\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector A(N + 2, 0);\n for (auto i = 1; i <= N; i++)\n {\n cin >> A[i];\n }\n vector> M(N + 2);\n M[0][0] = 0;\n for (auto i = 0; i <= N; i++)\n {\n for (auto const &x : M[i])\n {\n calc(A, M, i, x);\n }\n }\n cout << M[N + 1].end()->second << endl;\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 6\/8\/2020, 2:28:47 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- main() -----\n\nint main()\n{\n ll N, K;\n cin >> N >> K;\n vector A(N);\n for (auto i{0}; i < N; ++i)\n {\n cin >> A[i];\n A[i]--;\n }\n vector sum(N + 1, 0);\n for (auto i{0}; i < N; ++i)\n {\n sum[i + 1] = A[i] + sum[i];\n sum[i + 1] %= K;\n }\n map M;\n for (auto e : sum)\n {\n if (M.find(e) == M.end())\n {\n M[e] = 1;\n }\n else\n {\n M[e]++;\n }\n }\n ll ans{0};\n for (auto const &e : M)\n {\n auto c{e.second};\n ans += c * (c - 1) \/ 2;\n }\n cout << ans << endl;\n}\ntried E.cpp to 'E'#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 6\/8\/2020, 2:28:47 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- main() -----\n\nint main()\n{\n ll N, K;\n cin >> N >> K;\n vector A(N);\n for (auto i{0}; i < N; ++i)\n {\n cin >> A[i];\n A[i]--;\n }\n vector sum(N + 1, 0);\n for (auto i{0}; i < N; ++i)\n {\n sum[i + 1] = A[i] + sum[i];\n }\n map M;\n ll ans{0};\n for (auto i{0}; i < N + 1; ++i)\n {\n ans += M[sum[i]];\n if (i - K >= 0)\n {\n M[sum[i - K]]--;\n }\n }\n cout << ans << endl;\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 3\/21\/2020, 10:21:50 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{2LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nclass Solve\n{\n int N;\n vector V;\n bool zero_two;\n mint ans;\n\npublic:\n Solve(int N, vector V) : N{N}, V{V}\n {\n zero_two_init();\n two_zero_conv();\n calc_ans();\n flush();\n }\n\nprivate:\n void flush()\n {\n if (zero_two && ans == 1)\n {\n cout << 2 << endl;\n }\n else\n {\n cout << ans << endl;\n }\n }\n\n void two_zero_conv()\n {\n for (auto i = 0; i < N; ++i)\n {\n if (V[i] == 2)\n {\n V[i] = 0;\n }\n }\n#if DEBUG == 1\n for (auto x : V)\n {\n cerr << x;\n }\n cerr << endl;\n#endif\n }\n\n void calc_ans()\n {\n combination C;\n ans = 0;\n for (auto i = 0; i < N; ++i)\n {\n ans += C((N - 1) % MOD, i % MOD) * V[i];\n }\n }\n\n void zero_two_init()\n {\n zero_two = true;\n for (auto i = 0; i < N; ++i)\n {\n if (V[i] == 1)\n {\n zero_two = false;\n break;\n }\n }\n if (zero_two)\n {\n for (auto i = 0; i < N; ++i)\n {\n if (V[i] == 2)\n {\n V[i] = 1;\n }\n }\n }\n }\n};\n\nint main()\n{\n int N;\n cin >> N;\n vector A(N);\n string S;\n cin >> S;\n for (auto i = 0; i < N; ++i)\n {\n A[i] = S[i] - '0';\n A[i]--;\n }\n Solve solve(N, A);\n}\nsubmit B.cpp to 'B - 123 Triangle' (agc043) [C++14 (GCC 5.4.1)]#define DEBUG 1\n\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 3\/21\/2020, 10:21:50 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{998244353LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nclass Solve\n{\n int N;\n vector V;\n bool zero_two;\n mint ans;\n\npublic:\n Solve(int N, vector V) : N{N}, V{V}\n {\n zero_two_init();\n two_zero_conv();\n calc_ans();\n flush();\n }\n\nprivate:\n void flush()\n {\n if (zero_two && ans.x % 2 == 1)\n {\n cout << 2 << endl;\n }\n else\n {\n cout << ans.x % 2 << endl;\n }\n }\n\n void two_zero_conv()\n {\n for (auto i = 0; i < N; ++i)\n {\n if (V[i] == 2)\n {\n V[i] = 0;\n }\n }\n#if DEBUG == 1\n for (auto x : V)\n {\n cerr << x;\n }\n cerr << endl;\n#endif\n }\n\n void calc_ans()\n {\n combination C;\n ans = 0;\n for (auto i = 0; i < N; ++i)\n {\n ans += C(N - 1, i) * V[i];\n }\n }\n\n void zero_two_init()\n {\n zero_two = true;\n for (auto i = 0; i < N; ++i)\n {\n if (V[i] == 1)\n {\n zero_two = false;\n break;\n }\n }\n if (zero_two)\n {\n for (auto i = 0; i < N; ++i)\n {\n if (V[i] == 2)\n {\n V[i] = 1;\n }\n }\n }\n }\n};\n\nint main()\n{\n int N;\n cin >> N;\n vector A(N);\n string S;\n cin >> S;\n for (auto i = 0; i < N; ++i)\n {\n A[i] = S[i] - '0';\n A[i]--;\n }\n Solve solve(N, A);\n}\n<|endoftext|>"} {"text":"#include \"ovassvep_defines.h\"\n#include \n#include \n#include \n\n#include \"ovassvepCApplication.h\"\n#include \"GenericStimulator\/ovassvepCGenericStimulatorApplication.h\"\n#include \"Impact\/ovassvepCImpactApplication.h\"\n\nusing namespace OpenViBE;\n\n\/**\n *\/\nint main(int argc, char** argv)\n{\n\t\n\tif (argc < 2)\n\t{\n\t\tprintf(\"Usage : %s [application-subtype]\\n\", argv[0]);\n\t\texit(1);\n\t}\n\t\n\t\/\/ initialize the OpenViBE kernel\n\t\n\tOpenViBE::CKernelLoader l_oKernelLoader;\n\tOpenViBE::CString l_sError;\n\tOpenViBE::Kernel::IKernelDesc* l_poKernelDesc = NULL;\n\tOpenViBE::Kernel::IKernelContext* l_poKernelContext = NULL;\n\tOpenViBE::Kernel::ILogManager* l_poLogManager = NULL;\n\tOpenViBE::Kernel::IConfigurationManager* l_poConfigurationManager = NULL;\n\n\n\n\tCString l_sApplicationString = CString(argv[1]);\n\tCString l_sScenarioFolder = CString(argv[2]);\n\n\tCString l_sApplicationType, l_sApplicationSubtype;\n\n\tif (l_sApplicationString == CString(\"generic\"))\n\t{\n\t\tl_sApplicationType = \"generic\";\n\t\tl_sApplicationSubtype = \"\";\n\t}\n\telse if (l_sApplicationString == CString(\"impact-trainer\"))\n\t{\n\t\tl_sApplicationType = \"impact\";\n\t\tl_sApplicationSubtype = \"trainer\";\n\t}\n\telse if (l_sApplicationString == CString(\"impact-shooter\"))\n\t{\n\t\tl_sApplicationType = \"impact\";\n\t\tl_sApplicationSubtype = \"shooter\";\n\t}\n\n#ifdef OVA_OS_Windows\n\tstd::cout << \"[ INF ] Loading Windows kernel\\n\";\n\tif(!l_oKernelLoader.load(OpenViBE::Directories::getBinDir() + \"\/openvibe-kernel.dll\", &l_sError))\n#else\n\tstd::cout << \"[ INF ] Loading Linux kernel\\n\";\n\tif(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + \"\/libopenvibe-kernel.so\", &l_sError))\n#endif\n\t{\n\t\tstd::cout << \"[ FAILED ] Error loading kernel (\" << l_sError << \")\" << \"\\n\";\n\t}\n\telse\n\t{\n\t\tstd::cout<< \"[ INF ] Kernel module loaded, trying to get kernel descriptor\\n\";\n\n\t\tl_oKernelLoader.initialize();\n\t\tl_oKernelLoader.getKernelDesc(l_poKernelDesc);\n\n\t\tif(!l_poKernelDesc)\n\t\t{\n\t\t\tstd::cout << \"[ FAILED ] No kernel descriptor\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"[ INF ] Got kernel descriptor, trying to create kernel\\n\";\n\n\t\t\tl_poKernelContext = l_poKernelDesc->createKernel(\"ssvep-stimulator\", OpenViBE::Directories::getDataDir() + \"\/kernel\/openvibe.conf\");\n\n\t\t\tif(!l_poKernelContext)\n\t\t\t{\n\t\t\t\tstd::cout << \"[ FAILED ] No kernel created by kernel descriptor\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOpenViBEToolkit::initialize(*l_poKernelContext);\n\n\t\t\t\tl_poConfigurationManager = &(l_poKernelContext->getConfigurationManager());\n\t\t\t\tl_poConfigurationManager->addConfigurationFromFile(l_poConfigurationManager->expand(\"${Path_Data}\/kernel\/openvibe.conf\"));\n\t\t\t\t\/*\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_ApplicationDescriptor\", CString(argv[1]));\n\t\t\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Info << \"Application Descriptor : \" << argv[1] << \"\\n\";\n\t\t\t\t*\/\n\t\t\t\t\/*\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_ApplicationDescriptor\", l_sApplicationType);\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_ApplicationSubtype\", l_sApplicationSubtype);\n\t\t\t\t*\/\n\t\t\t\tl_poLogManager = &(l_poKernelContext->getLogManager());\n\n\t\t\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Info << l_poConfigurationManager->expand(\"${UserHome}\") << \"\\n\";\n\t\t\t\tl_poConfigurationManager->addConfigurationFromFile(l_sScenarioFolder + \"\/appconf\/application-configuration.conf\");\n\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_MindShooterFolderName\", \"ssvep-mind-shooter\");\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\tOpenViBESSVEP::CApplication* app = NULL;\n\n\n\n\tif (l_sApplicationType == CString(\"generic\"))\n\t{\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Debug << \"+ app = new OpenViBESSVEP::CGenericStimulatorApplication(...)\\n\";\n\t\tapp = new OpenViBESSVEP::CGenericStimulatorApplication(l_sScenarioFolder);\n\t}\n\telse if (l_sApplicationType == CString(\"impact\"))\n\t{\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Debug << \"+ app = new OpenViBESSVEP::CImpactApplication(...)\\n\";\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Info << \"application subtype \" << l_sApplicationSubtype << \"\\n\";\n\t\tapp = new OpenViBESSVEP::CImpactApplication(l_sScenarioFolder, l_sApplicationSubtype);\n\t}\n\telse\n\t{\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Error << \"Wrong application identifier specified\\n\";\n\n\t\treturn 1;\n\t}\n\n\tapp->setup(l_poKernelContext);\n\n\tapp->go();\n\n\n\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Debug << \"- app\\n\";\n\tdelete app;\n\n\treturn 0;\n}\n\n\n\nfixed kernel loading#include \"ovassvep_defines.h\"\n#include \n#include \n#include \n\n#include \"ovassvepCApplication.h\"\n#include \"GenericStimulator\/ovassvepCGenericStimulatorApplication.h\"\n#include \"Impact\/ovassvepCImpactApplication.h\"\n\nusing namespace OpenViBE;\n\n\/**\n *\/\nint main(int argc, char** argv)\n{\n\t\n\tif (argc < 2)\n\t{\n\t\tprintf(\"Usage : %s [application-subtype]\\n\", argv[0]);\n\t\texit(1);\n\t}\n\t\n\t\/\/ initialize the OpenViBE kernel\n\t\n\tOpenViBE::CKernelLoader l_oKernelLoader;\n\tOpenViBE::CString l_sError;\n\tOpenViBE::Kernel::IKernelDesc* l_poKernelDesc = NULL;\n\tOpenViBE::Kernel::IKernelContext* l_poKernelContext = NULL;\n\tOpenViBE::Kernel::ILogManager* l_poLogManager = NULL;\n\tOpenViBE::Kernel::IConfigurationManager* l_poConfigurationManager = NULL;\n\n\n\n\tCString l_sApplicationString = CString(argv[1]);\n\tCString l_sScenarioFolder = CString(argv[2]);\n\n\tCString l_sApplicationType, l_sApplicationSubtype;\n\n\tif (l_sApplicationString == CString(\"generic\"))\n\t{\n\t\tl_sApplicationType = \"generic\";\n\t\tl_sApplicationSubtype = \"\";\n\t}\n\telse if (l_sApplicationString == CString(\"impact-trainer\"))\n\t{\n\t\tl_sApplicationType = \"impact\";\n\t\tl_sApplicationSubtype = \"trainer\";\n\t}\n\telse if (l_sApplicationString == CString(\"impact-shooter\"))\n\t{\n\t\tl_sApplicationType = \"impact\";\n\t\tl_sApplicationSubtype = \"shooter\";\n\t}\n\n#ifdef TARGET_OS_Windows\n\tstd::cout << \"[ INF ] Loading Windows kernel\\n\";\n\tif(!l_oKernelLoader.load(OpenViBE::Directories::getBinDir() + \"\/openvibe-kernel.dll\", &l_sError))\n#else\n\tstd::cout << \"[ INF ] Loading Linux kernel\\n\";\n\tif(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + \"\/libopenvibe-kernel.so\", &l_sError))\n#endif\n\t{\n\t\tstd::cout << \"[ FAILED ] Error loading kernel (\" << l_sError << \")\" << \"\\n\";\n\t}\n\telse\n\t{\n\t\tstd::cout<< \"[ INF ] Kernel module loaded, trying to get kernel descriptor\\n\";\n\n\t\tl_oKernelLoader.initialize();\n\t\tl_oKernelLoader.getKernelDesc(l_poKernelDesc);\n\n\t\tif(!l_poKernelDesc)\n\t\t{\n\t\t\tstd::cout << \"[ FAILED ] No kernel descriptor\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"[ INF ] Got kernel descriptor, trying to create kernel\\n\";\n\n\t\t\tl_poKernelContext = l_poKernelDesc->createKernel(\"ssvep-stimulator\", OpenViBE::Directories::getDataDir() + \"\/kernel\/openvibe.conf\");\n\n\t\t\tif(!l_poKernelContext)\n\t\t\t{\n\t\t\t\tstd::cout << \"[ FAILED ] No kernel created by kernel descriptor\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOpenViBEToolkit::initialize(*l_poKernelContext);\n\n\t\t\t\tl_poConfigurationManager = &(l_poKernelContext->getConfigurationManager());\n\t\t\t\tl_poConfigurationManager->addConfigurationFromFile(l_poConfigurationManager->expand(\"${Path_Data}\/kernel\/openvibe.conf\"));\n\t\t\t\t\/*\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_ApplicationDescriptor\", CString(argv[1]));\n\t\t\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Info << \"Application Descriptor : \" << argv[1] << \"\\n\";\n\t\t\t\t*\/\n\t\t\t\t\/*\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_ApplicationDescriptor\", l_sApplicationType);\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_ApplicationSubtype\", l_sApplicationSubtype);\n\t\t\t\t*\/\n\t\t\t\tl_poLogManager = &(l_poKernelContext->getLogManager());\n\n\t\t\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Info << l_poConfigurationManager->expand(\"${UserHome}\") << \"\\n\";\n\t\t\t\tl_poConfigurationManager->addConfigurationFromFile(l_sScenarioFolder + \"\/appconf\/application-configuration.conf\");\n\n\t\t\t\tl_poConfigurationManager->createConfigurationToken(\"SSVEP_MindShooterFolderName\", \"ssvep-mind-shooter\");\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\tOpenViBESSVEP::CApplication* app = NULL;\n\n\n\n\tif (l_sApplicationType == CString(\"generic\"))\n\t{\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Debug << \"+ app = new OpenViBESSVEP::CGenericStimulatorApplication(...)\\n\";\n\t\tapp = new OpenViBESSVEP::CGenericStimulatorApplication(l_sScenarioFolder);\n\t}\n\telse if (l_sApplicationType == CString(\"impact\"))\n\t{\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Debug << \"+ app = new OpenViBESSVEP::CImpactApplication(...)\\n\";\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Info << \"application subtype \" << l_sApplicationSubtype << \"\\n\";\n\t\tapp = new OpenViBESSVEP::CImpactApplication(l_sScenarioFolder, l_sApplicationSubtype);\n\t}\n\telse\n\t{\n\t\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Error << \"Wrong application identifier specified\\n\";\n\n\t\treturn 1;\n\t}\n\n\tapp->setup(l_poKernelContext);\n\n\tapp->go();\n\n\n\t(*l_poLogManager) << OpenViBE::Kernel::LogLevel_Debug << \"- app\\n\";\n\tdelete app;\n\n\treturn 0;\n}\n\n\n\n<|endoftext|>"} {"text":"#include \"profilerui.h\"\n#include \"ui_profilerui.h\"\n#include \n#include \n\nstatic const int MAX_FRAMES = 200;\n\nProfileModel::Block::Block()\n{\n\tm_frames.reserve(MAX_FRAMES);\n\tfor(int i = 0; i < MAX_FRAMES; ++i)\n\t{\n\t\tm_frames.push_back(0);\n\t}\n\tm_hit_counts.reserve(MAX_FRAMES);\n\tfor (int i = 0; i < MAX_FRAMES; ++i)\n\t{\n\t\tm_hit_counts.push_back(0);\n\t}\n}\n\n\nProfileModel::ProfileModel(QWidget* parent)\n\t: QAbstractItemModel(parent)\n{\n\tLumix::g_profiler.getFrameListeners().bind(this);\n\tm_root = NULL;\n\tm_frame = -1;\n}\n\nvoid ProfileModel::cloneBlock(Block* my_block, Lumix::Profiler::Block* remote_block)\n{\n\tASSERT(my_block->m_name == remote_block->m_name);\n\tmy_block->m_frames.push_back(remote_block->getLength());\n\tmy_block->m_hit_counts.push_back(remote_block->getHitCount());\n\tif (my_block->m_frames.size() > MAX_FRAMES)\n\t{\n\t\tmy_block->m_frames.pop_front();\n\t}\n\tif (my_block->m_hit_counts.size() > MAX_FRAMES)\n\t{\n\t\tmy_block->m_hit_counts.pop_front();\n\t}\n\n\tif (!my_block->m_first_child && remote_block->m_first_child)\n\t{\n\t\tLumix::Profiler::Block* remote_child = remote_block->m_first_child;\n\t\tBlock* my_child = new Block;\n\t\tmy_child->m_function = remote_child->m_function;\n\t\tmy_child->m_name = remote_child->m_name;\n\t\tmy_child->m_parent = my_block;\n\t\tmy_child->m_next = NULL;\n\t\tmy_child->m_first_child = NULL;\n\t\tmy_block->m_first_child = my_child;\n\t\tcloneBlock(my_child, remote_child);\n\t}\n\telse if(my_block->m_first_child)\n\t{\n\t\tLumix::Profiler::Block* remote_child = remote_block->m_first_child;\n\t\tBlock* my_child = my_block->m_first_child;\n\t\tif(my_child->m_function != remote_child->m_function || my_child->m_name != remote_child->m_name)\n\t\t{\n\t\t\tBlock* my_new_child = new Block;\n\t\t\tmy_new_child->m_function = remote_child->m_function;\n\t\t\tmy_new_child->m_name = remote_child->m_name;\n\t\t\tmy_new_child->m_parent = my_block;\n\t\t\tmy_new_child->m_next = my_child;\n\t\t\tmy_new_child->m_first_child = NULL;\n\t\t\tmy_block->m_first_child = my_new_child;\n\t\t\tmy_child = my_new_child;\n\t\t}\n\t\tcloneBlock(my_child, remote_child);\n\t}\n\n\tif (!my_block->m_next && remote_block->m_next)\n\t{\n\t\tLumix::Profiler::Block* remote_next = remote_block->m_next;\n\t\tBlock* my_next = new Block;\n\t\tmy_next->m_function = remote_next->m_function;\n\t\tmy_next->m_name = remote_next->m_name;\n\t\tmy_next->m_parent = my_block->m_parent;\n\t\tmy_next->m_next = NULL;\n\t\tmy_next->m_first_child = NULL;\n\t\tmy_block->m_next = my_next;\n\t\tcloneBlock(my_next, remote_next);\n\n\t}\n\telse if (my_block->m_next)\n\t{\n\t\tif(my_block->m_next->m_function != remote_block->m_next->m_function || my_block->m_next->m_name != remote_block->m_next->m_name)\n\t\t{\n\t\t\tBlock* my_next = new Block;\n\t\t\tLumix::Profiler::Block* remote_next = remote_block->m_next;\n\t\t\tmy_next->m_function = remote_next->m_function;\n\t\t\tmy_next->m_name = remote_next->m_name;\n\t\t\tmy_next->m_parent = my_block->m_parent;\n\t\t\tmy_next->m_next = my_block->m_next;\n\t\t\tmy_next->m_first_child = NULL;\n\t\t\tmy_block->m_next = my_next;\n\t\t}\n\t\tcloneBlock(my_block->m_next, remote_block->m_next);\n\t}\n}\n\nvoid ProfileModel::onFrame()\n{\n\tif(!m_root && Lumix::g_profiler.getRootBlock())\n\t{\n\t\tm_root = new Block;\n\t\tm_root->m_function = Lumix::g_profiler.getRootBlock()->m_function;\n\t\tm_root->m_name = Lumix::g_profiler.getRootBlock()->m_name;\n\t\tm_root->m_parent = NULL;\n\t\tm_root->m_next = NULL;\n\t\tm_root->m_first_child = NULL;\n\t}\n\tif(m_root)\n\t{\n\t\tcloneBlock(m_root, Lumix::g_profiler.getRootBlock());\n\t}\n\tstatic int hit = 0;\n\t++hit;\n\tint count = 0;\n\tBlock* child = m_root->m_first_child;\n\twhile(child)\n\t{\n\t\t++count;\n\t\tchild = child->m_next;\n\t}\n\tif(hit % 10 == 0)\n\t{\n\t\temit dataChanged(createIndex(0, 0, m_root), createIndex(count, 0, m_root));\n\t}\n}\n\nQVariant ProfileModel::headerData(int section, Qt::Orientation, int role) const\n{\n\tif(role == Qt::DisplayRole)\n\t{\n\t\tswitch(section)\n\t\t{\n\t\t\tcase Values::FUNCTION:\n\t\t\t\treturn \"Function\";\n\t\t\tcase Values::NAME:\n\t\t\t\treturn \"Name\";\n\t\t\tcase Values::LENGTH:\n\t\t\t\treturn \"Length (ms)\";\n\t\t\tcase Values::LENGTH_EXCLUSIVE:\n\t\t\t\treturn \"Length exclusive (ms)\";\n\t\t\tcase Values::HIT_COUNT:\n\t\t\t\treturn \"Hit count\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tASSERT(false);\n\t\t\t\treturn QVariant();\n\t\t}\n\t}\n\treturn QVariant();\n}\n\nQModelIndex ProfileModel::index(int row, int column, const QModelIndex& parent) const\n{\n\tif(!hasIndex(row, column, parent))\n\t{\n\t\treturn QModelIndex();\n\t}\n\tBlock* block = NULL;\n\tif(parent.internalPointer() != NULL)\n\t{\n\t\tblock = static_cast(parent.internalPointer())->m_first_child;\n\t}\n\telse\n\t{\n\t\tblock = m_root;\n\t}\n\n\tint index = row;\n\twhile (block && index > 0)\n\t{\n\t\tblock = block->m_next;\n\t\t--index;\n\t}\n\n\treturn createIndex(row, column, block);\n}\n\t\nQModelIndex ProfileModel::parent(const QModelIndex& index) const\n{\n\tif (!index.isValid() || !index.internalPointer())\n\t{\n\t\treturn QModelIndex();\n\t}\n\n\tBlock* child = static_cast(index.internalPointer());\n\tBlock* parent = child->m_parent;\n\n\tif (parent == NULL)\n\t{\n\t\treturn QModelIndex();\n\t}\n\n\tint row = 0;\n\tBlock* row_sibling = parent->m_first_child;\n\twhile(row_sibling && row_sibling != child)\n\t{\n\t\trow_sibling = row_sibling->m_next;\n\t\t++row;\n\t}\n\tASSERT(row_sibling);\n\treturn createIndex(row, 0, parent);\n}\n\nint ProfileModel::rowCount(const QModelIndex& parent_index) const\n{\n\tBlock* parent;\n\tif (parent_index.column() > 0 || Lumix::g_profiler.getRootBlock() == NULL)\n\t\treturn 0;\n\n\tif (!parent_index.isValid() || !parent_index.internalPointer())\n\t{\n\t\tint count = 0;\n\t\tBlock* root = m_root;\n\t\twhile (root)\n\t\t{\n\t\t\t++count;\n\t\t\troot = root->m_next;\n\t\t}\n\t\treturn count;\n\t}\n\telse\n\t{\n\t\tparent = static_cast(parent_index.internalPointer());\n\t}\n\n\n\tint count = 0;\n\tBlock* child = parent->m_first_child;\n\twhile(child)\n\t{\n\t\t++count;\n\t\tchild = child->m_next;\n\t}\n\treturn count;\n}\n\nint ProfileModel::columnCount(const QModelIndex&) const\n{\n\treturn (int)Values::COUNT;\n}\n\n\nQVariant ProfileModel::data(const QModelIndex& index, int role) const\n{\n\tif (!index.isValid() || !index.internalPointer())\n\t{\n\t\treturn QVariant();\n\t}\n\n\tif (role != Qt::DisplayRole)\n\t{\n\t\treturn QVariant();\n\t}\n\tBlock* block = static_cast(index.internalPointer());\n\tswitch(index.column())\n\t{\n\t\tcase Values::FUNCTION:\n\t\t\treturn block->m_function;\n\t\tcase Values::NAME:\n\t\t\treturn block->m_name;\n\t\tcase Values::LENGTH:\n\t\t\treturn m_frame >= 0 && m_frame < block->m_frames.size() ? block->m_frames[m_frame] : (block->m_frames.isEmpty() ? 0 : block->m_frames.back());\n\t\tcase Values::LENGTH_EXCLUSIVE:\n\t\t\t{\n\t\t\t\tif (m_frame >= 0 && m_frame < block->m_frames.size())\n\t\t\t\t{\n\t\t\t\t\tfloat length = block->m_frames[m_frame];\n\t\t\t\t\tBlock* child = block->m_first_child;\n\t\t\t\t\twhile (child)\n\t\t\t\t\t{\n\t\t\t\t\t\tlength -= m_frame < child->m_frames.size() ? child->m_frames[m_frame] : (child->m_frames.isEmpty() ? 0 : child->m_frames.back());\n\t\t\t\t\t\tchild = child->m_next;\n\t\t\t\t\t}\n\t\t\t\t\treturn length;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfloat length = block->m_frames.isEmpty() ? 0 : block->m_frames.back();\n\t\t\t\t\tBlock* child = block->m_first_child;\n\t\t\t\t\twhile (child)\n\t\t\t\t\t{\n\t\t\t\t\t\tlength -= child->m_frames.isEmpty() ? 0 : child->m_frames.back();\n\t\t\t\t\t\tchild = child->m_next;\n\t\t\t\t\t}\n\t\t\t\t\treturn length;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Values::HIT_COUNT:\n\t\t\treturn m_frame >= 0 && m_frame < block->m_hit_counts.size() ? block->m_hit_counts[m_frame] : (block->m_hit_counts.isEmpty() ? 0 : block->m_hit_counts.back());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tASSERT(false);\n\t\t\treturn QVariant();\n\t}\n}\n\n\nProfilerUI::ProfilerUI(QWidget* parent) \n\t: QDockWidget(parent)\n\t, m_ui(new Ui::ProfilerUI)\n{\n\tm_sortable_model = new QSortFilterProxyModel(this);\n\tm_model = new ProfileModel(this);\n\tm_sortable_model->setSourceModel(m_model);\n\tm_ui->setupUi(this);\n\tm_ui->profileTreeView->setModel(m_sortable_model);\n\tm_ui->profileTreeView->header()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch);\n\tm_ui->profileTreeView->header()->setSectionResizeMode(1, QHeaderView::ResizeMode::ResizeToContents);\n\tm_ui->profileTreeView->header()->setSectionResizeMode(2, QHeaderView::ResizeMode::ResizeToContents);\n\tconnect(m_model, &QAbstractItemModel::dataChanged, this, &ProfilerUI::on_dataChanged);\n\tconnect(m_ui->graphView, &ProfilerGraph::frameSet, this, &ProfilerUI::on_frameSet);\n\tm_ui->graphView->setModel(m_model);\n}\n\n\nvoid ProfilerUI::on_dataChanged()\n{\n\tm_ui->graphView->update();\n}\n\n\nProfilerUI::~ProfilerUI()\n{\n\tdelete m_ui;\n}\n\nvoid ProfilerUI::on_recordCheckBox_stateChanged(int)\n{\n\tLumix::g_profiler.toggleRecording();\n\tm_ui->profileTreeView->setModel(NULL);\n\tm_sortable_model->setSourceModel(m_model);\n\tm_ui->profileTreeView->setModel(m_sortable_model);\n\tm_ui->profileTreeView->update();\n}\n\n\nvoid ProfilerUI::on_frameSet()\n{\n\tm_ui->recordCheckBox->setChecked(false);\n\tm_ui->profileTreeView->update();\n\tm_model->setFrame(m_ui->graphView->getFrame());\n}\n\n\nvoid ProfilerUI::on_profileTreeView_clicked(const QModelIndex &index)\n{\n\tif(index.internalPointer() != NULL)\n\t{\n\t\tm_ui->graphView->setBlock(static_cast(index.internalPointer()));\n\t\tm_ui->graphView->update();\n\t}\n}\ncrash in the profiler ui fixed#include \"profilerui.h\"\n#include \"ui_profilerui.h\"\n#include \n#include \n\nstatic const int MAX_FRAMES = 200;\n\nProfileModel::Block::Block()\n{\n\tm_frames.reserve(MAX_FRAMES);\n\tfor(int i = 0; i < MAX_FRAMES; ++i)\n\t{\n\t\tm_frames.push_back(0);\n\t}\n\tm_hit_counts.reserve(MAX_FRAMES);\n\tfor (int i = 0; i < MAX_FRAMES; ++i)\n\t{\n\t\tm_hit_counts.push_back(0);\n\t}\n}\n\n\nProfileModel::ProfileModel(QWidget* parent)\n\t: QAbstractItemModel(parent)\n{\n\tLumix::g_profiler.getFrameListeners().bind(this);\n\tm_root = NULL;\n\tm_frame = -1;\n}\n\nvoid ProfileModel::cloneBlock(Block* my_block, Lumix::Profiler::Block* remote_block)\n{\n\tASSERT(my_block->m_name == remote_block->m_name);\n\tmy_block->m_frames.push_back(remote_block->getLength());\n\tmy_block->m_hit_counts.push_back(remote_block->getHitCount());\n\tif (my_block->m_frames.size() > MAX_FRAMES)\n\t{\n\t\tmy_block->m_frames.pop_front();\n\t}\n\tif (my_block->m_hit_counts.size() > MAX_FRAMES)\n\t{\n\t\tmy_block->m_hit_counts.pop_front();\n\t}\n\n\tif (!my_block->m_first_child && remote_block->m_first_child)\n\t{\n\t\tLumix::Profiler::Block* remote_child = remote_block->m_first_child;\n\t\tBlock* my_child = new Block;\n\t\tmy_child->m_function = remote_child->m_function;\n\t\tmy_child->m_name = remote_child->m_name;\n\t\tmy_child->m_parent = my_block;\n\t\tmy_child->m_next = NULL;\n\t\tmy_child->m_first_child = NULL;\n\t\tmy_block->m_first_child = my_child;\n\t\tcloneBlock(my_child, remote_child);\n\t}\n\telse if(my_block->m_first_child)\n\t{\n\t\tLumix::Profiler::Block* remote_child = remote_block->m_first_child;\n\t\tBlock* my_child = my_block->m_first_child;\n\t\tif(my_child->m_function != remote_child->m_function || my_child->m_name != remote_child->m_name)\n\t\t{\n\t\t\tBlock* my_new_child = new Block;\n\t\t\tmy_new_child->m_function = remote_child->m_function;\n\t\t\tmy_new_child->m_name = remote_child->m_name;\n\t\t\tmy_new_child->m_parent = my_block;\n\t\t\tmy_new_child->m_next = my_child;\n\t\t\tmy_new_child->m_first_child = NULL;\n\t\t\tmy_block->m_first_child = my_new_child;\n\t\t\tmy_child = my_new_child;\n\t\t}\n\t\tcloneBlock(my_child, remote_child);\n\t}\n\n\tif (!my_block->m_next && remote_block->m_next)\n\t{\n\t\tLumix::Profiler::Block* remote_next = remote_block->m_next;\n\t\tBlock* my_next = new Block;\n\t\tmy_next->m_function = remote_next->m_function;\n\t\tmy_next->m_name = remote_next->m_name;\n\t\tmy_next->m_parent = my_block->m_parent;\n\t\tmy_next->m_next = NULL;\n\t\tmy_next->m_first_child = NULL;\n\t\tmy_block->m_next = my_next;\n\t\tcloneBlock(my_next, remote_next);\n\n\t}\n\telse if (my_block->m_next)\n\t{\n\t\tif(my_block->m_next->m_function != remote_block->m_next->m_function || my_block->m_next->m_name != remote_block->m_next->m_name)\n\t\t{\n\t\t\tBlock* my_next = new Block;\n\t\t\tLumix::Profiler::Block* remote_next = remote_block->m_next;\n\t\t\tmy_next->m_function = remote_next->m_function;\n\t\t\tmy_next->m_name = remote_next->m_name;\n\t\t\tmy_next->m_parent = my_block->m_parent;\n\t\t\tmy_next->m_next = my_block->m_next;\n\t\t\tmy_next->m_first_child = NULL;\n\t\t\tmy_block->m_next = my_next;\n\t\t}\n\t\tcloneBlock(my_block->m_next, remote_block->m_next);\n\t}\n}\n\nvoid ProfileModel::onFrame()\n{\n\tif(!m_root && Lumix::g_profiler.getRootBlock())\n\t{\n\t\tm_root = new Block;\n\t\tm_root->m_function = Lumix::g_profiler.getRootBlock()->m_function;\n\t\tm_root->m_name = Lumix::g_profiler.getRootBlock()->m_name;\n\t\tm_root->m_parent = NULL;\n\t\tm_root->m_next = NULL;\n\t\tm_root->m_first_child = NULL;\n\t}\n\tif(m_root)\n\t{\n\t\tcloneBlock(m_root, Lumix::g_profiler.getRootBlock());\n\t}\n\tstatic int hit = 0;\n\t++hit;\n\tint count = 0;\n\tBlock* child = m_root->m_first_child;\n\twhile(child)\n\t{\n\t\t++count;\n\t\tchild = child->m_next;\n\t}\n\tif(hit % 10 == 0)\n\t{\n\t\temit dataChanged(createIndex(0, 0, m_root), createIndex(count, 0, m_root));\n\t}\n}\n\nQVariant ProfileModel::headerData(int section, Qt::Orientation, int role) const\n{\n\tif(role == Qt::DisplayRole)\n\t{\n\t\tswitch(section)\n\t\t{\n\t\t\tcase Values::FUNCTION:\n\t\t\t\treturn \"Function\";\n\t\t\tcase Values::NAME:\n\t\t\t\treturn \"Name\";\n\t\t\tcase Values::LENGTH:\n\t\t\t\treturn \"Length (ms)\";\n\t\t\tcase Values::LENGTH_EXCLUSIVE:\n\t\t\t\treturn \"Length exclusive (ms)\";\n\t\t\tcase Values::HIT_COUNT:\n\t\t\t\treturn \"Hit count\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tASSERT(false);\n\t\t\t\treturn QVariant();\n\t\t}\n\t}\n\treturn QVariant();\n}\n\nQModelIndex ProfileModel::index(int row, int column, const QModelIndex& parent) const\n{\n\tif(!hasIndex(row, column, parent))\n\t{\n\t\treturn QModelIndex();\n\t}\n\tBlock* block = NULL;\n\tif(parent.internalPointer() != NULL)\n\t{\n\t\tblock = static_cast(parent.internalPointer())->m_first_child;\n\t}\n\telse\n\t{\n\t\tblock = m_root;\n\t}\n\n\tint index = row;\n\twhile (block && index > 0)\n\t{\n\t\tblock = block->m_next;\n\t\t--index;\n\t}\n\n\treturn createIndex(row, column, block);\n}\n\t\nQModelIndex ProfileModel::parent(const QModelIndex& index) const\n{\n\tif (!index.isValid() || !index.internalPointer())\n\t{\n\t\treturn QModelIndex();\n\t}\n\n\tBlock* child = static_cast(index.internalPointer());\n\tBlock* parent = child->m_parent;\n\n\tif (parent == NULL)\n\t{\n\t\treturn QModelIndex();\n\t}\n\n\tint row = 0;\n\tBlock* row_sibling = parent->m_first_child;\n\twhile(row_sibling && row_sibling != child)\n\t{\n\t\trow_sibling = row_sibling->m_next;\n\t\t++row;\n\t}\n\tASSERT(row_sibling);\n\treturn createIndex(row, 0, parent);\n}\n\nint ProfileModel::rowCount(const QModelIndex& parent_index) const\n{\n\tBlock* parent;\n\tif (parent_index.column() > 0 || Lumix::g_profiler.getRootBlock() == NULL)\n\t\treturn 0;\n\n\tif (!parent_index.isValid() || !parent_index.internalPointer())\n\t{\n\t\tint count = 0;\n\t\tBlock* root = m_root;\n\t\twhile (root)\n\t\t{\n\t\t\t++count;\n\t\t\troot = root->m_next;\n\t\t}\n\t\treturn count;\n\t}\n\telse\n\t{\n\t\tparent = static_cast(parent_index.internalPointer());\n\t}\n\n\n\tint count = 0;\n\tBlock* child = parent->m_first_child;\n\twhile(child)\n\t{\n\t\t++count;\n\t\tchild = child->m_next;\n\t}\n\treturn count;\n}\n\nint ProfileModel::columnCount(const QModelIndex&) const\n{\n\treturn (int)Values::COUNT;\n}\n\n\nQVariant ProfileModel::data(const QModelIndex& index, int role) const\n{\n\tif (!index.isValid() || !index.internalPointer())\n\t{\n\t\treturn QVariant();\n\t}\n\n\tif (role != Qt::DisplayRole)\n\t{\n\t\treturn QVariant();\n\t}\n\tBlock* block = static_cast(index.internalPointer());\n\tswitch(index.column())\n\t{\n\t\tcase Values::FUNCTION:\n\t\t\treturn block->m_function;\n\t\tcase Values::NAME:\n\t\t\treturn block->m_name;\n\t\tcase Values::LENGTH:\n\t\t\treturn m_frame >= 0 && m_frame < block->m_frames.size() ? block->m_frames[m_frame] : (block->m_frames.isEmpty() ? 0 : block->m_frames.back());\n\t\tcase Values::LENGTH_EXCLUSIVE:\n\t\t\t{\n\t\t\t\tif (m_frame >= 0 && m_frame < block->m_frames.size())\n\t\t\t\t{\n\t\t\t\t\tfloat length = block->m_frames[m_frame];\n\t\t\t\t\tBlock* child = block->m_first_child;\n\t\t\t\t\twhile (child)\n\t\t\t\t\t{\n\t\t\t\t\t\tlength -= m_frame < child->m_frames.size() ? child->m_frames[m_frame] : (child->m_frames.isEmpty() ? 0 : child->m_frames.back());\n\t\t\t\t\t\tchild = child->m_next;\n\t\t\t\t\t}\n\t\t\t\t\treturn length;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfloat length = block->m_frames.isEmpty() ? 0 : block->m_frames.back();\n\t\t\t\t\tBlock* child = block->m_first_child;\n\t\t\t\t\twhile (child)\n\t\t\t\t\t{\n\t\t\t\t\t\tlength -= child->m_frames.isEmpty() ? 0 : child->m_frames.back();\n\t\t\t\t\t\tchild = child->m_next;\n\t\t\t\t\t}\n\t\t\t\t\treturn length;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Values::HIT_COUNT:\n\t\t\treturn m_frame >= 0 && m_frame < block->m_hit_counts.size() ? block->m_hit_counts[m_frame] : (block->m_hit_counts.isEmpty() ? 0 : block->m_hit_counts.back());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tASSERT(false);\n\t\t\treturn QVariant();\n\t}\n}\n\n\nProfilerUI::ProfilerUI(QWidget* parent) \n\t: QDockWidget(parent)\n\t, m_ui(new Ui::ProfilerUI)\n{\n\tm_sortable_model = new QSortFilterProxyModel(this);\n\tm_model = new ProfileModel(this);\n\tm_sortable_model->setSourceModel(m_model);\n\tm_ui->setupUi(this);\n\tm_ui->profileTreeView->setModel(m_sortable_model);\n\tm_ui->profileTreeView->header()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch);\n\tm_ui->profileTreeView->header()->setSectionResizeMode(1, QHeaderView::ResizeMode::ResizeToContents);\n\tm_ui->profileTreeView->header()->setSectionResizeMode(2, QHeaderView::ResizeMode::ResizeToContents);\n\tconnect(m_model, &QAbstractItemModel::dataChanged, this, &ProfilerUI::on_dataChanged);\n\tconnect(m_ui->graphView, &ProfilerGraph::frameSet, this, &ProfilerUI::on_frameSet);\n\tm_ui->graphView->setModel(m_model);\n}\n\n\nvoid ProfilerUI::on_dataChanged()\n{\n\tm_ui->graphView->update();\n}\n\n\nProfilerUI::~ProfilerUI()\n{\n\tdelete m_ui;\n}\n\nvoid ProfilerUI::on_recordCheckBox_stateChanged(int)\n{\n\tLumix::g_profiler.toggleRecording();\n\tm_ui->profileTreeView->setModel(NULL);\n\tm_sortable_model->setSourceModel(m_model);\n\tm_ui->profileTreeView->setModel(m_sortable_model);\n\tm_ui->profileTreeView->update();\n}\n\n\nvoid ProfilerUI::on_frameSet()\n{\n\tm_ui->recordCheckBox->setChecked(false);\n\tm_ui->profileTreeView->update();\n\tm_model->setFrame(m_ui->graphView->getFrame());\n}\n\n\nvoid ProfilerUI::on_profileTreeView_clicked(const QModelIndex &index)\n{\n\tif(index.internalPointer() != NULL)\n\t{\n\t\tm_ui->graphView->setBlock(static_cast(m_sortable_model->mapToSource(index).internalPointer()));\n\t\tm_ui->graphView->update();\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************** \n** \n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies). \n** All rights reserved. \n** Contact: Nokia Corporation (testabilitydriver@nokia.com) \n** \n** This file is part of Testability Driver Qt Agent\n** \n** If you have questions regarding the use of this file, please contact \n** Nokia at testabilitydriver@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\n#include \n#include \n\n#include \n#include \n#include \"scenegraphtraverse.h\"\n\n#include \n#include \n#include \n#include \n\n\/*!\n \\class SceneGraphTraverse\n \\brief SceneGraphTraverse traverse QWidgets and QGraphicsItems\n\n Traverse the basic qt ui elements\n*\/\n\n\/*!\n Constructor\n*\/\nSceneGraphTraverse::SceneGraphTraverse(QObject* parent)\n : QObject(parent)\n{\n mTraverseUtils = new TasTraverseUtils();\n}\n\n\/*!\n Destructor\n*\/\nSceneGraphTraverse::~SceneGraphTraverse()\n{\n delete mTraverseUtils;\n}\n\nvoid SceneGraphTraverse::beginTraverse(TasCommand* command)\n{\n mTraverseUtils->createFilter(command);\n}\n\nvoid SceneGraphTraverse::endTraverse()\n{\n mTraverseUtils->clearFilter();\n}\n\n\/*!\n Traverse QGraphicsItem based objects.\n *\/\nvoid SceneGraphTraverse::traverseGraphicsItem(TasObject* objectInfo, QGraphicsItem* graphicsItem, TasCommand* command)\n{\n Q_UNUSED(objectInfo);\n Q_UNUSED(graphicsItem);\n Q_UNUSED(command);\n}\n\n\/*!\n Traverse QObject based items.\n*\/\nvoid SceneGraphTraverse::traverseObject(TasObject* objectInfo, QObject* object, TasCommand* command)\n{\n Q_UNUSED(command);\n\n QQuickItem* item = qobject_cast(object);\n\n if (item) {\n QQmlContext* context = QQmlEngine::contextForObject(object);\n\n if (context) {\n QString name = context->nameForObject(object);\n objectInfo->addAttribute(\"QML_ID\", name);\n }\n\n mTraverseUtils->addObjectDetails(objectInfo, object);\n\n objectInfo->addAttribute(\"objectType\", TYPE_QSCENEGRAPH);\n\n QPointF point = item->mapToScene(QPoint());\n\n objectInfo->addAttribute(\"x\", point.x());\n objectInfo->addAttribute(\"y\", point.y());\n objectInfo->addAttribute(\"x_absolute\", point.x());\n objectInfo->addAttribute(\"y_absolute\", point.y());\n\n objectInfo->addAttribute(\"x_relative\", item->x());\n objectInfo->addAttribute(\"y_relative\", item->y());\n\n \/\/ TODO already included?\n objectInfo->addAttribute(\"width\", item->width());\n objectInfo->addAttribute(\"height\", item->height());\n }\n}\n\n\n\n\nFixed problem with visualizer not being capable of handling fractional coordinates\/*************************************************************************** \n** \n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies). \n** All rights reserved. \n** Contact: Nokia Corporation (testabilitydriver@nokia.com) \n** \n** This file is part of Testability Driver Qt Agent\n** \n** If you have questions regarding the use of this file, please contact \n** Nokia at testabilitydriver@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\n#include \n#include \n\n#include \n#include \n#include \"scenegraphtraverse.h\"\n\n#include \n#include \n#include \n#include \n\n\/*!\n \\class SceneGraphTraverse\n \\brief SceneGraphTraverse traverse QWidgets and QGraphicsItems\n\n Traverse the basic qt ui elements\n*\/\n\n\/*!\n Constructor\n*\/\nSceneGraphTraverse::SceneGraphTraverse(QObject* parent)\n : QObject(parent)\n{\n mTraverseUtils = new TasTraverseUtils();\n}\n\n\/*!\n Destructor\n*\/\nSceneGraphTraverse::~SceneGraphTraverse()\n{\n delete mTraverseUtils;\n}\n\nvoid SceneGraphTraverse::beginTraverse(TasCommand* command)\n{\n mTraverseUtils->createFilter(command);\n}\n\nvoid SceneGraphTraverse::endTraverse()\n{\n mTraverseUtils->clearFilter();\n}\n\n\/*!\n Traverse QGraphicsItem based objects.\n *\/\nvoid SceneGraphTraverse::traverseGraphicsItem(TasObject* objectInfo, QGraphicsItem* graphicsItem, TasCommand* command)\n{\n Q_UNUSED(objectInfo);\n Q_UNUSED(graphicsItem);\n Q_UNUSED(command);\n}\n\n\/*!\n Traverse QObject based items.\n*\/\nvoid SceneGraphTraverse::traverseObject(TasObject* objectInfo, QObject* object, TasCommand* command)\n{\n Q_UNUSED(command);\n\n QQuickItem* item = qobject_cast(object);\n\n if (item) {\n QQmlContext* context = QQmlEngine::contextForObject(object);\n\n if (context) {\n QString name = context->nameForObject(object);\n objectInfo->addAttribute(\"QML_ID\", name);\n }\n\n mTraverseUtils->addObjectDetails(objectInfo, object);\n\n objectInfo->addAttribute(\"objectType\", TYPE_QSCENEGRAPH);\n\n QPointF point = item->mapToScene(QPoint());\n\n \/\/ needed for visualizer\n objectInfo->addAttribute(\"x\", (int)point.x());\n objectInfo->addAttribute(\"y\", (int)point.y());\n objectInfo->addAttribute(\"x_absolute\", (int)point.x());\n objectInfo->addAttribute(\"y_absolute\", (int)point.y());\n\n\n objectInfo->addAttribute(\"x_relative\", item->x());\n objectInfo->addAttribute(\"y_relative\", item->y());\n\n \/\/ TODO already included?\n objectInfo->addAttribute(\"width\", item->width());\n objectInfo->addAttribute(\"height\", item->height());\n }\n}\n\n\n\n\n<|endoftext|>"} {"text":"#include \"Application.h\"\n\n#include \"Module.h\"\n#include \"ModuleScripting.h\"\n#include \"ModuleAudio.h\"\n#include \"ModuleCamera3D.h\"\n#include \"ModuleFileSystem.h\"\n#include \"ModuleGOManager.h\"\n#include \"ModuleInput.h\"\n#include \"ModuleSceneIntro.h\"\n#include \"ModuleLighting.h\"\n#include \"ModulePhysics3D.h\"\n#include \"ModuleRenderer3D.h\"\n#include \"ModuleResourceManager.h\"\n#include \"ModuleEditor.h\"\n#include \"ModuleWindow.h\"\n\n#include \"Time.h\"\n#include \"Random.h\"\n#include \"EventQueue.h\"\n#include \"Data.h\"\n\n#include \"Brofiler\/include\/Brofiler.h\"\n\n#include \"ComponentCar.h\"\n\nusing namespace std;\n\nApplication::Application()\n{\n\t\/\/ Time controller\n\ttime = new Time();\n\t\n\t\/\/ Random\n\trnd = new Random();\n\n\t\/\/ EventQueue\n\tevent_queue = new EventQueue();\n\n\t\/\/ Modules\n\twindow = new ModuleWindow(\"window\");\n\tresource_manager = new ModuleResourceManager(\"resource_manager\");\n\tinput = new ModuleInput(\"input\");\n\taudio = new ModuleAudio(\"audio\");\n\tscene_intro = new ModuleSceneIntro(\"scene_intro\");\n\trenderer3D = new ModuleRenderer3D(\"renderer\");\n\tcamera = new ModuleCamera3D(\"camera\");\n\tphysics = new ModulePhysics3D(\"physics\");\n\tscripting = new ModuleScripting(\"scripting\");\n\teditor = new ModuleEditor(\"editor\");\n\tfile_system = new ModuleFileSystem(\"file_system\");\n\tgo_manager = new ModuleGOManager(\"go_manager\");\n\tlighting = new ModuleLighting(\"lighting\");\n\n\t\/\/Globals\n\tg_Debug = new DebugDraw(\"debug_draw\");\n\n\t\/\/ Modules will Init() Start() and Update in this order\n\t\/\/ They will CleanUp() in reverse order\n\n\t\/\/ Main Modules\n\tAddModule(file_system);\n\tAddModule(resource_manager);\n\tAddModule(window);\n\tAddModule(input);\n\tAddModule(g_Debug);\n\tAddModule(audio);\n\tAddModule(scripting);\n\tAddModule(physics);\n\tAddModule(go_manager);\n\tAddModule(camera);\t\n\tAddModule(lighting);\n\t\n\t\/\/ Scenes\n\tAddModule(scene_intro);\n\n\t\/\/Editor\n\tAddModule(editor);\n\n\t\/\/ Renderer last!\n\tAddModule(renderer3D);\n}\n\nApplication::~Application()\n{\n\tdelete rnd;\n\tdelete event_queue;\n\n\tvector::reverse_iterator i = list_modules.rbegin();\n\n\twhile (i != list_modules.rend())\n\t{\n\t\tdelete (*i);\n\t\t++i;\n\t}\n\n\tdelete time;\n}\n\nbool Application::Init()\n{\n\tbool ret = true;\n\n\t\/\/Load Configuration\n\tchar* buffer = nullptr;\n\tif (App->file_system->Load(\"Configuration.json\", &buffer) == 0)\n\t{\n\t\tLOG(\"Error while loading Configuration file\");\n\t\t\/\/Create a new Configuration file\n\t\tif (buffer)\n\t\t\tdelete[] buffer;\n\n\t\tData root_node;\n\t\troot_node.AppendBool(\"start_in_game\", false);\n\t\tvector::reverse_iterator i = list_modules.rbegin();\n\n\t\twhile (i != list_modules.rend())\n\t\t{\n\t\t\troot_node.AppendJObject((*i)->GetName());\n\t\t\t++i;\n\t\t}\n\n\t\tsize_t size = root_node.Serialize(&buffer);\n\t\tApp->file_system->Save(\"Configuration.json\", buffer, size);\n\t}\n\tData config(buffer);\n\tdelete[] buffer;\n\n\t\/\/ Game is initialized in PlayMode?\n\tif (config.GetBool(\"start_in_game\"))\n\t{\n\t\tstart_in_game = true;\n\t\tgame_state = GAME_RUNNING;\n\t}\t\t\n\n\t\/\/ Call Init() in all modules\n\tvector::iterator i = list_modules.begin();\n\n\twhile (i != list_modules.end() && ret == true)\n\t{\n\t\tret = (*i)->Init(config.GetJObject((*i)->GetName()));\n\t\t++i;\n\t}\n\n\t\/\/ After all Init calls we call Start() in all modules\n\tLOG(\"Application Start --------------\");\n\ti = list_modules.begin();\n\n\twhile(i != list_modules.end() && ret == true)\n\t{\n\t\tret = (*i)->Start();\n\t\t++i;\n\t}\n\n\tcapped_ms = 1000 \/ max_fps;\n\n\t\/\/\/\/ Play all Components of every GameObject on the scene\n\tif (start_in_game)\n\t{\t\t\n\t\ttime->Play();\n\n\t\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t\t\t(*it)->OnPlay();\n\t}\t\n\t\n\treturn ret;\n}\n\n\/\/ ---------------------------------------------\nvoid Application::PrepareUpdate()\n{\n\ttime->UpdateFrame();\n}\n\n\/\/ ---------------------------------------------\nvoid Application::FinishUpdate()\n{\n\tevent_queue->ProcessEvents();\n\tif (want_to_load == true)\n\t{\n\t\twant_to_load = false;\n\t\tresource_manager->LoadSceneFromAssets(scene_to_load);\n\t}\n}\n\nvoid Application::LoadScene(const char* path)\n{\n\tif (want_to_load == false)\n\t{\n\t\tscene_to_load = (char*)path;\n\t\twant_to_load = true;\n\t}\n}\n\nvoid Application::OnStop()\n{\n\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t{\n\t\t(*it)->OnStop();\n\t}\n}\n\nvoid Application::OnPlay()\n{\n\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t\t(*it)->OnPlay();\n}\n\nvoid Application::RunGame() \n{\n\t\/\/Save current scene only if the game was stopped\n\tif (game_state == GAME_STOP)\n\t\tgo_manager->SaveSceneBeforeRunning();\n\n\tgame_state = GAME_RUNNING;\n\ttime->Play();\n\n\tOnPlay();\n}\n\nvoid Application::PauseGame()\n{\n\tgame_state = GAME_PAUSED;\n\ttime->Pause();\n\n\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t{\n\t\t(*it)->OnPause();\n\t}\n}\n\nvoid Application::StopGame()\n{\n\tgame_state = GAME_STOP;\n\tOnStop();\n\tgo_manager->LoadSceneBeforeRunning();\n\ttime->Stop();\t\n}\n\n\/\/ Call PreUpdate, Update and PostUpdate on all modules\nupdate_status Application::Update()\n{\n\tBROFILER_FRAME(\"GameLoop\")\n\n\tupdate_status ret = UPDATE_CONTINUE;\n\tPrepareUpdate();\n\t\n\tvector::iterator i = list_modules.begin();\n\n\twhile (i != list_modules.end() && ret == UPDATE_CONTINUE)\n\t{\n\t\tret = (*i)->PreUpdate();\n\t\t++i;\n\t}\n\n\ti = list_modules.begin();\n\n\twhile(i != list_modules.end() && ret == UPDATE_CONTINUE)\n\t{\n\t\tret = (*i)->Update();\n\t\t++i;\n\t}\n\n\ti = list_modules.begin();\n\n\twhile (i != list_modules.end() && ret == UPDATE_CONTINUE)\n\t{\n\t\tret = (*i)->PostUpdate();\n\t\ti++;\n\t}\n\n\tFinishUpdate();\n\treturn ret;\n}\n\nbool Application::CleanUp()\n{\n\tbool ret = true;\n\n\tvector::reverse_iterator i = list_modules.rbegin();\n\n\twhile (i != list_modules.rend() && ret == true)\n\t{\n\t\tret = (*i)->CleanUp();\n\t\t++i;\n\t}\n\n\treturn ret;\n}\n\nvoid Application::SaveBeforeClosing()\n{\n\tData root_node;\n\tchar* buf;\n\n\troot_node.AppendBool(\"start_in_game\", start_in_game);\n\n\tvector::reverse_iterator i = list_modules.rbegin();\n\n\twhile (i != list_modules.rend())\n\t{\n\t\t(*i)->SaveBeforeClosing(root_node.AppendJObject((*i)->GetName()));\n\t\t++i;\n\t}\n\n\tsize_t size = root_node.Serialize(&buf);\n\tuint success = App->file_system->Save(\"Configuration.json\", buf, size);\n\n\tif (success == 0)\n\t\tLOG(\"Configuration could not be saved before closing\");\n\n\tdelete[] buf;\n}\n\nvoid Application::AddModule(Module* mod)\n{\n\tlist_modules.push_back(mod);\n}\n\nvoid Application::OpenURL(const char* url)\n{\n\tShellExecuteA(NULL, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n}\n\nvoid Application::SetMaxFPS(int max_fps)\n{\n\tthis->max_fps = max_fps;\n\tif (max_fps == 0) this->max_fps = -1;\n\tcapped_ms = 1000 \/ max_fps;\n}\n\nint Application::GetFPS()\n{\n\treturn 60; \/\/TODO: Update time with fps limit.\n}\n\nbool Application::ChangeGameState(GameStates new_state)\n{\n\tbool success = false;\n\tswitch (new_state)\n\t{\n\tcase GAME_STOP:\n\t\tif (game_state == GAME_RUNNING || game_state == GAME_PAUSED)\n\t\t{\n\t\t\tStopGame();\n\t\t\tsuccess = true;\n\t\t}\n\t\tbreak;\n\tcase GAME_RUNNING:\n\t\tif (game_state == GAME_STOP || game_state == GAME_PAUSED)\n\t\t{\n\t\t\tRunGame();\n\t\t\tsuccess = true;\n\t\t}\n\t\tbreak;\n\tcase GAME_PAUSED:\n\t\tif (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME)\n\t\t{\n\t\t\tPauseGame();\n\t\t\tsuccess = true;\n\t\t}\n\t\tbreak;\n\tcase GAME_NEXT_FRAME:\n\t\tif(game_state == GAME_RUNNING || game_state == GAME_PAUSED) \/\/TODO: Now this features is not available yet. Nothing happens in the game now. \n\t\t\t\/\/NextFrameGame();\n\t\tbreak;\n\t}\n\n\treturn success;\n}\n\n\/\/\/Returns true if the game simulation has started. If the game is paused also returns true.\nbool Application::IsGameRunning() const\n{\n\treturn (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME || game_state == GAME_PAUSED) ? true : false;\n}\n\n\/\/\/Returns true if the game is paused or in next frame mode. If the game is stop returns false.\nbool Application::IsGamePaused() const\n{\n\treturn (game_state == GAME_PAUSED || game_state == GAME_NEXT_FRAME) ? true : false;\n}\n\nbool Application::StartInGame() const\n{\n\treturn start_in_game;\n}\nNot saving configuration if startInGame == true#include \"Application.h\"\n\n#include \"Module.h\"\n#include \"ModuleScripting.h\"\n#include \"ModuleAudio.h\"\n#include \"ModuleCamera3D.h\"\n#include \"ModuleFileSystem.h\"\n#include \"ModuleGOManager.h\"\n#include \"ModuleInput.h\"\n#include \"ModuleSceneIntro.h\"\n#include \"ModuleLighting.h\"\n#include \"ModulePhysics3D.h\"\n#include \"ModuleRenderer3D.h\"\n#include \"ModuleResourceManager.h\"\n#include \"ModuleEditor.h\"\n#include \"ModuleWindow.h\"\n\n#include \"Time.h\"\n#include \"Random.h\"\n#include \"EventQueue.h\"\n#include \"Data.h\"\n\n#include \"Brofiler\/include\/Brofiler.h\"\n\n#include \"ComponentCar.h\"\n\nusing namespace std;\n\nApplication::Application()\n{\n\t\/\/ Time controller\n\ttime = new Time();\n\t\n\t\/\/ Random\n\trnd = new Random();\n\n\t\/\/ EventQueue\n\tevent_queue = new EventQueue();\n\n\t\/\/ Modules\n\twindow = new ModuleWindow(\"window\");\n\tresource_manager = new ModuleResourceManager(\"resource_manager\");\n\tinput = new ModuleInput(\"input\");\n\taudio = new ModuleAudio(\"audio\");\n\tscene_intro = new ModuleSceneIntro(\"scene_intro\");\n\trenderer3D = new ModuleRenderer3D(\"renderer\");\n\tcamera = new ModuleCamera3D(\"camera\");\n\tphysics = new ModulePhysics3D(\"physics\");\n\tscripting = new ModuleScripting(\"scripting\");\n\teditor = new ModuleEditor(\"editor\");\n\tfile_system = new ModuleFileSystem(\"file_system\");\n\tgo_manager = new ModuleGOManager(\"go_manager\");\n\tlighting = new ModuleLighting(\"lighting\");\n\n\t\/\/Globals\n\tg_Debug = new DebugDraw(\"debug_draw\");\n\n\t\/\/ Modules will Init() Start() and Update in this order\n\t\/\/ They will CleanUp() in reverse order\n\n\t\/\/ Main Modules\n\tAddModule(file_system);\n\tAddModule(resource_manager);\n\tAddModule(window);\n\tAddModule(input);\n\tAddModule(g_Debug);\n\tAddModule(audio);\n\tAddModule(scripting);\n\tAddModule(physics);\n\tAddModule(go_manager);\n\tAddModule(camera);\t\n\tAddModule(lighting);\n\t\n\t\/\/ Scenes\n\tAddModule(scene_intro);\n\n\t\/\/Editor\n\tAddModule(editor);\n\n\t\/\/ Renderer last!\n\tAddModule(renderer3D);\n}\n\nApplication::~Application()\n{\n\tdelete rnd;\n\tdelete event_queue;\n\n\tvector::reverse_iterator i = list_modules.rbegin();\n\n\twhile (i != list_modules.rend())\n\t{\n\t\tdelete (*i);\n\t\t++i;\n\t}\n\n\tdelete time;\n}\n\nbool Application::Init()\n{\n\tbool ret = true;\n\n\t\/\/Load Configuration\n\tchar* buffer = nullptr;\n\tif (App->file_system->Load(\"Configuration.json\", &buffer) == 0)\n\t{\n\t\tLOG(\"Error while loading Configuration file\");\n\t\t\/\/Create a new Configuration file\n\t\tif (buffer)\n\t\t\tdelete[] buffer;\n\n\t\tData root_node;\n\t\troot_node.AppendBool(\"start_in_game\", false);\n\t\tvector::reverse_iterator i = list_modules.rbegin();\n\n\t\twhile (i != list_modules.rend())\n\t\t{\n\t\t\troot_node.AppendJObject((*i)->GetName());\n\t\t\t++i;\n\t\t}\n\tif (App->StartInGame() == false)\n\t\t{\n\t\t\tsize_t size = root_node.Serialize(&buffer);\t\n\t\t\tApp->file_system->Save(\"Configuration.json\", buffer, size);\n\t\t}\n\t}\n\tData config(buffer);\n\tdelete[] buffer;\n\n\t\/\/ Game is initialized in PlayMode?\n\tif (config.GetBool(\"start_in_game\"))\n\t{\n\t\tstart_in_game = true;\n\t\tgame_state = GAME_RUNNING;\n\t}\t\t\n\n\t\/\/ Call Init() in all modules\n\tvector::iterator i = list_modules.begin();\n\n\twhile (i != list_modules.end() && ret == true)\n\t{\n\t\tret = (*i)->Init(config.GetJObject((*i)->GetName()));\n\t\t++i;\n\t}\n\n\t\/\/ After all Init calls we call Start() in all modules\n\tLOG(\"Application Start --------------\");\n\ti = list_modules.begin();\n\n\twhile(i != list_modules.end() && ret == true)\n\t{\n\t\tret = (*i)->Start();\n\t\t++i;\n\t}\n\n\tcapped_ms = 1000 \/ max_fps;\n\n\t\/\/\/\/ Play all Components of every GameObject on the scene\n\tif (start_in_game)\n\t{\t\t\n\t\ttime->Play();\n\n\t\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t\t\t(*it)->OnPlay();\n\t}\t\n\t\n\treturn ret;\n}\n\n\/\/ ---------------------------------------------\nvoid Application::PrepareUpdate()\n{\n\ttime->UpdateFrame();\n}\n\n\/\/ ---------------------------------------------\nvoid Application::FinishUpdate()\n{\n\tevent_queue->ProcessEvents();\n\tif (want_to_load == true)\n\t{\n\t\twant_to_load = false;\n\t\tresource_manager->LoadSceneFromAssets(scene_to_load);\n\t}\n}\n\nvoid Application::LoadScene(const char* path)\n{\n\tif (want_to_load == false)\n\t{\n\t\tscene_to_load = (char*)path;\n\t\twant_to_load = true;\n\t}\n}\n\nvoid Application::OnStop()\n{\n\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t{\n\t\t(*it)->OnStop();\n\t}\n}\n\nvoid Application::OnPlay()\n{\n\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t\t(*it)->OnPlay();\n}\n\nvoid Application::RunGame() \n{\n\t\/\/Save current scene only if the game was stopped\n\tif (game_state == GAME_STOP)\n\t\tgo_manager->SaveSceneBeforeRunning();\n\n\tgame_state = GAME_RUNNING;\n\ttime->Play();\n\n\tOnPlay();\n}\n\nvoid Application::PauseGame()\n{\n\tgame_state = GAME_PAUSED;\n\ttime->Pause();\n\n\tfor (std::vector::iterator it = list_modules.begin(); it != list_modules.end(); it++)\n\t{\n\t\t(*it)->OnPause();\n\t}\n}\n\nvoid Application::StopGame()\n{\n\tgame_state = GAME_STOP;\n\tOnStop();\n\tgo_manager->LoadSceneBeforeRunning();\n\ttime->Stop();\t\n}\n\n\/\/ Call PreUpdate, Update and PostUpdate on all modules\nupdate_status Application::Update()\n{\n\tBROFILER_FRAME(\"GameLoop\")\n\n\tupdate_status ret = UPDATE_CONTINUE;\n\tPrepareUpdate();\n\t\n\tvector::iterator i = list_modules.begin();\n\n\twhile (i != list_modules.end() && ret == UPDATE_CONTINUE)\n\t{\n\t\tret = (*i)->PreUpdate();\n\t\t++i;\n\t}\n\n\ti = list_modules.begin();\n\n\twhile(i != list_modules.end() && ret == UPDATE_CONTINUE)\n\t{\n\t\tret = (*i)->Update();\n\t\t++i;\n\t}\n\n\ti = list_modules.begin();\n\n\twhile (i != list_modules.end() && ret == UPDATE_CONTINUE)\n\t{\n\t\tret = (*i)->PostUpdate();\n\t\ti++;\n\t}\n\n\tFinishUpdate();\n\treturn ret;\n}\n\nbool Application::CleanUp()\n{\n\tbool ret = true;\n\n\tvector::reverse_iterator i = list_modules.rbegin();\n\n\twhile (i != list_modules.rend() && ret == true)\n\t{\n\t\tret = (*i)->CleanUp();\n\t\t++i;\n\t}\n\n\treturn ret;\n}\n\nvoid Application::SaveBeforeClosing()\n{\n\tData root_node;\n\tchar* buf;\n\n\troot_node.AppendBool(\"start_in_game\", start_in_game);\n\n\tvector::reverse_iterator i = list_modules.rbegin();\n\n\twhile (i != list_modules.rend())\n\t{\n\t\t(*i)->SaveBeforeClosing(root_node.AppendJObject((*i)->GetName()));\n\t\t++i;\n\t}\n\n\tsize_t size = root_node.Serialize(&buf);\n\tif (App->StartInGame() == false)\n\t{\n\t\tuint success = App->file_system->Save(\"Configuration.json\", buf, size);\n\t}\n\n\tif (success == 0)\n\t\tLOG(\"Configuration could not be saved before closing\");\n\n\tdelete[] buf;\n}\n\nvoid Application::AddModule(Module* mod)\n{\n\tlist_modules.push_back(mod);\n}\n\nvoid Application::OpenURL(const char* url)\n{\n\tShellExecuteA(NULL, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n}\n\nvoid Application::SetMaxFPS(int max_fps)\n{\n\tthis->max_fps = max_fps;\n\tif (max_fps == 0) this->max_fps = -1;\n\tcapped_ms = 1000 \/ max_fps;\n}\n\nint Application::GetFPS()\n{\n\treturn 60; \/\/TODO: Update time with fps limit.\n}\n\nbool Application::ChangeGameState(GameStates new_state)\n{\n\tbool success = false;\n\tswitch (new_state)\n\t{\n\tcase GAME_STOP:\n\t\tif (game_state == GAME_RUNNING || game_state == GAME_PAUSED)\n\t\t{\n\t\t\tStopGame();\n\t\t\tsuccess = true;\n\t\t}\n\t\tbreak;\n\tcase GAME_RUNNING:\n\t\tif (game_state == GAME_STOP || game_state == GAME_PAUSED)\n\t\t{\n\t\t\tRunGame();\n\t\t\tsuccess = true;\n\t\t}\n\t\tbreak;\n\tcase GAME_PAUSED:\n\t\tif (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME)\n\t\t{\n\t\t\tPauseGame();\n\t\t\tsuccess = true;\n\t\t}\n\t\tbreak;\n\tcase GAME_NEXT_FRAME:\n\t\tif(game_state == GAME_RUNNING || game_state == GAME_PAUSED) \/\/TODO: Now this features is not available yet. Nothing happens in the game now. \n\t\t\t\/\/NextFrameGame();\n\t\tbreak;\n\t}\n\n\treturn success;\n}\n\n\/\/\/Returns true if the game simulation has started. If the game is paused also returns true.\nbool Application::IsGameRunning() const\n{\n\treturn (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME || game_state == GAME_PAUSED) ? true : false;\n}\n\n\/\/\/Returns true if the game is paused or in next frame mode. If the game is stop returns false.\nbool Application::IsGamePaused() const\n{\n\treturn (game_state == GAME_PAUSED || game_state == GAME_NEXT_FRAME) ? true : false;\n}\n\nbool Application::StartInGame() const\n{\n\treturn start_in_game;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015, RangerUFO\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of ranger_bhvr_tree nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef RANGER_BHVR_TREE_AGENT_PROXY_HPP\n#define\tRANGER_BHVR_TREE_AGENT_PROXY_HPP\n\n#include \n#include \n\nnamespace ranger { namespace bhvr_tree {\n\ntemplate \nclass decorator_counter_node;\n\nnamespace detail {\n\ntemplate \nclass agent_proxy_base {\npublic:\n\tagent_proxy_base() = default;\n\n\tagent_proxy_base(const agent_proxy_base&) = delete;\n\tagent_proxy_base& operator = (const agent_proxy_base&) = delete;\n\n\tbool less_then_increase(const decorator_counter_node* key, size_t value) {\n\t\tstd::lock_guard lock(m_counters_mtx);\n\n\t\tauto it = m_counters.emplace(key, 0).first;\n\t\tif (it->second >= value) {\n\t\t\treturn false;\n\t\t}\n\n\t\t++it->second;\n\t\treturn true;\n\t}\n\n\tvoid clear_all_state() {\n\t\tstd::lock_guard lock(m_counters_mtx);\n\t\tm_counters.clear();\n\t}\n\nprivate:\n\tstd::map*, size_t> m_counters;\n\tMutex m_counters_mtx;\n};\n\n}\n\ntemplate \nclass agent_proxy : public detail::agent_proxy_base> {\npublic:\n\tusing agent_type = Agent;\n\tusing mutex_type = Mutex;\n\n\tagent_proxy(Agent& agent) : m_agent(agent) {\n\t\t\/\/ nop\n\t}\n\n\tAgent& get_agent() const {\n\t\treturn m_agent;\n\t}\n\n\tAgent* operator -> () const {\n\t\treturn &m_agent;\n\t}\n\nprivate:\n\tAgent& m_agent;\n};\n\ntemplate \nclass agent_proxy : public detail::agent_proxy_base> {\npublic:\n\tusing agent_type = void;\n\tusing mutex_type = Mutex;\n};\n\n\/\/ An optional policy for agent_proxy.\nstruct dummy_mutex {\n\tvoid lock() {\n\t\t\/\/ nop\n\t}\n\n\tbool try_lock() {\n\t\treturn true;\n\t}\n\n\tvoid unlock() {\n\t\t\/\/ nop\n\t}\n};\n\n} }\n\n#endif\t\/\/ RANGER_BHVR_TREE_AGENT_PROXY_HPP\n为`agent_proxy`增加`Clock Policy`\/\/ Copyright (c) 2015, RangerUFO\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of ranger_bhvr_tree nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef RANGER_BHVR_TREE_AGENT_PROXY_HPP\n#define\tRANGER_BHVR_TREE_AGENT_PROXY_HPP\n\n#include \n#include \n#include \n\nnamespace ranger { namespace bhvr_tree {\n\ntemplate \nclass decorator_counter_node;\n\nnamespace detail {\n\ntemplate \nclass agent_proxy_base {\npublic:\n\tagent_proxy_base() = default;\n\n\tagent_proxy_base(const agent_proxy_base&) = delete;\n\tagent_proxy_base& operator = (const agent_proxy_base&) = delete;\n\n\tbool less_then_increase(const decorator_counter_node* key, size_t value) {\n\t\tstd::lock_guard lock(m_counters_mtx);\n\n\t\tauto it = m_counters.emplace(key, 0).first;\n\t\tif (it->second >= value) {\n\t\t\treturn false;\n\t\t}\n\n\t\t++it->second;\n\t\treturn true;\n\t}\n\n\tvoid clear_all_state() {\n\t\tstd::lock_guard lock(m_counters_mtx);\n\t\tm_counters.clear();\n\t}\n\nprivate:\n\tstd::map*, size_t> m_counters;\n\tMutex m_counters_mtx;\n};\n\n}\n\ntemplate \nclass agent_proxy : public detail::agent_proxy_base> {\npublic:\n\tusing agent_type = Agent;\n\tusing mutex_type = Mutex;\n\tusing clock_type = Clock;\n\n\tagent_proxy(Agent& agent) : m_agent(agent) {\n\t\t\/\/ nop\n\t}\n\n\tAgent& get_agent() const {\n\t\treturn m_agent;\n\t}\n\n\tAgent* operator -> () const {\n\t\treturn &m_agent;\n\t}\n\nprivate:\n\tAgent& m_agent;\n};\n\ntemplate \nclass agent_proxy : public detail::agent_proxy_base> {\npublic:\n\tusing agent_type = void;\n\tusing mutex_type = Mutex;\n\tusing clock_type = Clock;\n};\n\n\/\/ An optional policy for agent_proxy.\nstruct dummy_mutex {\n\tvoid lock() {\n\t\t\/\/ nop\n\t}\n\n\tbool try_lock() {\n\t\treturn true;\n\t}\n\n\tvoid unlock() {\n\t\t\/\/ nop\n\t}\n};\n\n} }\n\n#endif\t\/\/ RANGER_BHVR_TREE_AGENT_PROXY_HPP\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"android_webview\/native\/aw_autofill_manager_delegate.h\"\n\n#include \"android_webview\/browser\/aw_browser_context.h\"\n#include \"android_webview\/browser\/aw_content_browser_client.h\"\n#include \"android_webview\/browser\/aw_pref_store.h\"\n#include \"android_webview\/native\/aw_contents.h\"\n#include \"base\/android\/jni_android.h\"\n#include \"base\/android\/jni_string.h\"\n#include \"base\/android\/scoped_java_ref.h\"\n#include \"base\/logging.h\"\n#include \"base\/prefs\/pref_registry_simple.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/prefs\/pref_service_builder.h\"\n#include \"components\/autofill\/content\/browser\/autocheckout\/whitelist_manager.h\"\n#include \"components\/autofill\/core\/browser\/autofill_popup_delegate.h\"\n#include \"components\/autofill\/core\/common\/autofill_pref_names.h\"\n#include \"components\/user_prefs\/user_prefs.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"jni\/AwAutofillManagerDelegate_jni.h\"\n\nusing base::android::AttachCurrentThread;\nusing base::android::ConvertUTF16ToJavaString;\nusing base::android::ScopedJavaLocalRef;\nusing content::WebContents;\n\nDEFINE_WEB_CONTENTS_USER_DATA_KEY(android_webview::AwAutofillManagerDelegate);\n\nnamespace android_webview {\n\n\/\/ Ownership: The native object is created (if autofill enabled) and owned by\n\/\/ AwContents. The native object creates the java peer which handles most\n\/\/ autofill functionality at the java side. The java peer is owned by Java\n\/\/ AwContents. The native object only maintains a weak ref to it.\nAwAutofillManagerDelegate::AwAutofillManagerDelegate(WebContents* contents)\n : web_contents_(contents),\n save_form_data_(false) {\n JNIEnv* env = AttachCurrentThread();\n ScopedJavaLocalRef delegate;\n delegate.Reset(\n Java_AwAutofillManagerDelegate_create(env, reinterpret_cast(this)));\n\n AwContents* aw_contents = AwContents::FromWebContents(web_contents_);\n aw_contents->SetAwAutofillManagerDelegate(delegate.obj());\n java_ref_ = JavaObjectWeakGlobalRef(env, delegate.obj());\n}\n\nAwAutofillManagerDelegate::~AwAutofillManagerDelegate() {\n HideAutofillPopup();\n}\n\nvoid AwAutofillManagerDelegate::SetSaveFormData(bool enabled) {\n save_form_data_ = enabled;\n}\n\nbool AwAutofillManagerDelegate::GetSaveFormData() {\n return save_form_data_;\n}\n\nPrefService* AwAutofillManagerDelegate::GetPrefs() {\n return user_prefs::UserPrefs::Get(\n AwContentBrowserClient::GetAwBrowserContext());\n}\n\nautofill::PersonalDataManager*\nAwAutofillManagerDelegate::GetPersonalDataManager() {\n return NULL;\n}\n\nautofill::autocheckout::WhitelistManager*\nAwAutofillManagerDelegate::GetAutocheckoutWhitelistManager() const {\n return NULL;\n}\n\nvoid AwAutofillManagerDelegate::ShowAutofillPopup(\n const gfx::RectF& element_bounds,\n base::i18n::TextDirection text_direction,\n const std::vector& values,\n const std::vector& labels,\n const std::vector& icons,\n const std::vector& identifiers,\n base::WeakPtr delegate) {\n\n values_ = values;\n identifiers_ = identifiers;\n delegate_ = delegate;\n\n \/\/ Convert element_bounds to be in screen space.\n gfx::Rect client_area;\n web_contents_->GetView()->GetContainerBounds(&client_area);\n gfx::RectF element_bounds_in_screen_space =\n element_bounds + client_area.OffsetFromOrigin();\n\n ShowAutofillPopupImpl(element_bounds_in_screen_space,\n values,\n labels,\n identifiers);\n}\n\nvoid AwAutofillManagerDelegate::ShowAutofillPopupImpl(\n const gfx::RectF& element_bounds,\n const std::vector& values,\n const std::vector& labels,\n const std::vector& identifiers) {\n JNIEnv* env = AttachCurrentThread();\n ScopedJavaLocalRef obj = java_ref_.get(env);\n if (obj.is_null())\n return;\n\n \/\/ We need an array of AutofillSuggestion.\n size_t count = values.size();\n\n ScopedJavaLocalRef data_array =\n Java_AwAutofillManagerDelegate_createAutofillSuggestionArray(env, count);\n\n for (size_t i = 0; i < count; ++i) {\n ScopedJavaLocalRef name = ConvertUTF16ToJavaString(env, values[i]);\n ScopedJavaLocalRef label =\n ConvertUTF16ToJavaString(env, labels[i]);\n Java_AwAutofillManagerDelegate_addToAutofillSuggestionArray(\n env,\n data_array.obj(),\n i,\n name.obj(),\n label.obj(),\n identifiers[i]);\n }\n\n Java_AwAutofillManagerDelegate_showAutofillPopup(\n env,\n obj.obj(),\n element_bounds.x(),\n element_bounds.y(), element_bounds.width(),\n element_bounds.height(), data_array.obj());\n}\n\nvoid AwAutofillManagerDelegate::UpdateAutofillPopupDataListValues(\n const std::vector& values,\n const std::vector& labels) {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::HideAutofillPopup() {\n JNIEnv* env = AttachCurrentThread();\n ScopedJavaLocalRef obj = java_ref_.get(env);\n if (obj.is_null())\n return;\n delegate_.reset();\n Java_AwAutofillManagerDelegate_hideAutofillPopup(env, obj.obj());\n}\n\nbool AwAutofillManagerDelegate::IsAutocompleteEnabled() {\n return GetSaveFormData();\n}\n\nvoid AwAutofillManagerDelegate::SuggestionSelected(JNIEnv* env,\n jobject object,\n jint position) {\n if (delegate_)\n delegate_->DidAcceptSuggestion(values_[position], identifiers_[position]);\n}\n\nvoid AwAutofillManagerDelegate::HideRequestAutocompleteDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::OnAutocheckoutError() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::OnAutocheckoutSuccess() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::ShowAutofillSettings() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::ConfirmSaveCreditCard(\n const autofill::AutofillMetrics& metric_logger,\n const autofill::CreditCard& credit_card,\n const base::Closure& save_card_callback) {\n NOTIMPLEMENTED();\n}\n\nbool AwAutofillManagerDelegate::ShowAutocheckoutBubble(\n const gfx::RectF& bounding_box,\n bool is_google_user,\n const base::Callback& callback) {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid AwAutofillManagerDelegate::HideAutocheckoutBubble() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::ShowRequestAutocompleteDialog(\n const autofill::FormData& form,\n const GURL& source_url,\n autofill::DialogType dialog_type,\n const base::Callback& callback) {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::AddAutocheckoutStep(\n autofill::AutocheckoutStepType step_type) {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::UpdateAutocheckoutStep(\n autofill::AutocheckoutStepType step_type,\n autofill::AutocheckoutStepStatus step_status) {\n NOTIMPLEMENTED();\n}\n\nbool RegisterAwAutofillManagerDelegate(JNIEnv* env) {\n return RegisterNativesImpl(env) >= 0;\n}\n\n} \/\/ namespace android_webview\nam 2c3943e4: Merge \"Prevent log spam in autofill\" into klp-dev\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"android_webview\/native\/aw_autofill_manager_delegate.h\"\n\n#include \"android_webview\/browser\/aw_browser_context.h\"\n#include \"android_webview\/browser\/aw_content_browser_client.h\"\n#include \"android_webview\/browser\/aw_pref_store.h\"\n#include \"android_webview\/native\/aw_contents.h\"\n#include \"base\/android\/jni_android.h\"\n#include \"base\/android\/jni_string.h\"\n#include \"base\/android\/scoped_java_ref.h\"\n#include \"base\/logging.h\"\n#include \"base\/prefs\/pref_registry_simple.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/prefs\/pref_service_builder.h\"\n#include \"components\/autofill\/content\/browser\/autocheckout\/whitelist_manager.h\"\n#include \"components\/autofill\/core\/browser\/autofill_popup_delegate.h\"\n#include \"components\/autofill\/core\/common\/autofill_pref_names.h\"\n#include \"components\/user_prefs\/user_prefs.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"jni\/AwAutofillManagerDelegate_jni.h\"\n\nusing base::android::AttachCurrentThread;\nusing base::android::ConvertUTF16ToJavaString;\nusing base::android::ScopedJavaLocalRef;\nusing content::WebContents;\n\nDEFINE_WEB_CONTENTS_USER_DATA_KEY(android_webview::AwAutofillManagerDelegate);\n\nnamespace android_webview {\n\n\/\/ Ownership: The native object is created (if autofill enabled) and owned by\n\/\/ AwContents. The native object creates the java peer which handles most\n\/\/ autofill functionality at the java side. The java peer is owned by Java\n\/\/ AwContents. The native object only maintains a weak ref to it.\nAwAutofillManagerDelegate::AwAutofillManagerDelegate(WebContents* contents)\n : web_contents_(contents),\n save_form_data_(false) {\n JNIEnv* env = AttachCurrentThread();\n ScopedJavaLocalRef delegate;\n delegate.Reset(\n Java_AwAutofillManagerDelegate_create(env, reinterpret_cast(this)));\n\n AwContents* aw_contents = AwContents::FromWebContents(web_contents_);\n aw_contents->SetAwAutofillManagerDelegate(delegate.obj());\n java_ref_ = JavaObjectWeakGlobalRef(env, delegate.obj());\n}\n\nAwAutofillManagerDelegate::~AwAutofillManagerDelegate() {\n HideAutofillPopup();\n}\n\nvoid AwAutofillManagerDelegate::SetSaveFormData(bool enabled) {\n save_form_data_ = enabled;\n}\n\nbool AwAutofillManagerDelegate::GetSaveFormData() {\n return save_form_data_;\n}\n\nPrefService* AwAutofillManagerDelegate::GetPrefs() {\n return user_prefs::UserPrefs::Get(\n AwContentBrowserClient::GetAwBrowserContext());\n}\n\nautofill::PersonalDataManager*\nAwAutofillManagerDelegate::GetPersonalDataManager() {\n return NULL;\n}\n\nautofill::autocheckout::WhitelistManager*\nAwAutofillManagerDelegate::GetAutocheckoutWhitelistManager() const {\n return NULL;\n}\n\nvoid AwAutofillManagerDelegate::ShowAutofillPopup(\n const gfx::RectF& element_bounds,\n base::i18n::TextDirection text_direction,\n const std::vector& values,\n const std::vector& labels,\n const std::vector& icons,\n const std::vector& identifiers,\n base::WeakPtr delegate) {\n\n values_ = values;\n identifiers_ = identifiers;\n delegate_ = delegate;\n\n \/\/ Convert element_bounds to be in screen space.\n gfx::Rect client_area;\n web_contents_->GetView()->GetContainerBounds(&client_area);\n gfx::RectF element_bounds_in_screen_space =\n element_bounds + client_area.OffsetFromOrigin();\n\n ShowAutofillPopupImpl(element_bounds_in_screen_space,\n values,\n labels,\n identifiers);\n}\n\nvoid AwAutofillManagerDelegate::ShowAutofillPopupImpl(\n const gfx::RectF& element_bounds,\n const std::vector& values,\n const std::vector& labels,\n const std::vector& identifiers) {\n JNIEnv* env = AttachCurrentThread();\n ScopedJavaLocalRef obj = java_ref_.get(env);\n if (obj.is_null())\n return;\n\n \/\/ We need an array of AutofillSuggestion.\n size_t count = values.size();\n\n ScopedJavaLocalRef data_array =\n Java_AwAutofillManagerDelegate_createAutofillSuggestionArray(env, count);\n\n for (size_t i = 0; i < count; ++i) {\n ScopedJavaLocalRef name = ConvertUTF16ToJavaString(env, values[i]);\n ScopedJavaLocalRef label =\n ConvertUTF16ToJavaString(env, labels[i]);\n Java_AwAutofillManagerDelegate_addToAutofillSuggestionArray(\n env,\n data_array.obj(),\n i,\n name.obj(),\n label.obj(),\n identifiers[i]);\n }\n\n Java_AwAutofillManagerDelegate_showAutofillPopup(\n env,\n obj.obj(),\n element_bounds.x(),\n element_bounds.y(), element_bounds.width(),\n element_bounds.height(), data_array.obj());\n}\n\nvoid AwAutofillManagerDelegate::UpdateAutofillPopupDataListValues(\n const std::vector& values,\n const std::vector& labels) {\n \/\/ Leaving as an empty method since updating autofill popup window\n \/\/ dynamically does not seem to be a useful feature for android webview.\n \/\/ See crrev.com\/18102002 if need to implement.\n}\n\nvoid AwAutofillManagerDelegate::HideAutofillPopup() {\n JNIEnv* env = AttachCurrentThread();\n ScopedJavaLocalRef obj = java_ref_.get(env);\n if (obj.is_null())\n return;\n delegate_.reset();\n Java_AwAutofillManagerDelegate_hideAutofillPopup(env, obj.obj());\n}\n\nbool AwAutofillManagerDelegate::IsAutocompleteEnabled() {\n return GetSaveFormData();\n}\n\nvoid AwAutofillManagerDelegate::SuggestionSelected(JNIEnv* env,\n jobject object,\n jint position) {\n if (delegate_)\n delegate_->DidAcceptSuggestion(values_[position], identifiers_[position]);\n}\n\nvoid AwAutofillManagerDelegate::HideRequestAutocompleteDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::OnAutocheckoutError() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::OnAutocheckoutSuccess() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::ShowAutofillSettings() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::ConfirmSaveCreditCard(\n const autofill::AutofillMetrics& metric_logger,\n const autofill::CreditCard& credit_card,\n const base::Closure& save_card_callback) {\n NOTIMPLEMENTED();\n}\n\nbool AwAutofillManagerDelegate::ShowAutocheckoutBubble(\n const gfx::RectF& bounding_box,\n bool is_google_user,\n const base::Callback& callback) {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid AwAutofillManagerDelegate::HideAutocheckoutBubble() {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::ShowRequestAutocompleteDialog(\n const autofill::FormData& form,\n const GURL& source_url,\n autofill::DialogType dialog_type,\n const base::Callback& callback) {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::AddAutocheckoutStep(\n autofill::AutocheckoutStepType step_type) {\n NOTIMPLEMENTED();\n}\n\nvoid AwAutofillManagerDelegate::UpdateAutocheckoutStep(\n autofill::AutocheckoutStepType step_type,\n autofill::AutocheckoutStepStatus step_status) {\n NOTIMPLEMENTED();\n}\n\nbool RegisterAwAutofillManagerDelegate(JNIEnv* env) {\n return RegisterNativesImpl(env) >= 0;\n}\n\n} \/\/ namespace android_webview\n<|endoftext|>"} {"text":"#include \n#include \"application_manager\/app_launch\/apps_launcher.h\"\n#include \"utils\/make_shared.h\"\n#include \"utils\/timer_task_impl.h\"\n#include \n\nnamespace app_launch {\nstruct LauncherGenerator {\n LauncherGenerator(AppsLauncher& apps_laucnher,\n connection_handler::ConnectionHandler& connection_handler,\n const uint16_t app_launch_max_retry_attempt,\n const uint16_t app_launch_retry_wait_time)\n : apps_laucnher_(apps_laucnher)\n , connection_handler_(connection_handler)\n , app_launch_max_retry_attempt_(app_launch_max_retry_attempt)\n , app_launch_retry_wait_time_(app_launch_retry_wait_time) {}\n AppsLauncher::LauncherPtr operator()() {\n return utils::MakeShared(\n apps_laucnher_,\n connection_handler_,\n app_launch_max_retry_attempt_,\n app_launch_retry_wait_time_);\n }\n\n AppsLauncher& apps_laucnher_;\n connection_handler::ConnectionHandler& connection_handler_;\n const uint16_t app_launch_max_retry_attempt_;\n const uint16_t app_launch_retry_wait_time_;\n};\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"AppLaunch\")\nAppsLauncher::AppsLauncher(\n connection_handler::ConnectionHandler& connection_handler,\n const uint16_t max_number_of_ios_device,\n const uint16_t app_launch_max_retry_attempt,\n const uint16_t app_launch_retry_wait_time) {\n sync_primitives::AutoLock lock(launchers_lock_);\n free_launchers_.resize(max_number_of_ios_device);\n std::generate(free_launchers_.begin(),\n free_launchers_.end(),\n LauncherGenerator(*this,\n connection_handler,\n app_launch_max_retry_attempt,\n app_launch_retry_wait_time));\n}\n\nvoid AppsLauncher::StartLaunching(ApplicationDataPtr app_data) {\n LOG4CXX_AUTO_TRACE(logger_);\n sync_primitives::AutoLock lock(launchers_lock_);\n DCHECK_OR_RETURN_VOID(!free_launchers_.empty())\n const AppLaunchers::iterator it = free_launchers_.begin();\n LauncherPtr app_launcher = *it;\n works_launchers_.push_back(app_launcher);\n free_launchers_.erase(it);\n app_launcher->PosponedLaunch(app_data);\n}\n\nstruct AppLauncherFinder {\n AppLauncherFinder(const ApplicationDataPtr& app_data) : app_data_(app_data) {}\n bool operator()(const AppsLauncher::LauncherPtr& launcher) const {\n DCHECK_OR_RETURN(launcher->app_data_ && app_data_, false)\n return *launcher->app_data_ == *app_data_;\n }\n const ApplicationDataPtr& app_data_;\n};\n\nvoid AppsLauncher::StopLaunching(ApplicationDataPtr app_data) {\n sync_primitives::AutoLock lock(launchers_lock_);\n const AppLaunchers::iterator it = std::find_if(works_launchers_.begin(),\n works_launchers_.end(),\n AppLauncherFinder(app_data));\n if (it != works_launchers_.end()) {\n LauncherPtr launcher = *it;\n launcher->Clear();\n free_launchers_.push_back(launcher);\n works_launchers_.erase(it);\n } else {\n LOG4CXX_DEBUG(logger_,\n \"Unable to StopLaunching\" << app_data->mobile_app_id_);\n }\n}\n\nvoid AppsLauncher::OnLaunched(ApplicationDataPtr app_data) {\n LOG4CXX_AUTO_TRACE(logger_);\n StopLaunching(app_data);\n}\n\nvoid AppsLauncher::OnRetryAttemptsExhausted(ApplicationDataPtr app_data) {\n LOG4CXX_AUTO_TRACE(logger_);\n StopLaunching(app_data);\n}\n\nAppsLauncher::Launcher::Launcher(\n AppsLauncher& parent,\n connection_handler::ConnectionHandler& connection_handler,\n const uint16_t app_launch_max_retry_attempt,\n const uint16_t app_launch_retry_wait_time)\n : retry_timer_(\n \"AppsLauncherTimer\",\n new timer::TimerTaskImpl(this, &Launcher::LaunchNow))\n , app_launch_max_retry_attempt_(app_launch_max_retry_attempt)\n , app_launch_retry_wait_time_(app_launch_retry_wait_time)\n , connection_handler_(connection_handler)\n , parent_(parent) {}\n\nvoid AppsLauncher::Launcher::PosponedLaunch(\n const app_launch::ApplicationDataPtr& app_data) {\n DCHECK(!app_data_);\n app_data_ = app_data;\n retry_index_ = 0;\n retry_timer_.Start(app_launch_retry_wait_time_, timer::kPeriodic);\n LOG4CXX_DEBUG(logger_,\n \"Applicaiton \" << app_data->mobile_app_id_ << \" on device \"\n << app_data->device_mac_\n << \" will be launched in \"\n << app_launch_retry_wait_time_ << \" ms\");\n}\n\nvoid AppsLauncher::Launcher::Clear() {\n retry_timer_.Stop();\n app_data_.reset();\n retry_index_ = 0;\n}\n\nvoid AppsLauncher::Launcher::LaunchNow() {\n if (retry_index_++ < app_launch_max_retry_attempt_) {\n LOG4CXX_DEBUG(logger_,\n \"Run App \" << app_data_->mobile_app_id_ << \"with bundle \"\n << app_data_->bundle_id_ << \" On Device \"\n << app_data_->device_mac_);\n\n connection_handler_.RunAppOnDevice(app_data_->device_mac_,\n app_data_->bundle_id_);\n } else {\n parent_.OnRetryAttemptsExhausted(app_data_);\n }\n}\n\n} \/\/ namespace app_launch\nFix for coverity issue 170762#include \n#include \"application_manager\/app_launch\/apps_launcher.h\"\n#include \"utils\/make_shared.h\"\n#include \"utils\/timer_task_impl.h\"\n#include \n\nnamespace app_launch {\nstruct LauncherGenerator {\n LauncherGenerator(AppsLauncher& apps_laucnher,\n connection_handler::ConnectionHandler& connection_handler,\n const uint16_t app_launch_max_retry_attempt,\n const uint16_t app_launch_retry_wait_time)\n : apps_laucnher_(apps_laucnher)\n , connection_handler_(connection_handler)\n , app_launch_max_retry_attempt_(app_launch_max_retry_attempt)\n , app_launch_retry_wait_time_(app_launch_retry_wait_time) {}\n AppsLauncher::LauncherPtr operator()() {\n return utils::MakeShared(\n apps_laucnher_,\n connection_handler_,\n app_launch_max_retry_attempt_,\n app_launch_retry_wait_time_);\n }\n\n AppsLauncher& apps_laucnher_;\n connection_handler::ConnectionHandler& connection_handler_;\n const uint16_t app_launch_max_retry_attempt_;\n const uint16_t app_launch_retry_wait_time_;\n};\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"AppLaunch\")\nAppsLauncher::AppsLauncher(\n connection_handler::ConnectionHandler& connection_handler,\n const uint16_t max_number_of_ios_device,\n const uint16_t app_launch_max_retry_attempt,\n const uint16_t app_launch_retry_wait_time) {\n sync_primitives::AutoLock lock(launchers_lock_);\n free_launchers_.resize(max_number_of_ios_device);\n std::generate(free_launchers_.begin(),\n free_launchers_.end(),\n LauncherGenerator(*this,\n connection_handler,\n app_launch_max_retry_attempt,\n app_launch_retry_wait_time));\n}\n\nvoid AppsLauncher::StartLaunching(ApplicationDataPtr app_data) {\n LOG4CXX_AUTO_TRACE(logger_);\n sync_primitives::AutoLock lock(launchers_lock_);\n DCHECK_OR_RETURN_VOID(!free_launchers_.empty())\n const AppLaunchers::iterator it = free_launchers_.begin();\n LauncherPtr app_launcher = *it;\n works_launchers_.push_back(app_launcher);\n free_launchers_.erase(it);\n app_launcher->PosponedLaunch(app_data);\n}\n\nstruct AppLauncherFinder {\n AppLauncherFinder(const ApplicationDataPtr& app_data) : app_data_(app_data) {}\n bool operator()(const AppsLauncher::LauncherPtr& launcher) const {\n DCHECK_OR_RETURN(launcher->app_data_ && app_data_, false)\n return *launcher->app_data_ == *app_data_;\n }\n const ApplicationDataPtr& app_data_;\n};\n\nvoid AppsLauncher::StopLaunching(ApplicationDataPtr app_data) {\n sync_primitives::AutoLock lock(launchers_lock_);\n const AppLaunchers::iterator it = std::find_if(works_launchers_.begin(),\n works_launchers_.end(),\n AppLauncherFinder(app_data));\n if (it != works_launchers_.end()) {\n LauncherPtr launcher = *it;\n launcher->Clear();\n free_launchers_.push_back(launcher);\n works_launchers_.erase(it);\n } else {\n LOG4CXX_DEBUG(logger_,\n \"Unable to StopLaunching\" << app_data->mobile_app_id_);\n }\n}\n\nvoid AppsLauncher::OnLaunched(ApplicationDataPtr app_data) {\n LOG4CXX_AUTO_TRACE(logger_);\n StopLaunching(app_data);\n}\n\nvoid AppsLauncher::OnRetryAttemptsExhausted(ApplicationDataPtr app_data) {\n LOG4CXX_AUTO_TRACE(logger_);\n StopLaunching(app_data);\n}\n\nAppsLauncher::Launcher::Launcher(\n AppsLauncher& parent,\n connection_handler::ConnectionHandler& connection_handler,\n const uint16_t app_launch_max_retry_attempt,\n const uint16_t app_launch_retry_wait_time)\n : retry_index_(0)\n , retry_timer_(\n \"AppsLauncherTimer\",\n new timer::TimerTaskImpl(this, &Launcher::LaunchNow))\n , app_launch_max_retry_attempt_(app_launch_max_retry_attempt)\n , app_launch_retry_wait_time_(app_launch_retry_wait_time)\n , connection_handler_(connection_handler)\n , parent_(parent) {}\n\nvoid AppsLauncher::Launcher::PosponedLaunch(\n const app_launch::ApplicationDataPtr& app_data) {\n DCHECK(!app_data_);\n app_data_ = app_data;\n retry_index_ = 0;\n retry_timer_.Start(app_launch_retry_wait_time_, timer::kPeriodic);\n LOG4CXX_DEBUG(logger_,\n \"Applicaiton \" << app_data->mobile_app_id_ << \" on device \"\n << app_data->device_mac_\n << \" will be launched in \"\n << app_launch_retry_wait_time_ << \" ms\");\n}\n\nvoid AppsLauncher::Launcher::Clear() {\n retry_timer_.Stop();\n app_data_.reset();\n retry_index_ = 0;\n}\n\nvoid AppsLauncher::Launcher::LaunchNow() {\n if (retry_index_++ < app_launch_max_retry_attempt_) {\n LOG4CXX_DEBUG(logger_,\n \"Run App \" << app_data_->mobile_app_id_ << \"with bundle \"\n << app_data_->bundle_id_ << \" On Device \"\n << app_data_->device_mac_);\n\n connection_handler_.RunAppOnDevice(app_data_->device_mac_,\n app_data_->bundle_id_);\n } else {\n parent_.OnRetryAttemptsExhausted(app_data_);\n }\n}\n\n} \/\/ namespace app_launch\n<|endoftext|>"} {"text":"#include \"buffer.h\"\n#include \"..\/sockets\/SocketW.h\"\n#include \n\nclass user{\n public:\n user(SWBaseSocket * newConn);\n void disconnect(std::string reason);\n void Send(buffer ** ringbuf, int buffers);\n bool is_connected;\n SWUnixSocket * Conn;\n int MyBuffer;\n int MyBuffer_num;\n int MyBuffer_len;\n int MyNum;\n void * lastpointer;\n static int UserCount;\n static SWBaseSocket::SWBaseError err;\n};\/\/user\n\nint user::UserCount = 0;\nSWBaseSocket::SWBaseError user::err;\n\nuser::user(SWBaseSocket * newConn) {\n Conn = (SWUnixSocket*)newConn;\n is_connected = (Conn != 0);\n MyNum = UserCount++;\n std::cout << \"User \" << MyNum << \" connected\" << std::endl;\n}\n\nvoid user::disconnect(std::string reason) {\n if (Conn) {\n Conn->disconnect(&err);\n Conn = NULL;\n std::cout << \"Disconnected user \" << MyNum << \": \" << reason << std::endl;\n }\n is_connected = false;\n}\n\nvoid user::Send(buffer ** ringbuf, int buffers){\n \/\/not connected? cancel\n if (!is_connected){return;}\n \/\/still waiting for next buffer? check it\n if (MyBuffer_num < 0){\n MyBuffer_num = ringbuf[MyBuffer]->number;\n \/\/still waiting? don't crash - wait longer.\n if (MyBuffer_num < 0){\n return;\n }else{\n MyBuffer_len = ringbuf[MyBuffer]->FLV->len;\n lastpointer = ringbuf[MyBuffer]->FLV->data;\n }\n }\n if (lastpointer != ringbuf[MyBuffer]->FLV->data){\n disconnect(\"Buffer resize at wrong time... had to disconnect\");\n return;\n }\n int ret = Conn->fsend(ringbuf[MyBuffer]->FLV->data, MyBuffer_len, &err);\n if ((err != SWBaseSocket::ok) && (err != SWBaseSocket::notReady)){\n disconnect(\"Socket error: \" + err.get_error());\n return;\n }\n if (ret == MyBuffer_len){\n \/\/completed a send - switch to next buffer\n if ((ringbuf[MyBuffer]->number != MyBuffer_num)){\n std::cout << \"Warning: User \" << MyNum << \" was send corrupt video data and send to the next keyframe!\" << std::endl;\n do{\n MyBuffer++;\n MyBuffer %= buffers;\n }while(!ringbuf[MyBuffer]->FLV->isKeyframe);\n }else{\n MyBuffer++;\n MyBuffer %= buffers;\n }\n MyBuffer_num = -1;\n lastpointer = 0;\n }\n}\nBuffer crash probleem fixed#include \"buffer.h\"\n#include \"..\/sockets\/SocketW.h\"\n#include \n\nclass user{\n public:\n user(SWBaseSocket * newConn);\n void disconnect(std::string reason);\n void Send(buffer ** ringbuf, int buffers);\n bool is_connected;\n SWUnixSocket * Conn;\n int MyBuffer;\n int MyBuffer_num;\n int MyBuffer_len;\n int MyNum;\n void * lastpointer;\n static int UserCount;\n static SWBaseSocket::SWBaseError err;\n};\/\/user\n\nint user::UserCount = 0;\nSWBaseSocket::SWBaseError user::err;\n\nuser::user(SWBaseSocket * newConn) {\n Conn = (SWUnixSocket*)newConn;\n is_connected = (Conn != 0);\n MyNum = UserCount++;\n std::cout << \"User \" << MyNum << \" connected\" << std::endl;\n}\n\nvoid user::disconnect(std::string reason) {\n if (Conn) {\n Conn->disconnect(&err);\n Conn = NULL;\n std::cout << \"Disconnected user \" << MyNum << \": \" << reason << std::endl;\n }\n is_connected = false;\n}\n\nvoid user::Send(buffer ** ringbuf, int buffers){\n \/\/not connected? cancel\n if (!is_connected){return;}\n \/\/still waiting for next buffer? check it\n if (MyBuffer_num < 0){\n MyBuffer_num = ringbuf[MyBuffer]->number;\n \/\/still waiting? don't crash - wait longer.\n if (MyBuffer_num < 0){\n return;\n }else{\n MyBuffer_len = ringbuf[MyBuffer]->FLV->len;\n lastpointer = ringbuf[MyBuffer]->FLV->data;\n }\n }\n if (lastpointer != ringbuf[MyBuffer]->FLV->data){\n disconnect(\"Buffer resize at wrong time... had to disconnect\");\n return;\n }\n int ret = Conn->fsend(ringbuf[MyBuffer]->FLV->data, MyBuffer_len, &err);\n if ((err != SWBaseSocket::ok) && (err != SWBaseSocket::notReady)){\n disconnect(\"Socket error: \" + err.get_error());\n return;\n }\n if (ret == MyBuffer_len){\n \/\/completed a send - switch to next buffer\n if ((ringbuf[MyBuffer]->number != MyBuffer_num)){\n std::cout << \"Warning: User \" << MyNum << \" was send corrupt video data and send to the next keyframe!\" << std::endl;\n int nocrashcount = 0;\n do{\n MyBuffer++;\n nocrashcount++;\n MyBuffer %= buffers;\n }while(!ringbuf[MyBuffer]->FLV->isKeyframe && (nocrashcount < buffers));\n if (nocrashcount >= buffers){\n std::cout << \"Warning: No keyframe found in buffers! Skipping search for now...\" << std::endl;\n return;\n }\n }else{\n MyBuffer++;\n MyBuffer %= buffers;\n }\n MyBuffer_num = -1;\n lastpointer = 0;\n }\n}\n<|endoftext|>"} {"text":"\/\/===- Chunks.cpp ---------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Chunks.h\"\n#include \"InputFiles.h\"\n#include \"Writer.h\"\n#include \"lld\/Core\/Error.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Object\/COFF.h\"\n#include \"llvm\/Support\/COFF.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Endian.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm::object;\nusing namespace llvm::support::endian;\nusing namespace llvm::COFF;\nusing llvm::RoundUpToAlignment;\n\nnamespace lld {\nnamespace coff {\n\nSectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI)\n : File(F), Header(H), SectionIndex(SI) {\n \/\/ Initialize SectionName.\n File->getCOFFObj()->getSectionName(Header, SectionName);\n \/\/ Bit [20:24] contains section alignment.\n unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1;\n Align = uint32_t(1) << Shift;\n}\n\nvoid SectionChunk::writeTo(uint8_t *Buf) {\n assert(hasData());\n ArrayRef Data;\n File->getCOFFObj()->getSectionContents(Header, Data);\n memcpy(Buf + FileOff, Data.data(), Data.size());\n}\n\n\/\/ Returns true if this chunk should be considered as a GC root.\nbool SectionChunk::isRoot() {\n \/\/ COMDAT sections are live only when they are referenced by something else.\n if (isCOMDAT())\n return false;\n\n \/\/ Associative sections are live if their parent COMDATs are live,\n \/\/ and vice versa, so they are not considered live by themselves.\n if (IsAssocChild)\n return false;\n\n \/\/ Only code is subject of dead-stripping.\n return !(Header->Characteristics & IMAGE_SCN_CNT_CODE);\n}\n\nvoid SectionChunk::markLive() {\n if (Live)\n return;\n Live = true;\n\n \/\/ Mark all symbols listed in the relocation table for this section.\n for (const auto &I : getSectionRef().relocations()) {\n const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);\n SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);\n if (auto *Def = dyn_cast(B))\n Def->markLive();\n }\n\n \/\/ Mark associative sections if any.\n for (Chunk *C : AssocChildren)\n C->markLive();\n}\n\nvoid SectionChunk::addAssociative(SectionChunk *Child) {\n Child->IsAssocChild = true;\n AssocChildren.push_back(Child);\n}\n\nvoid SectionChunk::applyRelocations(uint8_t *Buf) {\n for (const auto &I : getSectionRef().relocations()) {\n const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);\n applyReloc(Buf, Rel);\n }\n}\n\nstatic void add16(uint8_t *P, int32_t V) { write16le(P, read16le(P) + V); }\nstatic void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }\nstatic void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }\n\n\/\/ Implements x64 PE\/COFF relocations.\nvoid SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {\n using namespace llvm::COFF;\n uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;\n SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);\n uint64_t S = cast(Body)->getRVA();\n uint64_t P = RVA + Rel->VirtualAddress;\n switch (Rel->Type) {\n case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break;\n case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break;\n case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;\n case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break;\n case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break;\n case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break;\n case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break;\n case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break;\n case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break;\n case IMAGE_REL_AMD64_SECTION: add16(Off, Out->getSectionIndex()); break;\n case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break;\n default:\n llvm::report_fatal_error(\"Unsupported relocation type\");\n }\n}\n\nbool SectionChunk::hasData() const {\n return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);\n}\n\nuint32_t SectionChunk::getPermissions() const {\n return Header->Characteristics & PermMask;\n}\n\nbool SectionChunk::isCOMDAT() const {\n return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;\n}\n\n\/\/ Prints \"Discarded \" for all external function symbols.\nvoid SectionChunk::printDiscardedMessage() {\n uint32_t E = File->getCOFFObj()->getNumberOfSymbols();\n for (uint32_t I = 0; I < E; ++I) {\n auto SrefOrErr = File->getCOFFObj()->getSymbol(I);\n COFFSymbolRef Sym = SrefOrErr.get();\n if (uint32_t(Sym.getSectionNumber()) != SectionIndex)\n continue;\n if (!Sym.isFunctionDefinition())\n continue;\n StringRef SymbolName;\n File->getCOFFObj()->getSymbolName(Sym, SymbolName);\n llvm::dbgs() << \"Discarded \" << SymbolName << \" from \"\n << File->getShortName() << \"\\n\";\n I += Sym.getNumberOfAuxSymbols();\n }\n}\n\nSectionRef SectionChunk::getSectionRef() {\n DataRefImpl Ref;\n Ref.p = uintptr_t(Header);\n return SectionRef(Ref, File->getCOFFObj());\n}\n\nuint32_t CommonChunk::getPermissions() const {\n using namespace llvm::COFF;\n return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |\n IMAGE_SCN_MEM_WRITE;\n}\n\nvoid StringChunk::writeTo(uint8_t *Buf) {\n memcpy(Buf + FileOff, Str.data(), Str.size());\n}\n\nvoid ImportThunkChunk::writeTo(uint8_t *Buf) {\n memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));\n}\n\nvoid ImportThunkChunk::applyRelocations(uint8_t *Buf) {\n uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();\n \/\/ The first two bytes are a JMP instruction. Fill its operand.\n write32le(Buf + FileOff + 2, Operand);\n}\n\nHintNameChunk::HintNameChunk(StringRef N)\n : Name(N), Size(RoundUpToAlignment(Name.size() + 4, 2)) {}\n\nvoid HintNameChunk::writeTo(uint8_t *Buf) {\n \/\/ The first two bytes is Hint\/Name field.\n memcpy(Buf + FileOff + 2, Name.data(), Name.size());\n}\n\nvoid LookupChunk::applyRelocations(uint8_t *Buf) {\n write32le(Buf + FileOff, HintName->getRVA());\n}\n\nvoid DirectoryChunk::applyRelocations(uint8_t *Buf) {\n auto *E = (coff_import_directory_table_entry *)(Buf + FileOff);\n E->ImportLookupTableRVA = LookupTab->getRVA();\n E->NameRVA = DLLName->getRVA();\n E->ImportAddressTableRVA = AddressTab->getRVA();\n}\n\nImportTable::ImportTable(StringRef N,\n std::vector &Symbols) {\n DLLName = new StringChunk(N);\n DirTab = new DirectoryChunk(DLLName);\n for (DefinedImportData *S : Symbols)\n HintNameTables.push_back(new HintNameChunk(S->getExportName()));\n\n for (HintNameChunk *H : HintNameTables) {\n LookupTables.push_back(new LookupChunk(H));\n AddressTables.push_back(new LookupChunk(H));\n }\n\n for (int I = 0, E = Symbols.size(); I < E; ++I)\n Symbols[I]->setLocation(AddressTables[I]);\n\n DirTab->LookupTab = LookupTables[0];\n DirTab->AddressTab = AddressTables[0];\n}\n\n} \/\/ namespace coff\n} \/\/ namespace lld\nFix non-debug build.\/\/===- Chunks.cpp ---------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Chunks.h\"\n#include \"InputFiles.h\"\n#include \"Writer.h\"\n#include \"lld\/Core\/Error.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Object\/COFF.h\"\n#include \"llvm\/Support\/COFF.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Endian.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm::object;\nusing namespace llvm::support::endian;\nusing namespace llvm::COFF;\nusing llvm::RoundUpToAlignment;\n\nnamespace lld {\nnamespace coff {\n\nSectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI)\n : File(F), Header(H), SectionIndex(SI) {\n \/\/ Initialize SectionName.\n File->getCOFFObj()->getSectionName(Header, SectionName);\n \/\/ Bit [20:24] contains section alignment.\n unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1;\n Align = uint32_t(1) << Shift;\n}\n\nvoid SectionChunk::writeTo(uint8_t *Buf) {\n if (!hasData())\n return;\n ArrayRef Data;\n File->getCOFFObj()->getSectionContents(Header, Data);\n memcpy(Buf + FileOff, Data.data(), Data.size());\n}\n\n\/\/ Returns true if this chunk should be considered as a GC root.\nbool SectionChunk::isRoot() {\n \/\/ COMDAT sections are live only when they are referenced by something else.\n if (isCOMDAT())\n return false;\n\n \/\/ Associative sections are live if their parent COMDATs are live,\n \/\/ and vice versa, so they are not considered live by themselves.\n if (IsAssocChild)\n return false;\n\n \/\/ Only code is subject of dead-stripping.\n return !(Header->Characteristics & IMAGE_SCN_CNT_CODE);\n}\n\nvoid SectionChunk::markLive() {\n if (Live)\n return;\n Live = true;\n\n \/\/ Mark all symbols listed in the relocation table for this section.\n for (const auto &I : getSectionRef().relocations()) {\n const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);\n SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);\n if (auto *Def = dyn_cast(B))\n Def->markLive();\n }\n\n \/\/ Mark associative sections if any.\n for (Chunk *C : AssocChildren)\n C->markLive();\n}\n\nvoid SectionChunk::addAssociative(SectionChunk *Child) {\n Child->IsAssocChild = true;\n AssocChildren.push_back(Child);\n}\n\nvoid SectionChunk::applyRelocations(uint8_t *Buf) {\n for (const auto &I : getSectionRef().relocations()) {\n const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);\n applyReloc(Buf, Rel);\n }\n}\n\nstatic void add16(uint8_t *P, int32_t V) { write16le(P, read16le(P) + V); }\nstatic void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }\nstatic void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }\n\n\/\/ Implements x64 PE\/COFF relocations.\nvoid SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {\n using namespace llvm::COFF;\n uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;\n SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);\n uint64_t S = cast(Body)->getRVA();\n uint64_t P = RVA + Rel->VirtualAddress;\n switch (Rel->Type) {\n case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break;\n case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break;\n case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;\n case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break;\n case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break;\n case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break;\n case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break;\n case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break;\n case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break;\n case IMAGE_REL_AMD64_SECTION: add16(Off, Out->getSectionIndex()); break;\n case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break;\n default:\n llvm::report_fatal_error(\"Unsupported relocation type\");\n }\n}\n\nbool SectionChunk::hasData() const {\n return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);\n}\n\nuint32_t SectionChunk::getPermissions() const {\n return Header->Characteristics & PermMask;\n}\n\nbool SectionChunk::isCOMDAT() const {\n return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;\n}\n\n\/\/ Prints \"Discarded \" for all external function symbols.\nvoid SectionChunk::printDiscardedMessage() {\n uint32_t E = File->getCOFFObj()->getNumberOfSymbols();\n for (uint32_t I = 0; I < E; ++I) {\n auto SrefOrErr = File->getCOFFObj()->getSymbol(I);\n COFFSymbolRef Sym = SrefOrErr.get();\n if (uint32_t(Sym.getSectionNumber()) != SectionIndex)\n continue;\n if (!Sym.isFunctionDefinition())\n continue;\n StringRef SymbolName;\n File->getCOFFObj()->getSymbolName(Sym, SymbolName);\n llvm::dbgs() << \"Discarded \" << SymbolName << \" from \"\n << File->getShortName() << \"\\n\";\n I += Sym.getNumberOfAuxSymbols();\n }\n}\n\nSectionRef SectionChunk::getSectionRef() {\n DataRefImpl Ref;\n Ref.p = uintptr_t(Header);\n return SectionRef(Ref, File->getCOFFObj());\n}\n\nuint32_t CommonChunk::getPermissions() const {\n using namespace llvm::COFF;\n return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |\n IMAGE_SCN_MEM_WRITE;\n}\n\nvoid StringChunk::writeTo(uint8_t *Buf) {\n memcpy(Buf + FileOff, Str.data(), Str.size());\n}\n\nvoid ImportThunkChunk::writeTo(uint8_t *Buf) {\n memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));\n}\n\nvoid ImportThunkChunk::applyRelocations(uint8_t *Buf) {\n uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();\n \/\/ The first two bytes are a JMP instruction. Fill its operand.\n write32le(Buf + FileOff + 2, Operand);\n}\n\nHintNameChunk::HintNameChunk(StringRef N)\n : Name(N), Size(RoundUpToAlignment(Name.size() + 4, 2)) {}\n\nvoid HintNameChunk::writeTo(uint8_t *Buf) {\n \/\/ The first two bytes is Hint\/Name field.\n memcpy(Buf + FileOff + 2, Name.data(), Name.size());\n}\n\nvoid LookupChunk::applyRelocations(uint8_t *Buf) {\n write32le(Buf + FileOff, HintName->getRVA());\n}\n\nvoid DirectoryChunk::applyRelocations(uint8_t *Buf) {\n auto *E = (coff_import_directory_table_entry *)(Buf + FileOff);\n E->ImportLookupTableRVA = LookupTab->getRVA();\n E->NameRVA = DLLName->getRVA();\n E->ImportAddressTableRVA = AddressTab->getRVA();\n}\n\nImportTable::ImportTable(StringRef N,\n std::vector &Symbols) {\n DLLName = new StringChunk(N);\n DirTab = new DirectoryChunk(DLLName);\n for (DefinedImportData *S : Symbols)\n HintNameTables.push_back(new HintNameChunk(S->getExportName()));\n\n for (HintNameChunk *H : HintNameTables) {\n LookupTables.push_back(new LookupChunk(H));\n AddressTables.push_back(new LookupChunk(H));\n }\n\n for (int I = 0, E = Symbols.size(); I < E; ++I)\n Symbols[I]->setLocation(AddressTables[I]);\n\n DirTab->LookupTab = LookupTables[0];\n DirTab->AddressTab = AddressTables[0];\n}\n\n} \/\/ namespace coff\n} \/\/ namespace lld\n<|endoftext|>"} {"text":"\/\/\n\/\/ AKSequencerDSPKernel.hpp\n\/\/ AudioKit\n\/\/\n\/\/ Created by Jeff Cooper on 1\/25\/19.\n\/\/ Copyright © 2019 AudioKit. All rights reserved.\n\/\/\n\n#include \n#pragma once\n#include \nusing std::vector;\n\n#define NOTEON 0x90\n#define NOTEOFF 0x80\n\nstruct MIDIEvent {\n uint8_t status;\n uint8_t data1;\n uint8_t data2;\n double beat;\n};\n\nstruct MIDINote {\n struct MIDIEvent noteOn;\n struct MIDIEvent noteOff;\n};\n\nenum {\n startPointAddress = 0,\n};\n\nclass AKSequencerEngineDSPKernel : public AKDSPKernel, public AKOutputBuffered {\npublic:\n\n AKSequencerEngineDSPKernel() {}\n\n void init(int channelCount, double sampleRate) override {\n\n }\n\n void setTargetAU(AudioUnit target) {\n targetAU = target;\n }\n\n void start() {\n started = true;\n isPlaying = true;\n }\n\n void stop() {\n started = false;\n isPlaying = false;\n }\n\n void seekTo(double position) {\n positionInSamples = beatToSamples(position);\n }\n\n void setTempo(double newValue) {\n double lastPosition = currentPositionInBeats(); \/\/ 1) save where we are before we manipulate time\n tempo = newValue; \/\/ 2) manipulate time\n seekTo(lastPosition); \/\/ 3) go back to where we were before time manipulation\n }\n\n void reset() {\n resetted = true;\n startPointRamper.reset();\n }\n\n void destroy() {\n\n }\n\n void setStartPoint(float value) {\n startPoint = value;\n }\n\n void setParameter(AUParameterAddress address, AUValue value) {\n switch (address) {\n case startPointAddress:\n startPointRamper.setUIValue(clamp(value, 0.0f, 10.0f));\n break;\n }\n }\n\n AUValue getParameter(AUParameterAddress address) {\n switch (address) {\n case startPointAddress:\n return startPointRamper.getUIValue();\n\n default: return 0.0f;\n }\n }\n\n void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {\n switch (address) {\n case startPointAddress:\n startPointRamper.startRamp(clamp(value, 0.0f, 10.0f), duration);\n break;\n }\n }\n\n void addPlayingNote(MIDINote note, int offset) {\n if (note.noteOn.data2 > 0) {\n sendMidiData(note.noteOn.status, note.noteOn.data1, note.noteOn.data2, offset, note.noteOn.beat);\n playingNotes.push_back(note);\n } else {\n sendMidiData(note.noteOff.status, note.noteOff.data1, note.noteOff.data2, offset, note.noteOn.beat);\n }\n }\n\n void stopPlayingNote(MIDINote note, int offset, int index) {\n sendMidiData(note.noteOff.status, note.noteOff.data1, note.noteOff.data2, offset, note.noteOff.beat);\n playingNotes.erase(playingNotes.begin() + index);\n }\n\n void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {\n if (isPlaying) {\n if (positionInSamples >= lengthInSamples()){\n if (!loopEnabled) { \/\/stop if played enough\n stop();\n return;\n }\n }\n long currentStartSample = positionModulo();\n long currentEndSample = currentStartSample + frameCount;\n for (int i = 0; i < events.size(); i++) {\n \/\/ go through every event\n int triggerTime = beatToSamples(events[i].beat);\n if (currentStartSample <= triggerTime && triggerTime < currentEndSample) {\n \/\/ this event is supposed to trigger between currentStartSample and currentEndSample\n int offset = (int)(triggerTime - currentStartSample);\n sendMidiData(events[i].status, events[i].data1, events[i].data2,\n offset, events[i].beat);\n } else if (currentEndSample > lengthInSamples() && loopEnabled) {\n \/\/ this buffer extends beyond the length of the loop and looping is on\n int loopRestartInBuffer = (int)(lengthInSamples() - currentStartSample);\n int samplesOfBufferForNewLoop = frameCount - loopRestartInBuffer;\n if (triggerTime < samplesOfBufferForNewLoop) {\n \/\/ this event would trigger early enough in the next loop that it should happen in this buffer\n \/\/ ie. this buffer contains events from the previous loop, and the next loop\n int offset = (int)triggerTime + loopRestartInBuffer;\n sendMidiData(events[i].status, events[i].data1, events[i].data2,\n offset, events[i].beat);\n }\n }\n }\n\n \/\/ Check scheduled notes for note ons\n for (int i = 0; i < notes.size(); i++) {\n int triggerTime = beatToSamples(notes[i].noteOn.beat);\n if (currentStartSample <= triggerTime && triggerTime < currentEndSample) {\n int offset = (int)(triggerTime - currentStartSample);\n addPlayingNote(notes[i], offset);\n } else if (currentEndSample > lengthInSamples() && loopEnabled) {\n int loopRestartInBuffer = (int)(lengthInSamples() - currentStartSample);\n int samplesOfBufferForNewLoop = frameCount - loopRestartInBuffer;\n if (triggerTime < samplesOfBufferForNewLoop) {\n int offset = (int)triggerTime + loopRestartInBuffer;\n addPlayingNote(notes[i], offset);\n }\n }\n }\n\n \/\/ Check the playing notes for note offs\n int i = 0;\n\n while (i < playingNotes.size()) {\n int triggerTime = beatToSamples(playingNotes[i].noteOff.beat);\n if (currentStartSample <= triggerTime && triggerTime < currentEndSample) {\n int offset = (int)(triggerTime - currentStartSample);\n stopPlayingNote(playingNotes[i], offset, i);\n continue;\n }\n\n if (currentEndSample > lengthInSamples() && loopEnabled) {\n int loopRestartInBuffer = (int)(lengthInSamples() - currentStartSample);\n int samplesOfBufferForNewLoop = frameCount - loopRestartInBuffer;\n if (triggerTime < samplesOfBufferForNewLoop) {\n int offset = (int)triggerTime + loopRestartInBuffer;\n stopPlayingNote(playingNotes[i], offset, i);\n continue;\n }\n }\n i++;\n }\n\n positionInSamples += frameCount;\n }\n framesCounted += frameCount;\n }\n\n void addMIDIEvent(uint8_t status, uint8_t data1, uint8_t data2, double beat) {\n MIDIEvent newEvent;\n newEvent.status = status;\n newEvent.data1 = data1;\n newEvent.data2 = data2;\n newEvent.beat = beat;\n events.push_back(newEvent);\n }\n\n void addMIDINote(uint8_t number, uint8_t velocity, double beat, double duration) {\n MIDINote newNote;\n\n newNote.noteOn.status = NOTEON;\n newNote.noteOn.data1 = number;\n newNote.noteOn.data2 = velocity;\n newNote.noteOn.beat = beat;\n\n newNote.noteOff.status = NOTEOFF;\n newNote.noteOff.data1 = number;\n newNote.noteOff.data2 = velocity;\n newNote.noteOff.beat = beat + duration;\n\n notes.push_back(newNote);\n }\n\n void clear() {\n notes.clear();\n events.clear();\n }\n\n void stopPlayingNotes() {\n while (playingNotes.size() > 0) {\n stopPlayingNote(playingNotes[0], 0, 0);\n }\n }\n\n void sendMidiData(UInt8 status, UInt8 data1, UInt8 data2, double offset, double time) {\n\/\/ printf(\"%p: sending: %i %i %i at offset %f (%f beats)\\n\", &midiEndpoint, status, data1, data2, offset, time);\n if (midiPort == 0 || midiEndpoint == 0) {\n MusicDeviceMIDIEvent(targetAU, status, data1, data2, offset);\n } else {\n MIDIPacketList packetList;\n packetList.numPackets = 1;\n MIDIPacket* firstPacket = &packetList.packet[0];\n firstPacket->length = 3;\n firstPacket->data[0] = status;\n firstPacket->data[1] = data1;\n firstPacket->data[2] = data2;\n firstPacket->timeStamp = offset;\n MIDISend(midiPort, midiEndpoint, &packetList);\n }\n }\n\n long lengthInSamples() {\n return beatToSamples(length);\n }\n\n int beatToSamples(double beat) {\n return (int)(beat \/ tempo * 60 * sampleRate);\n }\n\n long positionModulo() {\n long length = lengthInSamples();\n if (positionInSamples == 0 || length == 0) {\n return 0;\n } else if (positionInSamples < 0) {\n return positionInSamples;\n } else {\n return positionInSamples % length;\n }\n }\n\n double currentPositionInBeats() {\n return (double)positionModulo() \/ sampleRate * (tempo \/ 60);\n }\n\n bool validTriggerTime(double beat){\n return true;\n }\n\nprivate:\n\n float startPoint = 0;\n AudioUnit targetAU;\n UInt64 framesCounted = 0;\n long positionInSamples = 0;\n\npublic:\n bool started = false;\n bool resetted = false;\n ParameterRamper startPointRamper = 1;\n\n bool isPlaying = false;\n MIDIPortRef midiPort;\n MIDIEndpointRef midiEndpoint;\n AKCCallback loopCallback = nullptr;\n vector events;\n vector notes;\n vector playingNotes;\n int maximumPlayCount = 0;\n double length = 4.0;\n double tempo = 120.0;\n bool loopEnabled = true;\n uint numberOfLoops = 0;\n};\nprocess noteOffs first in the sequencer to allow same note to end and restart on the same beat\/\/\n\/\/ AKSequencerDSPKernel.hpp\n\/\/ AudioKit\n\/\/\n\/\/ Created by Jeff Cooper on 1\/25\/19.\n\/\/ Copyright © 2019 AudioKit. All rights reserved.\n\/\/\n\n#include \n#pragma once\n#include \nusing std::vector;\n\n#define NOTEON 0x90\n#define NOTEOFF 0x80\n\nstruct MIDIEvent {\n uint8_t status;\n uint8_t data1;\n uint8_t data2;\n double beat;\n};\n\nstruct MIDINote {\n struct MIDIEvent noteOn;\n struct MIDIEvent noteOff;\n};\n\nenum {\n startPointAddress = 0,\n};\n\nclass AKSequencerEngineDSPKernel : public AKDSPKernel, public AKOutputBuffered {\npublic:\n\n AKSequencerEngineDSPKernel() {}\n\n void init(int channelCount, double sampleRate) override {\n\n }\n\n void setTargetAU(AudioUnit target) {\n targetAU = target;\n }\n\n void start() {\n started = true;\n isPlaying = true;\n }\n\n void stop() {\n started = false;\n isPlaying = false;\n }\n\n void seekTo(double position) {\n positionInSamples = beatToSamples(position);\n }\n\n void setTempo(double newValue) {\n double lastPosition = currentPositionInBeats(); \/\/ 1) save where we are before we manipulate time\n tempo = newValue; \/\/ 2) manipulate time\n seekTo(lastPosition); \/\/ 3) go back to where we were before time manipulation\n }\n\n void reset() {\n resetted = true;\n startPointRamper.reset();\n }\n\n void destroy() {\n\n }\n\n void setStartPoint(float value) {\n startPoint = value;\n }\n\n void setParameter(AUParameterAddress address, AUValue value) {\n switch (address) {\n case startPointAddress:\n startPointRamper.setUIValue(clamp(value, 0.0f, 10.0f));\n break;\n }\n }\n\n AUValue getParameter(AUParameterAddress address) {\n switch (address) {\n case startPointAddress:\n return startPointRamper.getUIValue();\n\n default: return 0.0f;\n }\n }\n\n void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {\n switch (address) {\n case startPointAddress:\n startPointRamper.startRamp(clamp(value, 0.0f, 10.0f), duration);\n break;\n }\n }\n\n void addPlayingNote(MIDINote note, int offset) {\n if (note.noteOn.data2 > 0) {\n sendMidiData(note.noteOn.status, note.noteOn.data1, note.noteOn.data2, offset, note.noteOn.beat);\n playingNotes.push_back(note);\n } else {\n sendMidiData(note.noteOff.status, note.noteOff.data1, note.noteOff.data2, offset, note.noteOn.beat);\n }\n }\n\n void stopPlayingNote(MIDINote note, int offset, int index) {\n sendMidiData(note.noteOff.status, note.noteOff.data1, note.noteOff.data2, offset, note.noteOff.beat);\n playingNotes.erase(playingNotes.begin() + index);\n }\n\n void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {\n if (isPlaying) {\n if (positionInSamples >= lengthInSamples()){\n if (!loopEnabled) { \/\/stop if played enough\n stop();\n return;\n }\n }\n long currentStartSample = positionModulo();\n long currentEndSample = currentStartSample + frameCount;\n for (int i = 0; i < events.size(); i++) {\n \/\/ go through every event\n int triggerTime = beatToSamples(events[i].beat);\n if (currentStartSample <= triggerTime && triggerTime < currentEndSample) {\n \/\/ this event is supposed to trigger between currentStartSample and currentEndSample\n int offset = (int)(triggerTime - currentStartSample);\n sendMidiData(events[i].status, events[i].data1, events[i].data2,\n offset, events[i].beat);\n } else if (currentEndSample > lengthInSamples() && loopEnabled) {\n \/\/ this buffer extends beyond the length of the loop and looping is on\n int loopRestartInBuffer = (int)(lengthInSamples() - currentStartSample);\n int samplesOfBufferForNewLoop = frameCount - loopRestartInBuffer;\n if (triggerTime < samplesOfBufferForNewLoop) {\n \/\/ this event would trigger early enough in the next loop that it should happen in this buffer\n \/\/ ie. this buffer contains events from the previous loop, and the next loop\n int offset = (int)triggerTime + loopRestartInBuffer;\n sendMidiData(events[i].status, events[i].data1, events[i].data2,\n offset, events[i].beat);\n }\n }\n }\n\n \/\/ Check the playing notes for note offs\n int i = 0;\n while (i < playingNotes.size()) {\n int triggerTime = beatToSamples(playingNotes[i].noteOff.beat);\n if (currentStartSample <= triggerTime && triggerTime < currentEndSample) {\n int offset = (int)(triggerTime - currentStartSample);\n stopPlayingNote(playingNotes[i], offset, i);\n continue;\n }\n\n if (currentEndSample > lengthInSamples() && loopEnabled) {\n int loopRestartInBuffer = (int)(lengthInSamples() - currentStartSample);\n int samplesOfBufferForNewLoop = frameCount - loopRestartInBuffer;\n if (triggerTime < samplesOfBufferForNewLoop) {\n int offset = (int)triggerTime + loopRestartInBuffer;\n stopPlayingNote(playingNotes[i], offset, i);\n continue;\n }\n }\n i++;\n }\n\n \/\/ Check scheduled notes for note ons\n for (int i = 0; i < notes.size(); i++) {\n int triggerTime = beatToSamples(notes[i].noteOn.beat);\n if (currentStartSample <= triggerTime && triggerTime < currentEndSample) {\n int offset = (int)(triggerTime - currentStartSample);\n addPlayingNote(notes[i], offset);\n } else if (currentEndSample > lengthInSamples() && loopEnabled) {\n int loopRestartInBuffer = (int)(lengthInSamples() - currentStartSample);\n int samplesOfBufferForNewLoop = frameCount - loopRestartInBuffer;\n if (triggerTime < samplesOfBufferForNewLoop) {\n int offset = (int)triggerTime + loopRestartInBuffer;\n addPlayingNote(notes[i], offset);\n }\n }\n }\n\n positionInSamples += frameCount;\n }\n framesCounted += frameCount;\n }\n\n void addMIDIEvent(uint8_t status, uint8_t data1, uint8_t data2, double beat) {\n MIDIEvent newEvent;\n newEvent.status = status;\n newEvent.data1 = data1;\n newEvent.data2 = data2;\n newEvent.beat = beat;\n events.push_back(newEvent);\n }\n\n void addMIDINote(uint8_t number, uint8_t velocity, double beat, double duration) {\n MIDINote newNote;\n\n newNote.noteOn.status = NOTEON;\n newNote.noteOn.data1 = number;\n newNote.noteOn.data2 = velocity;\n newNote.noteOn.beat = beat;\n\n newNote.noteOff.status = NOTEOFF;\n newNote.noteOff.data1 = number;\n newNote.noteOff.data2 = velocity;\n newNote.noteOff.beat = beat + duration;\n\n notes.push_back(newNote);\n }\n\n void clear() {\n notes.clear();\n events.clear();\n }\n\n void stopPlayingNotes() {\n while (playingNotes.size() > 0) {\n stopPlayingNote(playingNotes[0], 0, 0);\n }\n }\n\n void sendMidiData(UInt8 status, UInt8 data1, UInt8 data2, double offset, double time) {\n\/\/ printf(\"%p: sending: %i %i %i at offset %f (%f beats)\\n\", &midiEndpoint, status, data1, data2, offset, time);\n if (midiPort == 0 || midiEndpoint == 0) {\n MusicDeviceMIDIEvent(targetAU, status, data1, data2, offset);\n } else {\n MIDIPacketList packetList;\n packetList.numPackets = 1;\n MIDIPacket* firstPacket = &packetList.packet[0];\n firstPacket->length = 3;\n firstPacket->data[0] = status;\n firstPacket->data[1] = data1;\n firstPacket->data[2] = data2;\n firstPacket->timeStamp = offset;\n MIDISend(midiPort, midiEndpoint, &packetList);\n }\n }\n\n long lengthInSamples() {\n return beatToSamples(length);\n }\n\n int beatToSamples(double beat) {\n return (int)(beat \/ tempo * 60 * sampleRate);\n }\n\n long positionModulo() {\n long length = lengthInSamples();\n if (positionInSamples == 0 || length == 0) {\n return 0;\n } else if (positionInSamples < 0) {\n return positionInSamples;\n } else {\n return positionInSamples % length;\n }\n }\n\n double currentPositionInBeats() {\n return (double)positionModulo() \/ sampleRate * (tempo \/ 60);\n }\n\n bool validTriggerTime(double beat){\n return true;\n }\n\nprivate:\n\n float startPoint = 0;\n AudioUnit targetAU;\n UInt64 framesCounted = 0;\n long positionInSamples = 0;\n\npublic:\n bool started = false;\n bool resetted = false;\n ParameterRamper startPointRamper = 1;\n\n bool isPlaying = false;\n MIDIPortRef midiPort;\n MIDIEndpointRef midiEndpoint;\n AKCCallback loopCallback = nullptr;\n vector events;\n vector notes;\n vector playingNotes;\n int maximumPlayCount = 0;\n double length = 4.0;\n double tempo = 120.0;\n bool loopEnabled = true;\n uint numberOfLoops = 0;\n};\n<|endoftext|>"} {"text":"\/\/ Copyright 2010-2014 The CefSharp Project. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n#pragma once\n\n#include \"Stdafx.h\"\n\n#include \"JavascriptPropertyWrapper.h\"\n#include \"JavascriptObjectWrapper.h\"\n#include \"CefAppWrapper.h\"\n\nusing namespace System;\n\nnamespace CefSharp\n{\n void JavascriptPropertyWrapper::Bind()\n {\n auto methodName = StringUtils::ToNative(_javascriptProperty->JavascriptName);\n auto clrMethodName = _javascriptProperty->JavascriptName;\n\n if (_javascriptProperty->IsComplexType)\n {\n auto wrapperObject = gcnew JavascriptObjectWrapper(_javascriptProperty->Value);\n wrapperObject->V8Value = V8Value.get();\n wrapperObject->Bind();\n }\n else\n {\n auto propertyAttribute = _javascriptProperty->IsReadOnly ? V8_PROPERTY_ATTRIBUTE_READONLY : V8_PROPERTY_ATTRIBUTE_NONE;\n\n V8Value->SetValue(methodName, V8_ACCESS_CONTROL_DEFAULT, propertyAttribute);\n }\n };\n}Fix variable naming - was method, should be property\/\/ Copyright 2010-2014 The CefSharp Project. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n#pragma once\n\n#include \"Stdafx.h\"\n\n#include \"JavascriptPropertyWrapper.h\"\n#include \"JavascriptObjectWrapper.h\"\n#include \"CefAppWrapper.h\"\n\nusing namespace System;\n\nnamespace CefSharp\n{\n void JavascriptPropertyWrapper::Bind()\n {\n auto propertyName = StringUtils::ToNative(_javascriptProperty->JavascriptName);\n auto clrPropertyName = _javascriptProperty->JavascriptName;\n\n if (_javascriptProperty->IsComplexType)\n {\n auto wrapperObject = gcnew JavascriptObjectWrapper(_javascriptProperty->Value);\n wrapperObject->V8Value = V8Value.get();\n wrapperObject->Bind();\n }\n else\n {\n auto propertyAttribute = _javascriptProperty->IsReadOnly ? V8_PROPERTY_ATTRIBUTE_READONLY : V8_PROPERTY_ATTRIBUTE_NONE;\n\n V8Value->SetValue(propertyName, V8_ACCESS_CONTROL_DEFAULT, propertyAttribute);\n }\n };\n}<|endoftext|>"} {"text":"\/\/\r\n\/\/ Urho3D Engine\r\n\/\/ Copyright (c) 2008-2011 Lasse rni\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Precompiled.h\"\r\n#include \"Context.h\"\r\n#include \"CoreEvents.h\"\r\n#include \"Log.h\"\r\n#include \"MemoryBuffer.h\"\r\n#include \"Network.h\"\r\n#include \"NetworkEvents.h\"\r\n#include \"Profiler.h\"\r\n#include \"Protocol.h\"\r\n#include \"Scene.h\"\r\n#include \"StringUtils.h\"\r\n\r\n#include \r\n\r\n#include \"DebugNew.h\"\r\n\r\nstatic const int DEFAULT_UPDATE_FPS = 25;\r\nstatic const unsigned CONTROLS_CONTENT_ID = 1;\r\n\r\nOBJECTTYPESTATIC(Network);\r\n\r\nNetwork::Network(Context* context) :\r\n Object(context),\r\n updateFps_(DEFAULT_UPDATE_FPS),\r\n updateInterval_(1.0f \/ (float)DEFAULT_UPDATE_FPS),\r\n updateAcc_(0.0f)\r\n{\r\n network_ = new kNet::Network();\r\n \r\n SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));\r\n}\r\n\r\nNetwork::~Network()\r\n{\r\n \/\/ If server connection exists, disconnect, but do not send an event because we are shutting down\r\n Disconnect(100);\r\n serverConnection_.Reset();\r\n \r\n clientConnections_.Clear();\r\n \r\n delete network_;\r\n network_ = 0;\r\n}\r\n\r\nvoid Network::HandleMessage(kNet::MessageConnection* source, kNet::message_id_t id, const char* data, size_t numBytes)\r\n{\r\n PROFILE(HandleMessage);\r\n \r\n \/\/ Only process messages from known sources\r\n Connection* connection = GetConnection(source);\r\n if (connection)\r\n {\r\n MemoryBuffer msg(data, numBytes);\r\n \r\n bool handled = false;\r\n if (connection->IsClient())\r\n handled = OnClientMessage(connection, id, msg);\r\n else\r\n handled = OnServerMessage(connection, id, msg);\r\n \r\n \/\/ If message was not handled internally, forward as an event\r\n if (!handled)\r\n {\r\n using namespace NetworkMessage;\r\n \r\n VariantMap eventData;\r\n eventData[P_CONNECTION] = (void*)connection;\r\n eventData[P_MESSAGEID] = (int)id;\r\n eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());\r\n connection->SendEvent(E_NETWORKMESSAGE, eventData);\r\n }\r\n }\r\n else\r\n LOGWARNING(\"Discarding message from unknown MessageConnection \" + ToString((void*)source));\r\n}\r\n\r\nu32 Network::ComputeContentID(kNet::message_id_t id, const char* data, size_t numBytes)\r\n{\r\n switch (id)\r\n {\r\n case MSG_CONTROLSUPDATE:\r\n return CONTROLS_CONTENT_ID;\r\n \r\n default:\r\n return 0;\r\n }\r\n}\r\n\r\nvoid Network::NewConnectionEstablished(kNet::MessageConnection* connection)\r\n{\r\n connection->RegisterInboundMessageHandler(this);\r\n \r\n \/\/ Create a new client connection corresponding to this MessageConnection\r\n Connection* newConnection = new Connection(context_, true, kNet::SharedPtr(connection));\r\n clientConnections_[connection] = newConnection;\r\n LOGINFO(\"Client \" + newConnection->ToString() + \" connected\");\r\n \r\n using namespace ClientConnected;\r\n \r\n VariantMap eventData;\r\n eventData[P_CONNECTION] = (void*)newConnection;\r\n SendEvent(E_CLIENTCONNECTED, eventData);\r\n}\r\n\r\nvoid Network::ClientDisconnected(kNet::MessageConnection* connection)\r\n{\r\n connection->Disconnect(0);\r\n \r\n \/\/ Remove the client connection that corresponds to this MessageConnection\r\n Map >::Iterator i = clientConnections_.Find(connection);\r\n if (i != clientConnections_.End())\r\n {\r\n LOGINFO(\"Client \" + i->second_->ToString() + \" disconnected\");\r\n \r\n using namespace ClientDisconnected;\r\n \r\n VariantMap eventData;\r\n eventData[P_CONNECTION] = (void*)i->second_;\r\n SendEvent(E_CLIENTDISCONNECTED, eventData);\r\n \r\n clientConnections_.Erase(i);\r\n }\r\n}\r\n\r\nbool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)\r\n{\r\n PROFILE(Connect);\r\n \r\n \/\/ If a previous connection already exists, disconnect it and wait for some time for the connection to terminate\r\n if (serverConnection_)\r\n {\r\n serverConnection_->Disconnect(100);\r\n OnServerDisconnected();\r\n }\r\n \r\n kNet::SharedPtr connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);\r\n if (connection)\r\n {\r\n LOGINFO(\"Connecting to server \" + address + \":\" + String(port));\r\n serverConnection_ = new Connection(context_, false, connection);\r\n serverConnection_->SetScene(scene);\r\n serverConnection_->SetIdentity(identity);\r\n serverConnection_->SetConnectPending(true);\r\n return true;\r\n }\r\n else\r\n {\r\n LOGERROR(\"Failed to connect to server \" + address + \":\" + String(port));\r\n SendEvent(E_CONNECTFAILED);\r\n return false;\r\n }\r\n}\r\n\r\nvoid Network::Disconnect(int waitMSec)\r\n{\r\n if (!serverConnection_)\r\n return;\r\n \r\n PROFILE(Disconnect);\r\n serverConnection_->Disconnect(waitMSec);\r\n}\r\n\r\nbool Network::StartServer(unsigned short port)\r\n{\r\n if (IsServerRunning())\r\n return true;\r\n \r\n PROFILE(StartServer);\r\n \r\n \/\/\/ \\todo Investigate why server fails to restart after stopping when false is specified for reuse\r\n if (network_->StartServer(port, kNet::SocketOverUDP, this, true) != 0)\r\n {\r\n LOGINFO(\"Started server on port \" + String(port));\r\n return true;\r\n }\r\n else\r\n {\r\n LOGERROR(\"Failed to start server on port \" + String(port));\r\n return false;\r\n }\r\n}\r\n\r\nvoid Network::StopServer()\r\n{\r\n if (!IsServerRunning())\r\n return;\r\n \r\n PROFILE(StopServer);\r\n \r\n clientConnections_.Clear();\r\n network_->StopServer();\r\n LOGINFO(\"Stopped server\");\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg)\r\n{\r\n BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize());\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)\r\n{\r\n \/\/ Make sure not to use kNet internal message ID's\r\n if (msgID <= 0x4 || msgID >= 0x3ffffffe)\r\n {\r\n LOGERROR(\"Can not send message with reserved ID\");\r\n return;\r\n }\r\n \r\n kNet::NetworkServer* server = network_->GetServer();\r\n if (server)\r\n server->BroadcastMessage(msgID, reliable, inOrder, 0, 0, (const char*)data, numBytes);\r\n else\r\n LOGERROR(\"Server not running, can not broadcast messages\");\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)\r\n{\r\n BroadcastMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)\r\n{\r\n \/\/ Make sure not to use kNet internal message ID's\r\n if (msgID <= 0x4 || msgID >= 0x3ffffffe)\r\n {\r\n LOGERROR(\"Can not send message with reserved ID\");\r\n return;\r\n }\r\n \r\n kNet::NetworkServer* server = network_->GetServer();\r\n if (server)\r\n server->BroadcastMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);\r\n else\r\n LOGERROR(\"Server not running, can not broadcast messages\");\r\n}\r\n\r\nvoid Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)\r\n{\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n i->second_->SendRemoteEvent(eventType, inOrder, eventData);\r\n}\r\n\r\nvoid Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)\r\n{\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n {\r\n if (i->second_->GetScene() == scene)\r\n i->second_->SendRemoteEvent(eventType, inOrder, eventData);\r\n }\r\n}\r\n\r\nvoid Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)\r\n{\r\n if (!receiver)\r\n {\r\n LOGERROR(\"Null node for remote node event\");\r\n return;\r\n }\r\n if (receiver->GetID() >= FIRST_LOCAL_ID)\r\n {\r\n LOGERROR(\"Node has a local ID, can not send remote node event\");\r\n return;\r\n }\r\n \r\n Scene* scene = receiver->GetScene();\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n {\r\n if (i->second_->GetScene() == scene)\r\n i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);\r\n }\r\n}\r\n\r\nvoid Network::SetUpdateFps(int fps)\r\n{\r\n updateFps_ = Max(fps, 1);\r\n updateInterval_ = 1.0f \/ (float)updateFps_;\r\n updateAcc_ = 0.0f;\r\n}\r\n\r\nvoid Network::Update(float timeStep)\r\n{\r\n PROFILE(UpdateNetwork);\r\n \r\n \/\/ Check if periodic update should be made now\r\n updateAcc_ += timeStep;\r\n bool updateNow = updateAcc_ >= updateInterval_;\r\n \r\n if (updateNow)\r\n {\r\n \/\/ Notify of the impending update to allow for example updated client controls to be set\r\n SendEvent(E_NETWORKUPDATE);\r\n updateAcc_ = fmodf(updateAcc_, updateInterval_);\r\n }\r\n \r\n \/\/ Process server connection if it exists\r\n if (serverConnection_)\r\n {\r\n kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();\r\n connection->Process();\r\n \r\n \/\/ Check for state transitions\r\n kNet::ConnectionState state = connection->GetConnectionState();\r\n if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)\r\n OnServerConnected();\r\n else if (state == kNet::ConnectionPeerClosed)\r\n serverConnection_->Disconnect();\r\n else if (state == kNet::ConnectionClosed)\r\n OnServerDisconnected();\r\n \r\n \/\/ If scene has been assigned and loaded, send the controls packet on update\r\n if (updateNow && serverConnection_->GetScene() && serverConnection_->IsSceneLoaded())\r\n {\r\n const Controls& controls = serverConnection_->GetControls();\r\n \r\n VectorBuffer msg;\r\n msg.WriteUInt(controls.buttons_);\r\n msg.WriteFloat(controls.yaw_);\r\n msg.WriteFloat(controls.pitch_);\r\n msg.WriteVariantMap(controls.extraData_);\r\n serverConnection_->SendMessage(MSG_CONTROLSUPDATE, CONTROLS_CONTENT_ID, false, false, msg);\r\n }\r\n }\r\n \r\n \/\/ Process client connections if the server has been started\r\n kNet::NetworkServer* server = network_->GetServer();\r\n if (server)\r\n {\r\n server->Process();\r\n \r\n if (updateNow)\r\n {\r\n \/\/ Process scene replication for each client connection\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n i->second_->ProcessReplication();\r\n }\r\n }\r\n}\r\n\r\nConnection* Network::GetConnection(kNet::MessageConnection* connection) const\r\n{\r\n Map >::ConstIterator i = clientConnections_.Find(connection);\r\n if (i != clientConnections_.End())\r\n return i->second_;\r\n else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)\r\n return serverConnection_;\r\n else\r\n return 0;\r\n}\r\n\r\nConnection* Network::GetServerConnection() const\r\n{\r\n return serverConnection_;\r\n}\r\n\r\nbool Network::IsServerRunning() const\r\n{\r\n return network_->GetServer();\r\n}\r\n\r\nvoid Network::OnServerConnected()\r\n{\r\n serverConnection_->SetConnectPending(false);\r\n LOGINFO(\"Connected to server\");\r\n \r\n \/\/ Send the identity map now\r\n VectorBuffer msg;\r\n msg.WriteVariantMap(serverConnection_->GetIdentity());\r\n serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);\r\n \r\n SendEvent(E_SERVERCONNECTED);\r\n}\r\n\r\nvoid Network::OnServerDisconnected()\r\n{\r\n \/\/ Differentiate between failed connection, and disconnection\r\n bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();\r\n if (!failedConnect)\r\n {\r\n LOGINFO(\"Disconnected from server\");\r\n SendEvent(E_SERVERDISCONNECTED);\r\n }\r\n else\r\n {\r\n LOGERROR(\"Failed to connect to server\");\r\n SendEvent(E_CONNECTFAILED);\r\n }\r\n \r\n serverConnection_.Reset();\r\n}\r\n\r\nbool Network::OnServerMessage(Connection* connection, int msgID, MemoryBuffer& msg)\r\n{\r\n switch (msgID)\r\n {\r\n case MSG_REMOTEEVENT:\r\n case MSG_REMOTENODEEVENT:\r\n OnRemoteEvent(connection, msgID, msg);\r\n return true;\r\n }\r\n \r\n return false;\r\n}\r\n\r\nbool Network::OnClientMessage(Connection* connection, int msgID, MemoryBuffer& msg)\r\n{\r\n switch (msgID)\r\n {\r\n case MSG_IDENTITY:\r\n {\r\n connection->SetIdentity(msg.ReadVariantMap());\r\n \r\n using namespace ClientIdentity;\r\n \r\n VariantMap eventData = connection->GetIdentity();\r\n eventData[P_CONNECTION] = (void*)connection;\r\n eventData[P_ALLOW] = true;\r\n connection->SendEvent(E_CLIENTIDENTITY, eventData);\r\n \r\n \/\/ If connection was denied as a response to the event, disconnect the client now\r\n if (!eventData[P_ALLOW].GetBool())\r\n connection->Disconnect();\r\n }\r\n return true;\r\n \r\n case MSG_CONTROLSUPDATE:\r\n {\r\n Controls newControls;\r\n newControls.buttons_ = msg.ReadUInt();\r\n newControls.yaw_ = msg.ReadFloat();\r\n newControls.pitch_ = msg.ReadFloat();\r\n newControls.extraData_ = msg.ReadVariantMap();\r\n connection->SetControls(newControls);\r\n }\r\n return true;\r\n \r\n case MSG_REMOTEEVENT:\r\n case MSG_REMOTENODEEVENT:\r\n OnRemoteEvent(connection, msgID, msg);\r\n return true;\r\n }\r\n \r\n return false;\r\n}\r\n\r\nvoid Network::OnRemoteEvent(Connection* connection, int msgID, MemoryBuffer& msg)\r\n{\r\n \/\/\/ \\todo Check whether the remote event is allowed based on a black- or whitelist\r\n if (msgID == MSG_REMOTEEVENT)\r\n {\r\n StringHash eventType = msg.ReadStringHash();\r\n VariantMap eventData = msg.ReadVariantMap();\r\n connection->SendEvent(eventType, eventData);\r\n }\r\n else\r\n {\r\n Scene* scene = connection->GetScene();\r\n if (!scene)\r\n {\r\n LOGERROR(\"Connection has null scene, can not receive remote node event\");\r\n return;\r\n }\r\n unsigned nodeID = msg.ReadVLE();\r\n StringHash eventType = msg.ReadStringHash();\r\n VariantMap eventData = msg.ReadVariantMap();\r\n Node* receiver = scene->GetNodeByID(nodeID);\r\n if (!receiver)\r\n {\r\n LOGWARNING(\"Remote node event's receiver not found, discarding event\");\r\n return;\r\n }\r\n connection->SendEvent(receiver, eventType, eventData);\r\n }\r\n}\r\n\r\nvoid Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)\r\n{\r\n using namespace BeginFrame;\r\n \r\n Update(eventData[P_TIMESTEP].GetFloat());\r\n}\r\nAdded content ID computation for latestdata messages.\/\/\r\n\/\/ Urho3D Engine\r\n\/\/ Copyright (c) 2008-2011 Lasse rni\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Precompiled.h\"\r\n#include \"Context.h\"\r\n#include \"CoreEvents.h\"\r\n#include \"Log.h\"\r\n#include \"MemoryBuffer.h\"\r\n#include \"Network.h\"\r\n#include \"NetworkEvents.h\"\r\n#include \"Profiler.h\"\r\n#include \"Protocol.h\"\r\n#include \"Scene.h\"\r\n#include \"StringUtils.h\"\r\n\r\n#include \r\n\r\n#include \"DebugNew.h\"\r\n\r\nstatic const int DEFAULT_UPDATE_FPS = 25;\r\nstatic const unsigned CONTROLS_CONTENT_ID = 1;\r\n\r\nOBJECTTYPESTATIC(Network);\r\n\r\nNetwork::Network(Context* context) :\r\n Object(context),\r\n updateFps_(DEFAULT_UPDATE_FPS),\r\n updateInterval_(1.0f \/ (float)DEFAULT_UPDATE_FPS),\r\n updateAcc_(0.0f)\r\n{\r\n network_ = new kNet::Network();\r\n \r\n SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));\r\n}\r\n\r\nNetwork::~Network()\r\n{\r\n \/\/ If server connection exists, disconnect, but do not send an event because we are shutting down\r\n Disconnect(100);\r\n serverConnection_.Reset();\r\n \r\n clientConnections_.Clear();\r\n \r\n delete network_;\r\n network_ = 0;\r\n}\r\n\r\nvoid Network::HandleMessage(kNet::MessageConnection* source, kNet::message_id_t id, const char* data, size_t numBytes)\r\n{\r\n PROFILE(HandleMessage);\r\n \r\n \/\/ Only process messages from known sources\r\n Connection* connection = GetConnection(source);\r\n if (connection)\r\n {\r\n MemoryBuffer msg(data, numBytes);\r\n \r\n bool handled = false;\r\n if (connection->IsClient())\r\n handled = OnClientMessage(connection, id, msg);\r\n else\r\n handled = OnServerMessage(connection, id, msg);\r\n \r\n \/\/ If message was not handled internally, forward as an event\r\n if (!handled)\r\n {\r\n using namespace NetworkMessage;\r\n \r\n VariantMap eventData;\r\n eventData[P_CONNECTION] = (void*)connection;\r\n eventData[P_MESSAGEID] = (int)id;\r\n eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());\r\n connection->SendEvent(E_NETWORKMESSAGE, eventData);\r\n }\r\n }\r\n else\r\n LOGWARNING(\"Discarding message from unknown MessageConnection \" + ToString((void*)source));\r\n}\r\n\r\nu32 Network::ComputeContentID(kNet::message_id_t id, const char* data, size_t numBytes)\r\n{\r\n switch (id)\r\n {\r\n case MSG_CONTROLSUPDATE:\r\n \/\/ Return fixed content ID for controls\r\n return CONTROLS_CONTENT_ID;\r\n \r\n case MSG_NODELATESTDATA:\r\n case MSG_COMPONENTLATESTDATA:\r\n {\r\n \/\/ Return the node or component ID, which is first in the message\r\n MemoryBuffer msg(data, numBytes);\r\n return msg.ReadVLE();\r\n }\r\n \r\n default:\r\n \/\/ By default return no content ID\r\n return 0;\r\n }\r\n}\r\n\r\nvoid Network::NewConnectionEstablished(kNet::MessageConnection* connection)\r\n{\r\n connection->RegisterInboundMessageHandler(this);\r\n \r\n \/\/ Create a new client connection corresponding to this MessageConnection\r\n Connection* newConnection = new Connection(context_, true, kNet::SharedPtr(connection));\r\n clientConnections_[connection] = newConnection;\r\n LOGINFO(\"Client \" + newConnection->ToString() + \" connected\");\r\n \r\n using namespace ClientConnected;\r\n \r\n VariantMap eventData;\r\n eventData[P_CONNECTION] = (void*)newConnection;\r\n SendEvent(E_CLIENTCONNECTED, eventData);\r\n}\r\n\r\nvoid Network::ClientDisconnected(kNet::MessageConnection* connection)\r\n{\r\n connection->Disconnect(0);\r\n \r\n \/\/ Remove the client connection that corresponds to this MessageConnection\r\n Map >::Iterator i = clientConnections_.Find(connection);\r\n if (i != clientConnections_.End())\r\n {\r\n LOGINFO(\"Client \" + i->second_->ToString() + \" disconnected\");\r\n \r\n using namespace ClientDisconnected;\r\n \r\n VariantMap eventData;\r\n eventData[P_CONNECTION] = (void*)i->second_;\r\n SendEvent(E_CLIENTDISCONNECTED, eventData);\r\n \r\n clientConnections_.Erase(i);\r\n }\r\n}\r\n\r\nbool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)\r\n{\r\n PROFILE(Connect);\r\n \r\n \/\/ If a previous connection already exists, disconnect it and wait for some time for the connection to terminate\r\n if (serverConnection_)\r\n {\r\n serverConnection_->Disconnect(100);\r\n OnServerDisconnected();\r\n }\r\n \r\n kNet::SharedPtr connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);\r\n if (connection)\r\n {\r\n LOGINFO(\"Connecting to server \" + address + \":\" + String(port));\r\n serverConnection_ = new Connection(context_, false, connection);\r\n serverConnection_->SetScene(scene);\r\n serverConnection_->SetIdentity(identity);\r\n serverConnection_->SetConnectPending(true);\r\n return true;\r\n }\r\n else\r\n {\r\n LOGERROR(\"Failed to connect to server \" + address + \":\" + String(port));\r\n SendEvent(E_CONNECTFAILED);\r\n return false;\r\n }\r\n}\r\n\r\nvoid Network::Disconnect(int waitMSec)\r\n{\r\n if (!serverConnection_)\r\n return;\r\n \r\n PROFILE(Disconnect);\r\n serverConnection_->Disconnect(waitMSec);\r\n}\r\n\r\nbool Network::StartServer(unsigned short port)\r\n{\r\n if (IsServerRunning())\r\n return true;\r\n \r\n PROFILE(StartServer);\r\n \r\n \/\/\/ \\todo Investigate why server fails to restart after stopping when false is specified for reuse\r\n if (network_->StartServer(port, kNet::SocketOverUDP, this, true) != 0)\r\n {\r\n LOGINFO(\"Started server on port \" + String(port));\r\n return true;\r\n }\r\n else\r\n {\r\n LOGERROR(\"Failed to start server on port \" + String(port));\r\n return false;\r\n }\r\n}\r\n\r\nvoid Network::StopServer()\r\n{\r\n if (!IsServerRunning())\r\n return;\r\n \r\n PROFILE(StopServer);\r\n \r\n clientConnections_.Clear();\r\n network_->StopServer();\r\n LOGINFO(\"Stopped server\");\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg)\r\n{\r\n BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize());\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)\r\n{\r\n \/\/ Make sure not to use kNet internal message ID's\r\n if (msgID <= 0x4 || msgID >= 0x3ffffffe)\r\n {\r\n LOGERROR(\"Can not send message with reserved ID\");\r\n return;\r\n }\r\n \r\n kNet::NetworkServer* server = network_->GetServer();\r\n if (server)\r\n server->BroadcastMessage(msgID, reliable, inOrder, 0, 0, (const char*)data, numBytes);\r\n else\r\n LOGERROR(\"Server not running, can not broadcast messages\");\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)\r\n{\r\n BroadcastMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());\r\n}\r\n\r\nvoid Network::BroadcastMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)\r\n{\r\n \/\/ Make sure not to use kNet internal message ID's\r\n if (msgID <= 0x4 || msgID >= 0x3ffffffe)\r\n {\r\n LOGERROR(\"Can not send message with reserved ID\");\r\n return;\r\n }\r\n \r\n kNet::NetworkServer* server = network_->GetServer();\r\n if (server)\r\n server->BroadcastMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);\r\n else\r\n LOGERROR(\"Server not running, can not broadcast messages\");\r\n}\r\n\r\nvoid Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)\r\n{\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n i->second_->SendRemoteEvent(eventType, inOrder, eventData);\r\n}\r\n\r\nvoid Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)\r\n{\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n {\r\n if (i->second_->GetScene() == scene)\r\n i->second_->SendRemoteEvent(eventType, inOrder, eventData);\r\n }\r\n}\r\n\r\nvoid Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)\r\n{\r\n if (!receiver)\r\n {\r\n LOGERROR(\"Null node for remote node event\");\r\n return;\r\n }\r\n if (receiver->GetID() >= FIRST_LOCAL_ID)\r\n {\r\n LOGERROR(\"Node has a local ID, can not send remote node event\");\r\n return;\r\n }\r\n \r\n Scene* scene = receiver->GetScene();\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n {\r\n if (i->second_->GetScene() == scene)\r\n i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);\r\n }\r\n}\r\n\r\nvoid Network::SetUpdateFps(int fps)\r\n{\r\n updateFps_ = Max(fps, 1);\r\n updateInterval_ = 1.0f \/ (float)updateFps_;\r\n updateAcc_ = 0.0f;\r\n}\r\n\r\nvoid Network::Update(float timeStep)\r\n{\r\n PROFILE(UpdateNetwork);\r\n \r\n \/\/ Check if periodic update should be made now\r\n updateAcc_ += timeStep;\r\n bool updateNow = updateAcc_ >= updateInterval_;\r\n \r\n if (updateNow)\r\n {\r\n \/\/ Notify of the impending update to allow for example updated client controls to be set\r\n SendEvent(E_NETWORKUPDATE);\r\n updateAcc_ = fmodf(updateAcc_, updateInterval_);\r\n }\r\n \r\n \/\/ Process server connection if it exists\r\n if (serverConnection_)\r\n {\r\n kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();\r\n connection->Process();\r\n \r\n \/\/ Check for state transitions\r\n kNet::ConnectionState state = connection->GetConnectionState();\r\n if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)\r\n OnServerConnected();\r\n else if (state == kNet::ConnectionPeerClosed)\r\n serverConnection_->Disconnect();\r\n else if (state == kNet::ConnectionClosed)\r\n OnServerDisconnected();\r\n \r\n \/\/ If scene has been assigned and loaded, send the controls packet on update\r\n if (updateNow && serverConnection_->GetScene() && serverConnection_->IsSceneLoaded())\r\n {\r\n const Controls& controls = serverConnection_->GetControls();\r\n \r\n VectorBuffer msg;\r\n msg.WriteUInt(controls.buttons_);\r\n msg.WriteFloat(controls.yaw_);\r\n msg.WriteFloat(controls.pitch_);\r\n msg.WriteVariantMap(controls.extraData_);\r\n serverConnection_->SendMessage(MSG_CONTROLSUPDATE, CONTROLS_CONTENT_ID, false, false, msg);\r\n }\r\n }\r\n \r\n \/\/ Process client connections if the server has been started\r\n kNet::NetworkServer* server = network_->GetServer();\r\n if (server)\r\n {\r\n server->Process();\r\n \r\n if (updateNow)\r\n {\r\n \/\/ Process scene replication for each client connection\r\n for (Map >::ConstIterator i = clientConnections_.Begin();\r\n i != clientConnections_.End(); ++i)\r\n i->second_->ProcessReplication();\r\n }\r\n }\r\n}\r\n\r\nConnection* Network::GetConnection(kNet::MessageConnection* connection) const\r\n{\r\n Map >::ConstIterator i = clientConnections_.Find(connection);\r\n if (i != clientConnections_.End())\r\n return i->second_;\r\n else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)\r\n return serverConnection_;\r\n else\r\n return 0;\r\n}\r\n\r\nConnection* Network::GetServerConnection() const\r\n{\r\n return serverConnection_;\r\n}\r\n\r\nbool Network::IsServerRunning() const\r\n{\r\n return network_->GetServer();\r\n}\r\n\r\nvoid Network::OnServerConnected()\r\n{\r\n serverConnection_->SetConnectPending(false);\r\n LOGINFO(\"Connected to server\");\r\n \r\n \/\/ Send the identity map now\r\n VectorBuffer msg;\r\n msg.WriteVariantMap(serverConnection_->GetIdentity());\r\n serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);\r\n \r\n SendEvent(E_SERVERCONNECTED);\r\n}\r\n\r\nvoid Network::OnServerDisconnected()\r\n{\r\n \/\/ Differentiate between failed connection, and disconnection\r\n bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();\r\n if (!failedConnect)\r\n {\r\n LOGINFO(\"Disconnected from server\");\r\n SendEvent(E_SERVERDISCONNECTED);\r\n }\r\n else\r\n {\r\n LOGERROR(\"Failed to connect to server\");\r\n SendEvent(E_CONNECTFAILED);\r\n }\r\n \r\n serverConnection_.Reset();\r\n}\r\n\r\nbool Network::OnServerMessage(Connection* connection, int msgID, MemoryBuffer& msg)\r\n{\r\n switch (msgID)\r\n {\r\n case MSG_REMOTEEVENT:\r\n case MSG_REMOTENODEEVENT:\r\n OnRemoteEvent(connection, msgID, msg);\r\n return true;\r\n }\r\n \r\n return false;\r\n}\r\n\r\nbool Network::OnClientMessage(Connection* connection, int msgID, MemoryBuffer& msg)\r\n{\r\n switch (msgID)\r\n {\r\n case MSG_IDENTITY:\r\n {\r\n connection->SetIdentity(msg.ReadVariantMap());\r\n \r\n using namespace ClientIdentity;\r\n \r\n VariantMap eventData = connection->GetIdentity();\r\n eventData[P_CONNECTION] = (void*)connection;\r\n eventData[P_ALLOW] = true;\r\n connection->SendEvent(E_CLIENTIDENTITY, eventData);\r\n \r\n \/\/ If connection was denied as a response to the event, disconnect the client now\r\n if (!eventData[P_ALLOW].GetBool())\r\n connection->Disconnect();\r\n }\r\n return true;\r\n \r\n case MSG_CONTROLSUPDATE:\r\n {\r\n Controls newControls;\r\n newControls.buttons_ = msg.ReadUInt();\r\n newControls.yaw_ = msg.ReadFloat();\r\n newControls.pitch_ = msg.ReadFloat();\r\n newControls.extraData_ = msg.ReadVariantMap();\r\n connection->SetControls(newControls);\r\n }\r\n return true;\r\n \r\n case MSG_REMOTEEVENT:\r\n case MSG_REMOTENODEEVENT:\r\n OnRemoteEvent(connection, msgID, msg);\r\n return true;\r\n }\r\n \r\n return false;\r\n}\r\n\r\nvoid Network::OnRemoteEvent(Connection* connection, int msgID, MemoryBuffer& msg)\r\n{\r\n \/\/\/ \\todo Check whether the remote event is allowed based on a black- or whitelist\r\n if (msgID == MSG_REMOTEEVENT)\r\n {\r\n StringHash eventType = msg.ReadStringHash();\r\n VariantMap eventData = msg.ReadVariantMap();\r\n connection->SendEvent(eventType, eventData);\r\n }\r\n else\r\n {\r\n Scene* scene = connection->GetScene();\r\n if (!scene)\r\n {\r\n LOGERROR(\"Connection has null scene, can not receive remote node event\");\r\n return;\r\n }\r\n unsigned nodeID = msg.ReadVLE();\r\n StringHash eventType = msg.ReadStringHash();\r\n VariantMap eventData = msg.ReadVariantMap();\r\n Node* receiver = scene->GetNodeByID(nodeID);\r\n if (!receiver)\r\n {\r\n LOGWARNING(\"Remote node event's receiver not found, discarding event\");\r\n return;\r\n }\r\n connection->SendEvent(receiver, eventType, eventData);\r\n }\r\n}\r\n\r\nvoid Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)\r\n{\r\n using namespace BeginFrame;\r\n \r\n Update(eventData[P_TIMESTEP].GetFloat());\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"chrome\/browser\/bookmark_bar_context_menu_controller.h\"\n#include \"chrome\/browser\/bookmark_bar_model.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/views\/bookmark_bar_view.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome\/browser\/page_navigator.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ PageNavigator implementation that records the URL.\nclass TestingPageNavigator : public PageNavigator {\n public:\n virtual void OpenURL(const GURL& url,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n urls_.push_back(url);\n }\n\n std::vector urls_;\n};\n\n} \/\/ namespace\n\nclass BookmarkBarContextMenuControllerTest : public testing::Test {\n public:\n BookmarkBarContextMenuControllerTest() : bb_view_(NULL), model_(NULL) {\n }\n\n virtual void SetUp() {\n BookmarkBarView::testing_ = true;\n\n profile_.reset(new TestingProfile());\n profile_->set_has_history_service(true);\n profile_->CreateBookmarkBarModel();\n\n model_ = profile_->GetBookmarkBarModel();\n\n bb_view_ = new BookmarkBarView(profile_.get(), NULL);\n bb_view_->SetPageNavigator(&navigator_);\n\n AddTestData();\n }\n\n virtual void TearDown() {\n BookmarkBarView::testing_ = false;\n }\n\n protected:\n BookmarkBarModel* model_;\n BookmarkBarView* bb_view_;\n TestingPageNavigator navigator_;\n\n private:\n \/\/ Creates the following structure:\n \/\/ a\n \/\/ F1\n \/\/ f1a\n \/\/ F11\n \/\/ f11a\n \/\/ F2\n void AddTestData() {\n std::string test_base = \"file:\/\/\/c:\/tmp\/\";\n\n model_->AddURL(model_->GetBookmarkBarNode(), 0, L\"a\",\n GURL(test_base + \"a\"));\n BookmarkBarNode* f1 =\n model_->AddGroup(model_->GetBookmarkBarNode(), 1, L\"F1\");\n model_->AddURL(f1, 0, L\"f1a\", GURL(test_base + \"f1a\"));\n BookmarkBarNode* f11 = model_->AddGroup(f1, 1, L\"F11\");\n model_->AddURL(f11, 0, L\"f11a\", GURL(test_base + \"f11a\"));\n model_->AddGroup(model_->GetBookmarkBarNode(), 2, L\"F2\");\n }\n\n scoped_ptr profile_;\n};\n\n\/\/ Tests Deleting from the menu.\nTEST_F(BookmarkBarContextMenuControllerTest, DeleteURL) {\n BookmarkBarContextMenuController controller(\n bb_view_, model_->GetBookmarkBarNode()->GetChild(0));\n GURL url = model_->GetBookmarkBarNode()->GetChild(0)->GetURL();\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::delete_bookmark_id));\n \/\/ Delete the URL.\n controller.ExecuteCommand(\n BookmarkBarContextMenuController::delete_bookmark_id);\n \/\/ Model shouldn't have URL anymore.\n ASSERT_TRUE(model_->GetNodeByURL(url) == NULL);\n}\n\n\/\/ Tests openning from the menu.\nTEST_F(BookmarkBarContextMenuControllerTest, OpenURL) {\n BookmarkBarContextMenuController controller(\n bb_view_, model_->GetBookmarkBarNode()->GetChild(0));\n GURL url = model_->GetBookmarkBarNode()->GetChild(0)->GetURL();\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_bookmark_id));\n \/\/ Open it.\n controller.ExecuteCommand(\n BookmarkBarContextMenuController::open_bookmark_id);\n \/\/ Should have navigated to it.\n ASSERT_EQ(1, navigator_.urls_.size());\n ASSERT_TRUE(url == navigator_.urls_[0]);\n}\n\n\/\/ Tests open all on a folder with a couple of bookmarks.\nTEST_F(BookmarkBarContextMenuControllerTest, OpenAll) {\n BookmarkBarNode* folder = model_->GetBookmarkBarNode()->GetChild(1);\n BookmarkBarContextMenuController controller(bb_view_, folder);\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_id));\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_in_new_window_id));\n \/\/ Open it.\n controller.ExecuteCommand(\n BookmarkBarContextMenuController::open_all_bookmarks_id);\n \/\/ Should have navigated to F1's children.\n ASSERT_EQ(2, navigator_.urls_.size());\n ASSERT_TRUE(folder->GetChild(0)->GetURL() == navigator_.urls_[0]);\n ASSERT_TRUE(folder->GetChild(1)->GetChild(0)->GetURL() ==\n navigator_.urls_[1]);\n}\n\n\/\/ Tests that menus are appropriately disabled for empty folders.\nTEST_F(BookmarkBarContextMenuControllerTest, DisableForEmptyFolder) {\n BookmarkBarNode* folder = model_->GetBookmarkBarNode()->GetChild(2);\n BookmarkBarContextMenuController controller(bb_view_, folder);\n EXPECT_FALSE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_id));\n EXPECT_FALSE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_in_new_window_id));\n}\nFixes leak in BookmarkBarContextMenu test.\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"chrome\/browser\/bookmark_bar_context_menu_controller.h\"\n#include \"chrome\/browser\/bookmark_bar_model.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/views\/bookmark_bar_view.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome\/browser\/page_navigator.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ PageNavigator implementation that records the URL.\nclass TestingPageNavigator : public PageNavigator {\n public:\n virtual void OpenURL(const GURL& url,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n urls_.push_back(url);\n }\n\n std::vector urls_;\n};\n\n} \/\/ namespace\n\nclass BookmarkBarContextMenuControllerTest : public testing::Test {\n public:\n BookmarkBarContextMenuControllerTest() : bb_view_(NULL), model_(NULL) {\n }\n\n virtual void SetUp() {\n BookmarkBarView::testing_ = true;\n\n profile_.reset(new TestingProfile());\n profile_->set_has_history_service(true);\n profile_->CreateBookmarkBarModel();\n\n model_ = profile_->GetBookmarkBarModel();\n\n bb_view_.reset(new BookmarkBarView(profile_.get(), NULL));\n bb_view_->SetPageNavigator(&navigator_);\n\n AddTestData();\n }\n\n virtual void TearDown() {\n BookmarkBarView::testing_ = false;\n }\n\n protected:\n scoped_ptr profile_;\n BookmarkBarModel* model_;\n scoped_ptr bb_view_;\n TestingPageNavigator navigator_;\n\n private:\n \/\/ Creates the following structure:\n \/\/ a\n \/\/ F1\n \/\/ f1a\n \/\/ F11\n \/\/ f11a\n \/\/ F2\n void AddTestData() {\n std::string test_base = \"file:\/\/\/c:\/tmp\/\";\n\n model_->AddURL(model_->GetBookmarkBarNode(), 0, L\"a\",\n GURL(test_base + \"a\"));\n BookmarkBarNode* f1 =\n model_->AddGroup(model_->GetBookmarkBarNode(), 1, L\"F1\");\n model_->AddURL(f1, 0, L\"f1a\", GURL(test_base + \"f1a\"));\n BookmarkBarNode* f11 = model_->AddGroup(f1, 1, L\"F11\");\n model_->AddURL(f11, 0, L\"f11a\", GURL(test_base + \"f11a\"));\n model_->AddGroup(model_->GetBookmarkBarNode(), 2, L\"F2\");\n }\n};\n\n\/\/ Tests Deleting from the menu.\nTEST_F(BookmarkBarContextMenuControllerTest, DeleteURL) {\n BookmarkBarContextMenuController controller(\n bb_view_.get(), model_->GetBookmarkBarNode()->GetChild(0));\n GURL url = model_->GetBookmarkBarNode()->GetChild(0)->GetURL();\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::delete_bookmark_id));\n \/\/ Delete the URL.\n controller.ExecuteCommand(\n BookmarkBarContextMenuController::delete_bookmark_id);\n \/\/ Model shouldn't have URL anymore.\n ASSERT_TRUE(model_->GetNodeByURL(url) == NULL);\n}\n\n\/\/ Tests openning from the menu.\nTEST_F(BookmarkBarContextMenuControllerTest, OpenURL) {\n BookmarkBarContextMenuController controller(\n bb_view_.get(), model_->GetBookmarkBarNode()->GetChild(0));\n GURL url = model_->GetBookmarkBarNode()->GetChild(0)->GetURL();\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_bookmark_id));\n \/\/ Open it.\n controller.ExecuteCommand(\n BookmarkBarContextMenuController::open_bookmark_id);\n \/\/ Should have navigated to it.\n ASSERT_EQ(1, navigator_.urls_.size());\n ASSERT_TRUE(url == navigator_.urls_[0]);\n}\n\n\/\/ Tests open all on a folder with a couple of bookmarks.\nTEST_F(BookmarkBarContextMenuControllerTest, OpenAll) {\n BookmarkBarNode* folder = model_->GetBookmarkBarNode()->GetChild(1);\n BookmarkBarContextMenuController controller(bb_view_.get(), folder);\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_id));\n ASSERT_TRUE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_in_new_window_id));\n \/\/ Open it.\n controller.ExecuteCommand(\n BookmarkBarContextMenuController::open_all_bookmarks_id);\n \/\/ Should have navigated to F1's children.\n ASSERT_EQ(2, navigator_.urls_.size());\n ASSERT_TRUE(folder->GetChild(0)->GetURL() == navigator_.urls_[0]);\n ASSERT_TRUE(folder->GetChild(1)->GetChild(0)->GetURL() ==\n navigator_.urls_[1]);\n}\n\n\/\/ Tests that menus are appropriately disabled for empty folders.\nTEST_F(BookmarkBarContextMenuControllerTest, DisableForEmptyFolder) {\n BookmarkBarNode* folder = model_->GetBookmarkBarNode()->GetChild(2);\n BookmarkBarContextMenuController controller(bb_view_.get(), folder);\n EXPECT_FALSE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_id));\n EXPECT_FALSE(controller.IsCommandEnabled(\n BookmarkBarContextMenuController::open_all_bookmarks_in_new_window_id));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"grit\/generated_resources.h\"\n#include \"views\/controls\/button\/checkbox.h\"\n#include \"views\/controls\/image_view.h\"\n#include \"views\/controls\/label.h\"\n#include \"views\/controls\/link.h\"\n#include \"views\/standard_layout.h\"\n#include \"views\/view.h\"\n#include \"views\/window\/dialog_delegate.h\"\n#include \"views\/window\/window.h\"\n\n#if defined(OS_WIN)\n#include \"app\/win_util.h\"\n#endif\n\nclass Profile;\n\nnamespace {\n\nconst int kRightColumnWidth = 210;\nconst int kIconSize = 69;\n\n\/\/ Implements the extension installation prompt for Windows.\nclass InstallDialogContent : public views::View, public views::DialogDelegate {\n public:\n InstallDialogContent(ExtensionInstallUI::Delegate* delegate,\n Extension* extension, SkBitmap* icon, ExtensionInstallUI::PromptType type)\n : delegate_(delegate), icon_(NULL), type_(type) {\n \/\/ Scale down to icon size, but allow smaller icons (don't scale up).\n gfx::Size size(icon->width(), icon->height());\n if (size.width() > kIconSize || size.height() > kIconSize)\n size = gfx::Size(kIconSize, kIconSize);\n icon_ = new views::ImageView();\n icon_->SetImageSize(size);\n icon_->SetImage(*icon);\n AddChildView(icon_);\n\n heading_ = new views::Label(\n l10n_util::GetStringF(ExtensionInstallUI::kHeadingIds[type_],\n UTF8ToWide(extension->name())));\n heading_->SetMultiLine(true);\n heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n AddChildView(heading_);\n }\n\n private:\n \/\/ DialogDelegate\n virtual std::wstring GetDialogButtonLabel(\n MessageBoxFlags::DialogButton button) const {\n switch (button) {\n case MessageBoxFlags::DIALOGBUTTON_OK:\n return l10n_util::GetString(ExtensionInstallUI::kButtonIds[type_]);\n case MessageBoxFlags::DIALOGBUTTON_CANCEL:\n return l10n_util::GetString(IDS_CANCEL);\n default:\n NOTREACHED();\n return L\"\";\n }\n }\n\n virtual int GetDefaultDialogButton() const {\n return MessageBoxFlags::DIALOGBUTTON_CANCEL;\n }\n\n virtual bool Accept() {\n delegate_->InstallUIProceed();\n return true;\n }\n\n virtual bool Cancel() {\n delegate_->InstallUIAbort();\n return true;\n }\n\n \/\/ WindowDelegate\n virtual bool IsModal() const { return true; }\n virtual std::wstring GetWindowTitle() const {\n return l10n_util::GetString(ExtensionInstallUI::kTitleIds[type_]);\n }\n virtual views::View* GetContentsView() { return this; }\n\n \/\/ View\n virtual gfx::Size GetPreferredSize() {\n int width = kRightColumnWidth;\n width += kIconSize;\n width += kPanelHorizMargin * 3;\n\n int height = kPanelVertMargin * 2;\n height += heading_->GetHeightForWidth(kRightColumnWidth);\n\n return gfx::Size(width,\n std::max(height, kIconSize + kPanelVertMargin * 2));\n }\n\n virtual void Layout() {\n int x = kPanelHorizMargin;\n int y = kPanelVertMargin;\n\n heading_->SizeToFit(kRightColumnWidth);\n\n if (heading_->height() <= kIconSize) {\n icon_->SetBounds(x, y, kIconSize, kIconSize);\n x += kIconSize;\n x += kPanelHorizMargin;\n\n heading_->SetX(x);\n heading_->SetY(y + (kIconSize - heading_->height()) \/ 2);\n } else {\n icon_->SetBounds(x,\n y + (heading_->height() - kIconSize) \/ 2,\n kIconSize,\n kIconSize);\n x += kIconSize;\n x += kPanelHorizMargin;\n\n heading_->SetX(x);\n heading_->SetY(y);\n }\n }\n\n ExtensionInstallUI::Delegate* delegate_;\n views::ImageView* icon_;\n views::Label* heading_;\n ExtensionInstallUI::PromptType type_;\n\n DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);\n};\n\n} \/\/ namespace\n\n\/\/ static\nvoid ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(\n Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,\n PromptType type) {\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile);\n if (!browser) {\n delegate->InstallUIAbort();\n return;\n }\n\n BrowserWindow* window = browser->window();\n if (!window) {\n delegate->InstallUIAbort();\n return;\n }\n\n views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),\n new InstallDialogContent(delegate, extension, icon,\n type))->Show();\n}\nUse browser::CreateViewsWindow for ExtensionInstallUI.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n#include \"chrome\/browser\/views\/window.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"grit\/generated_resources.h\"\n#include \"views\/controls\/button\/checkbox.h\"\n#include \"views\/controls\/image_view.h\"\n#include \"views\/controls\/label.h\"\n#include \"views\/controls\/link.h\"\n#include \"views\/standard_layout.h\"\n#include \"views\/view.h\"\n#include \"views\/window\/dialog_delegate.h\"\n#include \"views\/window\/window.h\"\n\n#if defined(OS_WIN)\n#include \"app\/win_util.h\"\n#endif\n\nclass Profile;\n\nnamespace {\n\nconst int kRightColumnWidth = 210;\nconst int kIconSize = 69;\n\n\/\/ Implements the extension installation prompt for Windows.\nclass InstallDialogContent : public views::View, public views::DialogDelegate {\n public:\n InstallDialogContent(ExtensionInstallUI::Delegate* delegate,\n Extension* extension, SkBitmap* icon, ExtensionInstallUI::PromptType type)\n : delegate_(delegate), icon_(NULL), type_(type) {\n \/\/ Scale down to icon size, but allow smaller icons (don't scale up).\n gfx::Size size(icon->width(), icon->height());\n if (size.width() > kIconSize || size.height() > kIconSize)\n size = gfx::Size(kIconSize, kIconSize);\n icon_ = new views::ImageView();\n icon_->SetImageSize(size);\n icon_->SetImage(*icon);\n AddChildView(icon_);\n\n heading_ = new views::Label(\n l10n_util::GetStringF(ExtensionInstallUI::kHeadingIds[type_],\n UTF8ToWide(extension->name())));\n heading_->SetMultiLine(true);\n heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n AddChildView(heading_);\n }\n\n private:\n \/\/ DialogDelegate\n virtual std::wstring GetDialogButtonLabel(\n MessageBoxFlags::DialogButton button) const {\n switch (button) {\n case MessageBoxFlags::DIALOGBUTTON_OK:\n return l10n_util::GetString(ExtensionInstallUI::kButtonIds[type_]);\n case MessageBoxFlags::DIALOGBUTTON_CANCEL:\n return l10n_util::GetString(IDS_CANCEL);\n default:\n NOTREACHED();\n return L\"\";\n }\n }\n\n virtual int GetDefaultDialogButton() const {\n return MessageBoxFlags::DIALOGBUTTON_CANCEL;\n }\n\n virtual bool Accept() {\n delegate_->InstallUIProceed();\n return true;\n }\n\n virtual bool Cancel() {\n delegate_->InstallUIAbort();\n return true;\n }\n\n \/\/ WindowDelegate\n virtual bool IsModal() const { return true; }\n virtual std::wstring GetWindowTitle() const {\n return l10n_util::GetString(ExtensionInstallUI::kTitleIds[type_]);\n }\n virtual views::View* GetContentsView() { return this; }\n\n \/\/ View\n virtual gfx::Size GetPreferredSize() {\n int width = kRightColumnWidth;\n width += kIconSize;\n width += kPanelHorizMargin * 3;\n\n int height = kPanelVertMargin * 2;\n height += heading_->GetHeightForWidth(kRightColumnWidth);\n\n return gfx::Size(width,\n std::max(height, kIconSize + kPanelVertMargin * 2));\n }\n\n virtual void Layout() {\n int x = kPanelHorizMargin;\n int y = kPanelVertMargin;\n\n heading_->SizeToFit(kRightColumnWidth);\n\n if (heading_->height() <= kIconSize) {\n icon_->SetBounds(x, y, kIconSize, kIconSize);\n x += kIconSize;\n x += kPanelHorizMargin;\n\n heading_->SetX(x);\n heading_->SetY(y + (kIconSize - heading_->height()) \/ 2);\n } else {\n icon_->SetBounds(x,\n y + (heading_->height() - kIconSize) \/ 2,\n kIconSize,\n kIconSize);\n x += kIconSize;\n x += kPanelHorizMargin;\n\n heading_->SetX(x);\n heading_->SetY(y);\n }\n }\n\n ExtensionInstallUI::Delegate* delegate_;\n views::ImageView* icon_;\n views::Label* heading_;\n ExtensionInstallUI::PromptType type_;\n\n DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);\n};\n\n} \/\/ namespace\n\n\/\/ static\nvoid ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(\n Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,\n PromptType type) {\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile);\n if (!browser) {\n delegate->InstallUIAbort();\n return;\n }\n\n BrowserWindow* window = browser->window();\n if (!window) {\n delegate->InstallUIAbort();\n return;\n }\n\n browser::CreateViewsWindow(window->GetNativeHandle(), gfx::Rect(),\n new InstallDialogContent(delegate, extension, icon,\n type))->Show();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"ViewShadowNode.h\"\n#include \n\nnamespace facebook {\nnamespace react {\n\nchar const ViewComponentName[] = \"View\";\n\nViewShadowNode::ViewShadowNode(\n ShadowNodeFragment const &fragment,\n ShadowNodeFamily::Shared const &family,\n ShadowNodeTraits traits)\n : ConcreteViewShadowNode(fragment, family, traits) {\n initialize();\n}\n\nViewShadowNode::ViewShadowNode(\n ShadowNode const &sourceShadowNode,\n ShadowNodeFragment const &fragment)\n : ConcreteViewShadowNode(sourceShadowNode, fragment) {\n initialize();\n}\n\nstatic bool isColorMeaningful(SharedColor const &color) noexcept {\n if (!color) {\n return false;\n }\n\n return colorComponentsFromColor(color).alpha > 0;\n}\n\nvoid ViewShadowNode::initialize() noexcept {\n auto &viewProps = static_cast(*props_);\n\n bool formsStackingContext = !viewProps.collapsable ||\n viewProps.pointerEvents == PointerEventsMode::None ||\n !viewProps.nativeId.empty() || viewProps.accessible ||\n viewProps.opacity != 1.0 || viewProps.transform != Transform{} ||\n viewProps.elevation != 0 ||\n (viewProps.zIndex.has_value() &&\n viewProps.yogaStyle.positionType() != YGPositionTypeAbsolute) ||\n viewProps.yogaStyle.display() == YGDisplayNone ||\n viewProps.getClipsContentToBounds() ||\n isColorMeaningful(viewProps.shadowColor) ||\n viewProps.importantForAccessibility != ImportantForAccessibility::Auto;\n\n bool formsView = isColorMeaningful(viewProps.backgroundColor) ||\n isColorMeaningful(viewProps.foregroundColor) ||\n !(viewProps.yogaStyle.border() == YGStyle::Edges{});\n\n formsView = formsView || formsStackingContext;\n\n#ifdef ANDROID\n \/\/ Force `formsStackingContext` trait for nodes which have `formsView`.\n \/\/ TODO: T63560216 Investigate why\/how `formsView` entangled with\n \/\/ `formsStackingContext`.\n formsStackingContext = formsStackingContext || formsView;\n#endif\n\n if (formsView) {\n traits_.set(ShadowNodeTraits::Trait::FormsView);\n } else {\n traits_.unset(ShadowNodeTraits::Trait::FormsView);\n }\n\n if (formsStackingContext) {\n traits_.set(ShadowNodeTraits::Trait::FormsStackingContext);\n } else {\n traits_.unset(ShadowNodeTraits::Trait::FormsStackingContext);\n }\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\nFix a condition in forms stacking context evaluation\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"ViewShadowNode.h\"\n#include \n\nnamespace facebook {\nnamespace react {\n\nchar const ViewComponentName[] = \"View\";\n\nViewShadowNode::ViewShadowNode(\n ShadowNodeFragment const &fragment,\n ShadowNodeFamily::Shared const &family,\n ShadowNodeTraits traits)\n : ConcreteViewShadowNode(fragment, family, traits) {\n initialize();\n}\n\nViewShadowNode::ViewShadowNode(\n ShadowNode const &sourceShadowNode,\n ShadowNodeFragment const &fragment)\n : ConcreteViewShadowNode(sourceShadowNode, fragment) {\n initialize();\n}\n\nstatic bool isColorMeaningful(SharedColor const &color) noexcept {\n if (!color) {\n return false;\n }\n\n return colorComponentsFromColor(color).alpha > 0;\n}\n\nvoid ViewShadowNode::initialize() noexcept {\n auto &viewProps = static_cast(*props_);\n\n bool formsStackingContext = !viewProps.collapsable ||\n viewProps.pointerEvents == PointerEventsMode::None ||\n !viewProps.nativeId.empty() || viewProps.accessible ||\n viewProps.opacity != 1.0 || viewProps.transform != Transform{} ||\n viewProps.elevation != 0 ||\n (viewProps.zIndex.has_value() &&\n viewProps.yogaStyle.positionType() == YGPositionTypeAbsolute) ||\n viewProps.yogaStyle.display() == YGDisplayNone ||\n viewProps.getClipsContentToBounds() ||\n isColorMeaningful(viewProps.shadowColor) ||\n viewProps.importantForAccessibility != ImportantForAccessibility::Auto;\n\n bool formsView = isColorMeaningful(viewProps.backgroundColor) ||\n isColorMeaningful(viewProps.foregroundColor) ||\n !(viewProps.yogaStyle.border() == YGStyle::Edges{});\n\n formsView = formsView || formsStackingContext;\n\n#ifdef ANDROID\n \/\/ Force `formsStackingContext` trait for nodes which have `formsView`.\n \/\/ TODO: T63560216 Investigate why\/how `formsView` entangled with\n \/\/ `formsStackingContext`.\n formsStackingContext = formsStackingContext || formsView;\n#endif\n\n if (formsView) {\n traits_.set(ShadowNodeTraits::Trait::FormsView);\n } else {\n traits_.unset(ShadowNodeTraits::Trait::FormsView);\n }\n\n if (formsStackingContext) {\n traits_.set(ShadowNodeTraits::Trait::FormsStackingContext);\n } else {\n traits_.unset(ShadowNodeTraits::Trait::FormsStackingContext);\n }\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\n<|endoftext|>"} {"text":"\/\/ $Id$\n\n\/\/**************************************************************************\n\/\/* This file is property of and copyright by the ALICE HLT Project * \n\/\/* ALICE Experiment at CERN, All rights reserved. *\n\/\/* *\n\/\/* Primary Authors: Matthias Richter *\n\/\/* for The ALICE HLT Project. *\n\/\/* *\n\/\/* Permission to use, copy, modify and distribute this software and its *\n\/\/* documentation strictly for non-commercial purposes is hereby granted *\n\/\/* without fee, provided that the above copyright notice appears in all *\n\/\/* copies and that both the copyright notice and this permission notice *\n\/\/* appear in the supporting documentation. The authors make no claims *\n\/\/* about the suitability of this software for any purpose. It is *\n\/\/* provided \"as is\" without express or implied warranty. *\n\/\/**************************************************************************\n\n\/** @file AliHLTRCUAgent.cxx\n @author Matthias Richter\n @date \n @brief Agent of the libAliHLTRCU library\n*\/\n\n#include \n#include \"AliHLTRCUAgent.h\"\n#include \"AliHLTConfiguration.h\"\n\n\/\/ header files of library components\n#include \"AliHLTAltroChannelSelectorComponent.h\"\n#include \"AliHLTAltroTimebinAverageComponent.h\"\n\n\/** global instance for agent registration *\/\nAliHLTRCUAgent gAliHLTRCUAgent;\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTRCUAgent)\n\nAliHLTRCUAgent::AliHLTRCUAgent()\n :\n AliHLTModuleAgent(\"RCU\")\n{\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n}\n\nAliHLTRCUAgent::~AliHLTRCUAgent()\n{\n \/\/ see header file for class documentation\n}\n\nint AliHLTRCUAgent::CreateConfigurations(AliHLTConfigurationHandler* \/*handler*\/,\n\t\t\t\t\t AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n return 0;\n}\n\nconst char* AliHLTRCUAgent::GetReconstructionChains(AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nconst char* AliHLTRCUAgent::GetRequiredComponentLibraries() const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nint AliHLTRCUAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const\n{\n \/\/ see header file for class documentation\n assert(pHandler);\n if (!pHandler) return -EINVAL;\n pHandler->AddComponent(new AliHLTAltroChannelSelectorComponent);\n pHandler->AddComponent(new AliHLTAltroTimebinAverageComponent);\n return 0;\n}\nremoving unnecessary include file\/\/ $Id$\n\n\/\/**************************************************************************\n\/\/* This file is property of and copyright by the ALICE HLT Project * \n\/\/* ALICE Experiment at CERN, All rights reserved. *\n\/\/* *\n\/\/* Primary Authors: Matthias Richter *\n\/\/* for The ALICE HLT Project. *\n\/\/* *\n\/\/* Permission to use, copy, modify and distribute this software and its *\n\/\/* documentation strictly for non-commercial purposes is hereby granted *\n\/\/* without fee, provided that the above copyright notice appears in all *\n\/\/* copies and that both the copyright notice and this permission notice *\n\/\/* appear in the supporting documentation. The authors make no claims *\n\/\/* about the suitability of this software for any purpose. It is *\n\/\/* provided \"as is\" without express or implied warranty. *\n\/\/**************************************************************************\n\n\/** @file AliHLTRCUAgent.cxx\n @author Matthias Richter\n @date \n @brief Agent of the libAliHLTRCU library\n*\/\n\n#include \n#include \"AliHLTRCUAgent.h\"\n\n\/\/ header files of library components\n#include \"AliHLTAltroChannelSelectorComponent.h\"\n#include \"AliHLTAltroTimebinAverageComponent.h\"\n\n\/** global instance for agent registration *\/\nAliHLTRCUAgent gAliHLTRCUAgent;\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTRCUAgent)\n\nAliHLTRCUAgent::AliHLTRCUAgent()\n :\n AliHLTModuleAgent(\"RCU\")\n{\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n}\n\nAliHLTRCUAgent::~AliHLTRCUAgent()\n{\n \/\/ see header file for class documentation\n}\n\nint AliHLTRCUAgent::CreateConfigurations(AliHLTConfigurationHandler* \/*handler*\/,\n\t\t\t\t\t AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n return 0;\n}\n\nconst char* AliHLTRCUAgent::GetReconstructionChains(AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nconst char* AliHLTRCUAgent::GetRequiredComponentLibraries() const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nint AliHLTRCUAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const\n{\n \/\/ see header file for class documentation\n assert(pHandler);\n if (!pHandler) return -EINVAL;\n pHandler->AddComponent(new AliHLTAltroChannelSelectorComponent);\n pHandler->AddComponent(new AliHLTAltroTimebinAverageComponent);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: MNSInclude.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2002-10-18 08:51:22 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Willem van Dorp, Darren Kenny\n *\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_MAB_NS_INCLUDE_HXX_\n#define _CONNECTIVITY_MAB_NS_INCLUDE_HXX_ 1\n\n\/\/\n\/\/ Only include Mozilla include files once and using this file...\n\/\/\n\n#ifndef BOOL\n# define MOZ_BOOL\n\n# define BOOL mozBOOL\n# define Bool mozBooL\n#endif\n\n\/\/ Turn off DEBUG Assertions\n#ifdef _DEBUG\n #define _DEBUG_WAS_DEFINED _DEBUG\n #undef _DEBUG\n#else\n #undef _DEBUG_WAS_DEFINED\n#endif\n\n\/\/ and turn off the additional virtual methods which are part of some interfaces when compiled\n\/\/ with debug\n#ifdef DEBUG\n #define DEBUG_WAS_DEFINED DEBUG\n #undef DEBUG\n#else\n #undef DEBUG_WAS_DEFINED\n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef MOZ_BOOL\n# undef BOOL\n# undef Bool\n#endif\n\n#ifdef DEBUG_WAS_DEFINED\n #define DEBUG DEBUG_WAS_DEFINED\n#endif\n\n#ifdef _DEBUG_WAS_DEFINED\n #define _DEBUG _DEBUG_WAS_DEFINED\n#endif\n\n#endif \/\/ _CONNECTIVITY_MAB_NS_INCLUDE_HXX_\nINTEGRATION: CWS mozab04 (1.7.170); FILE MERGED 2004\/04\/27 03:13:36 windly 1.7.170.2: #i28398# update Mozilla components from v1.0 to v1.7 2004\/04\/12 10:15:55 windly 1.7.170.1: #i6883# make mozab driver threadsafe\/*************************************************************************\n *\n * $RCSfile: MNSInclude.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hjs $ $Date: 2004-06-25 18:32:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 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 * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Willem van Dorp, Darren Kenny\n *\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_MAB_NS_INCLUDE_HXX_\n#define _CONNECTIVITY_MAB_NS_INCLUDE_HXX_ 1\n\n\/\/\n\/\/ Only include Mozilla include files once and using this file...\n\/\/\n\n#ifndef BOOL\n# define MOZ_BOOL\n\n# define BOOL mozBOOL\n# define Bool mozBooL\n#endif\n\n\/\/ Turn off DEBUG Assertions\n#ifdef _DEBUG\n #define _DEBUG_WAS_DEFINED _DEBUG\n #undef _DEBUG\n#else\n #undef _DEBUG_WAS_DEFINED\n#endif\n\n\/\/ and turn off the additional virtual methods which are part of some interfaces when compiled\n\/\/ with debug\n#ifdef DEBUG\n #define DEBUG_WAS_DEFINED DEBUG\n #undef DEBUG\n#else\n #undef DEBUG_WAS_DEFINED\n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef MOZ_BOOL\n# undef BOOL\n# undef Bool\n#endif\n\n#ifdef DEBUG_WAS_DEFINED\n #define DEBUG DEBUG_WAS_DEFINED\n#endif\n\n#ifdef _DEBUG_WAS_DEFINED\n #define _DEBUG _DEBUG_WAS_DEFINED\n#endif\n\n#endif \/\/ _CONNECTIVITY_MAB_NS_INCLUDE_HXX_\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkGraphLayout.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkGraphLayout.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"vtkGraphLayoutStrategy.h\"\n\nvtkCxxRevisionMacro(vtkGraphLayout, \"1.3\");\nvtkStandardNewMacro(vtkGraphLayout);\n\n\/\/ ----------------------------------------------------------------------\n\nvtkGraphLayout::vtkGraphLayout()\n{\n this->LayoutStrategy = 0;\n this->LastInput = NULL;\n this->LastInputMTime = 0;\n this->InternalGraph = NULL;\n\n this->ObserverTag = 0;\n this->EventForwarder = vtkEventForwarderCommand::New();\n this->EventForwarder->SetTarget(this);\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvtkGraphLayout::~vtkGraphLayout()\n{\n if (this->LayoutStrategy)\n {\n this->LayoutStrategy->Delete();\n }\n if (this->InternalGraph)\n {\n this->InternalGraph->Delete();\n }\n this->EventForwarder->Delete();\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvoid \nvtkGraphLayout::SetLayoutStrategy(vtkGraphLayoutStrategy *strategy)\n{\n \/\/ This method is a cut and paste of vtkCxxSetObjectMacro\n \/\/ except for the call to SetGraph in the middle :)\n if (strategy != this->LayoutStrategy)\n {\n vtkGraphLayoutStrategy *tmp = this->LayoutStrategy;\n this->LayoutStrategy = strategy;\n if (this->LayoutStrategy != NULL)\n {\n this->LayoutStrategy->Register(this);\n this->ObserverTag =\n this->LayoutStrategy->AddObserver(vtkCommand::ProgressEvent, \n this->EventForwarder);\n if (this->InternalGraph)\n {\n \/\/ Set the graph in the layout strategy\n this->LayoutStrategy->SetGraph(this->InternalGraph);\n }\n }\n if (tmp != NULL)\n {\n tmp->UnRegister(this);\n tmp->RemoveObserver(this->ObserverTag);\n }\n this->Modified();\n }\n \n}\n\n\/\/ ----------------------------------------------------------------------\n\nunsigned long \nvtkGraphLayout::GetMTime()\n{\n unsigned long mTime = this->Superclass::GetMTime();\n unsigned long time;\n\n if (this->LayoutStrategy != NULL)\n {\n time = this->LayoutStrategy->GetMTime();\n mTime = (time > mTime ? time : mTime);\n }\n return mTime;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nint \nvtkGraphLayout::IsLayoutComplete()\n{\n if (this->LayoutStrategy)\n {\n return this->LayoutStrategy->IsLayoutComplete();\n }\n \n \/\/ This is an error condition\n vtkErrorMacro(\"IsLayoutComplete called with layout strategy==NULL\");\n return 0;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nint \nvtkGraphLayout::RequestData(vtkInformation *vtkNotUsed(request),\n vtkInformationVector **inputVector,\n vtkInformationVector *outputVector)\n{\n if (this->LayoutStrategy == NULL)\n {\n vtkErrorMacro(<< \"Layout strategy must me non-null.\");\n return 0;\n }\n\n \/\/ get the info objects\n vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n \/\/ get the input and output\n vtkAbstractGraph *input = vtkAbstractGraph::SafeDownCast(\n inInfo->Get(vtkDataObject::DATA_OBJECT()));\n vtkAbstractGraph *output = vtkAbstractGraph::SafeDownCast(\n outInfo->Get(vtkDataObject::DATA_OBJECT()));\n \n \/\/ See if the input is the same as the last input\n \/\/ Note: This is keeping state and in vtk filter\n \/\/ land this is a bad thing. :)\n if ((input != this->LastInput) ||\n (input->GetMTime() != this->LastInputMTime))\n {\n \n \/\/ Okay create an internal graph for supporting\n \/\/ iterative graph layout strategies\n if (this->InternalGraph)\n {\n this->InternalGraph->Delete();\n }\n this->InternalGraph = input->NewInstance();\n \n \/\/ Capture info about graph\n this->LastInput = input;\n this->LastInputMTime = input->GetMTime();\n \n \/\/ Shallow copy data to output.\n this->InternalGraph->ShallowCopy(input);\n\n \/\/ Deep copy the point data from input to output\n vtkPoints* oldPoints = input->GetPoints();\n vtkPoints* newPoints = vtkPoints::New();\n newPoints->DeepCopy(oldPoints);\n this->InternalGraph->SetPoints(newPoints);\n newPoints->Delete();\n \n \/\/ Set the graph in the layout strategy\n this->LayoutStrategy->SetGraph(this->InternalGraph);\n }\n\n this->LayoutStrategy->Layout();\n output->ShallowCopy(this->InternalGraph);\n\n return 1;\n}\n\n\/\/ ----------------------------------------------------------------------\n\n\nvoid vtkGraphLayout::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"LayoutStrategy: \" << (this->LayoutStrategy ? \"\" : \"(none)\") << endl;\n if (this->LayoutStrategy)\n {\n this->LayoutStrategy->PrintSelf(os, indent.GetNextIndent());\n }\n os << indent << \"InternalGraph: \" << (this->InternalGraph ? \"\" : \"(none)\") << endl;\n if (this->InternalGraph)\n {\n this->InternalGraph->PrintSelf(os, indent.GetNextIndent());\n }\n}\nBUG: Don't delete an object and *then* remove the observer... it might already be gone.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkGraphLayout.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkGraphLayout.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"vtkGraphLayoutStrategy.h\"\n\nvtkCxxRevisionMacro(vtkGraphLayout, \"1.4\");\nvtkStandardNewMacro(vtkGraphLayout);\n\n\/\/ ----------------------------------------------------------------------\n\nvtkGraphLayout::vtkGraphLayout()\n{\n this->LayoutStrategy = 0;\n this->LastInput = NULL;\n this->LastInputMTime = 0;\n this->InternalGraph = NULL;\n\n this->ObserverTag = 0;\n this->EventForwarder = vtkEventForwarderCommand::New();\n this->EventForwarder->SetTarget(this);\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvtkGraphLayout::~vtkGraphLayout()\n{\n if (this->LayoutStrategy)\n {\n this->LayoutStrategy->Delete();\n }\n if (this->InternalGraph)\n {\n this->InternalGraph->Delete();\n }\n this->EventForwarder->Delete();\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvoid \nvtkGraphLayout::SetLayoutStrategy(vtkGraphLayoutStrategy *strategy)\n{\n \/\/ This method is a cut and paste of vtkCxxSetObjectMacro\n \/\/ except for the call to SetGraph in the middle :)\n if (strategy != this->LayoutStrategy)\n {\n vtkGraphLayoutStrategy *tmp = this->LayoutStrategy;\n this->LayoutStrategy = strategy;\n if (this->LayoutStrategy != NULL)\n {\n this->LayoutStrategy->Register(this);\n this->ObserverTag =\n this->LayoutStrategy->AddObserver(vtkCommand::ProgressEvent, \n this->EventForwarder);\n if (this->InternalGraph)\n {\n \/\/ Set the graph in the layout strategy\n this->LayoutStrategy->SetGraph(this->InternalGraph);\n }\n }\n if (tmp != NULL)\n {\n tmp->RemoveObserver(this->ObserverTag);\n tmp->UnRegister(this);\n }\n this->Modified();\n }\n \n}\n\n\/\/ ----------------------------------------------------------------------\n\nunsigned long \nvtkGraphLayout::GetMTime()\n{\n unsigned long mTime = this->Superclass::GetMTime();\n unsigned long time;\n\n if (this->LayoutStrategy != NULL)\n {\n time = this->LayoutStrategy->GetMTime();\n mTime = (time > mTime ? time : mTime);\n }\n return mTime;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nint \nvtkGraphLayout::IsLayoutComplete()\n{\n if (this->LayoutStrategy)\n {\n return this->LayoutStrategy->IsLayoutComplete();\n }\n \n \/\/ This is an error condition\n vtkErrorMacro(\"IsLayoutComplete called with layout strategy==NULL\");\n return 0;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nint \nvtkGraphLayout::RequestData(vtkInformation *vtkNotUsed(request),\n vtkInformationVector **inputVector,\n vtkInformationVector *outputVector)\n{\n if (this->LayoutStrategy == NULL)\n {\n vtkErrorMacro(<< \"Layout strategy must me non-null.\");\n return 0;\n }\n\n \/\/ get the info objects\n vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n \/\/ get the input and output\n vtkAbstractGraph *input = vtkAbstractGraph::SafeDownCast(\n inInfo->Get(vtkDataObject::DATA_OBJECT()));\n vtkAbstractGraph *output = vtkAbstractGraph::SafeDownCast(\n outInfo->Get(vtkDataObject::DATA_OBJECT()));\n \n \/\/ See if the input is the same as the last input\n \/\/ Note: This is keeping state and in vtk filter\n \/\/ land this is a bad thing. :)\n if ((input != this->LastInput) ||\n (input->GetMTime() != this->LastInputMTime))\n {\n \n \/\/ Okay create an internal graph for supporting\n \/\/ iterative graph layout strategies\n if (this->InternalGraph)\n {\n this->InternalGraph->Delete();\n }\n this->InternalGraph = input->NewInstance();\n \n \/\/ Capture info about graph\n this->LastInput = input;\n this->LastInputMTime = input->GetMTime();\n \n \/\/ Shallow copy data to output.\n this->InternalGraph->ShallowCopy(input);\n\n \/\/ Deep copy the point data from input to output\n vtkPoints* oldPoints = input->GetPoints();\n vtkPoints* newPoints = vtkPoints::New();\n newPoints->DeepCopy(oldPoints);\n this->InternalGraph->SetPoints(newPoints);\n newPoints->Delete();\n \n \/\/ Set the graph in the layout strategy\n this->LayoutStrategy->SetGraph(this->InternalGraph);\n }\n\n this->LayoutStrategy->Layout();\n output->ShallowCopy(this->InternalGraph);\n\n return 1;\n}\n\n\/\/ ----------------------------------------------------------------------\n\n\nvoid vtkGraphLayout::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"LayoutStrategy: \" << (this->LayoutStrategy ? \"\" : \"(none)\") << endl;\n if (this->LayoutStrategy)\n {\n this->LayoutStrategy->PrintSelf(os, indent.GetNextIndent());\n }\n os << indent << \"InternalGraph: \" << (this->InternalGraph ? \"\" : \"(none)\") << endl;\n if (this->InternalGraph)\n {\n this->InternalGraph->PrintSelf(os, indent.GetNextIndent());\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/serial\/serial_connection.h\"\n\n#include \n\n#include \n\nnamespace extensions {\n\nnamespace {\n\nint BitrateToSpeedConstant(int bitrate) {\n#define BITRATE_TO_SPEED_CASE(x) case x: return CBR_ ## x;\n switch (bitrate) {\n BITRATE_TO_SPEED_CASE(110);\n BITRATE_TO_SPEED_CASE(300);\n BITRATE_TO_SPEED_CASE(600);\n BITRATE_TO_SPEED_CASE(1200);\n BITRATE_TO_SPEED_CASE(2400);\n BITRATE_TO_SPEED_CASE(4800);\n BITRATE_TO_SPEED_CASE(9600);\n BITRATE_TO_SPEED_CASE(14400);\n BITRATE_TO_SPEED_CASE(19200);\n BITRATE_TO_SPEED_CASE(38400);\n BITRATE_TO_SPEED_CASE(57600);\n BITRATE_TO_SPEED_CASE(115200);\n BITRATE_TO_SPEED_CASE(128000);\n BITRATE_TO_SPEED_CASE(256000);\n default:\n \/\/ If the bitrate doesn't match that of one of the standard\n \/\/ index constants, it may be provided as-is to the DCB\n \/\/ structure, according to MSDN.\n return bitrate;\n }\n#undef BITRATE_TO_SPEED_CASE\n}\n\nint DataBitsEnumToConstant(api::serial::DataBits data_bits) {\n switch (data_bits) {\n case api::serial::DATA_BITS_SEVEN:\n return 7;\n case api::serial::DATA_BITS_EIGHT:\n default:\n return 8;\n }\n}\n\nint ParityBitEnumToConstant(api::serial::ParityBit parity_bit) {\n switch (parity_bit) {\n case api::serial::PARITY_BIT_EVEN:\n return EVENPARITY;\n case api::serial::PARITY_BIT_ODD:\n return SPACEPARITY;\n case api::serial::PARITY_BIT_NO:\n default:\n return NOPARITY;\n }\n}\n\nint StopBitsEnumToConstant(api::serial::StopBits stop_bits) {\n switch (stop_bits) {\n case api::serial::STOP_BITS_TWO:\n return TWOSTOPBITS;\n case api::serial::STOP_BITS_ONE:\n default:\n return ONESTOPBIT;\n }\n}\n\nint SpeedConstantToBitrate(int speed) {\n#define SPEED_TO_BITRATE_CASE(x) case CBR_ ## x: return x;\n switch (speed) {\n SPEED_TO_BITRATE_CASE(110);\n SPEED_TO_BITRATE_CASE(300);\n SPEED_TO_BITRATE_CASE(600);\n SPEED_TO_BITRATE_CASE(1200);\n SPEED_TO_BITRATE_CASE(2400);\n SPEED_TO_BITRATE_CASE(4800);\n SPEED_TO_BITRATE_CASE(9600);\n SPEED_TO_BITRATE_CASE(14400);\n SPEED_TO_BITRATE_CASE(19200);\n SPEED_TO_BITRATE_CASE(38400);\n SPEED_TO_BITRATE_CASE(57600);\n SPEED_TO_BITRATE_CASE(115200);\n SPEED_TO_BITRATE_CASE(128000);\n SPEED_TO_BITRATE_CASE(256000);\n default:\n \/\/ If it's not one of the standard index constants,\n \/\/ it should be an integral baud rate, according to\n \/\/ MSDN.\n return speed;\n }\n#undef SPEED_TO_BITRATE_CASE\n}\n\napi::serial::DataBits DataBitsConstantToEnum(int data_bits) {\n switch (data_bits) {\n case 7:\n return api::serial::DATA_BITS_SEVEN;\n case 8:\n default:\n return api::serial::DATA_BITS_EIGHT;\n }\n}\n\napi::serial::ParityBit ParityBitConstantToEnum(int parity_bit) {\n switch (parity_bit) {\n case EVENPARITY:\n return api::serial::PARITY_BIT_EVEN;\n case ODDPARITY:\n return api::serial::PARITY_BIT_ODD;\n case NOPARITY:\n default:\n return api::serial::PARITY_BIT_NO;\n }\n}\n\napi::serial::StopBits StopBitsConstantToEnum(int stop_bits) {\n switch (stop_bits) {\n case TWOSTOPBITS:\n return api::serial::STOP_BITS_TWO;\n case ONESTOPBIT:\n default:\n return api::serial::STOP_BITS_ONE;\n }\n}\n\n} \/\/ namespace\n\nbool SerialConnection::ConfigurePort(\n const api::serial::ConnectionOptions& options) {\n DCB config = { 0 };\n config.DCBlength = sizeof(config);\n if (!GetCommState(file_, &config)) {\n return false;\n }\n if (options.bitrate.get())\n config.BaudRate = BitrateToSpeedConstant(*options.bitrate);\n if (options.data_bits != api::serial::DATA_BITS_NONE)\n config.ByteSize = DataBitsEnumToConstant(options.data_bits);\n if (options.parity_bit != api::serial::PARITY_BIT_NONE)\n config.Parity = ParityBitEnumToConstant(options.parity_bit);\n if (options.stop_bits != api::serial::STOP_BITS_NONE)\n config.StopBits = StopBitsEnumToConstant(options.stop_bits);\n if (options.cts_flow_control.get()) {\n if (*options.cts_flow_control) {\n config.fOutxCtsFlow = TRUE;\n config.fRtsControl = RTS_CONTROL_HANDSHAKE;\n } else {\n config.fOutxCtsFlow = FALSE;\n config.fRtsControl = RTS_CONTROL_ENABLE;\n }\n }\n return SetCommState(file_, &config) != 0;\n}\n\nbool SerialConnection::PostOpen() {\n \/\/ Set a very brief read interval timeout. This prevents the asynchronous I\/O\n \/\/ system from being way too eager to fire off completion events which would\n \/\/ in turn result in a lot of onReceive events being fired (i.e., one for\n \/\/ every individual byte received on the serial buffer.)\n COMMTIMEOUTS timeouts = { 0 };\n timeouts.ReadIntervalTimeout = 10;\n if (!::SetCommTimeouts(file_, &timeouts)) {\n return false;\n }\n\n DCB config = { 0 };\n config.DCBlength = sizeof(config);\n if (!GetCommState(file_, &config)) {\n return false;\n }\n \/\/ Setup some sane default state.\n config.fBinary = TRUE;\n config.fParity = FALSE;\n config.fAbortOnError = TRUE;\n config.fOutxCtsFlow = FALSE;\n config.fOutxDsrFlow = FALSE;\n config.fRtsControl = RTS_CONTROL_ENABLE;\n config.fDtrControl = DTR_CONTROL_ENABLE;\n config.fDsrSensitivity = FALSE;\n config.fOutX = FALSE;\n config.fInX = FALSE;\n return SetCommState(file_, &config) != 0;\n}\n\nbool SerialConnection::Flush() const {\n return PurgeComm(file_, PURGE_RXCLEAR | PURGE_TXCLEAR) != 0;\n}\n\nbool SerialConnection::GetControlSignals(\n api::serial::DeviceControlSignals* signals) const {\n DWORD status;\n if (!GetCommModemStatus(file_, &status)) {\n return false;\n }\n signals->dcd = (status & MS_RLSD_ON) != 0;\n signals->cts = (status & MS_CTS_ON) != 0;\n signals->dsr = (status & MS_DSR_ON) != 0;\n signals->ri = (status & MS_RING_ON) != 0;\n return true;\n}\n\nbool SerialConnection::SetControlSignals(\n const api::serial::HostControlSignals& signals) {\n if (signals.dtr.get()) {\n if (!EscapeCommFunction(file_, *signals.dtr ? SETDTR : CLRDTR)) {\n return false;\n }\n }\n if (signals.rts.get()) {\n if (!EscapeCommFunction(file_, *signals.rts ? SETRTS : CLRRTS)) {\n return false;\n }\n }\n return true;\n}\n\nbool SerialConnection::GetPortInfo(api::serial::ConnectionInfo* info) const {\n DCB config = { 0 };\n config.DCBlength = sizeof(config);\n if (!GetCommState(file_, &config)) {\n return false;\n }\n info->bitrate.reset(new int(SpeedConstantToBitrate(config.BaudRate)));\n info->data_bits = DataBitsConstantToEnum(config.ByteSize);\n info->parity_bit = ParityBitConstantToEnum(config.Parity);\n info->stop_bits = StopBitsConstantToEnum(config.StopBits);\n info->cts_flow_control.reset(new bool(config.fOutxCtsFlow != 0));\n return true;\n}\n\nstd::string SerialConnection::MaybeFixUpPortName(\n const std::string &port_name) {\n \/\/ For COM numbers less than 9, CreateFile is called with a string such as\n \/\/ \"COM1\". For numbers greater than 9, a prefix of \"\\\\\\\\.\\\\\" must be added.\n if (port_name.length() > std::string(\"COM9\").length())\n return std::string(\"\\\\\\\\.\\\\\").append(port_name);\n\n return port_name;\n}\n\n} \/\/ namespace extensions\nRemove timeout behavior from Windows serial I\/O\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/serial\/serial_connection.h\"\n\n#include \n\n#include \n\nnamespace extensions {\n\nnamespace {\n\nint BitrateToSpeedConstant(int bitrate) {\n#define BITRATE_TO_SPEED_CASE(x) case x: return CBR_ ## x;\n switch (bitrate) {\n BITRATE_TO_SPEED_CASE(110);\n BITRATE_TO_SPEED_CASE(300);\n BITRATE_TO_SPEED_CASE(600);\n BITRATE_TO_SPEED_CASE(1200);\n BITRATE_TO_SPEED_CASE(2400);\n BITRATE_TO_SPEED_CASE(4800);\n BITRATE_TO_SPEED_CASE(9600);\n BITRATE_TO_SPEED_CASE(14400);\n BITRATE_TO_SPEED_CASE(19200);\n BITRATE_TO_SPEED_CASE(38400);\n BITRATE_TO_SPEED_CASE(57600);\n BITRATE_TO_SPEED_CASE(115200);\n BITRATE_TO_SPEED_CASE(128000);\n BITRATE_TO_SPEED_CASE(256000);\n default:\n \/\/ If the bitrate doesn't match that of one of the standard\n \/\/ index constants, it may be provided as-is to the DCB\n \/\/ structure, according to MSDN.\n return bitrate;\n }\n#undef BITRATE_TO_SPEED_CASE\n}\n\nint DataBitsEnumToConstant(api::serial::DataBits data_bits) {\n switch (data_bits) {\n case api::serial::DATA_BITS_SEVEN:\n return 7;\n case api::serial::DATA_BITS_EIGHT:\n default:\n return 8;\n }\n}\n\nint ParityBitEnumToConstant(api::serial::ParityBit parity_bit) {\n switch (parity_bit) {\n case api::serial::PARITY_BIT_EVEN:\n return EVENPARITY;\n case api::serial::PARITY_BIT_ODD:\n return SPACEPARITY;\n case api::serial::PARITY_BIT_NO:\n default:\n return NOPARITY;\n }\n}\n\nint StopBitsEnumToConstant(api::serial::StopBits stop_bits) {\n switch (stop_bits) {\n case api::serial::STOP_BITS_TWO:\n return TWOSTOPBITS;\n case api::serial::STOP_BITS_ONE:\n default:\n return ONESTOPBIT;\n }\n}\n\nint SpeedConstantToBitrate(int speed) {\n#define SPEED_TO_BITRATE_CASE(x) case CBR_ ## x: return x;\n switch (speed) {\n SPEED_TO_BITRATE_CASE(110);\n SPEED_TO_BITRATE_CASE(300);\n SPEED_TO_BITRATE_CASE(600);\n SPEED_TO_BITRATE_CASE(1200);\n SPEED_TO_BITRATE_CASE(2400);\n SPEED_TO_BITRATE_CASE(4800);\n SPEED_TO_BITRATE_CASE(9600);\n SPEED_TO_BITRATE_CASE(14400);\n SPEED_TO_BITRATE_CASE(19200);\n SPEED_TO_BITRATE_CASE(38400);\n SPEED_TO_BITRATE_CASE(57600);\n SPEED_TO_BITRATE_CASE(115200);\n SPEED_TO_BITRATE_CASE(128000);\n SPEED_TO_BITRATE_CASE(256000);\n default:\n \/\/ If it's not one of the standard index constants,\n \/\/ it should be an integral baud rate, according to\n \/\/ MSDN.\n return speed;\n }\n#undef SPEED_TO_BITRATE_CASE\n}\n\napi::serial::DataBits DataBitsConstantToEnum(int data_bits) {\n switch (data_bits) {\n case 7:\n return api::serial::DATA_BITS_SEVEN;\n case 8:\n default:\n return api::serial::DATA_BITS_EIGHT;\n }\n}\n\napi::serial::ParityBit ParityBitConstantToEnum(int parity_bit) {\n switch (parity_bit) {\n case EVENPARITY:\n return api::serial::PARITY_BIT_EVEN;\n case ODDPARITY:\n return api::serial::PARITY_BIT_ODD;\n case NOPARITY:\n default:\n return api::serial::PARITY_BIT_NO;\n }\n}\n\napi::serial::StopBits StopBitsConstantToEnum(int stop_bits) {\n switch (stop_bits) {\n case TWOSTOPBITS:\n return api::serial::STOP_BITS_TWO;\n case ONESTOPBIT:\n default:\n return api::serial::STOP_BITS_ONE;\n }\n}\n\n} \/\/ namespace\n\nbool SerialConnection::ConfigurePort(\n const api::serial::ConnectionOptions& options) {\n DCB config = { 0 };\n config.DCBlength = sizeof(config);\n if (!GetCommState(file_, &config)) {\n return false;\n }\n if (options.bitrate.get())\n config.BaudRate = BitrateToSpeedConstant(*options.bitrate);\n if (options.data_bits != api::serial::DATA_BITS_NONE)\n config.ByteSize = DataBitsEnumToConstant(options.data_bits);\n if (options.parity_bit != api::serial::PARITY_BIT_NONE)\n config.Parity = ParityBitEnumToConstant(options.parity_bit);\n if (options.stop_bits != api::serial::STOP_BITS_NONE)\n config.StopBits = StopBitsEnumToConstant(options.stop_bits);\n if (options.cts_flow_control.get()) {\n if (*options.cts_flow_control) {\n config.fOutxCtsFlow = TRUE;\n config.fRtsControl = RTS_CONTROL_HANDSHAKE;\n } else {\n config.fOutxCtsFlow = FALSE;\n config.fRtsControl = RTS_CONTROL_ENABLE;\n }\n }\n return SetCommState(file_, &config) != 0;\n}\n\nbool SerialConnection::PostOpen() {\n \/\/ A ReadIntervalTimeout of MAXDWORD will cause async reads to complete\n \/\/ immediately with any data that's available, even if there is none.\n \/\/ This is OK because we never issue a read request until WaitCommEvent\n \/\/ signals that data is available.\n COMMTIMEOUTS timeouts = { 0 };\n timeouts.ReadIntervalTimeout = MAXDWORD;\n if (!::SetCommTimeouts(file_, &timeouts)) {\n return false;\n }\n\n DCB config = { 0 };\n config.DCBlength = sizeof(config);\n if (!GetCommState(file_, &config)) {\n return false;\n }\n \/\/ Setup some sane default state.\n config.fBinary = TRUE;\n config.fParity = FALSE;\n config.fAbortOnError = TRUE;\n config.fOutxCtsFlow = FALSE;\n config.fOutxDsrFlow = FALSE;\n config.fRtsControl = RTS_CONTROL_ENABLE;\n config.fDtrControl = DTR_CONTROL_ENABLE;\n config.fDsrSensitivity = FALSE;\n config.fOutX = FALSE;\n config.fInX = FALSE;\n return SetCommState(file_, &config) != 0;\n}\n\nbool SerialConnection::Flush() const {\n return PurgeComm(file_, PURGE_RXCLEAR | PURGE_TXCLEAR) != 0;\n}\n\nbool SerialConnection::GetControlSignals(\n api::serial::DeviceControlSignals* signals) const {\n DWORD status;\n if (!GetCommModemStatus(file_, &status)) {\n return false;\n }\n signals->dcd = (status & MS_RLSD_ON) != 0;\n signals->cts = (status & MS_CTS_ON) != 0;\n signals->dsr = (status & MS_DSR_ON) != 0;\n signals->ri = (status & MS_RING_ON) != 0;\n return true;\n}\n\nbool SerialConnection::SetControlSignals(\n const api::serial::HostControlSignals& signals) {\n if (signals.dtr.get()) {\n if (!EscapeCommFunction(file_, *signals.dtr ? SETDTR : CLRDTR)) {\n return false;\n }\n }\n if (signals.rts.get()) {\n if (!EscapeCommFunction(file_, *signals.rts ? SETRTS : CLRRTS)) {\n return false;\n }\n }\n return true;\n}\n\nbool SerialConnection::GetPortInfo(api::serial::ConnectionInfo* info) const {\n DCB config = { 0 };\n config.DCBlength = sizeof(config);\n if (!GetCommState(file_, &config)) {\n return false;\n }\n info->bitrate.reset(new int(SpeedConstantToBitrate(config.BaudRate)));\n info->data_bits = DataBitsConstantToEnum(config.ByteSize);\n info->parity_bit = ParityBitConstantToEnum(config.Parity);\n info->stop_bits = StopBitsConstantToEnum(config.StopBits);\n info->cts_flow_control.reset(new bool(config.fOutxCtsFlow != 0));\n return true;\n}\n\nstd::string SerialConnection::MaybeFixUpPortName(\n const std::string &port_name) {\n \/\/ For COM numbers less than 9, CreateFile is called with a string such as\n \/\/ \"COM1\". For numbers greater than 9, a prefix of \"\\\\\\\\.\\\\\" must be added.\n if (port_name.length() > std::string(\"COM9\").length())\n return std::string(\"\\\\\\\\.\\\\\").append(port_name);\n\n return port_name;\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"Fix issue with selecting proper JNI libraries<|endoftext|>"} {"text":"\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Lexer for the pretty CellML format\n\/\/==============================================================================\n\n#include \"prettycellmlviewlexer.h\"\n#include \"qscintillawidget.h\"\n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace PrettyCellMLView {\n\n\/\/==============================================================================\n\nPrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :\n QsciLexerCustom(pParent),\n mFullText(QString())\n{\n \/\/ Some initialisations\n\n mKeywords = QStringList() << \"as\" << \"comp\" << \"def\" << \"enddef\" << \"model\" << \"unit\";\n mCellmlKeywords = QStringList() << \"base\"\n << \"ampere\" << \"candela\" << \"coulomb\" << \"joule\" << \"kelvin\" << \"kilogram\" << \"liter\" << \"litre\" << \"lumen\" << \"meter\" << \"metre\" << \"mole\" << \"newton\" << \"second\" << \"steradian\" << \"volt\" << \"watt\" << \"weber\";\n mParameterKeywords = QStringList() << \"pref\" << \"expo\" << \"mult\" << \"off\";\n mParameterValueKeywords = QStringList() << \"milli\";\n}\n\n\/\/==============================================================================\n\nconst char * PrettyCellmlViewLexer::language() const\n{\n \/\/ Return the language for our lexer\n\n return \"Pretty CellML\";\n}\n\n\/\/==============================================================================\n\nQString PrettyCellmlViewLexer::description(int pStyle) const\n{\n \/\/ Return the given style's description\n\n switch (pStyle) {\n case Default:\n return QObject::tr(\"Default\");\n case Comment:\n return QObject::tr(\"Comment\");\n case Keyword:\n return QObject::tr(\"Keyword\");\n case CellmlKeyword:\n return QObject::tr(\"CellML keyword\");\n case Number:\n return QObject::tr(\"Number\");\n case ParameterGroup:\n return QObject::tr(\"Parameter group\");\n case ParameterKeyword:\n return QObject::tr(\"Parameter keyword\");\n case ParameterValueKeyword:\n return QObject::tr(\"Parameter value keyword\");\n case ParameterNumber:\n return QObject::tr(\"Parameter number\");\n }\n\n return QString();\n}\n\n\/\/==============================================================================\n\nQColor PrettyCellmlViewLexer::color(int pStyle) const\n{\n \/\/ Return the given style's colour\n\n switch (pStyle) {\n case Default:\n case ParameterGroup:\n return QColor(0x1f, 0x1f, 0x1f);\n case Comment:\n return QColor(0x00, 0x7f, 0x00);\n case Keyword:\n case ParameterKeyword:\n return QColor(0x00, 0x00, 0x7f);\n case CellmlKeyword:\n case ParameterValueKeyword:\n return QColor(0x7f, 0x00, 0x7f);\n case Number:\n case ParameterNumber:\n return QColor(0x7f, 0x7f, 0x00);\n }\n\n return QsciLexerCustom::color(pStyle);\n}\n\n\/\/==============================================================================\n\nQFont PrettyCellmlViewLexer::font(int pStyle) const\n{\n \/\/ Return the given style's colour\n\n QFont res = QsciLexer::font(pStyle);\n\n switch (pStyle) {\n case ParameterGroup:\n case ParameterKeyword:\n case ParameterValueKeyword:\n case ParameterNumber:\n res.setItalic(true);\n\n break;\n }\n\n return res;\n}\n\n\/\/==============================================================================\n\nvoid PrettyCellmlViewLexer::styleText(int pStart, int pEnd)\n{\n \/\/ Make sure that we have an editor\n\n if (!editor())\n return;\n\n \/\/ Retrieve the text to style\n\n char *data = new char[pEnd-pStart+1];\n\n editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);\n\n QString text = QString(data);\n\n delete[] data;\n\n if (text.isEmpty())\n return;\n\n \/\/ Effectively style our text\n\n mFullText = editor()->text();\n\n doStyleText(pStart, pEnd, text, false);\n}\n\n\/\/==============================================================================\n\nvoid PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,\n bool pParameterGroup)\n{\n \/\/ Make sure that we are given some text to style\n\n if (pText.trimmed().isEmpty())\n return;\n\n \/\/ Check whether a \/* XXX *\/ comment started before or at the beginning of\n \/\/ the given text\n\n static const QString StartCommentString = \"\/*\";\n static const QString EndCommentString = \"*\/\";\n static const int StartCommentLength = StartCommentString.length();\n static const int EndCommentLength = EndCommentString.length();\n\n int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength);\n\n if (commentStartPosition != -1) {\n \/\/ A \/* XXX *\/ comment started before or at the beginning of the given\n \/\/ text, so now look for where it ends\n\n int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);\n\n if (commentEndPosition == -1)\n commentEndPosition = mFullText.length();\n\n if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {\n \/\/ The beginning of the given text is a comment, so style it\n\n int realEnd = commentEndPosition+EndCommentLength;\n int end = qMin(pEnd, realEnd);\n\n startStyling(pStart, 0x1f);\n setStyling(end-pStart, Comment);\n\n \/\/ Style everything that is behind the comment, if anything\n\n if (end == realEnd)\n doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);\n\n return;\n }\n }\n\n \/\/ Check whether a parameter group started before or at the beginning of the\n \/\/ given text\n\n static const QString StartParameterGroupString = \"{\";\n static const QString EndParameterGroupString = \"}\";\n static const int StartParameterGroupLength = StartParameterGroupString.length();\n static const int EndParameterGroupLength = EndParameterGroupString.length();\n\n int parameterGroupStartPosition = mFullText.lastIndexOf(StartParameterGroupString, pStart+StartParameterGroupLength);\n\n if (parameterGroupStartPosition != -1) {\n \/\/ A parameter group started before or at the beginning of the given\n \/\/ text, so now look for where it ends\n\n int parameterGroupEndPosition = mFullText.indexOf(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);\n\n if (parameterGroupEndPosition == -1)\n parameterGroupEndPosition = mFullText.length();\n\n if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {\n \/\/ The beginning of the given text is a parameter group, so style\n \/\/ everything that is behind the parameter group, if anything\n\n int realEnd = parameterGroupEndPosition+EndParameterGroupLength;\n int end = qMin(pEnd, realEnd);\n\n if (end == realEnd)\n doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);\n\n \/\/ Style the beginning and the end of the parameter group\n\n startStyling(pStart, 0x1f);\n setStyling(StartParameterGroupLength, ParameterGroup);\n\n if (end == realEnd) {\n startStyling(end-EndParameterGroupLength, 0x1f);\n setStyling(EndParameterGroupLength, ParameterGroup);\n }\n\n \/\/ Now style the contents of the parameter group\n\n int startShift = pText.left(StartParameterGroupLength).compare(StartParameterGroupString)?0:StartParameterGroupLength;\n\n pStart += startShift;\n pEnd = end-(pText.mid(end-EndParameterGroupLength, EndParameterGroupLength).compare(EndParameterGroupString)?0:EndParameterGroupLength);\n pText = pText.mid(startShift, pEnd-pStart);\n pParameterGroup = true;\n }\n }\n\n \/\/ Check whether the given text contains a \/\/ comment\n\n static const QString CommentString = \"\/\/\";\n\n int commentPosition = pText.indexOf(CommentString);\n\n if (commentPosition != -1) {\n \/\/ There is a \/\/ comment to style, so first style everything that is\n \/\/ before the \/\/ comment\n\n doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),\n pParameterGroup);\n\n \/\/ Now, style everything that is after the \/\/ comment, if anything, by\n \/\/ looking for the end of the line on which the \/\/ comment is\n\n QString eolString = qobject_cast(editor())->eolString();\n int eolStringLength = eolString.length();\n int eolPosition = pText.indexOf(eolString, commentPosition+eolStringLength);\n\n if (eolPosition != -1) {\n int start = pStart+eolPosition+eolStringLength;\n\n doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);\n }\n\n \/\/ Style the \/\/ comment itself\n\n int start = pStart+commentPosition;\n\n startStyling(start, 0x1f);\n setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);\n\n return;\n }\n\n \/\/ Check whether the given text contains a \/* XXX *\/ comment\n\n commentStartPosition = pText.indexOf(StartCommentString);\n\n if (commentStartPosition != -1) {\n \/\/ There is a \/* XXX *\/ comment to style, so first style everything that\n \/\/ is before it\n\n doStyleText(pStart, pStart+commentStartPosition,\n pText.left(commentStartPosition), pParameterGroup);\n\n \/\/ Now style everything from the comment onwards\n \/\/ Note: to style everything from the comment onwards means that we will\n \/\/ find that a \/* XXX *\/ comment starts at the beginning of the\n \/\/ 'new' given text...\n\n doStyleText(pStart+commentStartPosition, pEnd,\n pText.right(pEnd-pStart-commentStartPosition),\n pParameterGroup);\n\n return;\n }\n\n \/\/ Check whether the given text contains a parameter group\n\n parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);\n\n if (parameterGroupStartPosition != -1) {\n \/\/ There is a parameter group, so first style everything that is before\n \/\/ it\n\n doStyleText(pStart, pStart+parameterGroupStartPosition,\n pText.left(parameterGroupStartPosition), pParameterGroup);\n\n \/\/ Now style everything from the parameter group onwards\n \/\/ Note: to style everything from the parameter group onwards means that\n \/\/ we will find that a parameter group starts at the beginning of\n \/\/ the 'new' given text...\n\n doStyleText(pStart+parameterGroupStartPosition, pEnd,\n pText.right(pEnd-pStart-parameterGroupStartPosition),\n pParameterGroup);\n\n return;\n }\n\n \/\/ Use a default style for the given text\n\n startStyling(pStart, 0x1f);\n setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);\n\n \/\/ Check whether the given text contains keywords from various categories\n\n doStyleTextKeyword(pStart, pText, mKeywords, Keyword);\n doStyleTextKeyword(pStart, pText, mCellmlKeywords, CellmlKeyword);\n doStyleTextKeyword(pStart, pText, mParameterKeywords, ParameterKeyword);\n doStyleTextKeyword(pStart, pText, mParameterValueKeywords, ParameterValueKeyword);\n}\n\n\/\/==============================================================================\n\nvoid PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,\n const QString &pText,\n const QStringList pKeywords,\n const int &pKeywordStyle)\n{\n \/\/ Check whether the given text contains some of the given keywords\n\n foreach (const QString &keyword, pKeywords) {\n QRegularExpressionMatchIterator regExMatchIter = QRegularExpression(\"\\\\b\"+keyword+\"\\\\b\").globalMatch(pText);\n\n while (regExMatchIter.hasNext()) {\n QRegularExpressionMatch regExMatch = regExMatchIter.next();\n\n \/\/ We found a keyword, so style it as such\n\n startStyling(pStart+regExMatch.capturedStart(), 0x1f);\n setStyling(regExMatch.capturedLength(), pKeywordStyle);\n }\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace PrettyCellMLView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\nPretty CellML view: some work on providing syntax highlighting for the pretty CellML format (#530) [ci skip].\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Lexer for the pretty CellML format\n\/\/==============================================================================\n\n#include \"prettycellmlviewlexer.h\"\n#include \"qscintillawidget.h\"\n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace PrettyCellMLView {\n\n\/\/==============================================================================\n\nPrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :\n QsciLexerCustom(pParent),\n mFullText(QString())\n{\n \/\/ Some initialisations\n\n mKeywords = QStringList() << \"as\" << \"comp\" << \"def\" << \"enddef\" << \"model\" << \"unit\";\n mCellmlKeywords = QStringList() << \"base\"\n << \"ampere\" << \"candela\" << \"coulomb\" << \"joule\" << \"kelvin\" << \"kilogram\" << \"liter\" << \"litre\" << \"lumen\" << \"meter\" << \"metre\" << \"mole\" << \"newton\" << \"second\" << \"steradian\" << \"volt\" << \"watt\" << \"weber\";\n mParameterKeywords = QStringList() << \"pref\" << \"expo\" << \"mult\" << \"off\";\n mParameterValueKeywords = QStringList() << \"milli\";\n}\n\n\/\/==============================================================================\n\nconst char * PrettyCellmlViewLexer::language() const\n{\n \/\/ Return the language for our lexer\n\n return \"Pretty CellML\";\n}\n\n\/\/==============================================================================\n\nQString PrettyCellmlViewLexer::description(int pStyle) const\n{\n \/\/ Return the given style's description\n\n switch (pStyle) {\n case Default:\n return QObject::tr(\"Default\");\n case Comment:\n return QObject::tr(\"Comment\");\n case Keyword:\n return QObject::tr(\"Keyword\");\n case CellmlKeyword:\n return QObject::tr(\"CellML keyword\");\n case Number:\n return QObject::tr(\"Number\");\n case ParameterGroup:\n return QObject::tr(\"Parameter group\");\n case ParameterKeyword:\n return QObject::tr(\"Parameter keyword\");\n case ParameterValueKeyword:\n return QObject::tr(\"Parameter value keyword\");\n case ParameterNumber:\n return QObject::tr(\"Parameter number\");\n }\n\n return QString();\n}\n\n\/\/==============================================================================\n\nQColor PrettyCellmlViewLexer::color(int pStyle) const\n{\n \/\/ Return the given style's colour\n\n switch (pStyle) {\n case Default:\n case ParameterGroup:\n return QColor(0x1f, 0x1f, 0x1f);\n case Comment:\n return QColor(0x00, 0x7f, 0x00);\n case Keyword:\n case ParameterKeyword:\n return QColor(0x00, 0x00, 0x7f);\n case CellmlKeyword:\n case ParameterValueKeyword:\n return QColor(0x7f, 0x00, 0x7f);\n case Number:\n case ParameterNumber:\n return QColor(0x7f, 0x7f, 0x00);\n }\n\n return QsciLexerCustom::color(pStyle);\n}\n\n\/\/==============================================================================\n\nQFont PrettyCellmlViewLexer::font(int pStyle) const\n{\n \/\/ Return the given style's colour\n\n QFont res = QsciLexer::font(pStyle);\n\n switch (pStyle) {\n case ParameterGroup:\n case ParameterKeyword:\n case ParameterValueKeyword:\n case ParameterNumber:\n res.setItalic(true);\n\n break;\n }\n\n return res;\n}\n\n\/\/==============================================================================\n\nvoid PrettyCellmlViewLexer::styleText(int pStart, int pEnd)\n{\n \/\/ Make sure that we have an editor\n\n if (!editor())\n return;\n\n \/\/ Retrieve the text to style\n\n char *data = new char[pEnd-pStart+1];\n\n editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);\n\n QString text = QString(data);\n\n delete[] data;\n\n if (text.isEmpty())\n return;\n\n \/\/ Effectively style our text\n\n mFullText = editor()->text();\n\n doStyleText(pStart, pEnd, text, false);\n}\n\n\/\/==============================================================================\n\nvoid PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,\n bool pParameterGroup)\n{\n \/\/ Make sure that we are given some text to style\n\n if (pText.trimmed().isEmpty())\n return;\n\n \/\/ Check whether a \/* XXX *\/ comment started before or at the beginning of\n \/\/ the given text\n\n static const QString StartCommentString = \"\/*\";\n static const QString EndCommentString = \"*\/\";\n static const int StartCommentLength = StartCommentString.length();\n static const int EndCommentLength = EndCommentString.length();\n\n int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength);\n\n if (commentStartPosition != -1) {\n \/\/ A \/* XXX *\/ comment started before or at the beginning of the given\n \/\/ text, so now look for where it ends\n\n int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);\n\n if (commentEndPosition == -1)\n commentEndPosition = mFullText.length();\n\n if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {\n \/\/ The beginning of the given text is a comment, so style it\n\n int realEnd = commentEndPosition+EndCommentLength;\n int end = qMin(pEnd, realEnd);\n\n startStyling(pStart, 0x1f);\n setStyling(end-pStart, Comment);\n\n \/\/ Style everything that is behind the comment, if anything\n\n if (end == realEnd)\n doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);\n\n return;\n }\n }\n\n \/\/ Check whether a parameter group started before or at the beginning of the\n \/\/ given text\n\n static const QString StartParameterGroupString = \"{\";\n static const QString EndParameterGroupString = \"}\";\n static const int StartParameterGroupLength = StartParameterGroupString.length();\n static const int EndParameterGroupLength = EndParameterGroupString.length();\n\n int parameterGroupStartPosition = mFullText.lastIndexOf(StartParameterGroupString, pStart+StartParameterGroupLength);\n\n if (parameterGroupStartPosition != -1) {\n \/\/ A parameter group started before or at the beginning of the given\n \/\/ text, so now look for where it ends\n\n int parameterGroupEndPosition = mFullText.indexOf(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);\n\n if (parameterGroupEndPosition == -1)\n parameterGroupEndPosition = mFullText.length();\n\n if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {\n \/\/ The beginning of the given text is a parameter group, so style\n \/\/ everything that is behind the parameter group, if anything\n\n int realEnd = parameterGroupEndPosition+EndParameterGroupLength;\n int end = qMin(pEnd, realEnd);\n\n if (end == realEnd)\n doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);\n\n \/\/ Style the beginning and the end of the parameter group\n\n startStyling(pStart, 0x1f);\n setStyling(StartParameterGroupLength, ParameterGroup);\n\n if (end == realEnd) {\n startStyling(end-EndParameterGroupLength, 0x1f);\n setStyling(EndParameterGroupLength, ParameterGroup);\n }\n\n \/\/ Now style the contents of the parameter group\n\n int startShift = pText.left(StartParameterGroupLength).compare(StartParameterGroupString)?0:StartParameterGroupLength;\n\n pStart += startShift;\n pEnd = end-(pText.mid(end-EndParameterGroupLength, EndParameterGroupLength).compare(EndParameterGroupString)?0:EndParameterGroupLength);\n pText = pText.mid(startShift, pEnd-pStart);\n pParameterGroup = true;\n }\n }\n\n \/\/ Check whether the given text contains a \/\/ comment\n\n static const QString CommentString = \"\/\/\";\n\n int commentPosition = pText.indexOf(CommentString);\n\n if (commentPosition != -1) {\n \/\/ There is a \/\/ comment to style, so first style everything that is\n \/\/ before the \/\/ comment\n\n doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),\n pParameterGroup);\n\n \/\/ Now, style everything that is after the \/\/ comment, if anything, by\n \/\/ looking for the end of the line on which the \/\/ comment is\n\n QString eolString = qobject_cast(editor())->eolString();\n int eolStringLength = eolString.length();\n int eolPosition = pText.indexOf(eolString, commentPosition+eolStringLength);\n\n if (eolPosition != -1) {\n int start = pStart+eolPosition+eolStringLength;\n\n doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);\n }\n\n \/\/ Style the \/\/ comment itself\n\n int start = pStart+commentPosition;\n\n startStyling(start, 0x1f);\n setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);\n\n return;\n }\n\n \/\/ Check whether the given text contains a \/* XXX *\/ comment\n\n commentStartPosition = pText.indexOf(StartCommentString);\n\n if (commentStartPosition != -1) {\n \/\/ There is a \/* XXX *\/ comment to style, so first style everything that\n \/\/ is before it\n\n doStyleText(pStart, pStart+commentStartPosition,\n pText.left(commentStartPosition), pParameterGroup);\n\n \/\/ Now style everything from the comment onwards\n \/\/ Note: to style everything from the comment onwards means that we will\n \/\/ find that a \/* XXX *\/ comment starts at the beginning of the\n \/\/ 'new' given text...\n\n doStyleText(pStart+commentStartPosition, pEnd,\n pText.right(pEnd-pStart-commentStartPosition),\n pParameterGroup);\n\n return;\n }\n\n \/\/ Check whether the given text contains a parameter group\n\n parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);\n\n if (parameterGroupStartPosition != -1) {\n \/\/ There is a parameter group, so first style everything that is before\n \/\/ it\n\n doStyleText(pStart, pStart+parameterGroupStartPosition,\n pText.left(parameterGroupStartPosition), pParameterGroup);\n\n \/\/ Now style everything from the parameter group onwards\n \/\/ Note: to style everything from the parameter group onwards means that\n \/\/ we will find that a parameter group starts at the beginning of\n \/\/ the 'new' given text...\n\n doStyleText(pStart+parameterGroupStartPosition, pEnd,\n pText.right(pEnd-pStart-parameterGroupStartPosition),\n pParameterGroup);\n\n return;\n }\n\n \/\/ Use a default style for the given text\n\n startStyling(pStart, 0x1f);\n setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);\n\n \/\/ Check whether the given text contains keywords from various categories\n\n doStyleTextKeyword(pStart, pText, mKeywords, pParameterGroup?ParameterGroup:Keyword);\n doStyleTextKeyword(pStart, pText, mCellmlKeywords, pParameterGroup?ParameterGroup:CellmlKeyword);\n doStyleTextKeyword(pStart, pText, mParameterKeywords, pParameterGroup?ParameterKeyword:Default);\n doStyleTextKeyword(pStart, pText, mParameterValueKeywords, pParameterGroup?ParameterValueKeyword:Default);\n}\n\n\/\/==============================================================================\n\nvoid PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,\n const QString &pText,\n const QStringList pKeywords,\n const int &pKeywordStyle)\n{\n \/\/ Check whether the given text contains some of the given keywords\n\n foreach (const QString &keyword, pKeywords) {\n QRegularExpressionMatchIterator regExMatchIter = QRegularExpression(\"\\\\b\"+keyword+\"\\\\b\").globalMatch(pText);\n\n while (regExMatchIter.hasNext()) {\n QRegularExpressionMatch regExMatch = regExMatchIter.next();\n\n \/\/ We found a keyword, so style it as such\n\n startStyling(pStart+regExMatch.capturedStart(), 0x1f);\n setStyling(regExMatch.capturedLength(), pKeywordStyle);\n }\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace PrettyCellMLView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"\/*\n * Rooms Model - A model of chatrooms.\n * Copyright (C) 2012 Dominik Cermak \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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"rooms-model.h\"\n#include \n#include \n\n\/\/ RoomsModel\nKTp::RoomsModel::RoomsModel(QObject *parent): QAbstractListModel(parent)\n{\n}\n\nint KTp::RoomsModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return m_roomInfoList.size();\n }\n}\n\nint KTp::RoomsModel::columnCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return 4;\n }\n}\n\nQVariant KTp::RoomsModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid()) {\n return QVariant();\n }\n\n if (index.row() >= m_roomInfoList.count()) {\n return QVariant();\n }\n\n const int row = index.row();\n const Tp::RoomInfo &roomInfo = m_roomInfoList.at(row);\n\n \/\/ this is handled here because when putting it in the switch below\n \/\/ all columns get an empty space for the decoration\n if (index.column() == PasswordColumn) {\n switch (role) {\n case Qt::DecorationRole:\n if (roomInfo.info.value(QLatin1String(\"password\")).toBool()) {\n return KIcon(QLatin1String(\"object-locked\"));\n } else {\n return QVariant();\n }\n case Qt::ToolTipRole:\n if (roomInfo.info.value(QLatin1String(\"password\")).toBool()) {\n return i18n(\"Password required\");\n } else {\n return i18n(\"No password required\");\n }\n }\n }\n\n switch(role) {\n case Qt::DisplayRole:\n switch (index.column()) {\n case PasswordColumn:\n return QVariant();\n case NameColumn:\n return roomInfo.info.value(QLatin1String(\"name\"));\n case DescriptionColumn:\n return roomInfo.info.value(QLatin1String(\"description\"));\n case MembersColumn:\n return roomInfo.info.value(QLatin1String(\"members\"));\n }\n case Qt::ToolTipRole:\n switch (index.column()) {\n case MembersColumn:\n return i18n(\"Member count\");\n }\n case RoomsModel::HandleNameRole:\n return roomInfo.info.value(QLatin1String(\"handle-name\"));\n }\n\n return QVariant();\n}\n\nQVariant KTp::RoomsModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if (role != Qt::DisplayRole && role != Qt::DecorationRole) {\n return QVariant();\n }\n\n if (orientation == Qt::Horizontal) {\n switch (role) {\n case Qt::DisplayRole:\n switch (section) {\n case NameColumn:\n return i18nc(\"Chatrooms name\", \"Name\");\n case DescriptionColumn:\n return i18nc(\"Chatrooms description\", \"Description\");\n }\n case Qt::DecorationRole:\n switch (section) {\n case PasswordColumn:\n return KIcon(QLatin1String(\"object-locked\"));\n case MembersColumn:\n return KIcon(QLatin1String(\"meeting-participant\"));\n }\n }\n }\n\n return QVariant();\n}\n\nvoid KTp::RoomsModel::addRooms(const Tp::RoomInfoList newRoomList)\n{\n if (newRoomList.size() > 0) {\n beginInsertRows(QModelIndex(), m_roomInfoList.size(), m_roomInfoList.size() + newRoomList.size() - 1);\n m_roomInfoList.append(newRoomList);\n endInsertRows();\n }\n}\n\nvoid KTp::RoomsModel::clearRoomInfoList()\n{\n if (m_roomInfoList.size() > 0) {\n beginRemoveRows(QModelIndex(), 0, m_roomInfoList.size() - 1);\n m_roomInfoList.clear();\n endRemoveRows();\n }\n}\n\n\/\/ FavoriteRoomsModel\nKTp::FavoriteRoomsModel::FavoriteRoomsModel(QObject *parent): QAbstractListModel(parent)\n{\n}\n\nint KTp::FavoriteRoomsModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return m_favoriteRoomsList.size();\n }\n}\n\nint KTp::FavoriteRoomsModel::columnCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return 3;\n }\n}\n\nQVariant KTp::FavoriteRoomsModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid()) {\n return QVariant();\n }\n\n if (index.row() >= m_favoriteRoomsList.size()) {\n return QVariant();\n }\n\n const int row = index.row();\n const QVariantMap &room = m_favoriteRoomsList.at(row);\n\n switch(role) {\n case Qt::DisplayRole:\n switch (index.column()) {\n case NameColumn:\n return room.value(QLatin1String(\"name\"));\n case HandleNameColumn:\n return room.value(QLatin1String(\"handle-name\"));\n case AccountIdentifierColumn:\n return room.value(QLatin1String(\"account-identifier\"));\n }\n case Qt::ToolTipRole:\n return room.value(QLatin1String(\"handle-name\"));\n case FavoriteRoomsModel::HandleNameRole:\n return room.value(QLatin1String(\"handle-name\"));\n case FavoriteRoomsModel::NameRole:\n return room.value(QLatin1String(\"name\"));\n case FavoriteRoomsModel::AccountRole:\n return room.value(QLatin1String(\"account-identifier\"));\n case FavoriteRoomsModel::FavoriteRoomRole:\n return QVariant::fromValue(room);\n }\n\n return QVariant();\n}\n\nbool KTp::FavoriteRoomsModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if (!index.isValid() || index.row() >= m_favoriteRoomsList.size()) {\n return false;\n }\n\n const int row = index.row();\n QVariantMap &room = m_favoriteRoomsList[row];\n\n if (role == Qt::EditRole) {\n switch (index.column()) {\n case NameColumn:\n room.insert(QLatin1String(\"name\"), value);\n break;\n case HandleNameColumn:\n room.insert(QLatin1String(\"handle-name\"), value);\n break;\n case AccountIdentifierColumn:\n room.insert(QLatin1String(\"account-identifier\"), value);\n break;\n default:\n return false;\n }\n Q_EMIT dataChanged(index, index);\n return true;\n }\n return false;\n}\n\nQt::ItemFlags KTp::FavoriteRoomsModel::flags(const QModelIndex &index) const {\n Q_UNUSED(index);\n return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n}\n\nvoid KTp::FavoriteRoomsModel::addRooms(const QList newRoomList)\n{\n if (newRoomList.size() > 0) {\n beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size() + newRoomList.size() - 1);\n m_favoriteRoomsList.append(newRoomList);\n endInsertRows();\n }\n}\n\nvoid KTp::FavoriteRoomsModel::addRoom(const QVariantMap &room)\n{\n beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size());\n m_favoriteRoomsList.append(room);\n endInsertRows();\n}\n\nvoid KTp::FavoriteRoomsModel::removeRoom(const QVariantMap &room)\n{\n int row = m_favoriteRoomsList.indexOf(room);\n beginRemoveRows(QModelIndex(), row, row);\n m_favoriteRoomsList.removeOne(room);\n endRemoveRows();\n}\n\nbool KTp::FavoriteRoomsModel::containsRoom(const QString &handle, const QString &account) const\n{\n bool contains = false;\n\n Q_FOREACH(const QVariantMap &room, m_favoriteRoomsList) {\n if ((room.value(QLatin1String(\"handle-name\")) == handle) && (room.value(QLatin1String(\"account-identifier\")) == account)) {\n contains = true;\n }\n }\n\n return contains;\n}\n\nint KTp::FavoriteRoomsModel::countForAccount(const QString &account) const\n{\n int count = 0;\n\n Q_FOREACH (const QVariantMap &room, m_favoriteRoomsList) {\n if (room.value(QLatin1String(\"account-identifier\")) == account) {\n count++;\n }\n }\n\n return count;\n}\nFavoriteRoomsModel: Return DisplayRole values for EditRole as well.\/*\n * Rooms Model - A model of chatrooms.\n * Copyright (C) 2012 Dominik Cermak \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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"rooms-model.h\"\n#include \n#include \n\n\/\/ RoomsModel\nKTp::RoomsModel::RoomsModel(QObject *parent): QAbstractListModel(parent)\n{\n}\n\nint KTp::RoomsModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return m_roomInfoList.size();\n }\n}\n\nint KTp::RoomsModel::columnCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return 4;\n }\n}\n\nQVariant KTp::RoomsModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid()) {\n return QVariant();\n }\n\n if (index.row() >= m_roomInfoList.count()) {\n return QVariant();\n }\n\n const int row = index.row();\n const Tp::RoomInfo &roomInfo = m_roomInfoList.at(row);\n\n \/\/ this is handled here because when putting it in the switch below\n \/\/ all columns get an empty space for the decoration\n if (index.column() == PasswordColumn) {\n switch (role) {\n case Qt::DecorationRole:\n if (roomInfo.info.value(QLatin1String(\"password\")).toBool()) {\n return KIcon(QLatin1String(\"object-locked\"));\n } else {\n return QVariant();\n }\n case Qt::ToolTipRole:\n if (roomInfo.info.value(QLatin1String(\"password\")).toBool()) {\n return i18n(\"Password required\");\n } else {\n return i18n(\"No password required\");\n }\n }\n }\n\n switch(role) {\n case Qt::DisplayRole:\n switch (index.column()) {\n case PasswordColumn:\n return QVariant();\n case NameColumn:\n return roomInfo.info.value(QLatin1String(\"name\"));\n case DescriptionColumn:\n return roomInfo.info.value(QLatin1String(\"description\"));\n case MembersColumn:\n return roomInfo.info.value(QLatin1String(\"members\"));\n }\n case Qt::ToolTipRole:\n switch (index.column()) {\n case MembersColumn:\n return i18n(\"Member count\");\n }\n case RoomsModel::HandleNameRole:\n return roomInfo.info.value(QLatin1String(\"handle-name\"));\n }\n\n return QVariant();\n}\n\nQVariant KTp::RoomsModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if (role != Qt::DisplayRole && role != Qt::DecorationRole) {\n return QVariant();\n }\n\n if (orientation == Qt::Horizontal) {\n switch (role) {\n case Qt::DisplayRole:\n switch (section) {\n case NameColumn:\n return i18nc(\"Chatrooms name\", \"Name\");\n case DescriptionColumn:\n return i18nc(\"Chatrooms description\", \"Description\");\n }\n case Qt::DecorationRole:\n switch (section) {\n case PasswordColumn:\n return KIcon(QLatin1String(\"object-locked\"));\n case MembersColumn:\n return KIcon(QLatin1String(\"meeting-participant\"));\n }\n }\n }\n\n return QVariant();\n}\n\nvoid KTp::RoomsModel::addRooms(const Tp::RoomInfoList newRoomList)\n{\n if (newRoomList.size() > 0) {\n beginInsertRows(QModelIndex(), m_roomInfoList.size(), m_roomInfoList.size() + newRoomList.size() - 1);\n m_roomInfoList.append(newRoomList);\n endInsertRows();\n }\n}\n\nvoid KTp::RoomsModel::clearRoomInfoList()\n{\n if (m_roomInfoList.size() > 0) {\n beginRemoveRows(QModelIndex(), 0, m_roomInfoList.size() - 1);\n m_roomInfoList.clear();\n endRemoveRows();\n }\n}\n\n\/\/ FavoriteRoomsModel\nKTp::FavoriteRoomsModel::FavoriteRoomsModel(QObject *parent): QAbstractListModel(parent)\n{\n}\n\nint KTp::FavoriteRoomsModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return m_favoriteRoomsList.size();\n }\n}\n\nint KTp::FavoriteRoomsModel::columnCount(const QModelIndex &parent) const\n{\n if (parent.isValid()) {\n return 0;\n } else {\n return 3;\n }\n}\n\nQVariant KTp::FavoriteRoomsModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid()) {\n return QVariant();\n }\n\n if (index.row() >= m_favoriteRoomsList.size()) {\n return QVariant();\n }\n\n const int row = index.row();\n const QVariantMap &room = m_favoriteRoomsList.at(row);\n\n switch(role) {\n case Qt::EditRole: \/\/ Return same values for both Display and Edit roles\n case Qt::DisplayRole:\n switch (index.column()) {\n case NameColumn:\n return room.value(QLatin1String(\"name\"));\n case HandleNameColumn:\n return room.value(QLatin1String(\"handle-name\"));\n case AccountIdentifierColumn:\n return room.value(QLatin1String(\"account-identifier\"));\n }\n case Qt::ToolTipRole:\n return room.value(QLatin1String(\"handle-name\"));\n case FavoriteRoomsModel::HandleNameRole:\n return room.value(QLatin1String(\"handle-name\"));\n case FavoriteRoomsModel::NameRole:\n return room.value(QLatin1String(\"name\"));\n case FavoriteRoomsModel::AccountRole:\n return room.value(QLatin1String(\"account-identifier\"));\n case FavoriteRoomsModel::FavoriteRoomRole:\n return QVariant::fromValue(room);\n }\n\n return QVariant();\n}\n\nbool KTp::FavoriteRoomsModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if (!index.isValid() || index.row() >= m_favoriteRoomsList.size()) {\n return false;\n }\n\n const int row = index.row();\n QVariantMap &room = m_favoriteRoomsList[row];\n\n if (role == Qt::EditRole) {\n switch (index.column()) {\n case NameColumn:\n room.insert(QLatin1String(\"name\"), value);\n break;\n case HandleNameColumn:\n room.insert(QLatin1String(\"handle-name\"), value);\n break;\n case AccountIdentifierColumn:\n room.insert(QLatin1String(\"account-identifier\"), value);\n break;\n default:\n return false;\n }\n Q_EMIT dataChanged(index, index);\n return true;\n }\n return false;\n}\n\nQt::ItemFlags KTp::FavoriteRoomsModel::flags(const QModelIndex &index) const {\n Q_UNUSED(index);\n return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n}\n\nvoid KTp::FavoriteRoomsModel::addRooms(const QList newRoomList)\n{\n if (newRoomList.size() > 0) {\n beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size() + newRoomList.size() - 1);\n m_favoriteRoomsList.append(newRoomList);\n endInsertRows();\n }\n}\n\nvoid KTp::FavoriteRoomsModel::addRoom(const QVariantMap &room)\n{\n beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size());\n m_favoriteRoomsList.append(room);\n endInsertRows();\n}\n\nvoid KTp::FavoriteRoomsModel::removeRoom(const QVariantMap &room)\n{\n int row = m_favoriteRoomsList.indexOf(room);\n beginRemoveRows(QModelIndex(), row, row);\n m_favoriteRoomsList.removeOne(room);\n endRemoveRows();\n}\n\nbool KTp::FavoriteRoomsModel::containsRoom(const QString &handle, const QString &account) const\n{\n bool contains = false;\n\n Q_FOREACH(const QVariantMap &room, m_favoriteRoomsList) {\n if ((room.value(QLatin1String(\"handle-name\")) == handle) && (room.value(QLatin1String(\"account-identifier\")) == account)) {\n contains = true;\n }\n }\n\n return contains;\n}\n\nint KTp::FavoriteRoomsModel::countForAccount(const QString &account) const\n{\n int count = 0;\n\n Q_FOREACH (const QVariantMap &room, m_favoriteRoomsList) {\n if (room.value(QLatin1String(\"account-identifier\")) == account) {\n count++;\n }\n }\n\n return count;\n}\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n* @file layoutloader.cpp\n* @author Lorenz Esch ;\n* Christoph Dinh ;\n* Matti Hamalainen ;\n* @version 1.0\n* @date September, 2014\n*\n* @section LICENSE\n*\n* Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Implementation of the LayoutLoader class\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"layoutloader.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace UTILSLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nLayoutLoader::LayoutLoader()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\nbool LayoutLoader::readAsaElcFile(QString path, QStringList &channelNames, QVector > &location3D, QVector > &location2D, QString &unit)\n{\n \/\/Open .elc file\n if(!path.contains(\".elc\"))\n return false;\n\n QFile file(path);\n if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n qDebug()<<\"Error opening elc file\";\n return false;\n }\n\n \/\/Start reading from file\n double numberElectrodes;\n QTextStream in(&file);\n bool read2D = false;\n\n while(!in.atEnd())\n {\n QString line = in.readLine();\n\n QStringList fields = line.split(QRegExp(\"\\\\s+\"));\n\n \/\/Delete last element if it is a blank character\n if(fields.at(fields.size()-1) == \"\")\n fields.removeLast();\n\n if(!line.contains(\"#\")) \/\/Skip commented areas in file\n {\n \/\/Read number of electrodes\n if(line.contains(\"NumberPositions\"))\n numberElectrodes = fields.at(1).toDouble();\n\n \/\/Read the unit of the position values\n if(line.contains(\"UnitPosition\"))\n unit = fields.at(1);\n\n \/\/Read actual electrode positions\n if(line.contains(\"Positions2D\"))\n read2D = true;\n\n if(line.contains(\":\") && !read2D) \/\/Read 3D positions\n {\n channelNames.push_back(fields.at(0));\n QVector posTemp;\n\n posTemp.push_back(fields.at(fields.size()-3).toDouble()); \/\/x\n posTemp.push_back(fields.at(fields.size()-2).toDouble()); \/\/y\n posTemp.push_back(fields.at(fields.size()-1).toDouble()); \/\/z\n\n location3D.push_back(posTemp);\n }\n\n if(line.contains(\":\") && read2D) \/\/Read 2D positions\n {\n QVector posTemp;\n posTemp.push_back(fields.at(fields.size()-2).toDouble()); \/\/x\n posTemp.push_back(fields.at(fields.size()-1).toDouble()); \/\/y\n location2D.push_back(posTemp);\n }\n\n \/\/Read channel names\n if(line.contains(\"Labels\"))\n {\n line = in.readLine();\n fields = line.split(QRegExp(\"\\\\s+\"));\n\n \/\/Delete last element if it is a blank character\n if(fields.at(fields.size()-1) == \"\")\n fields.removeLast();\n\n channelNames = fields;\n }\n }\n }\n\n Q_UNUSED(numberElectrodes);\n\n file.close();\n\n return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nbool LayoutLoader::readMNELoutFile(QString path, QMap &channelData)\n{\n \/\/Open .elc file\n if(!path.contains(\".lout\"))\n return false;\n\n channelData.clear();\n\n QFile file(path);\n if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n qDebug()<<\"Error opening mne lout file\";\n return false;\n }\n\n \/\/Start reading from file\n QTextStream in(&file);\n\n \/\/skip first line\n in.readLine();\n\n while(!in.atEnd()) {\n QString line = in.readLine();\n\n QStringList fields = line.split(QRegExp(\"\\\\s+\"));\n\n \/\/Delete last element if it is a blank character\n if(fields.at(fields.size()-1) == \"\")\n fields.removeLast();\n\n QPointF posTemp;\n posTemp.setX(fields.at(1).toDouble()); \/\/x\n posTemp.setY(fields.at(2).toDouble()); \/\/y\n\n \/\/Create channel data map entry\n QString key = QString(\"%1 %2\").arg(fields.at(fields.size()-2)).arg(fields.at(fields.size()-1));\n channelData.insert(key, posTemp);\n }\n\n file.close();\n\n return true;\n}\nmissing unix include\/\/=============================================================================================================\n\/**\n* @file layoutloader.cpp\n* @author Lorenz Esch ;\n* Christoph Dinh ;\n* Matti Hamalainen ;\n* @version 1.0\n* @date September, 2014\n*\n* @section LICENSE\n*\n* Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Implementation of the LayoutLoader class\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"layoutloader.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Qt INCLUDES\n\/\/=============================================================================================================\n\n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace UTILSLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nLayoutLoader::LayoutLoader()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\nbool LayoutLoader::readAsaElcFile(QString path, QStringList &channelNames, QVector > &location3D, QVector > &location2D, QString &unit)\n{\n \/\/Open .elc file\n if(!path.contains(\".elc\"))\n return false;\n\n QFile file(path);\n if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n qDebug()<<\"Error opening elc file\";\n return false;\n }\n\n \/\/Start reading from file\n double numberElectrodes;\n QTextStream in(&file);\n bool read2D = false;\n\n while(!in.atEnd())\n {\n QString line = in.readLine();\n\n QStringList fields = line.split(QRegExp(\"\\\\s+\"));\n\n \/\/Delete last element if it is a blank character\n if(fields.at(fields.size()-1) == \"\")\n fields.removeLast();\n\n if(!line.contains(\"#\")) \/\/Skip commented areas in file\n {\n \/\/Read number of electrodes\n if(line.contains(\"NumberPositions\"))\n numberElectrodes = fields.at(1).toDouble();\n\n \/\/Read the unit of the position values\n if(line.contains(\"UnitPosition\"))\n unit = fields.at(1);\n\n \/\/Read actual electrode positions\n if(line.contains(\"Positions2D\"))\n read2D = true;\n\n if(line.contains(\":\") && !read2D) \/\/Read 3D positions\n {\n channelNames.push_back(fields.at(0));\n QVector posTemp;\n\n posTemp.push_back(fields.at(fields.size()-3).toDouble()); \/\/x\n posTemp.push_back(fields.at(fields.size()-2).toDouble()); \/\/y\n posTemp.push_back(fields.at(fields.size()-1).toDouble()); \/\/z\n\n location3D.push_back(posTemp);\n }\n\n if(line.contains(\":\") && read2D) \/\/Read 2D positions\n {\n QVector posTemp;\n posTemp.push_back(fields.at(fields.size()-2).toDouble()); \/\/x\n posTemp.push_back(fields.at(fields.size()-1).toDouble()); \/\/y\n location2D.push_back(posTemp);\n }\n\n \/\/Read channel names\n if(line.contains(\"Labels\"))\n {\n line = in.readLine();\n fields = line.split(QRegExp(\"\\\\s+\"));\n\n \/\/Delete last element if it is a blank character\n if(fields.at(fields.size()-1) == \"\")\n fields.removeLast();\n\n channelNames = fields;\n }\n }\n }\n\n Q_UNUSED(numberElectrodes);\n\n file.close();\n\n return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nbool LayoutLoader::readMNELoutFile(QString path, QMap &channelData)\n{\n \/\/Open .elc file\n if(!path.contains(\".lout\"))\n return false;\n\n channelData.clear();\n\n QFile file(path);\n if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n qDebug()<<\"Error opening mne lout file\";\n return false;\n }\n\n \/\/Start reading from file\n QTextStream in(&file);\n\n \/\/skip first line\n in.readLine();\n\n while(!in.atEnd()) {\n QString line = in.readLine();\n\n QStringList fields = line.split(QRegExp(\"\\\\s+\"));\n\n \/\/Delete last element if it is a blank character\n if(fields.at(fields.size()-1) == \"\")\n fields.removeLast();\n\n QPointF posTemp;\n posTemp.setX(fields.at(1).toDouble()); \/\/x\n posTemp.setY(fields.at(2).toDouble()); \/\/y\n\n \/\/Create channel data map entry\n QString key = QString(\"%1 %2\").arg(fields.at(fields.size()-2)).arg(fields.at(fields.size()-1));\n channelData.insert(key, posTemp);\n }\n\n file.close();\n\n return true;\n}\n<|endoftext|>"} {"text":"fixed warnings<|endoftext|>"} {"text":"#include \"dreal\/api\/api.h\"\n\n#include \n\n#include \"dreal\/solver\/formula_evaluator.h\"\n\nnamespace dreal {\nnamespace {\n\nclass ApiTest : public ::testing::Test {\n protected:\n const Variable x_{\"x\", Variable::Type::CONTINUOUS};\n const Variable y_{\"y\", Variable::Type::CONTINUOUS};\n const Variable z_{\"z\", Variable::Type::CONTINUOUS};\n};\n\n::testing::AssertionResult CheckSolution(const Formula& f,\n const Box& solution) {\n FormulaEvaluator formula_evaluator{\n make_relational_formula_evaluator(f, solution.variables())};\n const FormulaEvaluationResult formula_evaluation_result{\n formula_evaluator(solution)};\n if (formula_evaluation_result.type() ==\n FormulaEvaluationResult::Type::UNSAT) {\n return ::testing::AssertionFailure() << \"UNSAT detected!\";\n }\n if (!formula_evaluation_result.evaluation().contains(0.0)) {\n return ::testing::AssertionFailure() << \"The interval evaluation indicates \"\n \"that the solution does not \"\n \"satisfy the constraint.\";\n }\n return ::testing::AssertionSuccess();\n}\n\n\/\/ Tests CheckSatisfiability (δ-SAT case).\nTEST_F(ApiTest, CheckSatisfiability_DeltaSat) {\n \/\/ 0 ≤ x ≤ 5\n \/\/ 0 ≤ y ≤ 5\n \/\/ 0 ≤ z ≤ 5\n \/\/ 2x + y = z\n const Formula f1{0 <= x_ && x_ <= 5};\n const Formula f2{0 <= y_ && y_ <= 5};\n const Formula f3{0 <= z_ && z_ <= 5};\n const Formula f4{2 * x_ + y_ == z_};\n\n \/\/ Checks the API returning an optional.\n {\n auto result = CheckSatisfiability(f1 && f2 && f3 && f4, 0.001);\n ASSERT_TRUE(result);\n EXPECT_TRUE(CheckSolution(f4, *result));\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result{CheckSatisfiability(f1 && f2 && f3 && f4, 0.001, &b)};\n ASSERT_TRUE(result);\n EXPECT_TRUE(CheckSolution(f4, b));\n }\n}\n\n\/\/ Tests CheckSatisfiability (UNSAT case).\nTEST_F(ApiTest, CheckSatisfiability_Unsat) {\n \/\/ 2x² + 6x + 5 < 0\n \/\/ -10 ≤ x ≤ 10\n const Formula f1{2 * x_ * x_ + 6 * x_ + 5 < 0};\n const Formula f2{-10 <= x_ && x_ <= 10};\n\n \/\/ Checks the API returning an optional.\n {\n auto result = CheckSatisfiability(f1 && f2, 0.001);\n EXPECT_FALSE(result);\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result{CheckSatisfiability(f1 && f2, 0.001, &b)};\n EXPECT_FALSE(result);\n }\n}\n\nTEST_F(ApiTest, Minimize1) {\n \/\/ minimize 2x² + 6x + 5 s.t. -4 ≤ x ≤ 0\n const Expression objective{2 * x_ * x_ + 6 * x_ + 5};\n const Formula constraint{-10 <= x_ && x_ <= 10};\n const double delta{0.01};\n const double known_minimum = 0.5;\n\n \/\/ Checks the API returning an optional.\n {\n const auto result = Minimize(objective, constraint, delta);\n ASSERT_TRUE(result);\n const double x = (*result)[x_].mid();\n EXPECT_TRUE(-10 <= x && x <= 10);\n EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta);\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result = Minimize(objective, constraint, delta, &b);\n ASSERT_TRUE(result);\n const double x = b[x_].mid();\n EXPECT_TRUE(-10 <= x && x <= 10);\n EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta);\n }\n}\n\nTEST_F(ApiTest, Minimize2) {\n \/\/ minimize sin(3x) - 2cos(x) s.t. -3 ≤ x ≤ 3\n const Expression objective{sin(3 * x_) - 2 * cos(x_)};\n const Formula constraint{-3 <= x_ && x_ <= 3};\n const double delta{0.001};\n const double known_minimum = -2.77877;\n\n \/\/ Checks the API returning an optional.\n {\n const auto result = Minimize(objective, constraint, delta);\n ASSERT_TRUE(result);\n const double x = (*result)[x_].mid();\n EXPECT_TRUE(-3 <= x && x <= 3);\n EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta);\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result = Minimize(objective, constraint, delta, &b);\n ASSERT_TRUE(result);\n const double x = b[x_].mid();\n EXPECT_TRUE(-3 <= x && x <= 3);\n EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta);\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace dreal\ntest(api\/api_test.cc): Add CheckSatisfiabilityMixedBooleanAndContinuous#include \"dreal\/api\/api.h\"\n\n#include \n#include \n\n#include \"dreal\/solver\/formula_evaluator.h\"\n\nnamespace dreal {\nnamespace {\n\nclass ApiTest : public ::testing::Test {\n protected:\n const Variable x_{\"x\", Variable::Type::CONTINUOUS};\n const Variable y_{\"y\", Variable::Type::CONTINUOUS};\n const Variable z_{\"z\", Variable::Type::CONTINUOUS};\n};\n\n::testing::AssertionResult CheckSolution(const Formula& f,\n const Box& solution) {\n FormulaEvaluator formula_evaluator{\n make_relational_formula_evaluator(f, solution.variables())};\n const FormulaEvaluationResult formula_evaluation_result{\n formula_evaluator(solution)};\n if (formula_evaluation_result.type() ==\n FormulaEvaluationResult::Type::UNSAT) {\n return ::testing::AssertionFailure() << \"UNSAT detected!\";\n }\n if (!formula_evaluation_result.evaluation().contains(0.0)) {\n return ::testing::AssertionFailure() << \"The interval evaluation indicates \"\n \"that the solution does not \"\n \"satisfy the constraint.\";\n }\n return ::testing::AssertionSuccess();\n}\n\n\/\/ Tests CheckSatisfiability (δ-SAT case).\nTEST_F(ApiTest, CheckSatisfiabilityMixedBooleanAndContinuous) {\n const Variable b1{\"b1\", Variable::Type::BOOLEAN};\n const Variable b2{\"b2\", Variable::Type::BOOLEAN};\n const auto result = CheckSatisfiability(\n !b1 && b2 && (sin(x_) == 1) && x_ > 0 && x_ < 2 * 3.141592, 0.001);\n ASSERT_TRUE(result);\n EXPECT_EQ((*result)[b1], 0.0);\n EXPECT_EQ((*result)[b2], 1.0);\n EXPECT_NEAR(std::sin((*result)[x_].mid()), 1.0, 0.001);\n}\n\n\/\/ Tests CheckSatisfiability (δ-SAT case).\nTEST_F(ApiTest, CheckSatisfiabilityDeltaSat) {\n \/\/ 0 ≤ x ≤ 5\n \/\/ 0 ≤ y ≤ 5\n \/\/ 0 ≤ z ≤ 5\n \/\/ 2x + y = z\n const Formula f1{0 <= x_ && x_ <= 5};\n const Formula f2{0 <= y_ && y_ <= 5};\n const Formula f3{0 <= z_ && z_ <= 5};\n const Formula f4{2 * x_ + y_ == z_};\n\n \/\/ Checks the API returning an optional.\n {\n auto result = CheckSatisfiability(f1 && f2 && f3 && f4, 0.001);\n ASSERT_TRUE(result);\n EXPECT_TRUE(CheckSolution(f4, *result));\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result{CheckSatisfiability(f1 && f2 && f3 && f4, 0.001, &b)};\n ASSERT_TRUE(result);\n EXPECT_TRUE(CheckSolution(f4, b));\n }\n}\n\n\/\/ Tests CheckSatisfiability (UNSAT case).\nTEST_F(ApiTest, CheckSatisfiabilityUnsat) {\n \/\/ 2x² + 6x + 5 < 0\n \/\/ -10 ≤ x ≤ 10\n const Formula f1{2 * x_ * x_ + 6 * x_ + 5 < 0};\n const Formula f2{-10 <= x_ && x_ <= 10};\n\n \/\/ Checks the API returning an optional.\n {\n auto result = CheckSatisfiability(f1 && f2, 0.001);\n EXPECT_FALSE(result);\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result{CheckSatisfiability(f1 && f2, 0.001, &b)};\n EXPECT_FALSE(result);\n }\n}\n\nTEST_F(ApiTest, Minimize1) {\n \/\/ minimize 2x² + 6x + 5 s.t. -4 ≤ x ≤ 0\n const Expression objective{2 * x_ * x_ + 6 * x_ + 5};\n const Formula constraint{-10 <= x_ && x_ <= 10};\n const double delta{0.01};\n const double known_minimum = 0.5;\n\n \/\/ Checks the API returning an optional.\n {\n const auto result = Minimize(objective, constraint, delta);\n ASSERT_TRUE(result);\n const double x = (*result)[x_].mid();\n EXPECT_TRUE(-10 <= x && x <= 10);\n EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta);\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result = Minimize(objective, constraint, delta, &b);\n ASSERT_TRUE(result);\n const double x = b[x_].mid();\n EXPECT_TRUE(-10 <= x && x <= 10);\n EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta);\n }\n}\n\nTEST_F(ApiTest, Minimize2) {\n \/\/ minimize sin(3x) - 2cos(x) s.t. -3 ≤ x ≤ 3\n const Expression objective{sin(3 * x_) - 2 * cos(x_)};\n const Formula constraint{-3 <= x_ && x_ <= 3};\n const double delta{0.001};\n const double known_minimum = -2.77877;\n\n \/\/ Checks the API returning an optional.\n {\n const auto result = Minimize(objective, constraint, delta);\n ASSERT_TRUE(result);\n const double x = (*result)[x_].mid();\n EXPECT_TRUE(-3 <= x && x <= 3);\n EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta);\n }\n\n \/\/ Checks the API returning a bool.\n {\n Box b;\n const bool result = Minimize(objective, constraint, delta, &b);\n ASSERT_TRUE(result);\n const double x = b[x_].mid();\n EXPECT_TRUE(-3 <= x && x <= 3);\n EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta);\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace dreal\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager.h\"\n\n#include \"base\/logging.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility_state_impl.h\"\n#include \"content\/common\/accessibility_messages.h\"\n\nnamespace content {\n\nBrowserAccessibility* BrowserAccessibilityFactory::Create() {\n return BrowserAccessibility::Create();\n}\n\n\/\/ Start child IDs at -1 and decrement each time, because clients use\n\/\/ child IDs of 1, 2, 3, ... to access the children of an object by\n\/\/ index, so we use negative IDs to clearly distinguish between indices\n\/\/ and unique IDs.\n\/\/ static\nint32 BrowserAccessibilityManager::next_child_id_ = -1;\n\n#if !defined(OS_MACOSX) && \\\n !(defined(OS_WIN) && !defined(USE_AURA)) && \\\n !defined(TOOLKIT_GTK)\n\/\/ We have subclassess of BrowserAccessibilityManager on Mac, Linux\/GTK,\n\/\/ and non-Aura Win. For any other platform, instantiate the base class.\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n gfx::NativeView parent_view,\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManager(\n parent_view, src, delegate, factory);\n}\n#endif\n\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(\n gfx::NativeView parent_view,\n AccessibilityNodeData::State state,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n \/\/ Use empty document to process notifications\n AccessibilityNodeData empty_document;\n empty_document.id = 0;\n empty_document.role = AccessibilityNodeData::ROLE_ROOT_WEB_AREA;\n empty_document.state = state | (1 << AccessibilityNodeData::STATE_READONLY);\n return BrowserAccessibilityManager::Create(\n parent_view, empty_document, delegate, factory);\n}\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n gfx::NativeView parent_view,\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : parent_view_(parent_view),\n delegate_(delegate),\n factory_(factory),\n root_(NULL),\n focus_(NULL),\n osk_state_(OSK_ALLOWED) {\n std::vector nodes;\n nodes.push_back(src);\n if (!UpdateNodes(nodes))\n return;\n if (!focus_)\n SetFocus(root_, false);\n}\n\n\/\/ static\nint32 BrowserAccessibilityManager::GetNextChildID() {\n \/\/ Get the next child ID, and wrap around when we get near the end\n \/\/ of a 32-bit integer range. It's okay to wrap around; we just want\n \/\/ to avoid it as long as possible because clients may cache the ID of\n \/\/ an object for a while to determine if they've seen it before.\n next_child_id_--;\n if (next_child_id_ == -2000000000)\n next_child_id_ = -1;\n\n return next_child_id_;\n}\n\nBrowserAccessibilityManager::~BrowserAccessibilityManager() {\n if (root_)\n root_->Destroy();\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetRoot() {\n return root_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(\n int32 child_id) {\n base::hash_map::iterator iter =\n child_id_map_.find(child_id);\n if (iter != child_id_map_.end()) {\n return iter->second;\n } else {\n return NULL;\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(\n int32 renderer_id) {\n base::hash_map::iterator iter =\n renderer_id_to_child_id_map_.find(renderer_id);\n if (iter == renderer_id_to_child_id_map_.end())\n return NULL;\n\n int32 child_id = iter->second;\n return GetFromChildID(child_id);\n}\n\nvoid BrowserAccessibilityManager::GotFocus(bool touch_event_context) {\n if (!touch_event_context)\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED;\n\n if (!focus_)\n return;\n\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n}\n\nvoid BrowserAccessibilityManager::WasHidden() {\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_HIDDEN;\n}\n\nvoid BrowserAccessibilityManager::GotMouseDown() {\n osk_state_ = OSK_ALLOWED_WITHIN_FOCUSED_OBJECT;\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n}\n\nbool BrowserAccessibilityManager::IsOSKAllowed(const gfx::Rect& bounds) {\n if (!delegate_ || !delegate_->HasFocus())\n return false;\n\n gfx::Point touch_point = delegate_->GetLastTouchEventLocation();\n return bounds.Contains(touch_point);\n}\n\nvoid BrowserAccessibilityManager::Remove(BrowserAccessibility* node) {\n if (node == focus_)\n SetFocus(root_, false);\n int child_id = node->child_id();\n int renderer_id = node->renderer_id();\n child_id_map_.erase(child_id);\n DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);\n \/\/ Make sure we don't overwrite a newer entry (see UpdateNode for a possible\n \/\/ corner case).\n if (renderer_id_to_child_id_map_[renderer_id] == child_id)\n renderer_id_to_child_id_map_.erase(renderer_id);\n}\n\nvoid BrowserAccessibilityManager::OnAccessibilityNotifications(\n const std::vector& params) {\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_NotificationParams& param = params[index];\n\n \/\/ Update nodes that changed.\n if (!UpdateNodes(param.nodes))\n return;\n\n \/\/ Find the node corresponding to the id that's the target of the\n \/\/ notification (which may not be the root of the update tree).\n BrowserAccessibility* node = GetFromRendererID(param.id);\n if (!node)\n continue;\n\n int notification_type = param.notification_type;\n if (notification_type == AccessibilityNotificationFocusChanged ||\n notification_type == AccessibilityNotificationBlur) {\n SetFocus(node, false);\n\n if (osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_HIDDEN &&\n osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED)\n osk_state_ = OSK_ALLOWED;\n\n \/\/ Don't send a native focus event if the window itself doesn't\n \/\/ have focus.\n if (delegate_ && !delegate_->HasFocus())\n continue;\n }\n\n \/\/ Send the notification event to the operating system.\n NotifyAccessibilityEvent(notification_type, node);\n\n \/\/ Set initial focus when a page is loaded.\n if (notification_type == AccessibilityNotificationLoadComplete) {\n if (!focus_)\n SetFocus(root_, false);\n if (!delegate_ || delegate_->HasFocus())\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n }\n }\n}\n\ngfx::NativeView BrowserAccessibilityManager::GetParentView() {\n return parent_view_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFocus(\n BrowserAccessibility* root) {\n if (focus_ && (!root || focus_->IsDescendantOf(root)))\n return focus_;\n\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::SetFocus(\n BrowserAccessibility* node, bool notify) {\n if (focus_ != node)\n focus_ = node;\n\n if (notify && node && delegate_)\n delegate_->SetAccessibilityFocus(node->renderer_id());\n}\n\nvoid BrowserAccessibilityManager::DoDefaultAction(\n const BrowserAccessibility& node) {\n if (delegate_)\n delegate_->AccessibilityDoDefaultAction(node.renderer_id());\n}\n\nvoid BrowserAccessibilityManager::ScrollToMakeVisible(\n const BrowserAccessibility& node, gfx::Rect subfocus) {\n if (delegate_) {\n delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);\n }\n}\n\nvoid BrowserAccessibilityManager::ScrollToPoint(\n const BrowserAccessibility& node, gfx::Point point) {\n if (delegate_) {\n delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);\n }\n}\n\nvoid BrowserAccessibilityManager::SetTextSelection(\n const BrowserAccessibility& node, int start_offset, int end_offset) {\n if (delegate_) {\n delegate_->AccessibilitySetTextSelection(\n node.renderer_id(), start_offset, end_offset);\n }\n}\n\ngfx::Rect BrowserAccessibilityManager::GetViewBounds() {\n if (delegate_)\n return delegate_->GetViewBounds();\n return gfx::Rect();\n}\n\nvoid BrowserAccessibilityManager::UpdateNodesForTesting(\n const AccessibilityNodeData& node1,\n const AccessibilityNodeData& node2 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node3 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node4 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node5 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node6 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node7 \/* = AccessibilityNodeData() *\/) {\n std::vector nodes;\n nodes.push_back(node1);\n if (node2.id != AccessibilityNodeData().id)\n nodes.push_back(node2);\n if (node3.id != AccessibilityNodeData().id)\n nodes.push_back(node3);\n if (node4.id != AccessibilityNodeData().id)\n nodes.push_back(node4);\n if (node5.id != AccessibilityNodeData().id)\n nodes.push_back(node5);\n if (node6.id != AccessibilityNodeData().id)\n nodes.push_back(node6);\n if (node7.id != AccessibilityNodeData().id)\n nodes.push_back(node7);\n UpdateNodes(nodes);\n}\n\nbool BrowserAccessibilityManager::UpdateNodes(\n const std::vector& nodes) {\n bool success = true;\n\n \/\/ First, update all of the nodes in the tree.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n if (!UpdateNode(nodes[i]))\n success = false;\n }\n\n \/\/ In a second pass, call PostInitialize on each one - this must\n \/\/ be called after all of each node's children are initialized too.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n BrowserAccessibility* instance = GetFromRendererID(nodes[i].id);\n if (instance) {\n instance->PostInitialize();\n } else {\n success = false;\n }\n }\n\n if (!success) {\n \/\/ A bad accessibility tree could lead to memory corruption.\n \/\/ Ask the delegate to crash the renderer, or if not available,\n \/\/ crash the browser.\n if (delegate_)\n delegate_->FatalAccessibilityTreeError();\n else\n CHECK(false);\n }\n\n return success;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::CreateNode(\n BrowserAccessibility* parent,\n int32 renderer_id,\n int32 index_in_parent) {\n BrowserAccessibility* instance = factory_->Create();\n int32 child_id = GetNextChildID();\n instance->InitializeTreeStructure(\n this, parent, child_id, renderer_id, index_in_parent);\n child_id_map_[child_id] = instance;\n renderer_id_to_child_id_map_[renderer_id] = child_id;\n return instance;\n}\n\nbool BrowserAccessibilityManager::UpdateNode(const AccessibilityNodeData& src) {\n \/\/ This method updates one node in the tree based on serialized data\n \/\/ received from the renderer. First, look up the node by id. If it's\n \/\/ not found, then either the root of the tree is being swapped, or\n \/\/ we're out of sync with the renderer and this is a serious error.\n BrowserAccessibility* instance = GetFromRendererID(src.id);\n if (!instance) {\n if (src.role != AccessibilityNodeData::ROLE_ROOT_WEB_AREA)\n return false;\n instance = CreateNode(NULL, src.id, 0);\n }\n\n \/\/ Update all of the node-specific data, like its role, state, name, etc.\n instance->InitializeData(src);\n\n \/\/\n \/\/ Update the children in three steps:\n \/\/\n \/\/ 1. Iterate over the old children and delete nodes that are no longer\n \/\/ in the tree.\n \/\/ 2. Build up a vector of new children, reusing children that haven't\n \/\/ changed (but may have been reordered) and adding new empty\n \/\/ objects for new children.\n \/\/ 3. Swap in the new children vector for the old one.\n\n \/\/ Delete any previous children of this instance that are no longer\n \/\/ children first. We make a deletion-only pass first to prevent a\n \/\/ node that's being reparented from being the child of both its old\n \/\/ parent and new parent, which could lead to a double-free.\n \/\/ If a node is reparented, the renderer will always send us a fresh\n \/\/ copy of the node.\n std::set new_child_ids;\n for (size_t i = 0; i < src.child_ids.size(); ++i) {\n if (new_child_ids.find(src.child_ids[i]) != new_child_ids.end())\n return false;\n new_child_ids.insert(src.child_ids[i]);\n }\n const std::vector& old_children = instance->children();\n for (size_t i = 0; i < old_children.size(); ++i) {\n int old_id = old_children[i]->renderer_id();\n if (new_child_ids.find(old_id) == new_child_ids.end())\n old_children[i]->Destroy();\n }\n\n \/\/ Now build a vector of new children, reusing objects that were already\n \/\/ children of this node before.\n std::vector new_children;\n for (size_t i = 0; i < src.child_ids.size(); i++) {\n int32 child_renderer_id = src.child_ids[i];\n int32 index_in_parent = static_cast(i);\n BrowserAccessibility* child = GetFromRendererID(child_renderer_id);\n if (child) {\n if (child->parent() != instance) {\n instance->SwapChildren(new_children);\n return false;\n }\n child->UpdateParent(instance, index_in_parent);\n } else {\n child = CreateNode(instance, child_renderer_id, index_in_parent);\n }\n new_children.push_back(child);\n }\n\n \/\/ Finally, swap in the new children vector for the old.\n instance->SwapChildren(new_children);\n\n \/\/ Handle the case where this node is the new root of the tree.\n if (src.role == AccessibilityNodeData::ROLE_ROOT_WEB_AREA &&\n (!root_ || root_->renderer_id() != src.id)) {\n if (root_)\n root_->Destroy();\n if (focus_ == root_)\n focus_ = instance;\n root_ = instance;\n }\n\n \/\/ Keep track of what node is focused.\n if ((src.state >> AccessibilityNodeData::STATE_FOCUSED) & 1)\n SetFocus(instance, false);\n\n return true;\n}\n\n} \/\/ namespace content\nFix memory leak in BrowserAccessibilityManager::UpdateNode.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager.h\"\n\n#include \"base\/logging.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility_state_impl.h\"\n#include \"content\/common\/accessibility_messages.h\"\n\nnamespace content {\n\nBrowserAccessibility* BrowserAccessibilityFactory::Create() {\n return BrowserAccessibility::Create();\n}\n\n\/\/ Start child IDs at -1 and decrement each time, because clients use\n\/\/ child IDs of 1, 2, 3, ... to access the children of an object by\n\/\/ index, so we use negative IDs to clearly distinguish between indices\n\/\/ and unique IDs.\n\/\/ static\nint32 BrowserAccessibilityManager::next_child_id_ = -1;\n\n#if !defined(OS_MACOSX) && \\\n !(defined(OS_WIN) && !defined(USE_AURA)) && \\\n !defined(TOOLKIT_GTK)\n\/\/ We have subclassess of BrowserAccessibilityManager on Mac, Linux\/GTK,\n\/\/ and non-Aura Win. For any other platform, instantiate the base class.\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n gfx::NativeView parent_view,\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManager(\n parent_view, src, delegate, factory);\n}\n#endif\n\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(\n gfx::NativeView parent_view,\n AccessibilityNodeData::State state,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n \/\/ Use empty document to process notifications\n AccessibilityNodeData empty_document;\n empty_document.id = 0;\n empty_document.role = AccessibilityNodeData::ROLE_ROOT_WEB_AREA;\n empty_document.state = state | (1 << AccessibilityNodeData::STATE_READONLY);\n return BrowserAccessibilityManager::Create(\n parent_view, empty_document, delegate, factory);\n}\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n gfx::NativeView parent_view,\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : parent_view_(parent_view),\n delegate_(delegate),\n factory_(factory),\n root_(NULL),\n focus_(NULL),\n osk_state_(OSK_ALLOWED) {\n std::vector nodes;\n nodes.push_back(src);\n if (!UpdateNodes(nodes))\n return;\n if (!focus_)\n SetFocus(root_, false);\n}\n\n\/\/ static\nint32 BrowserAccessibilityManager::GetNextChildID() {\n \/\/ Get the next child ID, and wrap around when we get near the end\n \/\/ of a 32-bit integer range. It's okay to wrap around; we just want\n \/\/ to avoid it as long as possible because clients may cache the ID of\n \/\/ an object for a while to determine if they've seen it before.\n next_child_id_--;\n if (next_child_id_ == -2000000000)\n next_child_id_ = -1;\n\n return next_child_id_;\n}\n\nBrowserAccessibilityManager::~BrowserAccessibilityManager() {\n if (root_)\n root_->Destroy();\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetRoot() {\n return root_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(\n int32 child_id) {\n base::hash_map::iterator iter =\n child_id_map_.find(child_id);\n if (iter != child_id_map_.end()) {\n return iter->second;\n } else {\n return NULL;\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(\n int32 renderer_id) {\n base::hash_map::iterator iter =\n renderer_id_to_child_id_map_.find(renderer_id);\n if (iter == renderer_id_to_child_id_map_.end())\n return NULL;\n\n int32 child_id = iter->second;\n return GetFromChildID(child_id);\n}\n\nvoid BrowserAccessibilityManager::GotFocus(bool touch_event_context) {\n if (!touch_event_context)\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED;\n\n if (!focus_)\n return;\n\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n}\n\nvoid BrowserAccessibilityManager::WasHidden() {\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_HIDDEN;\n}\n\nvoid BrowserAccessibilityManager::GotMouseDown() {\n osk_state_ = OSK_ALLOWED_WITHIN_FOCUSED_OBJECT;\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n}\n\nbool BrowserAccessibilityManager::IsOSKAllowed(const gfx::Rect& bounds) {\n if (!delegate_ || !delegate_->HasFocus())\n return false;\n\n gfx::Point touch_point = delegate_->GetLastTouchEventLocation();\n return bounds.Contains(touch_point);\n}\n\nvoid BrowserAccessibilityManager::Remove(BrowserAccessibility* node) {\n if (node == focus_)\n SetFocus(root_, false);\n int child_id = node->child_id();\n int renderer_id = node->renderer_id();\n child_id_map_.erase(child_id);\n DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);\n \/\/ Make sure we don't overwrite a newer entry (see UpdateNode for a possible\n \/\/ corner case).\n if (renderer_id_to_child_id_map_[renderer_id] == child_id)\n renderer_id_to_child_id_map_.erase(renderer_id);\n}\n\nvoid BrowserAccessibilityManager::OnAccessibilityNotifications(\n const std::vector& params) {\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_NotificationParams& param = params[index];\n\n \/\/ Update nodes that changed.\n if (!UpdateNodes(param.nodes))\n return;\n\n \/\/ Find the node corresponding to the id that's the target of the\n \/\/ notification (which may not be the root of the update tree).\n BrowserAccessibility* node = GetFromRendererID(param.id);\n if (!node)\n continue;\n\n int notification_type = param.notification_type;\n if (notification_type == AccessibilityNotificationFocusChanged ||\n notification_type == AccessibilityNotificationBlur) {\n SetFocus(node, false);\n\n if (osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_HIDDEN &&\n osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED)\n osk_state_ = OSK_ALLOWED;\n\n \/\/ Don't send a native focus event if the window itself doesn't\n \/\/ have focus.\n if (delegate_ && !delegate_->HasFocus())\n continue;\n }\n\n \/\/ Send the notification event to the operating system.\n NotifyAccessibilityEvent(notification_type, node);\n\n \/\/ Set initial focus when a page is loaded.\n if (notification_type == AccessibilityNotificationLoadComplete) {\n if (!focus_)\n SetFocus(root_, false);\n if (!delegate_ || delegate_->HasFocus())\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n }\n }\n}\n\ngfx::NativeView BrowserAccessibilityManager::GetParentView() {\n return parent_view_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFocus(\n BrowserAccessibility* root) {\n if (focus_ && (!root || focus_->IsDescendantOf(root)))\n return focus_;\n\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::SetFocus(\n BrowserAccessibility* node, bool notify) {\n if (focus_ != node)\n focus_ = node;\n\n if (notify && node && delegate_)\n delegate_->SetAccessibilityFocus(node->renderer_id());\n}\n\nvoid BrowserAccessibilityManager::DoDefaultAction(\n const BrowserAccessibility& node) {\n if (delegate_)\n delegate_->AccessibilityDoDefaultAction(node.renderer_id());\n}\n\nvoid BrowserAccessibilityManager::ScrollToMakeVisible(\n const BrowserAccessibility& node, gfx::Rect subfocus) {\n if (delegate_) {\n delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);\n }\n}\n\nvoid BrowserAccessibilityManager::ScrollToPoint(\n const BrowserAccessibility& node, gfx::Point point) {\n if (delegate_) {\n delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);\n }\n}\n\nvoid BrowserAccessibilityManager::SetTextSelection(\n const BrowserAccessibility& node, int start_offset, int end_offset) {\n if (delegate_) {\n delegate_->AccessibilitySetTextSelection(\n node.renderer_id(), start_offset, end_offset);\n }\n}\n\ngfx::Rect BrowserAccessibilityManager::GetViewBounds() {\n if (delegate_)\n return delegate_->GetViewBounds();\n return gfx::Rect();\n}\n\nvoid BrowserAccessibilityManager::UpdateNodesForTesting(\n const AccessibilityNodeData& node1,\n const AccessibilityNodeData& node2 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node3 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node4 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node5 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node6 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node7 \/* = AccessibilityNodeData() *\/) {\n std::vector nodes;\n nodes.push_back(node1);\n if (node2.id != AccessibilityNodeData().id)\n nodes.push_back(node2);\n if (node3.id != AccessibilityNodeData().id)\n nodes.push_back(node3);\n if (node4.id != AccessibilityNodeData().id)\n nodes.push_back(node4);\n if (node5.id != AccessibilityNodeData().id)\n nodes.push_back(node5);\n if (node6.id != AccessibilityNodeData().id)\n nodes.push_back(node6);\n if (node7.id != AccessibilityNodeData().id)\n nodes.push_back(node7);\n UpdateNodes(nodes);\n}\n\nbool BrowserAccessibilityManager::UpdateNodes(\n const std::vector& nodes) {\n bool success = true;\n\n \/\/ First, update all of the nodes in the tree.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n if (!UpdateNode(nodes[i]))\n success = false;\n }\n\n \/\/ In a second pass, call PostInitialize on each one - this must\n \/\/ be called after all of each node's children are initialized too.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n BrowserAccessibility* instance = GetFromRendererID(nodes[i].id);\n if (instance) {\n instance->PostInitialize();\n } else {\n success = false;\n }\n }\n\n if (!success) {\n \/\/ A bad accessibility tree could lead to memory corruption.\n \/\/ Ask the delegate to crash the renderer, or if not available,\n \/\/ crash the browser.\n if (delegate_)\n delegate_->FatalAccessibilityTreeError();\n else\n CHECK(false);\n }\n\n return success;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::CreateNode(\n BrowserAccessibility* parent,\n int32 renderer_id,\n int32 index_in_parent) {\n BrowserAccessibility* instance = factory_->Create();\n int32 child_id = GetNextChildID();\n instance->InitializeTreeStructure(\n this, parent, child_id, renderer_id, index_in_parent);\n child_id_map_[child_id] = instance;\n renderer_id_to_child_id_map_[renderer_id] = child_id;\n return instance;\n}\n\nbool BrowserAccessibilityManager::UpdateNode(const AccessibilityNodeData& src) {\n \/\/ This method updates one node in the tree based on serialized data\n \/\/ received from the renderer.\n\n \/\/ Create a set of child ids in |src| for fast lookup. If a duplicate id is\n \/\/ found, exit now with a fatal error before changing anything else.\n std::set new_child_ids;\n for (size_t i = 0; i < src.child_ids.size(); ++i) {\n if (new_child_ids.find(src.child_ids[i]) != new_child_ids.end())\n return false;\n new_child_ids.insert(src.child_ids[i]);\n }\n\n \/\/ Look up the node by id. If it's not found, then either the root\n \/\/ of the tree is being swapped, or we're out of sync with the renderer\n \/\/ and this is a serious error.\n BrowserAccessibility* instance = GetFromRendererID(src.id);\n if (!instance) {\n if (src.role != AccessibilityNodeData::ROLE_ROOT_WEB_AREA)\n return false;\n instance = CreateNode(NULL, src.id, 0);\n }\n\n \/\/ Update all of the node-specific data, like its role, state, name, etc.\n instance->InitializeData(src);\n\n \/\/\n \/\/ Update the children in three steps:\n \/\/\n \/\/ 1. Iterate over the old children and delete nodes that are no longer\n \/\/ in the tree.\n \/\/ 2. Build up a vector of new children, reusing children that haven't\n \/\/ changed (but may have been reordered) and adding new empty\n \/\/ objects for new children.\n \/\/ 3. Swap in the new children vector for the old one.\n\n \/\/ Delete any previous children of this instance that are no longer\n \/\/ children first. We make a deletion-only pass first to prevent a\n \/\/ node that's being reparented from being the child of both its old\n \/\/ parent and new parent, which could lead to a double-free.\n \/\/ If a node is reparented, the renderer will always send us a fresh\n \/\/ copy of the node.\n const std::vector& old_children = instance->children();\n for (size_t i = 0; i < old_children.size(); ++i) {\n int old_id = old_children[i]->renderer_id();\n if (new_child_ids.find(old_id) == new_child_ids.end())\n old_children[i]->Destroy();\n }\n\n \/\/ Now build a vector of new children, reusing objects that were already\n \/\/ children of this node before.\n std::vector new_children;\n bool success = true;\n for (size_t i = 0; i < src.child_ids.size(); i++) {\n int32 child_renderer_id = src.child_ids[i];\n int32 index_in_parent = static_cast(i);\n BrowserAccessibility* child = GetFromRendererID(child_renderer_id);\n if (child) {\n if (child->parent() != instance) {\n \/\/ This is a serious error - nodes should never be reparented.\n \/\/ If this case occurs, continue so this node isn't left in an\n \/\/ inconsistent state, but return failure at the end.\n success = false;\n continue;\n }\n child->UpdateParent(instance, index_in_parent);\n } else {\n child = CreateNode(instance, child_renderer_id, index_in_parent);\n }\n new_children.push_back(child);\n }\n\n \/\/ Finally, swap in the new children vector for the old.\n instance->SwapChildren(new_children);\n\n \/\/ Handle the case where this node is the new root of the tree.\n if (src.role == AccessibilityNodeData::ROLE_ROOT_WEB_AREA &&\n (!root_ || root_->renderer_id() != src.id)) {\n if (root_)\n root_->Destroy();\n if (focus_ == root_)\n focus_ = instance;\n root_ = instance;\n }\n\n \/\/ Keep track of what node is focused.\n if ((src.state >> AccessibilityNodeData::STATE_FOCUSED) & 1)\n SetFocus(instance, false);\n\n return success;\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"#include \"SchedulerTrack.h\"\n\n#include \"Capture.h\"\n#include \"EventTrack.h\"\n#include \"GlCanvas.h\"\n#include \"TimeGraph.h\"\n\nconst Color kInactiveColor(100, 100, 100, 255);\nconst Color kSelectionColor(0, 128, 255, 255);\n\nvoid SchedulerTrack::Draw(GlCanvas* canvas, bool picking) {\n ThreadTrack::Draw(canvas, picking);\n}\n\nfloat SchedulerTrack::GetHeight() const {\n TimeGraphLayout& layout = time_graph_->GetLayout();\n return depth_ *\n (layout.GetTextCoresHeight() + layout.GetSpaceBetweenCores()) +\n layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();\n}\n\ninline Color GetTimerColor(const Timer& timer, TimeGraph* time_graph,\n bool is_selected, bool same_tid, bool same_pid,\n bool inactive) {\n if (is_selected) {\n return kSelectionColor;\n } else if (!same_tid && (inactive || !same_pid)) {\n return kInactiveColor;\n }\n return time_graph->GetTimesliceColor(timer);\n}\n\ninline float GetYFromDepth(const TimeGraphLayout& layout, float track_y,\n uint32_t depth) {\n return track_y - layout.GetEventTrackHeight() -\n layout.GetSpaceBetweenTracksAndThread() -\n (layout.GetTextCoresHeight() + layout.GetSpaceBetweenCores()) *\n (depth + 1);\n}\n\nvoid SchedulerTrack::UpdatePrimitives(uint64_t min_tick, uint64_t max_tick) {\n event_track_->UpdatePrimitives(min_tick, max_tick);\n\n Batcher* batcher = &time_graph_->GetBatcher();\n GlCanvas* canvas = time_graph_->GetCanvas();\n const TimeGraphLayout& layout = time_graph_->GetLayout();\n const auto& target_process = Capture::GTargetProcess;\n uint32_t target_pid = target_process ? target_process->GetID() : 0;\n uint32_t selected_thread_id = Capture::GSelectedThreadId;\n\n float world_start_x = canvas->GetWorldTopLeftX();\n float world_width = canvas->GetWorldWidth();\n double inv_time_window = 1.0 \/ time_graph_->GetTimeWindowUs();\n\n std::vector> chains_by_depth = GetTimers();\n for (std::shared_ptr& timer_chain : chains_by_depth) {\n for (TextBox& text_box : *timer_chain) {\n const Timer& timer = text_box.GetTimer();\n if (min_tick > timer.m_End || max_tick < timer.m_Start) continue;\n\n UpdateDepth(timer.m_Depth + 1);\n double start_us = time_graph_->GetUsFromTick(timer.m_Start);\n double end_us = time_graph_->GetUsFromTick(timer.m_End);\n double elapsed_us = end_us - start_us;\n double normalized_start = start_us * inv_time_window;\n double normalized_length = elapsed_us * inv_time_window;\n float world_timer_width =\n static_cast(normalized_length * world_width);\n float world_timer_x =\n static_cast(world_start_x + normalized_start * world_width);\n float world_timer_y = GetYFromDepth(layout, m_Pos[1], timer.m_Depth);\n\n bool is_visible_width = normalized_length * canvas->getWidth() > 1;\n bool is_same_pid_as_target = target_pid == 0 || target_pid == timer.m_PID;\n bool is_same_tid_as_selected = timer.m_TID == selected_thread_id;\n bool is_inactive = selected_thread_id != 0 && !is_same_tid_as_selected;\n bool is_selected = &text_box == Capture::GSelectedTextBox;\n\n Vec2 pos(world_timer_x, world_timer_y);\n Vec2 size(world_timer_width, layout.GetTextCoresHeight());\n float z = GlCanvas::Z_VALUE_BOX_ACTIVE;\n Color color = GetTimerColor(timer, time_graph_, is_selected,\n is_same_tid_as_selected,\n is_same_pid_as_target, is_inactive);\n\n if (is_visible_width) {\n batcher->AddShadedBox(pos, size, z, color, PickingID::BOX, &text_box);\n } else {\n auto type = PickingID::LINE;\n batcher->AddVerticalLine(pos, size[1], z, color, type, &text_box);\n }\n }\n }\n}\nFix crash in SchedulerTrack.#include \"SchedulerTrack.h\"\n\n#include \"Capture.h\"\n#include \"EventTrack.h\"\n#include \"GlCanvas.h\"\n#include \"TimeGraph.h\"\n\nconst Color kInactiveColor(100, 100, 100, 255);\nconst Color kSelectionColor(0, 128, 255, 255);\n\nvoid SchedulerTrack::Draw(GlCanvas* canvas, bool picking) {\n ThreadTrack::Draw(canvas, picking);\n}\n\nfloat SchedulerTrack::GetHeight() const {\n TimeGraphLayout& layout = time_graph_->GetLayout();\n return depth_ *\n (layout.GetTextCoresHeight() + layout.GetSpaceBetweenCores()) +\n layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();\n}\n\ninline Color GetTimerColor(const Timer& timer, TimeGraph* time_graph,\n bool is_selected, bool same_tid, bool same_pid,\n bool inactive) {\n if (is_selected) {\n return kSelectionColor;\n } else if (!same_tid && (inactive || !same_pid)) {\n return kInactiveColor;\n }\n return time_graph->GetTimesliceColor(timer);\n}\n\ninline float GetYFromDepth(const TimeGraphLayout& layout, float track_y,\n uint32_t depth) {\n return track_y - layout.GetEventTrackHeight() -\n layout.GetSpaceBetweenTracksAndThread() -\n (layout.GetTextCoresHeight() + layout.GetSpaceBetweenCores()) *\n (depth + 1);\n}\n\nvoid SchedulerTrack::UpdatePrimitives(uint64_t min_tick, uint64_t max_tick) {\n event_track_->UpdatePrimitives(min_tick, max_tick);\n\n Batcher* batcher = &time_graph_->GetBatcher();\n GlCanvas* canvas = time_graph_->GetCanvas();\n const TimeGraphLayout& layout = time_graph_->GetLayout();\n const auto& target_process = Capture::GTargetProcess;\n uint32_t target_pid = target_process ? target_process->GetID() : 0;\n uint32_t selected_thread_id = Capture::GSelectedThreadId;\n\n float world_start_x = canvas->GetWorldTopLeftX();\n float world_width = canvas->GetWorldWidth();\n double inv_time_window = 1.0 \/ time_graph_->GetTimeWindowUs();\n\n std::vector> chains_by_depth = GetTimers();\n for (std::shared_ptr& timer_chain : chains_by_depth) {\n if (timer_chain == nullptr) continue;\n for (TextBox& text_box : *timer_chain) {\n const Timer& timer = text_box.GetTimer();\n if (min_tick > timer.m_End || max_tick < timer.m_Start) continue;\n\n UpdateDepth(timer.m_Depth + 1);\n double start_us = time_graph_->GetUsFromTick(timer.m_Start);\n double end_us = time_graph_->GetUsFromTick(timer.m_End);\n double elapsed_us = end_us - start_us;\n double normalized_start = start_us * inv_time_window;\n double normalized_length = elapsed_us * inv_time_window;\n float world_timer_width =\n static_cast(normalized_length * world_width);\n float world_timer_x =\n static_cast(world_start_x + normalized_start * world_width);\n float world_timer_y = GetYFromDepth(layout, m_Pos[1], timer.m_Depth);\n\n bool is_visible_width = normalized_length * canvas->getWidth() > 1;\n bool is_same_pid_as_target = target_pid == 0 || target_pid == timer.m_PID;\n bool is_same_tid_as_selected = timer.m_TID == selected_thread_id;\n bool is_inactive = selected_thread_id != 0 && !is_same_tid_as_selected;\n bool is_selected = &text_box == Capture::GSelectedTextBox;\n\n Vec2 pos(world_timer_x, world_timer_y);\n Vec2 size(world_timer_width, layout.GetTextCoresHeight());\n float z = GlCanvas::Z_VALUE_BOX_ACTIVE;\n Color color = GetTimerColor(timer, time_graph_, is_selected,\n is_same_tid_as_selected,\n is_same_pid_as_target, is_inactive);\n\n if (is_visible_width) {\n batcher->AddShadedBox(pos, size, z, color, PickingID::BOX, &text_box);\n } else {\n auto type = PickingID::LINE;\n batcher->AddVerticalLine(pos, size[1], z, color, type, &text_box);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#include \n\nusing namespace GameServer::Common;\nusing namespace GameServer::Persistence;\n\nnamespace GameServer\n{\nnamespace Human\n{\n\nGetHumansOperator::GetHumansOperator(\n IHumanPersistenceFacadeShrPtr a_human_persistence_facade\n)\n : m_human_persistence_facade(a_human_persistence_facade)\n{\n}\n\nGetHumansOperatorExitCode GetHumansOperator::getHumans(\n ITransactionShrPtr a_transaction,\n IDHolder const & a_id_holder\n) const\n{\n try\n {\n HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, a_id_holder);\n\n return GetHumansOperatorExitCode(GET_HUMANS_OPERATOR_EXIT_CODE_HUMANS_HAVE_BEEN_GOT, humans);\n }\n catch (...)\n {\n return GetHumansOperatorExitCode(GET_HUMANS_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR);\n }\n}\n\n} \/\/ namespace Human\n} \/\/ namespace GameServer\nFix: bugs found during testing.\/\/ Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#include \n\nusing namespace GameServer::Common;\nusing namespace GameServer::Persistence;\n\nnamespace GameServer\n{\nnamespace Human\n{\n\nGetHumansOperator::GetHumansOperator(\n IHumanPersistenceFacadeShrPtr a_human_persistence_facade\n)\n : m_human_persistence_facade(a_human_persistence_facade)\n{\n}\n\nGetHumansOperatorExitCode GetHumansOperator::getHumans(\n ITransactionShrPtr a_transaction,\n IDHolder const & a_id_holder\n) const\n{\n try\n {\n HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, a_id_holder);\n\n return (humans.empty())\n ? GetHumansOperatorExitCode(GET_HUMANS_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR)\n : GetHumansOperatorExitCode(GET_HUMANS_OPERATOR_EXIT_CODE_HUMANS_HAVE_BEEN_GOT, humans);\n }\n catch (...)\n {\n return GetHumansOperatorExitCode(GET_HUMANS_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR);\n }\n}\n\n} \/\/ namespace Human\n} \/\/ namespace GameServer\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/frame\/app_non_client_frame_view_aura.h\"\n\n#include \"base\/debug\/stack_trace.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_frame.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/compositor\/layer.h\"\n#include \"ui\/gfx\/compositor\/scoped_layer_animation_settings.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/point.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/window\/non_client_view.h\"\n\nnamespace {\n\/\/ The number of pixels to use as a hover zone at the top of the screen.\nconst int kTopMargin = 1;\n\/\/ How long the hover animation takes if uninterrupted.\nconst int kHoverFadeDurationMs = 130;\n\/\/ The number of pixels within the shadow to draw the buttons.\nconst int kShadowStart = 28;\n}\n\nclass AppNonClientFrameViewAura::ControlView\n : public views::View, public views::ButtonListener {\n public:\n explicit ControlView(AppNonClientFrameViewAura* owner) :\n owner_(owner),\n close_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_CLOSE)),\n restore_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_RESTORE)) {\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n separator_ =\n *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SEPARATOR).ToSkBitmap();\n shadow_ = *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToSkBitmap();\n AddChildView(close_button_);\n AddChildView(restore_button_);\n }\n\n virtual void Layout() OVERRIDE {\n restore_button_->SetPosition(gfx::Point(kShadowStart, 0));\n close_button_->SetPosition(\n gfx::Point(kShadowStart + close_button_->width() + separator_.width(),\n 0));\n }\n\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return gfx::Size(shadow_.width(), shadow_.height());\n }\n\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n views::View::OnPaint(canvas);\n canvas->DrawBitmapInt(\n separator_, restore_button_->x() + restore_button_->width(), 0);\n canvas->DrawBitmapInt(shadow_, 0, 0);\n }\n\n void ButtonPressed(\n views::Button* sender,\n const views::Event& event) OVERRIDE {\n if (sender == close_button_)\n owner_->Close();\n else if (sender == restore_button_)\n owner_->Restore();\n }\n\n private:\n \/\/ Gets an image representing 3 bitmaps laid out horizontally that will be\n \/\/ used as the normal, hot and pushed states for the created button.\n views::ImageButton* CreateImageButton(int resource_id) {\n views::ImageButton* button = new views::ImageButton(this);\n const SkBitmap* all_images =\n ResourceBundle::GetSharedInstance().GetImageNamed(\n resource_id).ToSkBitmap();\n int width = all_images->width() \/ 3;\n int height = all_images->height();\n\n SkBitmap normal, hot, pushed;\n all_images->extractSubset(\n &normal,\n SkIRect::MakeXYWH(0, 0, width, height));\n all_images->extractSubset(\n &hot,\n SkIRect::MakeXYWH(width, 0, width, height));\n all_images->extractSubset(\n &pushed,\n SkIRect::MakeXYWH(2 * width, 0, width, height));\n button->SetImage(views::CustomButton::BS_NORMAL, &normal);\n button->SetImage(views::CustomButton::BS_HOT, &hot);\n button->SetImage(views::CustomButton::BS_PUSHED, &pushed);\n\n button->SizeToPreferredSize();\n return button;\n }\n\n AppNonClientFrameViewAura* owner_;\n views::ImageButton* close_button_;\n views::ImageButton* restore_button_;\n SkBitmap separator_;\n SkBitmap shadow_;\n\n DISALLOW_COPY_AND_ASSIGN(ControlView);\n};\n\nclass AppNonClientFrameViewAura::Host : public views::MouseWatcherHost {\n public:\n explicit Host(AppNonClientFrameViewAura* owner) : owner_(owner) {}\n virtual ~Host() {}\n\n virtual bool Contains(\n const gfx::Point& screen_point,\n views::MouseWatcherHost::MouseEventType type) {\n gfx::Rect top_margin = owner_->GetScreenBounds();\n top_margin.set_height(kTopMargin);\n gfx::Rect control_bounds = owner_->GetControlBounds();\n control_bounds.Inset(kShadowStart, 0, 0, kShadowStart);\n return top_margin.Contains(screen_point) ||\n control_bounds.Contains(screen_point);\n }\n\n AppNonClientFrameViewAura* owner_;\n\n DISALLOW_COPY_AND_ASSIGN(Host);\n};\n\nAppNonClientFrameViewAura::AppNonClientFrameViewAura(\n BrowserFrame* frame, BrowserView* browser_view)\n : BrowserNonClientFrameView(frame, browser_view),\n control_view_(new ControlView(this)),\n control_widget_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n mouse_watcher_(new Host(this), this)) {\n}\n\nAppNonClientFrameViewAura::~AppNonClientFrameViewAura() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForClientView() const {\n gfx::Rect bounds = GetLocalBounds();\n bounds.Inset(0, kTopMargin, 0, 0);\n return bounds;\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n gfx::Rect bounds = client_bounds;\n bounds.Inset(0, -kTopMargin, 0, 0);\n return bounds;\n}\n\nint AppNonClientFrameViewAura::NonClientHitTest(\n const gfx::Point& point) {\n return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;\n}\n\nvoid AppNonClientFrameViewAura::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n}\n\nvoid AppNonClientFrameViewAura::ResetWindowControls() {\n}\n\nvoid AppNonClientFrameViewAura::UpdateWindowIcon() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForTabStrip(\n views::View* tabstrip) const {\n return gfx::Rect();\n}\n\nint AppNonClientFrameViewAura::GetHorizontalTabStripVerticalOffset(\n bool restored) const {\n return 0;\n}\n\nvoid AppNonClientFrameViewAura::UpdateThrobber(bool running) {\n}\n\nvoid AppNonClientFrameViewAura::OnMouseEntered(\n const views::MouseEvent& event) {\n if (!control_widget_) {\n control_widget_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);\n params.parent = browser_view()->GetNativeHandle();\n params.transparent = true;\n control_widget_->Init(params);\n control_widget_->SetContentsView(control_view_);\n aura::Window* window = control_widget_->GetNativeView();\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n window->SetBounds(control_bounds);\n control_widget_->Show();\n }\n\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n layer->SetBounds(GetControlBounds());\n layer->SetOpacity(1);\n\n mouse_watcher_.Start();\n}\n\nvoid AppNonClientFrameViewAura::MouseMovedOutOfHost() {\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n layer->SetBounds(control_bounds);\n layer->SetOpacity(0);\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetControlBounds() const {\n gfx::Size preferred = control_view_->GetPreferredSize();\n gfx::Point location(width() - preferred.width(), 0);\n ConvertPointToWidget(this, &location);\n return gfx::Rect(\n location.x(), location.y(),\n preferred.width(), preferred.height());\n}\n\nvoid AppNonClientFrameViewAura::Close() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Close();\n}\n\nvoid AppNonClientFrameViewAura::Restore() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Restore();\n}\nCreate black background for full screen app windows BUG=118111 TEST=Visual\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/frame\/app_non_client_frame_view_aura.h\"\n\n#include \"base\/debug\/stack_trace.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_frame.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/compositor\/layer.h\"\n#include \"ui\/gfx\/compositor\/scoped_layer_animation_settings.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/point.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/window\/non_client_view.h\"\n\nnamespace {\n\/\/ The number of pixels to use as a hover zone at the top of the screen.\nconst int kTopMargin = 1;\n\/\/ How long the hover animation takes if uninterrupted.\nconst int kHoverFadeDurationMs = 130;\n\/\/ The number of pixels within the shadow to draw the buttons.\nconst int kShadowStart = 28;\n}\n\nclass AppNonClientFrameViewAura::ControlView\n : public views::View, public views::ButtonListener {\n public:\n explicit ControlView(AppNonClientFrameViewAura* owner) :\n owner_(owner),\n close_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_CLOSE)),\n restore_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_RESTORE)) {\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n separator_ =\n *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SEPARATOR).ToSkBitmap();\n shadow_ = *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToSkBitmap();\n AddChildView(close_button_);\n AddChildView(restore_button_);\n }\n\n virtual void Layout() OVERRIDE {\n restore_button_->SetPosition(gfx::Point(kShadowStart, 0));\n close_button_->SetPosition(\n gfx::Point(kShadowStart + close_button_->width() + separator_.width(),\n 0));\n }\n\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return gfx::Size(shadow_.width(), shadow_.height());\n }\n\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n views::View::OnPaint(canvas);\n canvas->DrawBitmapInt(\n separator_, restore_button_->x() + restore_button_->width(), 0);\n canvas->DrawBitmapInt(shadow_, 0, 0);\n }\n\n void ButtonPressed(\n views::Button* sender,\n const views::Event& event) OVERRIDE {\n if (sender == close_button_)\n owner_->Close();\n else if (sender == restore_button_)\n owner_->Restore();\n }\n\n private:\n \/\/ Gets an image representing 3 bitmaps laid out horizontally that will be\n \/\/ used as the normal, hot and pushed states for the created button.\n views::ImageButton* CreateImageButton(int resource_id) {\n views::ImageButton* button = new views::ImageButton(this);\n const SkBitmap* all_images =\n ResourceBundle::GetSharedInstance().GetImageNamed(\n resource_id).ToSkBitmap();\n int width = all_images->width() \/ 3;\n int height = all_images->height();\n\n SkBitmap normal, hot, pushed;\n all_images->extractSubset(\n &normal,\n SkIRect::MakeXYWH(0, 0, width, height));\n all_images->extractSubset(\n &hot,\n SkIRect::MakeXYWH(width, 0, width, height));\n all_images->extractSubset(\n &pushed,\n SkIRect::MakeXYWH(2 * width, 0, width, height));\n button->SetImage(views::CustomButton::BS_NORMAL, &normal);\n button->SetImage(views::CustomButton::BS_HOT, &hot);\n button->SetImage(views::CustomButton::BS_PUSHED, &pushed);\n\n button->SizeToPreferredSize();\n return button;\n }\n\n AppNonClientFrameViewAura* owner_;\n views::ImageButton* close_button_;\n views::ImageButton* restore_button_;\n SkBitmap separator_;\n SkBitmap shadow_;\n\n DISALLOW_COPY_AND_ASSIGN(ControlView);\n};\n\nclass AppNonClientFrameViewAura::Host : public views::MouseWatcherHost {\n public:\n explicit Host(AppNonClientFrameViewAura* owner) : owner_(owner) {}\n virtual ~Host() {}\n\n virtual bool Contains(\n const gfx::Point& screen_point,\n views::MouseWatcherHost::MouseEventType type) {\n gfx::Rect top_margin = owner_->GetScreenBounds();\n top_margin.set_height(kTopMargin);\n gfx::Rect control_bounds = owner_->GetControlBounds();\n control_bounds.Inset(kShadowStart, 0, 0, kShadowStart);\n return top_margin.Contains(screen_point) ||\n control_bounds.Contains(screen_point);\n }\n\n AppNonClientFrameViewAura* owner_;\n\n DISALLOW_COPY_AND_ASSIGN(Host);\n};\n\nAppNonClientFrameViewAura::AppNonClientFrameViewAura(\n BrowserFrame* frame, BrowserView* browser_view)\n : BrowserNonClientFrameView(frame, browser_view),\n control_view_(new ControlView(this)),\n control_widget_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n mouse_watcher_(new Host(this), this)) {\n set_background(views::Background::CreateSolidBackground(SK_ColorBLACK));\n}\n\nAppNonClientFrameViewAura::~AppNonClientFrameViewAura() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForClientView() const {\n gfx::Rect bounds = GetLocalBounds();\n bounds.Inset(0, kTopMargin, 0, 0);\n return bounds;\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n gfx::Rect bounds = client_bounds;\n bounds.Inset(0, -kTopMargin, 0, 0);\n return bounds;\n}\n\nint AppNonClientFrameViewAura::NonClientHitTest(\n const gfx::Point& point) {\n return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;\n}\n\nvoid AppNonClientFrameViewAura::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n}\n\nvoid AppNonClientFrameViewAura::ResetWindowControls() {\n}\n\nvoid AppNonClientFrameViewAura::UpdateWindowIcon() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForTabStrip(\n views::View* tabstrip) const {\n return gfx::Rect();\n}\n\nint AppNonClientFrameViewAura::GetHorizontalTabStripVerticalOffset(\n bool restored) const {\n return 0;\n}\n\nvoid AppNonClientFrameViewAura::UpdateThrobber(bool running) {\n}\n\nvoid AppNonClientFrameViewAura::OnMouseEntered(\n const views::MouseEvent& event) {\n if (!control_widget_) {\n control_widget_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);\n params.parent = browser_view()->GetNativeHandle();\n params.transparent = true;\n control_widget_->Init(params);\n control_widget_->SetContentsView(control_view_);\n aura::Window* window = control_widget_->GetNativeView();\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n window->SetBounds(control_bounds);\n control_widget_->Show();\n }\n\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n layer->SetBounds(GetControlBounds());\n layer->SetOpacity(1);\n\n mouse_watcher_.Start();\n}\n\nvoid AppNonClientFrameViewAura::MouseMovedOutOfHost() {\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n layer->SetBounds(control_bounds);\n layer->SetOpacity(0);\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetControlBounds() const {\n gfx::Size preferred = control_view_->GetPreferredSize();\n gfx::Point location(width() - preferred.width(), 0);\n ConvertPointToWidget(this, &location);\n return gfx::Rect(\n location.x(), location.y(),\n preferred.width(), preferred.height());\n}\n\nvoid AppNonClientFrameViewAura::Close() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Close();\n}\n\nvoid AppNonClientFrameViewAura::Restore() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Restore();\n}\n<|endoftext|>"} {"text":"\n#include \n\n#include \n\n#include \"drake\/systems\/plants\/constraint\/dynamic_constraint.h\"\n#include \"drake\/util\/eigen_matrix_compare.h\"\n\nusing drake::util::MatrixCompareType;\n\nnamespace drake {\nnamespace systems {\nnamespace {\n\nclass PendulumTestDynamicConstraint : public DynamicConstraint {\n public:\n PendulumTestDynamicConstraint(int num_states, int num_inputs)\n : DynamicConstraint(num_states, num_inputs) {}\n\n protected:\n void dynamics(const Drake::TaylorVecXd& state,\n const Drake::TaylorVecXd& input,\n Drake::TaylorVecXd* xdot) const override {\n \/\/ From the Pendulum example:\n const double m = 1.0;\n const double b = 0.1;\n const double lc = .5;\n const double I = 0.25;\n const double g = 9.81;\n\n ASSERT_EQ(state.size(), 2);\n ASSERT_EQ(input.size(), 1);\n xdot->resize(2);\n (*xdot)(0) = state(1);\n (*xdot)(1) = (input(0) - m * g * lc * sin(state(0)) - b * state(1)) \/ I;\n }\n};\n\nGTEST_TEST(DynamicConstraintPendulumDynamicsTest, DynamicConstraintTest) {\n const int kNumStates = 2;\n const int kNumInputs = 1;\n\n\n Eigen::VectorXd x(1 + 2 * kNumStates + 2 * kNumInputs);\n x(0) = 0.2; \/\/ h\n x(1) = 0; \/\/ x0(0)\n x(2) = 0; \/\/ x0(1)\n x(3) = 0.05 * M_PI; \/\/ x1(0)\n x(4) = 0; \/\/ x1(1)\n x(5) = 0.00537668; \/\/ u0\n x(6) = 0.018339; \/\/ u1\n\n PendulumTestDynamicConstraint dut(kNumStates, kNumInputs);\n\n Drake::TaylorVecXd result;\n dut.eval(Drake::initializeAutoDiff(x), result);\n\n \/\/ Expected values came from running the MATLAB code for\n \/\/ PendulumPlant through the constraint function in\n \/\/ DircolTrajectoryOptimization.m and printing the results.\n EXPECT_NEAR(result(0).value(), 1.1027, 1e-4);\n EXPECT_NEAR(result(1).value(), 2.2657, 1e-4);\n\n Eigen::VectorXd d_0_expected(x.size());\n d_0_expected << -6.26766, -7.0095, -0.74, 7.015539, -0.76, -0.1, 0.1;\n Eigen::VectorXd d_1_expected(x.size());\n d_1_expected << 0.1508698, 14.488559, -6.715012, 14.818155,\n 7.315012, -2.96, -3.04;\n EXPECT_TRUE(CompareMatrices(result(0).derivatives(), d_0_expected, 1e-4,\n MatrixCompareType::absolute));\n EXPECT_TRUE(CompareMatrices(result(1).derivatives(), d_1_expected, 1e-4,\n MatrixCompareType::absolute));\n}\n\n} \/\/ anonymous namespace\n} \/\/ namespace systems\n} \/\/ namespace drake\nClarify a comment\n#include \n\n#include \n\n#include \"drake\/systems\/plants\/constraint\/dynamic_constraint.h\"\n#include \"drake\/util\/eigen_matrix_compare.h\"\n\nusing drake::util::MatrixCompareType;\n\nnamespace drake {\nnamespace systems {\nnamespace {\n\nclass PendulumTestDynamicConstraint : public DynamicConstraint {\n public:\n PendulumTestDynamicConstraint(int num_states, int num_inputs)\n : DynamicConstraint(num_states, num_inputs) {}\n\n protected:\n void dynamics(const Drake::TaylorVecXd& state,\n const Drake::TaylorVecXd& input,\n Drake::TaylorVecXd* xdot) const override {\n \/\/ From the Pendulum example:\n const double m = 1.0;\n const double b = 0.1;\n const double lc = .5;\n const double I = 0.25;\n const double g = 9.81;\n\n ASSERT_EQ(state.size(), 2);\n ASSERT_EQ(input.size(), 1);\n xdot->resize(2);\n (*xdot)(0) = state(1);\n (*xdot)(1) = (input(0) - m * g * lc * sin(state(0)) - b * state(1)) \/ I;\n }\n};\n\nGTEST_TEST(DynamicConstraintPendulumDynamicsTest, DynamicConstraintTest) {\n const int kNumStates = 2;\n const int kNumInputs = 1;\n\n\n \/\/ Initial state\/input and expected result values came from running\n \/\/ the MATLAB code for PendulumPlant through the constraint function\n \/\/ in DircolTrajectoryOptimization.m and printing the results.\n Eigen::VectorXd x(1 + 2 * kNumStates + 2 * kNumInputs);\n x(0) = 0.2; \/\/ h\n x(1) = 0; \/\/ x0(0)\n x(2) = 0; \/\/ x0(1)\n x(3) = 0.05 * M_PI; \/\/ x1(0)\n x(4) = 0; \/\/ x1(1)\n x(5) = 0.00537668; \/\/ u0\n x(6) = 0.018339; \/\/ u1\n\n PendulumTestDynamicConstraint dut(kNumStates, kNumInputs);\n\n Drake::TaylorVecXd result;\n dut.eval(Drake::initializeAutoDiff(x), result);\n\n EXPECT_NEAR(result(0).value(), 1.1027, 1e-4);\n EXPECT_NEAR(result(1).value(), 2.2657, 1e-4);\n\n Eigen::VectorXd d_0_expected(x.size());\n d_0_expected << -6.26766, -7.0095, -0.74, 7.015539, -0.76, -0.1, 0.1;\n Eigen::VectorXd d_1_expected(x.size());\n d_1_expected << 0.1508698, 14.488559, -6.715012, 14.818155,\n 7.315012, -2.96, -3.04;\n EXPECT_TRUE(CompareMatrices(result(0).derivatives(), d_0_expected, 1e-4,\n MatrixCompareType::absolute));\n EXPECT_TRUE(CompareMatrices(result(1).derivatives(), d_1_expected, 1e-4,\n MatrixCompareType::absolute));\n}\n\n} \/\/ anonymous namespace\n} \/\/ namespace systems\n} \/\/ namespace drake\n<|endoftext|>"} {"text":"#ifndef DUNE_COMMON_COLOR_HH\n#define DUNE_COMMON_COLOR_HH\n\n#include \n#include \n#include \n\n#ifdef __GNUC__\n #include \n#endif\n#include \n\n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/**\n * @brief namespace to define color constants that can be\n * used to print colored text in an output stream.\n *\n * * \\todo this could go into libdune-stuff\n * @warning Some color codes might be unsupported by your terminal.\n *\/\nstruct Colors {\n\n#define DS_CONST_CHAR const constexpr char*\n\n\/\/ foreground colors\nstatic DS_CONST_CHAR black = \"\\033[30m\";\nstatic DS_CONST_CHAR red = \"\\033[31m\";\nstatic DS_CONST_CHAR green = \"\\033[32m\";\nstatic DS_CONST_CHAR brown = \"\\033[33m\";\nstatic DS_CONST_CHAR blue = \"\\033[34m\";\nstatic DS_CONST_CHAR purple = \"\\033[35m\";\nstatic DS_CONST_CHAR cyan = \"\\033[36m\";\nstatic DS_CONST_CHAR lightgray = \"\\033[37m\";\n\/\/ light foreground colors\nstatic DS_CONST_CHAR darkgray = \"\\033[1;30m\";\nstatic DS_CONST_CHAR lightred = \"\\033[1;31m\";\nstatic DS_CONST_CHAR lightgreen = \"\\033[1;32m\";\nstatic DS_CONST_CHAR yellow = \"\\033[1;33m\";\nstatic DS_CONST_CHAR lightblue = \"\\033[1;34m\";\nstatic DS_CONST_CHAR lightpurple = \"\\033[1;35m\";\nstatic DS_CONST_CHAR lightcyan = \"\\033[1;36m\";\nstatic DS_CONST_CHAR white = \"\\033[1;37m\";\n\n\/\/ background colors\nstatic DS_CONST_CHAR bblack = \"\\033[40m\";\nstatic DS_CONST_CHAR bred = \"\\033[41m\";\nstatic DS_CONST_CHAR bgreen = \"\\033[42m\";\nstatic DS_CONST_CHAR bbrown = \"\\033[43m\";\nstatic DS_CONST_CHAR bblue = \"\\033[44m\";\nstatic DS_CONST_CHAR bpurple = \"\\033[45m\";\nstatic DS_CONST_CHAR bcyan = \"\\033[46m\";\nstatic DS_CONST_CHAR blightgray = \"\\033[47m\";\n\/\/ light background colors\nstatic DS_CONST_CHAR bdarkgray = \"\\033[1;40m\";\nstatic DS_CONST_CHAR blightred = \"\\033[1;41m\";\nstatic DS_CONST_CHAR blightgreen = \"\\033[1;42m\";\nstatic DS_CONST_CHAR byellow = \"\\033[1;43m\";\nstatic DS_CONST_CHAR blightblue = \"\\033[1;44m\";\nstatic DS_CONST_CHAR blightpurple = \"\\033[1;45m\";\nstatic DS_CONST_CHAR blightcyan = \"\\033[1;46m\";\nstatic DS_CONST_CHAR bwhite = \"\\033[1;47m\";\n};\n\/\/ modifiers\nstruct StreamModifiers {\nstatic DS_CONST_CHAR normal = \"\\033[0m\";\nstatic DS_CONST_CHAR bold = \"\\033[1m\";\nstatic DS_CONST_CHAR italic = \"\\033[2m\";\nstatic DS_CONST_CHAR underline = \"\\033[4m\";\nstatic DS_CONST_CHAR blink = \"\\033[5m\";\nstatic DS_CONST_CHAR reverse = \"\\033[7m\";\nstatic DS_CONST_CHAR enditalic = \"\\033[22m\";\nstatic DS_CONST_CHAR endunderline = \"\\033[24m\";\nstatic DS_CONST_CHAR endblink = \"\\033[25m\";\nstatic DS_CONST_CHAR endreverse = \"\\033[27m\";\n#undef DS_CONST_CHAR\n};\n\/**\n * @brief Chooses a color from a 256 color map for a foreground color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string color(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/**\n * @brief Chooses a color from a 256 color map for a background color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string backcolor(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/\/ maybe you want to choose your own color\nint templateColorChooser(int i) {\n return i % 256;\n}\n\n\/**\n * @brief Highlights templates depending on the \"template\"-level.\n *\n * @param str The string containing the template string\n * @param maxlevel The maximal template-level the string is reduced to.\n * @returns A colored template string.\n *\/\nstd::string highlightTemplate(std::string str, int maxlevel = 10000) {\n if (maxlevel < 0)\n maxlevel = 0;\n int startindex = 0;\n int level = 0;\n for (size_t i = 0; i < str.size(); i++)\n {\n if (str[i] == '<')\n {\n level++;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(i, dummy);\n i += dummy.size();\n if (level == maxlevel)\n startindex = i + 1;\n } else if (str[i] == '>') {\n level--;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(++i, dummy);\n if (level + 1 == maxlevel)\n {\n int size = i - startindex - 1;\n str.erase(startindex, size);\n i = startindex + 1;\n }\n i += dummy.size();\n }\n }\n str += \"\\033[38;5;0m\";\n return str;\n} \/\/ highlightTemplate\n\n\/**\n * @brief A simple function highlighting a whole string in a specified foreground color.\n *\n * @param str The string you want to highlight.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightString(std::string str, int colornr = 0) {\n return \"\\033[38;5;\" + toString(colornr % 256) + \"m\" + str + \"\\033[0m\"; \/\/\"\\033[38;5;0m\";\n}\n\nstd::string highlightString(const std::string string, const std::string color = Colors::red)\n{\n return color + string + \"\\033[0m\";\n}\n\n\/**\n * @brief Highlights a substring of another string in a specified color.\n *\n * @param str The string where you want to highlight substrings.\n * @param substr The sub string you want to highlight in str.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {\n int index = str.find(substr, 0);\n\n while ( index != int(std::string::npos) )\n {\n std::string dummy = \"\\033[38;5;\" + toString(colornr % 256) + \"m\";\n std::string dummy2 = \"\\033[38;5;0m\";\n str.insert(index, dummy);\n str.insert(index + substr.size() + dummy.size(), dummy2);\n index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );\n }\n return str;\n} \/\/ highlightSearchString\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ end of DUNE_COMMON_COLOR_HH\n\n\/** Copyright (c) 2012, Stefan Girke\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n[common.color] renamed highlichtString() to colorString()#ifndef DUNE_COMMON_COLOR_HH\n#define DUNE_COMMON_COLOR_HH\n\n#include \n#include \n#include \n\n#ifdef __GNUC__\n #include \n#endif\n#include \n\n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/**\n * @brief namespace to define color constants that can be\n * used to print colored text in an output stream.\n *\n * * \\todo this could go into libdune-stuff\n * @warning Some color codes might be unsupported by your terminal.\n *\/\nstruct Colors {\n\n#define DS_CONST_CHAR const constexpr char*\n\n\/\/ foreground colors\nstatic DS_CONST_CHAR black = \"\\033[30m\";\nstatic DS_CONST_CHAR red = \"\\033[31m\";\nstatic DS_CONST_CHAR green = \"\\033[32m\";\nstatic DS_CONST_CHAR brown = \"\\033[33m\";\nstatic DS_CONST_CHAR blue = \"\\033[34m\";\nstatic DS_CONST_CHAR purple = \"\\033[35m\";\nstatic DS_CONST_CHAR cyan = \"\\033[36m\";\nstatic DS_CONST_CHAR lightgray = \"\\033[37m\";\n\/\/ light foreground colors\nstatic DS_CONST_CHAR darkgray = \"\\033[1;30m\";\nstatic DS_CONST_CHAR lightred = \"\\033[1;31m\";\nstatic DS_CONST_CHAR lightgreen = \"\\033[1;32m\";\nstatic DS_CONST_CHAR yellow = \"\\033[1;33m\";\nstatic DS_CONST_CHAR lightblue = \"\\033[1;34m\";\nstatic DS_CONST_CHAR lightpurple = \"\\033[1;35m\";\nstatic DS_CONST_CHAR lightcyan = \"\\033[1;36m\";\nstatic DS_CONST_CHAR white = \"\\033[1;37m\";\n\n\/\/ background colors\nstatic DS_CONST_CHAR bblack = \"\\033[40m\";\nstatic DS_CONST_CHAR bred = \"\\033[41m\";\nstatic DS_CONST_CHAR bgreen = \"\\033[42m\";\nstatic DS_CONST_CHAR bbrown = \"\\033[43m\";\nstatic DS_CONST_CHAR bblue = \"\\033[44m\";\nstatic DS_CONST_CHAR bpurple = \"\\033[45m\";\nstatic DS_CONST_CHAR bcyan = \"\\033[46m\";\nstatic DS_CONST_CHAR blightgray = \"\\033[47m\";\n\/\/ light background colors\nstatic DS_CONST_CHAR bdarkgray = \"\\033[1;40m\";\nstatic DS_CONST_CHAR blightred = \"\\033[1;41m\";\nstatic DS_CONST_CHAR blightgreen = \"\\033[1;42m\";\nstatic DS_CONST_CHAR byellow = \"\\033[1;43m\";\nstatic DS_CONST_CHAR blightblue = \"\\033[1;44m\";\nstatic DS_CONST_CHAR blightpurple = \"\\033[1;45m\";\nstatic DS_CONST_CHAR blightcyan = \"\\033[1;46m\";\nstatic DS_CONST_CHAR bwhite = \"\\033[1;47m\";\n};\n\/\/ modifiers\nstruct StreamModifiers {\nstatic DS_CONST_CHAR normal = \"\\033[0m\";\nstatic DS_CONST_CHAR bold = \"\\033[1m\";\nstatic DS_CONST_CHAR italic = \"\\033[2m\";\nstatic DS_CONST_CHAR underline = \"\\033[4m\";\nstatic DS_CONST_CHAR blink = \"\\033[5m\";\nstatic DS_CONST_CHAR reverse = \"\\033[7m\";\nstatic DS_CONST_CHAR enditalic = \"\\033[22m\";\nstatic DS_CONST_CHAR endunderline = \"\\033[24m\";\nstatic DS_CONST_CHAR endblink = \"\\033[25m\";\nstatic DS_CONST_CHAR endreverse = \"\\033[27m\";\n#undef DS_CONST_CHAR\n};\n\/**\n * @brief Chooses a color from a 256 color map for a foreground color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string color(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/**\n * @brief Chooses a color from a 256 color map for a background color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string backcolor(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/\/ maybe you want to choose your own color\nint templateColorChooser(int i) {\n return i % 256;\n}\n\n\/**\n * @brief Highlights templates depending on the \"template\"-level.\n *\n * @param str The string containing the template string\n * @param maxlevel The maximal template-level the string is reduced to.\n * @returns A colored template string.\n *\/\nstd::string highlightTemplate(std::string str, int maxlevel = 10000) {\n if (maxlevel < 0)\n maxlevel = 0;\n int startindex = 0;\n int level = 0;\n for (size_t i = 0; i < str.size(); i++)\n {\n if (str[i] == '<')\n {\n level++;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(i, dummy);\n i += dummy.size();\n if (level == maxlevel)\n startindex = i + 1;\n } else if (str[i] == '>') {\n level--;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(++i, dummy);\n if (level + 1 == maxlevel)\n {\n int size = i - startindex - 1;\n str.erase(startindex, size);\n i = startindex + 1;\n }\n i += dummy.size();\n }\n }\n str += \"\\033[38;5;0m\";\n return str;\n} \/\/ highlightTemplate\n\n\/**\n * @brief A simple function highlighting a whole string in a specified foreground color.\n *\n * @param str The string you want to highlight.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightString(std::string str, int colornr = 0) {\n return \"\\033[38;5;\" + toString(colornr % 256) + \"m\" + str + \"\\033[0m\"; \/\/\"\\033[38;5;0m\";\n}\n\nstd::string colorString(const std::string string, const std::string color = Colors::brown)\n{\n return color + string + \"\\033[0m\";\n}\n\n\/**\n * @brief Highlights a substring of another string in a specified color.\n *\n * @param str The string where you want to highlight substrings.\n * @param substr The sub string you want to highlight in str.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {\n int index = str.find(substr, 0);\n\n while ( index != int(std::string::npos) )\n {\n std::string dummy = \"\\033[38;5;\" + toString(colornr % 256) + \"m\";\n std::string dummy2 = \"\\033[38;5;0m\";\n str.insert(index, dummy);\n str.insert(index + substr.size() + dummy.size(), dummy2);\n index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );\n }\n return str;\n} \/\/ highlightSearchString\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ end of DUNE_COMMON_COLOR_HH\n\n\/** Copyright (c) 2012, Stefan Girke\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n<|endoftext|>"} {"text":"#include \"UpdaterWindow.h\"\n\n#include \"..\/3RVX\/3RVX.h\"\n#include \"..\/3RVX\/Logger.h\"\n#include \"..\/3RVX\/CommCtl.h\"\n#include \"..\/3RVX\/NotifyIcon.h\"\n#include \"..\/3RVX\/Settings.h\"\n#include \"resource.h\"\n#include \"Updater.h\"\n\nUpdaterWindow::UpdaterWindow() :\nWindow(L\"3RVX-UpdateWindow\") {\n HRESULT hr;\n hr = LoadIconMetric(\n Window::InstanceHandle(),\n MAKEINTRESOURCE(IDI_MAINICON),\n LIM_SMALL,\n &_smallIcon);\n if (hr != S_OK) {\n CLOG(L\"Could not load notification icon\");\n }\n\n hr = LoadIconMetric(\n Window::InstanceHandle(),\n MAKEINTRESOURCE(IDI_MAINICON),\n LIM_LARGE,\n &_largeIcon);\n if (hr != S_OK) {\n CLOG(L\"Could not load large notification icon\");\n }\n\n _menu = CreatePopupMenu();\n\n InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, L\"Install\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, L\"Ignore version\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, L\"Remind me later\");\n\n _menuFlags = TPM_RIGHTBUTTON;\n if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {\n _menuFlags |= TPM_RIGHTALIGN;\n } else {\n _menuFlags |= TPM_LEFTALIGN;\n }\n}\n\nUpdaterWindow::~UpdaterWindow() {\n delete _notifyIcon;\n DestroyIcon(_smallIcon);\n DestroyIcon(_largeIcon);\n}\n\nLRESULT UpdaterWindow::WndProc(\n HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {\n\n if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {\n switch (wParam) {\n case _3RVX::MSG_UPDATEICON:\n _settings = Settings::Instance();\n _settings->Load();\n\n \/* Set that we just checked for updates now *\/\n _settings->LastUpdateCheckNow();\n _settings->Save();\n\n std::pair newVersion = Updater::RemoteVersion();\n _versionString = Updater::VersionToString(newVersion);\n if (newVersion.first <= 0\n || _versionString == _settings->IgnoreUpdate()) {\n SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);\n break;\n }\n\n CLOG(L\"Creating update icon\");\n _notifyIcon = new NotifyIcon(\n Window::Handle(),\n L\"Update Available\",\n _smallIcon);\n\n CLOG(L\"Launching balloon notification\");\n _notifyIcon->Balloon(L\"Update Available\",\n L\"3RVX \" + _versionString, _largeIcon);\n break;\n }\n\n }\n\n return Window::WndProc(hWnd, message, wParam, lParam);\n}\n\nvoid UpdaterWindow::DoModal() {\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n}Implement the popup menu#include \"UpdaterWindow.h\"\n\n#include \"..\/3RVX\/3RVX.h\"\n#include \"..\/3RVX\/Logger.h\"\n#include \"..\/3RVX\/CommCtl.h\"\n#include \"..\/3RVX\/NotifyIcon.h\"\n#include \"..\/3RVX\/Settings.h\"\n#include \"resource.h\"\n#include \"Updater.h\"\n\nUpdaterWindow::UpdaterWindow() :\nWindow(L\"3RVX-UpdateWindow\") {\n HRESULT hr;\n hr = LoadIconMetric(\n Window::InstanceHandle(),\n MAKEINTRESOURCE(IDI_MAINICON),\n LIM_SMALL,\n &_smallIcon);\n if (hr != S_OK) {\n CLOG(L\"Could not load notification icon\");\n }\n\n hr = LoadIconMetric(\n Window::InstanceHandle(),\n MAKEINTRESOURCE(IDI_MAINICON),\n LIM_LARGE,\n &_largeIcon);\n if (hr != S_OK) {\n CLOG(L\"Could not load large notification icon\");\n }\n\n _menu = CreatePopupMenu();\n\n InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, L\"Install\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, L\"Ignore version\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, L\"Remind me later\");\n\n _menuFlags = TPM_RIGHTBUTTON;\n if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {\n _menuFlags |= TPM_RIGHTALIGN;\n } else {\n _menuFlags |= TPM_LEFTALIGN;\n }\n}\n\nUpdaterWindow::~UpdaterWindow() {\n delete _notifyIcon;\n DestroyIcon(_smallIcon);\n DestroyIcon(_largeIcon);\n}\n\nLRESULT UpdaterWindow::WndProc(\n HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {\n\n if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {\n switch (wParam) {\n case _3RVX::MSG_UPDATEICON:\n _settings = Settings::Instance();\n _settings->Load();\n\n \/* Set that we just checked for updates now *\/\n _settings->LastUpdateCheckNow();\n _settings->Save();\n\n std::pair newVersion = Updater::RemoteVersion();\n _versionString = Updater::VersionToString(newVersion);\n if (newVersion.first <= 0\n || _versionString == _settings->IgnoreUpdate()) {\n SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);\n break;\n }\n\n CLOG(L\"Creating update icon\");\n _notifyIcon = new NotifyIcon(\n Window::Handle(),\n L\"Update Available\",\n _smallIcon);\n\n CLOG(L\"Launching balloon notification\");\n _notifyIcon->Balloon(L\"Update Available\",\n L\"3RVX \" + _versionString, _largeIcon);\n break;\n }\n } else if (message == MSG_NOTIFYICON) {\n if (lParam == WM_LBUTTONUP\n || lParam == WM_RBUTTONUP\n || lParam == NIN_BALLOONUSERCLICK) {\n POINT p;\n GetCursorPos(&p);\n SetForegroundWindow(hWnd);\n TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y,\n Window::Handle(), NULL);\n PostMessage(hWnd, WM_NULL, 0, 0);\n }\n\n }\n\n return Window::WndProc(hWnd, message, wParam, lParam);\n}\n\nvoid UpdaterWindow::DoModal() {\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbOSMDownloader.h\"\n\n#include \n#include \"otbCommandLineArgumentParser.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n\n#include \"otbImageToEnvelopeVectorDataFilter.h\"\n#include \"otbVectorDataProperties.h\"\n#include \"otbOSMDataToVectorDataGenerator.h\"\n#include \"otbVectorDataFileWriter.h\"\n\nnamespace otb\n{\n\nint OSMDownloader::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"OSMDownloader\");\n descriptor->SetDescription(\"Generate a vector data from OSM on the input image extend\");\n descriptor->AddOption(\"InputImage\", \"Support to estimate the models on\",\n \"in\", 1, true, ApplicationDescriptor::InputImage);\n descriptor->AddOption(\"OSMKey\", \"OSM key (highway, building...)\",\n \"key\", 1, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"OSMValue\", \"OSM Value (motorway, footway...)\",\n \"val\", 1, false, ApplicationDescriptor::String);\n descriptor->AddOption(\"DEMDirectory\", \"DEM directory\",\n \"dem\", 1, false, ApplicationDescriptor::DirectoryName);\n descriptor->AddOption(\"Output\", \"OutputVectorData\",\n \"out\", 1, false, ApplicationDescriptor::FileName);\n return EXIT_SUCCESS;\n}\n\n\nint OSMDownloader::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n typedef otb::OSMDataToVectorDataGenerator VectorDataProviderType;\n typedef VectorDataProviderType::VectorDataType VectorDataType;\n typedef VectorDataType::ValuePrecisionType PrecisionType;\n typedef VectorDataType::PrecisionType CoordRepType;\n\n typedef otb::VectorImage ImageType;\n typedef otb::ImageFileReader ImageReaderType;\n\n typedef otb::ImageToEnvelopeVectorDataFilter\n EnvelopeFilterType;\n typedef otb::VectorDataProperties VectorDataPropertiesType;\n typedef otb::VectorDataFileWriter VectorDataWriterType;\n\n\n \/\/Instantiate\n ImageReaderType::Pointer imgReader = ImageReaderType::New();\n EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New();\n VectorDataProviderType::Pointer vdOSMGenerator = VectorDataProviderType::New();\n VectorDataPropertiesType::Pointer vdProperties = VectorDataPropertiesType::New();\n VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();\n\n \/\/Read the image\n imgReader->SetFileName(parseResult->GetParameterString(\"InputImage\"));\n imgReader->UpdateOutputInformation();\n\n \/\/Generate the envelope\n envelopeFilter->SetInput(imgReader->GetOutput()); \/\/->Output in WGS84\n if (parseResult->IsOptionPresent(\"CriterionFormula\"))\n {\n envelopeFilter->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n }\n envelopeFilter->Update();\n\n vdProperties->SetVectorDataObject(envelopeFilter->GetOutput());\n vdProperties->ComputeBoundingRegion();\n\n double north, south, east, west;\n north = vdProperties->GetBoundingRegion().GetIndex()[1]\n + vdProperties->GetBoundingRegion().GetSize()[1];\n south = vdProperties->GetBoundingRegion().GetIndex()[1];\n east = vdProperties->GetBoundingRegion().GetIndex()[0]\n + vdProperties->GetBoundingRegion().GetSize()[0];\n west = vdProperties->GetBoundingRegion().GetIndex()[0];\n\n \/*\n std::cout << \"north : \" << north << std::endl;\n std::cout << \"south : \" << south << std::endl;\n std::cout << \"east : \" << east << std::endl;\n std::cout << \"west : \" << west << std::endl;\n *\/\n\n vdOSMGenerator->SetNorth(north);\n vdOSMGenerator->SetSouth(south);\n vdOSMGenerator->SetEast(east);\n vdOSMGenerator->SetWest(west);\n\n try\n {\n vdOSMGenerator->Update();\n }\n catch ( itk::ExceptionObject & err )\n {\n std::cout << \"Exception itk::ExceptionObject raised !\" << std::endl;\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString(\"OSMKey\"))->Size()-3\n << std::endl;\n\n if (parseResult->IsOptionPresent(\"OSMValue\"))\n {\n vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString(\"OSMKey\"),\n parseResult->GetParameterString(\"OSMValue\")));\n }\n else\n {\n vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString(\"OSMKey\")));\n }\n\n vdWriter->SetFileName(parseResult->GetParameterString(\"Output\"));\n vdWriter->Update();\n\n return EXIT_SUCCESS;\n}\n\n}\nENH:enriched output message for OSMDownloader-cli application\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbOSMDownloader.h\"\n\n#include \n#include \"otbCommandLineArgumentParser.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n\n#include \"otbImageToEnvelopeVectorDataFilter.h\"\n#include \"otbVectorDataProperties.h\"\n#include \"otbOSMDataToVectorDataGenerator.h\"\n#include \"otbVectorDataFileWriter.h\"\n\nnamespace otb\n{\n\nint OSMDownloader::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"OSMDownloader\");\n descriptor->SetDescription(\"Generate a vector data from OSM on the input image extend\");\n descriptor->AddOption(\"InputImage\", \"Support to estimate the models on\",\n \"in\", 1, true, ApplicationDescriptor::InputImage);\n descriptor->AddOption(\"OSMKey\", \"OSM key (highway, building...)\",\n \"key\", 1, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"OSMValue\", \"OSM Value (motorway, footway...)\",\n \"val\", 1, false, ApplicationDescriptor::String);\n descriptor->AddOption(\"DEMDirectory\", \"DEM directory\",\n \"dem\", 1, false, ApplicationDescriptor::DirectoryName);\n descriptor->AddOption(\"Output\", \"OutputVectorData\",\n \"out\", 1, false, ApplicationDescriptor::FileName);\n return EXIT_SUCCESS;\n}\n\n\nint OSMDownloader::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n typedef otb::OSMDataToVectorDataGenerator VectorDataProviderType;\n typedef VectorDataProviderType::VectorDataType VectorDataType;\n typedef VectorDataType::ValuePrecisionType PrecisionType;\n typedef VectorDataType::PrecisionType CoordRepType;\n\n typedef otb::VectorImage ImageType;\n typedef otb::ImageFileReader ImageReaderType;\n\n typedef otb::ImageToEnvelopeVectorDataFilter\n EnvelopeFilterType;\n typedef otb::VectorDataProperties VectorDataPropertiesType;\n typedef otb::VectorDataFileWriter VectorDataWriterType;\n\n\n \/\/Instantiate\n ImageReaderType::Pointer imgReader = ImageReaderType::New();\n EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New();\n VectorDataProviderType::Pointer vdOSMGenerator = VectorDataProviderType::New();\n VectorDataPropertiesType::Pointer vdProperties = VectorDataPropertiesType::New();\n VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();\n\n \/\/Read the image\n imgReader->SetFileName(parseResult->GetParameterString(\"InputImage\"));\n imgReader->UpdateOutputInformation();\n\n \/\/Generate the envelope\n envelopeFilter->SetInput(imgReader->GetOutput()); \/\/->Output in WGS84\n if (parseResult->IsOptionPresent(\"CriterionFormula\"))\n {\n envelopeFilter->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n }\n envelopeFilter->Update();\n\n vdProperties->SetVectorDataObject(envelopeFilter->GetOutput());\n vdProperties->ComputeBoundingRegion();\n\n double north, south, east, west;\n north = vdProperties->GetBoundingRegion().GetIndex()[1]\n + vdProperties->GetBoundingRegion().GetSize()[1];\n south = vdProperties->GetBoundingRegion().GetIndex()[1];\n east = vdProperties->GetBoundingRegion().GetIndex()[0]\n + vdProperties->GetBoundingRegion().GetSize()[0];\n west = vdProperties->GetBoundingRegion().GetIndex()[0];\n\n \/*\n std::cout << \"north : \" << north << std::endl;\n std::cout << \"south : \" << south << std::endl;\n std::cout << \"east : \" << east << std::endl;\n std::cout << \"west : \" << west << std::endl;\n *\/\n\n vdOSMGenerator->SetNorth(north);\n vdOSMGenerator->SetSouth(south);\n vdOSMGenerator->SetEast(east);\n vdOSMGenerator->SetWest(west);\n\n try\n {\n vdOSMGenerator->Update();\n }\n catch ( itk::ExceptionObject & err )\n {\n std::cout << \"Exception itk::ExceptionObject raised !\" << std::endl;\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString(\"OSMKey\"))->Size()-3\n << \" vector elements retrieved\" << std::endl;\n\n if (parseResult->IsOptionPresent(\"OSMValue\"))\n {\n vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString(\"OSMKey\"),\n parseResult->GetParameterString(\"OSMValue\")));\n }\n else\n {\n vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString(\"OSMKey\")));\n }\n\n vdWriter->SetFileName(parseResult->GetParameterString(\"Output\"));\n vdWriter->Update();\n\n return EXIT_SUCCESS;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2009, 2010 Google 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\n#include \n#include \n\n#include \n\nstd::map ProxyControl::proxyConstructorMap;\n\nProxyControl::ProxyControl(NPP npp) :\n npp(npp),\n nestingCount(1)\n{\n}\n\nProxyControl::~ProxyControl()\n{\n \/\/ TODO: Release objects in newList and oldList\n}\n\nObject* ProxyControl::createProxy(NPObject* object, const Reflect::Type type)\n{\n if (!object)\n {\n return 0;\n }\n\n std::string className = getInterfaceName(npp, object);\n if (className == \"Object\")\n {\n \/\/ TODO: We should define 'Object' interface\n return 0;\n }\n\n bool usedHint = false;\n for (;;)\n {\n std::map::iterator it;\n it = proxyConstructorMap.find(className);\n if (it != proxyConstructorMap.end())\n {\n ProxyObject browserObject(object, npp);\n if (Object* object = (*it).second(browserObject))\n {\n return track(object);\n }\n }\n if (!type.isObject() || usedHint)\n {\n break;\n }\n className = type.getQualifiedName();\n size_t pos = className.rfind(':');\n if (pos != std::string::npos)\n {\n className = className.substr(pos + 1);\n printf(\"%s: use the class name '%s' as hinted.\\n\", __func__, className.c_str());\n }\n usedHint = true;\n }\n return 0;\n}\n\nlong ProxyControl::enter()\n{\n return ++nestingCount;\n}\n\nlong ProxyControl::leave()\n{\n --nestingCount;\n assert(0 <= nestingCount);\n if (nestingCount == 0)\n {\n while (!newList.empty())\n {\n Object* object = newList.front();\n newList.pop_front();\n if (0 < object->release())\n {\n oldList.push_back(object);\n }\n }\n }\n return nestingCount;\n}\n\nvoid ProxyControl::registerMetaData(const char* meta, Object* (*createProxy)(ProxyObject object), const char* alias)\n{\n Reflect::Interface interface(meta);\n std::string name = interface.getName();\n if (alias)\n {\n name = alias;\n }\n proxyConstructorMap[name] = createProxy;\n printf(\"%s\\n\", name.c_str());\n}\n\nProxyObject::ProxyObject(NPObject* object, NPP npp) :\n object(object),\n npp(npp),\n count(0)\n{\n}\n\nProxyObject::ProxyObject(const ProxyObject& original) :\n object(original.object),\n npp(original.npp),\n count(original.count)\n{\n}\n\nProxyObject::~ProxyObject()\n{\n \/\/ TODO: Remove this from newList or oldList is it is still included\n}\n\nunsigned int ProxyObject::retain()\n{\n NPN_RetainObject(object);\n return ++count;\n}\n\nunsigned int ProxyObject::release()\n{\n if (0 < count)\n {\n NPN_ReleaseObject(object);\n --count;\n }\n if (count == 0)\n {\n delete this;\n return 0;\n }\n return count;\n}\n\nunsigned int ProxyObject::mark()\n{\n return ++count;\n}\n\nPluginInstance::PluginInstance(NPP npp, NPObject* window) :\n proxyControl(npp),\n stubControl(npp),\n window(0)\n{\n npp->pdata = this;\n this->window = interface_cast(proxyControl.createProxy(window, Reflect::Type(\"O14::html::Window\")));\n if (this->window)\n {\n ProxyObject* proxy = interface_cast(this->window);\n proxy->mark();\n proxy->retain();\n }\n}\n\nPluginInstance::~PluginInstance()\n{\n if (window)\n {\n window->release();\n }\n}\n\n(~ProxyObject) : Fix a typo.\/*\n * Copyright 2009, 2010 Google 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\n#include \n#include \n\n#include \n\nstd::map ProxyControl::proxyConstructorMap;\n\nProxyControl::ProxyControl(NPP npp) :\n npp(npp),\n nestingCount(1)\n{\n}\n\nProxyControl::~ProxyControl()\n{\n \/\/ TODO: Release objects in newList and oldList\n}\n\nObject* ProxyControl::createProxy(NPObject* object, const Reflect::Type type)\n{\n if (!object)\n {\n return 0;\n }\n\n std::string className = getInterfaceName(npp, object);\n if (className == \"Object\")\n {\n \/\/ TODO: We should define 'Object' interface\n return 0;\n }\n\n bool usedHint = false;\n for (;;)\n {\n std::map::iterator it;\n it = proxyConstructorMap.find(className);\n if (it != proxyConstructorMap.end())\n {\n ProxyObject browserObject(object, npp);\n if (Object* object = (*it).second(browserObject))\n {\n return track(object);\n }\n }\n if (!type.isObject() || usedHint)\n {\n break;\n }\n className = type.getQualifiedName();\n size_t pos = className.rfind(':');\n if (pos != std::string::npos)\n {\n className = className.substr(pos + 1);\n printf(\"%s: use the class name '%s' as hinted.\\n\", __func__, className.c_str());\n }\n usedHint = true;\n }\n return 0;\n}\n\nlong ProxyControl::enter()\n{\n return ++nestingCount;\n}\n\nlong ProxyControl::leave()\n{\n --nestingCount;\n assert(0 <= nestingCount);\n if (nestingCount == 0)\n {\n while (!newList.empty())\n {\n Object* object = newList.front();\n newList.pop_front();\n if (0 < object->release())\n {\n oldList.push_back(object);\n }\n }\n }\n return nestingCount;\n}\n\nvoid ProxyControl::registerMetaData(const char* meta, Object* (*createProxy)(ProxyObject object), const char* alias)\n{\n Reflect::Interface interface(meta);\n std::string name = interface.getName();\n if (alias)\n {\n name = alias;\n }\n proxyConstructorMap[name] = createProxy;\n printf(\"%s\\n\", name.c_str());\n}\n\nProxyObject::ProxyObject(NPObject* object, NPP npp) :\n object(object),\n npp(npp),\n count(0)\n{\n}\n\nProxyObject::ProxyObject(const ProxyObject& original) :\n object(original.object),\n npp(original.npp),\n count(original.count)\n{\n}\n\nProxyObject::~ProxyObject()\n{\n \/\/ TODO: Remove this from newList or oldList if it is still included\n}\n\nunsigned int ProxyObject::retain()\n{\n NPN_RetainObject(object);\n return ++count;\n}\n\nunsigned int ProxyObject::release()\n{\n if (0 < count)\n {\n NPN_ReleaseObject(object);\n --count;\n }\n if (count == 0)\n {\n delete this;\n return 0;\n }\n return count;\n}\n\nunsigned int ProxyObject::mark()\n{\n return ++count;\n}\n\nPluginInstance::PluginInstance(NPP npp, NPObject* window) :\n proxyControl(npp),\n stubControl(npp),\n window(0)\n{\n npp->pdata = this;\n this->window = interface_cast(proxyControl.createProxy(window, Reflect::Type(\"O14::html::Window\")));\n if (this->window)\n {\n ProxyObject* proxy = interface_cast(this->window);\n proxy->mark();\n proxy->retain();\n }\n}\n\nPluginInstance::~PluginInstance()\n{\n if (window)\n {\n window->release();\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/debugger\/devtools_netlog_observer.h\"\n\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/io_thread.h\"\n#include \"content\/common\/resource_response.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_net_log_params.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_netlog_params.h\"\n#include \"webkit\/glue\/resource_loader_bridge.h\"\n\nconst size_t kMaxNumEntries = 1000;\n\nDevToolsNetLogObserver* DevToolsNetLogObserver::instance_ = NULL;\n\nDevToolsNetLogObserver::DevToolsNetLogObserver(ChromeNetLog* chrome_net_log)\n : ChromeNetLog::ThreadSafeObserver(net::NetLog::LOG_ALL_BUT_BYTES),\n chrome_net_log_(chrome_net_log) {\n chrome_net_log_->AddObserver(this);\n}\n\nDevToolsNetLogObserver::~DevToolsNetLogObserver() {\n chrome_net_log_->RemoveObserver(this);\n}\n\nDevToolsNetLogObserver::ResourceInfo*\nDevToolsNetLogObserver::GetResourceInfo(uint32 id) {\n RequestToInfoMap::iterator it = request_to_info_.find(id);\n if (it != request_to_info_.end())\n return it->second;\n return NULL;\n}\n\nvoid DevToolsNetLogObserver::OnAddEntry(net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n \/\/ The events that the Observer is interested in only occur on the IO thread.\n if (!BrowserThread::CurrentlyOn(BrowserThread::IO))\n return;\n\n \/\/ The events that the Observer is interested in only occur on the IO thread.\n if (!BrowserThread::CurrentlyOn(BrowserThread::IO))\n return;\n if (source.type == net::NetLog::SOURCE_URL_REQUEST)\n OnAddURLRequestEntry(type, time, source, phase, params);\n else if (source.type == net::NetLog::SOURCE_HTTP_STREAM_JOB)\n OnAddHTTPStreamJobEntry(type, time, source, phase, params);\n else if (source.type == net::NetLog::SOURCE_SOCKET)\n OnAddSocketEntry(type, time, source, phase, params);\n}\n\nvoid DevToolsNetLogObserver::OnAddURLRequestEntry(\n net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n bool is_begin = phase == net::NetLog::PHASE_BEGIN;\n bool is_end = phase == net::NetLog::PHASE_END;\n\n if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {\n if (is_begin) {\n int load_flags = static_cast<\n net::URLRequestStartEventParameters*>(params)->load_flags();\n if (!(load_flags & net::LOAD_REPORT_RAW_HEADERS))\n return;\n\n if (request_to_info_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The raw headers observer url request count has grown \"\n \"larger than expected, resetting\";\n request_to_info_.clear();\n }\n\n request_to_info_[source.id] = new ResourceInfo();\n\n if (request_to_encoded_data_length_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The encoded data length observer url request count \"\n \"has grown larger than expected, resetting\";\n request_to_encoded_data_length_.clear();\n }\n\n request_to_encoded_data_length_[source.id] = 0;\n }\n return;\n } else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {\n \/\/ Cleanup records based on the TYPE_REQUEST_ALIVE entry.\n if (is_end) {\n request_to_info_.erase(source.id);\n request_to_encoded_data_length_.erase(source.id);\n }\n return;\n }\n\n ResourceInfo* info = GetResourceInfo(source.id);\n if (!info)\n return;\n\n switch (type) {\n case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS: {\n net::NetLogHttpRequestParameter* request_parameter =\n static_cast(params);\n const net::HttpRequestHeaders &request_headers =\n request_parameter->GetHeaders();\n for (net::HttpRequestHeaders::Iterator it(request_headers);\n it.GetNext();) {\n info->request_headers.push_back(std::make_pair(it.name(),\n it.value()));\n }\n info->request_headers_text =\n request_parameter->GetLine() +\n request_parameter->GetHeaders().ToString();\n break;\n }\n case net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS: {\n const net::HttpResponseHeaders& response_headers =\n static_cast(params)->GetHeaders();\n info->http_status_code = response_headers.response_code();\n info->http_status_text = response_headers.GetStatusText();\n std::string name, value;\n for (void* it = NULL;\n response_headers.EnumerateHeaderLines(&it, &name, &value); ) {\n info->response_headers.push_back(std::make_pair(name, value));\n }\n info->response_headers_text =\n net::HttpUtil::ConvertHeadersBackToHTTPResponse(\n response_headers.raw_headers());\n break;\n }\n case net::NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_JOB: {\n uint32 http_stream_job_id = static_cast(\n params)->value().id;\n HTTPStreamJobToSocketMap::iterator it =\n http_stream_job_to_socket_.find(http_stream_job_id);\n if (it == http_stream_job_to_socket_.end())\n return;\n uint32 socket_id = it->second;\n\n if (socket_to_request_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The url request observer socket count has grown \"\n \"larger than expected, resetting\";\n socket_to_request_.clear();\n }\n\n socket_to_request_[socket_id] = source.id;\n http_stream_job_to_socket_.erase(http_stream_job_id);\n break;\n }\n default:\n break;\n }\n}\n\nvoid DevToolsNetLogObserver::OnAddHTTPStreamJobEntry(\n net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n if (type == net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET) {\n uint32 socket_id = static_cast(\n params)->value().id;\n\n \/\/ Prevents us from passively growing the memory unbounded in\n \/\/ case something went wrong. Should not happen.\n if (http_stream_job_to_socket_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The load timing observer http stream job count \"\n \"has grown larger than expected, resetting\";\n http_stream_job_to_socket_.clear();\n }\n http_stream_job_to_socket_[source.id] = socket_id;\n }\n}\n\nvoid DevToolsNetLogObserver::OnAddSocketEntry(\n net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n bool is_end = phase == net::NetLog::PHASE_END;\n\n SocketToRequestMap::iterator it = socket_to_request_.find(source.id);\n if (it == socket_to_request_.end())\n return;\n uint32 request_id = it->second;\n\n if (type == net::NetLog::TYPE_SOCKET_IN_USE) {\n if (is_end)\n socket_to_request_.erase(source.id);\n return;\n }\n\n RequestToEncodedDataLengthMap::iterator encoded_data_length_it =\n request_to_encoded_data_length_.find(request_id);\n if (encoded_data_length_it == request_to_encoded_data_length_.end())\n return;\n\n if (net::NetLog::TYPE_SOCKET_BYTES_RECEIVED == type) {\n int byte_count = 0;\n scoped_ptr value(params->ToValue());\n if (!value->IsType(Value::TYPE_DICTIONARY))\n return;\n\n DictionaryValue* dValue = static_cast(value.get());\n if (!dValue->GetInteger(\"byte_count\", &byte_count))\n return;\n\n encoded_data_length_it->second += byte_count;\n }\n}\n\nvoid DevToolsNetLogObserver::Attach(IOThread* io_thread) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(!instance_);\n\n instance_ = new DevToolsNetLogObserver(io_thread->net_log());\n}\n\nvoid DevToolsNetLogObserver::Detach() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(instance_);\n\n delete instance_;\n instance_ = NULL;\n}\n\nDevToolsNetLogObserver* DevToolsNetLogObserver::GetInstance() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n return instance_;\n}\n\n\/\/ static\nvoid DevToolsNetLogObserver::PopulateResponseInfo(net::URLRequest* request,\n ResourceResponse* response) {\n if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))\n return;\n\n uint32 source_id = request->net_log().source().id;\n DevToolsNetLogObserver* dev_tools_net_log_observer =\n DevToolsNetLogObserver::GetInstance();\n if (dev_tools_net_log_observer == NULL)\n return;\n response->response_head.devtools_info =\n dev_tools_net_log_observer->GetResourceInfo(source_id);\n}\n\n\/\/ static\nint DevToolsNetLogObserver::GetAndResetEncodedDataLength(\n net::URLRequest* request) {\n if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))\n return -1;\n\n uint32 source_id = request->net_log().source().id;\n DevToolsNetLogObserver* dev_tools_net_log_observer =\n DevToolsNetLogObserver::GetInstance();\n if (dev_tools_net_log_observer == NULL)\n return -1;\n\n RequestToEncodedDataLengthMap::iterator it =\n dev_tools_net_log_observer->request_to_encoded_data_length_.find(\n source_id);\n if (it == dev_tools_net_log_observer->request_to_encoded_data_length_.end())\n return -1;\n int encoded_data_length = it->second;\n it->second = 0;\n return encoded_data_length;\n}\nClear devtools headers when url_request is reused for several HTTP requests\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/debugger\/devtools_netlog_observer.h\"\n\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/io_thread.h\"\n#include \"content\/common\/resource_response.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_net_log_params.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_netlog_params.h\"\n#include \"webkit\/glue\/resource_loader_bridge.h\"\n\nconst size_t kMaxNumEntries = 1000;\n\nDevToolsNetLogObserver* DevToolsNetLogObserver::instance_ = NULL;\n\nDevToolsNetLogObserver::DevToolsNetLogObserver(ChromeNetLog* chrome_net_log)\n : ChromeNetLog::ThreadSafeObserver(net::NetLog::LOG_ALL_BUT_BYTES),\n chrome_net_log_(chrome_net_log) {\n chrome_net_log_->AddObserver(this);\n}\n\nDevToolsNetLogObserver::~DevToolsNetLogObserver() {\n chrome_net_log_->RemoveObserver(this);\n}\n\nDevToolsNetLogObserver::ResourceInfo*\nDevToolsNetLogObserver::GetResourceInfo(uint32 id) {\n RequestToInfoMap::iterator it = request_to_info_.find(id);\n if (it != request_to_info_.end())\n return it->second;\n return NULL;\n}\n\nvoid DevToolsNetLogObserver::OnAddEntry(net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n \/\/ The events that the Observer is interested in only occur on the IO thread.\n if (!BrowserThread::CurrentlyOn(BrowserThread::IO))\n return;\n\n \/\/ The events that the Observer is interested in only occur on the IO thread.\n if (!BrowserThread::CurrentlyOn(BrowserThread::IO))\n return;\n if (source.type == net::NetLog::SOURCE_URL_REQUEST)\n OnAddURLRequestEntry(type, time, source, phase, params);\n else if (source.type == net::NetLog::SOURCE_HTTP_STREAM_JOB)\n OnAddHTTPStreamJobEntry(type, time, source, phase, params);\n else if (source.type == net::NetLog::SOURCE_SOCKET)\n OnAddSocketEntry(type, time, source, phase, params);\n}\n\nvoid DevToolsNetLogObserver::OnAddURLRequestEntry(\n net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n bool is_begin = phase == net::NetLog::PHASE_BEGIN;\n bool is_end = phase == net::NetLog::PHASE_END;\n\n if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {\n if (is_begin) {\n int load_flags = static_cast<\n net::URLRequestStartEventParameters*>(params)->load_flags();\n if (!(load_flags & net::LOAD_REPORT_RAW_HEADERS))\n return;\n\n if (request_to_info_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The raw headers observer url request count has grown \"\n \"larger than expected, resetting\";\n request_to_info_.clear();\n }\n\n request_to_info_[source.id] = new ResourceInfo();\n\n if (request_to_encoded_data_length_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The encoded data length observer url request count \"\n \"has grown larger than expected, resetting\";\n request_to_encoded_data_length_.clear();\n }\n\n request_to_encoded_data_length_[source.id] = 0;\n }\n return;\n } else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {\n \/\/ Cleanup records based on the TYPE_REQUEST_ALIVE entry.\n if (is_end) {\n request_to_info_.erase(source.id);\n request_to_encoded_data_length_.erase(source.id);\n }\n return;\n }\n\n ResourceInfo* info = GetResourceInfo(source.id);\n if (!info)\n return;\n\n switch (type) {\n case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS: {\n net::NetLogHttpRequestParameter* request_parameter =\n static_cast(params);\n const net::HttpRequestHeaders &request_headers =\n request_parameter->GetHeaders();\n\n \/\/ We need to clear headers in case the same url_request is reused for\n \/\/ several http requests (e.g. see http:\/\/crbug.com\/80157).\n info->request_headers.clear();\n\n for (net::HttpRequestHeaders::Iterator it(request_headers);\n it.GetNext();) {\n info->request_headers.push_back(std::make_pair(it.name(),\n it.value()));\n }\n info->request_headers_text =\n request_parameter->GetLine() +\n request_parameter->GetHeaders().ToString();\n break;\n }\n case net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS: {\n const net::HttpResponseHeaders& response_headers =\n static_cast(params)->GetHeaders();\n info->http_status_code = response_headers.response_code();\n info->http_status_text = response_headers.GetStatusText();\n std::string name, value;\n\n \/\/ We need to clear headers in case the same url_request is reused for\n \/\/ several http requests (e.g. see http:\/\/crbug.com\/80157).\n info->response_headers.clear();\n\n for (void* it = NULL;\n response_headers.EnumerateHeaderLines(&it, &name, &value); ) {\n info->response_headers.push_back(std::make_pair(name, value));\n }\n info->response_headers_text =\n net::HttpUtil::ConvertHeadersBackToHTTPResponse(\n response_headers.raw_headers());\n break;\n }\n case net::NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_JOB: {\n uint32 http_stream_job_id = static_cast(\n params)->value().id;\n HTTPStreamJobToSocketMap::iterator it =\n http_stream_job_to_socket_.find(http_stream_job_id);\n if (it == http_stream_job_to_socket_.end())\n return;\n uint32 socket_id = it->second;\n\n if (socket_to_request_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The url request observer socket count has grown \"\n \"larger than expected, resetting\";\n socket_to_request_.clear();\n }\n\n socket_to_request_[socket_id] = source.id;\n http_stream_job_to_socket_.erase(http_stream_job_id);\n break;\n }\n default:\n break;\n }\n}\n\nvoid DevToolsNetLogObserver::OnAddHTTPStreamJobEntry(\n net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n if (type == net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET) {\n uint32 socket_id = static_cast(\n params)->value().id;\n\n \/\/ Prevents us from passively growing the memory unbounded in\n \/\/ case something went wrong. Should not happen.\n if (http_stream_job_to_socket_.size() > kMaxNumEntries) {\n LOG(WARNING) << \"The load timing observer http stream job count \"\n \"has grown larger than expected, resetting\";\n http_stream_job_to_socket_.clear();\n }\n http_stream_job_to_socket_[source.id] = socket_id;\n }\n}\n\nvoid DevToolsNetLogObserver::OnAddSocketEntry(\n net::NetLog::EventType type,\n const base::TimeTicks& time,\n const net::NetLog::Source& source,\n net::NetLog::EventPhase phase,\n net::NetLog::EventParameters* params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n bool is_end = phase == net::NetLog::PHASE_END;\n\n SocketToRequestMap::iterator it = socket_to_request_.find(source.id);\n if (it == socket_to_request_.end())\n return;\n uint32 request_id = it->second;\n\n if (type == net::NetLog::TYPE_SOCKET_IN_USE) {\n if (is_end)\n socket_to_request_.erase(source.id);\n return;\n }\n\n RequestToEncodedDataLengthMap::iterator encoded_data_length_it =\n request_to_encoded_data_length_.find(request_id);\n if (encoded_data_length_it == request_to_encoded_data_length_.end())\n return;\n\n if (net::NetLog::TYPE_SOCKET_BYTES_RECEIVED == type) {\n int byte_count = 0;\n scoped_ptr value(params->ToValue());\n if (!value->IsType(Value::TYPE_DICTIONARY))\n return;\n\n DictionaryValue* dValue = static_cast(value.get());\n if (!dValue->GetInteger(\"byte_count\", &byte_count))\n return;\n\n encoded_data_length_it->second += byte_count;\n }\n}\n\nvoid DevToolsNetLogObserver::Attach(IOThread* io_thread) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(!instance_);\n\n instance_ = new DevToolsNetLogObserver(io_thread->net_log());\n}\n\nvoid DevToolsNetLogObserver::Detach() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(instance_);\n\n delete instance_;\n instance_ = NULL;\n}\n\nDevToolsNetLogObserver* DevToolsNetLogObserver::GetInstance() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n return instance_;\n}\n\n\/\/ static\nvoid DevToolsNetLogObserver::PopulateResponseInfo(net::URLRequest* request,\n ResourceResponse* response) {\n if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))\n return;\n\n uint32 source_id = request->net_log().source().id;\n DevToolsNetLogObserver* dev_tools_net_log_observer =\n DevToolsNetLogObserver::GetInstance();\n if (dev_tools_net_log_observer == NULL)\n return;\n response->response_head.devtools_info =\n dev_tools_net_log_observer->GetResourceInfo(source_id);\n}\n\n\/\/ static\nint DevToolsNetLogObserver::GetAndResetEncodedDataLength(\n net::URLRequest* request) {\n if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))\n return -1;\n\n uint32 source_id = request->net_log().source().id;\n DevToolsNetLogObserver* dev_tools_net_log_observer =\n DevToolsNetLogObserver::GetInstance();\n if (dev_tools_net_log_observer == NULL)\n return -1;\n\n RequestToEncodedDataLengthMap::iterator it =\n dev_tools_net_log_observer->request_to_encoded_data_length_.find(\n source_id);\n if (it == dev_tools_net_log_observer->request_to_encoded_data_length_.end())\n return -1;\n int encoded_data_length = it->second;\n it->second = 0;\n return encoded_data_length;\n}\n<|endoftext|>"} {"text":"DevTools: temporarily disable completion test which fails on Linux<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\n\nnamespace {\n\n\/\/ Used to block until a dev tools client window's browser is closed.\nclass BrowserClosedObserver : public NotificationObserver {\n public:\n BrowserClosedObserver(Browser* browser) {\n registrar_.Add(this, NotificationType::BROWSER_CLOSED,\n Source(browser));\n ui_test_utils::RunMessageLoop();\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n MessageLoopForUI::current()->Quit();\n }\n\n private:\n NotificationRegistrar registrar_;\n DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);\n};\n\n\/\/ The delay waited in some cases where we don't have a notifications for an\n\/\/ action we take.\nconst int kActionDelayMs = 500;\n\nconst wchar_t kConsoleTestPage[] = L\"files\/devtools\/console_test_page.html\";\nconst wchar_t kDebuggerTestPage[] = L\"files\/devtools\/debugger_test_page.html\";\nconst wchar_t kEvalTestPage[] = L\"files\/devtools\/eval_test_page.html\";\nconst wchar_t kJsPage[] = L\"files\/devtools\/js_page.html\";\nconst wchar_t kResourceTestPage[] = L\"files\/devtools\/resource_test_page.html\";\nconst wchar_t kSimplePage[] = L\"files\/devtools\/simple_page.html\";\n\nclass DevToolsSanityTest : public InProcessBrowserTest {\n public:\n DevToolsSanityTest() {\n set_show_window(true);\n EnableDOMAutomation();\n }\n\n protected:\n void RunTest(const std::string& test_name, const std::wstring& test_page) {\n OpenDevToolsWindow(test_page);\n std::string result;\n\n \/\/ At first check that JavaScript part of the front-end is loaded by\n \/\/ checking that global variable uiTests exists(it's created after all js\n \/\/ files have been loaded) and has runTest method.\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"'' + (window.uiTests && (typeof uiTests.runTest)));\",\n &result));\n\n if (result == \"function\") {\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n UTF8ToWide(StringPrintf(\"uiTests.runTest('%s')\",\n test_name.c_str())),\n &result));\n EXPECT_EQ(\"[OK]\", result);\n } else {\n FAIL() << \"DevTools front-end is broken.\";\n }\n CloseDevToolsWindow();\n }\n\n void OpenDevToolsWindow(const std::wstring& test_page) {\n HTTPTestServer* server = StartHTTPServer();\n GURL url = server->TestServerPageW(test_page);\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* tab = browser()->GetTabContentsAt(0);\n inspected_rvh_ = tab->render_view_host();\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n devtools_manager->OpenDevToolsWindow(inspected_rvh_);\n\n DevToolsClientHost* client_host =\n devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);\n window_ = client_host->AsDevToolsWindow();\n RenderViewHost* client_rvh = window_->GetRenderViewHost();\n client_contents_ = client_rvh->delegate()->GetAsTabContents();\n ui_test_utils::WaitForNavigation(&client_contents_->controller());\n }\n\n void CloseDevToolsWindow() {\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n \/\/ UnregisterDevToolsClientHostFor may destroy window_ so store the browser\n \/\/ first.\n Browser* browser = window_->browser();\n devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);\n BrowserClosedObserver close_observer(browser);\n }\n\n TabContents* client_contents_;\n DevToolsWindow* window_;\n RenderViewHost* inspected_rvh_;\n};\n\n\/\/ WebInspector opens.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {\n RunTest(\"testHostIsPresent\", kSimplePage);\n}\n\n\/\/ Tests elements panel basics.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {\n RunTest(\"testElementsTreeRoot\", kSimplePage);\n}\n\n\/\/ Tests main resource load.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {\n RunTest(\"testMainResource\", kSimplePage);\n}\n\n\/\/ Tests resources panel enabling.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {\n RunTest(\"testEnableResourcesTab\", kSimplePage);\n}\n\n\/\/ Tests resource headers.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {\n RunTest(\"testResourceHeaders\", kResourceTestPage);\n}\n\n\/\/ Tests profiler panel.\n\/\/ Flaky, http:\/\/crbug.com\/21108\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {\n RunTest(\"testProfilerTab\", kJsPage);\n}\n\n\/\/ Tests scripts panel showing.\n\/\/ http:\/\/crbug.com\/16767\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {\n RunTest(\"testShowScriptsTab\", kDebuggerTestPage);\n}\n\n\/\/ Tests set breakpoint.\n\/\/ http:\/\/crbug.com\/16767\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {\n RunTest(\"testSetBreakpoint\", kDebuggerTestPage);\n}\n\n\/\/ Tests that 'Pause' button works for eval.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {\n RunTest(\"testPauseInEval\", kDebuggerTestPage);\n}\n\n\/\/ Tests console eval.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {\n RunTest(\"testConsoleEval\", kConsoleTestPage);\n}\n\n\/\/ Tests console log.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {\n RunTest(\"testConsoleLog\", kConsoleTestPage);\n}\n\n\/\/ Tests eval global values.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {\n RunTest(\"testEvalGlobal\", kEvalTestPage);\n}\n\n\/\/ Tests eval on call frame.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {\n RunTest(\"testEvalCallFrame\", kEvalTestPage);\n}\n\n} \/\/ namespace\nDevTools: re-enable some devtools interactive ui tests that started to fail after WebKit roll.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\n\nnamespace {\n\n\/\/ Used to block until a dev tools client window's browser is closed.\nclass BrowserClosedObserver : public NotificationObserver {\n public:\n BrowserClosedObserver(Browser* browser) {\n registrar_.Add(this, NotificationType::BROWSER_CLOSED,\n Source(browser));\n ui_test_utils::RunMessageLoop();\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n MessageLoopForUI::current()->Quit();\n }\n\n private:\n NotificationRegistrar registrar_;\n DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);\n};\n\n\/\/ The delay waited in some cases where we don't have a notifications for an\n\/\/ action we take.\nconst int kActionDelayMs = 500;\n\nconst wchar_t kConsoleTestPage[] = L\"files\/devtools\/console_test_page.html\";\nconst wchar_t kDebuggerTestPage[] = L\"files\/devtools\/debugger_test_page.html\";\nconst wchar_t kEvalTestPage[] = L\"files\/devtools\/eval_test_page.html\";\nconst wchar_t kJsPage[] = L\"files\/devtools\/js_page.html\";\nconst wchar_t kResourceTestPage[] = L\"files\/devtools\/resource_test_page.html\";\nconst wchar_t kSimplePage[] = L\"files\/devtools\/simple_page.html\";\n\nclass DevToolsSanityTest : public InProcessBrowserTest {\n public:\n DevToolsSanityTest() {\n set_show_window(true);\n EnableDOMAutomation();\n }\n\n protected:\n void RunTest(const std::string& test_name, const std::wstring& test_page) {\n OpenDevToolsWindow(test_page);\n std::string result;\n\n \/\/ At first check that JavaScript part of the front-end is loaded by\n \/\/ checking that global variable uiTests exists(it's created after all js\n \/\/ files have been loaded) and has runTest method.\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"'' + (window.uiTests && (typeof uiTests.runTest)));\",\n &result));\n\n if (result == \"function\") {\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n UTF8ToWide(StringPrintf(\"uiTests.runTest('%s')\",\n test_name.c_str())),\n &result));\n EXPECT_EQ(\"[OK]\", result);\n } else {\n FAIL() << \"DevTools front-end is broken.\";\n }\n CloseDevToolsWindow();\n }\n\n void OpenDevToolsWindow(const std::wstring& test_page) {\n HTTPTestServer* server = StartHTTPServer();\n GURL url = server->TestServerPageW(test_page);\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* tab = browser()->GetTabContentsAt(0);\n inspected_rvh_ = tab->render_view_host();\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n devtools_manager->OpenDevToolsWindow(inspected_rvh_);\n\n DevToolsClientHost* client_host =\n devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);\n window_ = client_host->AsDevToolsWindow();\n RenderViewHost* client_rvh = window_->GetRenderViewHost();\n client_contents_ = client_rvh->delegate()->GetAsTabContents();\n ui_test_utils::WaitForNavigation(&client_contents_->controller());\n }\n\n void CloseDevToolsWindow() {\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n \/\/ UnregisterDevToolsClientHostFor may destroy window_ so store the browser\n \/\/ first.\n Browser* browser = window_->browser();\n devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);\n BrowserClosedObserver close_observer(browser);\n }\n\n TabContents* client_contents_;\n DevToolsWindow* window_;\n RenderViewHost* inspected_rvh_;\n};\n\n\/\/ WebInspector opens.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {\n RunTest(\"testHostIsPresent\", kSimplePage);\n}\n\n\/\/ Tests elements panel basics.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {\n RunTest(\"testElementsTreeRoot\", kSimplePage);\n}\n\n\/\/ Tests main resource load.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {\n RunTest(\"testMainResource\", kSimplePage);\n}\n\n\/\/ Tests resources panel enabling.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {\n RunTest(\"testEnableResourcesTab\", kSimplePage);\n}\n\n\/\/ Tests resource headers.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {\n RunTest(\"testResourceHeaders\", kResourceTestPage);\n}\n\n\/\/ Tests profiler panel.\n\/\/ Flaky, http:\/\/crbug.com\/21108\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {\n RunTest(\"testProfilerTab\", kJsPage);\n}\n\n\/\/ Tests scripts panel showing.\n\/\/ http:\/\/crbug.com\/16767\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {\n RunTest(\"testShowScriptsTab\", kDebuggerTestPage);\n}\n\n\/\/ Tests set breakpoint.\n\/\/ http:\/\/crbug.com\/16767\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {\n RunTest(\"testSetBreakpoint\", kDebuggerTestPage);\n}\n\n\/\/ Tests that 'Pause' button works for eval.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {\n RunTest(\"testPauseInEval\", kDebuggerTestPage);\n}\n\n\/\/ Tests console eval.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {\n RunTest(\"testConsoleEval\", kConsoleTestPage);\n}\n\n\/\/ Tests console log.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {\n RunTest(\"testConsoleLog\", kConsoleTestPage);\n}\n\n\/\/ Tests eval global values.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {\n RunTest(\"testEvalGlobal\", kEvalTestPage);\n}\n\n\/\/ Tests eval on call frame.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {\n RunTest(\"testEvalCallFrame\", kEvalTestPage);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"DevTools: check that devtools front-end JS files are loaded before running a test, otherwise the test will hang waiting for reponse from the front-end. Review URL: http:\/\/codereview.chromium.org\/151143<|endoftext|>"} {"text":"Rollback 23350. Fix build breakage: no object file generated. TBR=mnaganov<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace {\n\n\/\/ Used to block until a dev tools client window's browser is closed.\nclass BrowserClosedObserver : public NotificationObserver {\n public:\n explicit BrowserClosedObserver(Browser* browser) {\n registrar_.Add(this, NotificationType::BROWSER_CLOSED,\n Source(browser));\n ui_test_utils::RunMessageLoop();\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n MessageLoopForUI::current()->Quit();\n }\n\n private:\n NotificationRegistrar registrar_;\n DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);\n};\n\n\/\/ The delay waited in some cases where we don't have a notifications for an\n\/\/ action we take.\nconst int kActionDelayMs = 500;\n\nconst char kDebuggerTestPage[] = \"files\/devtools\/debugger_test_page.html\";\nconst char kHeapProfilerPage[] = \"files\/devtools\/heap_profiler.html\";\nconst char kPauseWhenLoadingDevTools[] =\n \"files\/devtools\/pause_when_loading_devtools.html\";\nconst char kPauseWhenScriptIsRunning[] =\n \"files\/devtools\/pause_when_script_is_running.html\";\nconst char kPageWithContentScript[] =\n \"files\/devtools\/page_with_content_script.html\";\n\n\nclass DevToolsSanityTest : public InProcessBrowserTest {\n public:\n DevToolsSanityTest() {\n set_show_window(true);\n EnableDOMAutomation();\n }\n\n protected:\n void RunTest(const std::string& test_name, const std::string& test_page) {\n OpenDevToolsWindow(test_page);\n std::string result;\n\n \/\/ At first check that JavaScript part of the front-end is loaded by\n \/\/ checking that global variable uiTests exists(it's created after all js\n \/\/ files have been loaded) and has runTest method.\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"'' + (window.uiTests && (typeof uiTests.runTest)));\",\n &result));\n\n if (result == \"function\") {\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n UTF8ToWide(StringPrintf(\"uiTests.runTest('%s')\",\n test_name.c_str())),\n &result));\n EXPECT_EQ(\"[OK]\", result);\n } else {\n FAIL() << \"DevTools front-end is broken.\";\n }\n CloseDevToolsWindow();\n }\n\n void OpenDevToolsWindow(const std::string& test_page) {\n ASSERT_TRUE(test_server()->Start());\n GURL url = test_server()->GetURL(test_page);\n ui_test_utils::NavigateToURL(browser(), url);\n\n inspected_rvh_ = GetInspectedTab()->render_view_host();\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n devtools_manager->OpenDevToolsWindow(inspected_rvh_);\n\n DevToolsClientHost* client_host =\n devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);\n window_ = client_host->AsDevToolsWindow();\n RenderViewHost* client_rvh = window_->GetRenderViewHost();\n client_contents_ = client_rvh->delegate()->GetAsTabContents();\n ui_test_utils::WaitForNavigation(&client_contents_->controller());\n }\n\n TabContents* GetInspectedTab() {\n return browser()->GetTabContentsAt(0);\n }\n\n void CloseDevToolsWindow() {\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n \/\/ UnregisterDevToolsClientHostFor may destroy window_ so store the browser\n \/\/ first.\n Browser* browser = window_->browser();\n devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);\n\n \/\/ Wait only when DevToolsWindow has a browser. For docked DevTools, this\n \/\/ is NULL and we skip the wait.\n if (browser)\n BrowserClosedObserver close_observer(browser);\n }\n\n TabContents* client_contents_;\n DevToolsWindow* window_;\n RenderViewHost* inspected_rvh_;\n};\n\n\nclass CancelableQuitTask : public Task {\n public:\n explicit CancelableQuitTask(const std::string& timeout_message)\n : timeout_message_(timeout_message),\n cancelled_(false) {\n }\n\n void cancel() {\n cancelled_ = true;\n }\n\n virtual void Run() {\n if (cancelled_) {\n return;\n }\n FAIL() << timeout_message_;\n MessageLoop::current()->Quit();\n }\n\n private:\n std::string timeout_message_;\n bool cancelled_;\n};\n\n\n\/\/ Base class for DevTools tests that test devtools functionality for\n\/\/ extensions and content scripts.\nclass DevToolsExtensionDebugTest : public DevToolsSanityTest,\n public NotificationObserver {\n public:\n DevToolsExtensionDebugTest() : DevToolsSanityTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"devtools\");\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"extensions\");\n }\n\n protected:\n \/\/ Load an extention from test\\data\\devtools\\extensions\\\n void LoadExtension(const char* extension_name) {\n FilePath path = test_extensions_dir_.AppendASCII(extension_name);\n ASSERT_TRUE(LoadExtensionFromPath(path)) << \"Failed to load extension.\";\n }\n\n private:\n bool LoadExtensionFromPath(const FilePath& path) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t num_before = service->extensions()->size();\n {\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_LOADED,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n service->LoadExtension(path);\n ui_test_utils::RunMessageLoop();\n delayed_quit->cancel();\n }\n size_t num_after = service->extensions()->size();\n if (num_after != (num_before + 1))\n return false;\n\n return WaitForExtensionHostsToLoad();\n }\n\n bool WaitForExtensionHostsToLoad() {\n \/\/ Wait for all the extension hosts that exist to finish loading.\n \/\/ NOTE: This assumes that the extension host list is not changing while\n \/\/ this method is running.\n\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension host load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n\n ExtensionProcessManager* manager =\n browser()->profile()->GetExtensionProcessManager();\n for (ExtensionProcessManager::const_iterator iter = manager->begin();\n iter != manager->end();) {\n if ((*iter)->did_stop_loading())\n ++iter;\n else\n ui_test_utils::RunMessageLoop();\n }\n\n delayed_quit->cancel();\n return true;\n }\n\n void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::EXTENSION_LOADED:\n case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:\n MessageLoopForUI::current()->Quit();\n break;\n default:\n NOTREACHED();\n break;\n }\n }\n\n FilePath test_extensions_dir_;\n};\n\n\/\/ Tests heap profiler.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {\n RunTest(\"testHeapProfiler\", kHeapProfilerPage);\n}\n\n\/\/ Tests scripts panel showing.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {\n RunTest(\"testShowScriptsTab\", kDebuggerTestPage);\n}\n\n\/\/ Tests that scripts tab is populated with inspected scripts even if it\n\/\/ hadn't been shown by the moment inspected paged refreshed.\n\/\/ @see http:\/\/crbug.com\/26312\n\/\/ Marked as disabled: crbug\/73289.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n DISABLED_TestScriptsTabIsPopulatedOnInspectedPageRefresh) {\n \/\/ Clear inspector settings to ensure that Elements will be\n \/\/ current panel when DevTools window is open.\n GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();\n RunTest(\"testScriptsTabIsPopulatedOnInspectedPageRefresh\",\n kDebuggerTestPage);\n}\n\n\/\/ Tests that a content script is in the scripts list.\n\/\/ This test is disabled, see bug 28961.\nIN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,\n TestContentScriptIsPresent) {\n LoadExtension(\"simple_content_script\");\n RunTest(\"testContentScriptIsPresent\", kPageWithContentScript);\n}\n\n\/\/ Tests that scripts are not duplicated after Scripts Panel switch.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestNoScriptDuplicatesOnPanelSwitch) {\n RunTest(\"testNoScriptDuplicatesOnPanelSwitch\", kDebuggerTestPage);\n}\n\n\/\/ Tests that debugger works correctly if pause event occurs when DevTools\n\/\/ frontend is being loaded.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {\n RunTest(\"testPauseWhenLoadingDevTools\", kPauseWhenLoadingDevTools);\n}\n\n\/\/ Tests that pressing 'Pause' will pause script execution if the script\n\/\/ is already running.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {\n RunTest(\"testPauseWhenScriptIsRunning\", kPauseWhenScriptIsRunning);\n}\n\n} \/\/ namespace\nEnable back DevToolsSanityTest.TestScriptsTabIsPopulatedOnInspectedPageRefresh Should pass after the last WK roll (r75275).\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace {\n\n\/\/ Used to block until a dev tools client window's browser is closed.\nclass BrowserClosedObserver : public NotificationObserver {\n public:\n explicit BrowserClosedObserver(Browser* browser) {\n registrar_.Add(this, NotificationType::BROWSER_CLOSED,\n Source(browser));\n ui_test_utils::RunMessageLoop();\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n MessageLoopForUI::current()->Quit();\n }\n\n private:\n NotificationRegistrar registrar_;\n DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);\n};\n\n\/\/ The delay waited in some cases where we don't have a notifications for an\n\/\/ action we take.\nconst int kActionDelayMs = 500;\n\nconst char kDebuggerTestPage[] = \"files\/devtools\/debugger_test_page.html\";\nconst char kHeapProfilerPage[] = \"files\/devtools\/heap_profiler.html\";\nconst char kPauseWhenLoadingDevTools[] =\n \"files\/devtools\/pause_when_loading_devtools.html\";\nconst char kPauseWhenScriptIsRunning[] =\n \"files\/devtools\/pause_when_script_is_running.html\";\nconst char kPageWithContentScript[] =\n \"files\/devtools\/page_with_content_script.html\";\n\n\nclass DevToolsSanityTest : public InProcessBrowserTest {\n public:\n DevToolsSanityTest() {\n set_show_window(true);\n EnableDOMAutomation();\n }\n\n protected:\n void RunTest(const std::string& test_name, const std::string& test_page) {\n OpenDevToolsWindow(test_page);\n std::string result;\n\n \/\/ At first check that JavaScript part of the front-end is loaded by\n \/\/ checking that global variable uiTests exists(it's created after all js\n \/\/ files have been loaded) and has runTest method.\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"'' + (window.uiTests && (typeof uiTests.runTest)));\",\n &result));\n\n if (result == \"function\") {\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n UTF8ToWide(StringPrintf(\"uiTests.runTest('%s')\",\n test_name.c_str())),\n &result));\n EXPECT_EQ(\"[OK]\", result);\n } else {\n FAIL() << \"DevTools front-end is broken.\";\n }\n CloseDevToolsWindow();\n }\n\n void OpenDevToolsWindow(const std::string& test_page) {\n ASSERT_TRUE(test_server()->Start());\n GURL url = test_server()->GetURL(test_page);\n ui_test_utils::NavigateToURL(browser(), url);\n\n inspected_rvh_ = GetInspectedTab()->render_view_host();\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n devtools_manager->OpenDevToolsWindow(inspected_rvh_);\n\n DevToolsClientHost* client_host =\n devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);\n window_ = client_host->AsDevToolsWindow();\n RenderViewHost* client_rvh = window_->GetRenderViewHost();\n client_contents_ = client_rvh->delegate()->GetAsTabContents();\n ui_test_utils::WaitForNavigation(&client_contents_->controller());\n }\n\n TabContents* GetInspectedTab() {\n return browser()->GetTabContentsAt(0);\n }\n\n void CloseDevToolsWindow() {\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n \/\/ UnregisterDevToolsClientHostFor may destroy window_ so store the browser\n \/\/ first.\n Browser* browser = window_->browser();\n devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);\n\n \/\/ Wait only when DevToolsWindow has a browser. For docked DevTools, this\n \/\/ is NULL and we skip the wait.\n if (browser)\n BrowserClosedObserver close_observer(browser);\n }\n\n TabContents* client_contents_;\n DevToolsWindow* window_;\n RenderViewHost* inspected_rvh_;\n};\n\n\nclass CancelableQuitTask : public Task {\n public:\n explicit CancelableQuitTask(const std::string& timeout_message)\n : timeout_message_(timeout_message),\n cancelled_(false) {\n }\n\n void cancel() {\n cancelled_ = true;\n }\n\n virtual void Run() {\n if (cancelled_) {\n return;\n }\n FAIL() << timeout_message_;\n MessageLoop::current()->Quit();\n }\n\n private:\n std::string timeout_message_;\n bool cancelled_;\n};\n\n\n\/\/ Base class for DevTools tests that test devtools functionality for\n\/\/ extensions and content scripts.\nclass DevToolsExtensionDebugTest : public DevToolsSanityTest,\n public NotificationObserver {\n public:\n DevToolsExtensionDebugTest() : DevToolsSanityTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"devtools\");\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"extensions\");\n }\n\n protected:\n \/\/ Load an extention from test\\data\\devtools\\extensions\\\n void LoadExtension(const char* extension_name) {\n FilePath path = test_extensions_dir_.AppendASCII(extension_name);\n ASSERT_TRUE(LoadExtensionFromPath(path)) << \"Failed to load extension.\";\n }\n\n private:\n bool LoadExtensionFromPath(const FilePath& path) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t num_before = service->extensions()->size();\n {\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_LOADED,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n service->LoadExtension(path);\n ui_test_utils::RunMessageLoop();\n delayed_quit->cancel();\n }\n size_t num_after = service->extensions()->size();\n if (num_after != (num_before + 1))\n return false;\n\n return WaitForExtensionHostsToLoad();\n }\n\n bool WaitForExtensionHostsToLoad() {\n \/\/ Wait for all the extension hosts that exist to finish loading.\n \/\/ NOTE: This assumes that the extension host list is not changing while\n \/\/ this method is running.\n\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension host load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n\n ExtensionProcessManager* manager =\n browser()->profile()->GetExtensionProcessManager();\n for (ExtensionProcessManager::const_iterator iter = manager->begin();\n iter != manager->end();) {\n if ((*iter)->did_stop_loading())\n ++iter;\n else\n ui_test_utils::RunMessageLoop();\n }\n\n delayed_quit->cancel();\n return true;\n }\n\n void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::EXTENSION_LOADED:\n case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:\n MessageLoopForUI::current()->Quit();\n break;\n default:\n NOTREACHED();\n break;\n }\n }\n\n FilePath test_extensions_dir_;\n};\n\n\/\/ Tests heap profiler.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {\n RunTest(\"testHeapProfiler\", kHeapProfilerPage);\n}\n\n\/\/ Tests scripts panel showing.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {\n RunTest(\"testShowScriptsTab\", kDebuggerTestPage);\n}\n\n\/\/ Tests that scripts tab is populated with inspected scripts even if it\n\/\/ hadn't been shown by the moment inspected paged refreshed.\n\/\/ @see http:\/\/crbug.com\/26312\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestScriptsTabIsPopulatedOnInspectedPageRefresh) {\n \/\/ Clear inspector settings to ensure that Elements will be\n \/\/ current panel when DevTools window is open.\n GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();\n RunTest(\"testScriptsTabIsPopulatedOnInspectedPageRefresh\",\n kDebuggerTestPage);\n}\n\n\/\/ Tests that a content script is in the scripts list.\n\/\/ This test is disabled, see bug 28961.\nIN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,\n TestContentScriptIsPresent) {\n LoadExtension(\"simple_content_script\");\n RunTest(\"testContentScriptIsPresent\", kPageWithContentScript);\n}\n\n\/\/ Tests that scripts are not duplicated after Scripts Panel switch.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestNoScriptDuplicatesOnPanelSwitch) {\n RunTest(\"testNoScriptDuplicatesOnPanelSwitch\", kDebuggerTestPage);\n}\n\n\/\/ Tests that debugger works correctly if pause event occurs when DevTools\n\/\/ frontend is being loaded.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {\n RunTest(\"testPauseWhenLoadingDevTools\", kPauseWhenLoadingDevTools);\n}\n\n\/\/ Tests that pressing 'Pause' will pause script execution if the script\n\/\/ is already running.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {\n RunTest(\"testPauseWhenScriptIsRunning\", kPauseWhenScriptIsRunning);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/generated_resources.h\"\n#include \"skia\/ext\/image_operations.h\"\n\nclass Profile;\n\nnamespace {\n\nconst int kRightColumnWidth = 290;\n\nconst int kImageSize = 69;\n\n\/\/ Padding on all sides of each permission in the permissions list.\nconst int kPermissionsPadding = 8;\n\n\/\/ Make a GtkLabel with |str| as its text, using the formatting in |format|.\nGtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {\n GtkWidget* label = gtk_label_new(NULL);\n char* markup = g_markup_printf_escaped(format, str.c_str());\n gtk_label_set_markup(GTK_LABEL(label), markup);\n g_free(markup);\n\n \/\/ Left align it.\n gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);\n\n return label;\n}\n\nvoid OnDialogResponse(GtkDialog* dialog, int response_id,\n ExtensionInstallUI::Delegate* delegate) {\n if (response_id == GTK_RESPONSE_ACCEPT) {\n delegate->InstallUIProceed(false);\n } else {\n delegate->InstallUIAbort();\n }\n\n gtk_widget_destroy(GTK_WIDGET(dialog));\n}\n\nvoid ShowInstallPromptDialog2(GtkWindow* parent, SkBitmap* skia_icon,\n Extension* extension,\n ExtensionInstallUI::Delegate *delegate,\n const std::vector& permissions) {\n \/\/ Build the dialog.\n GtkWidget* dialog = gtk_dialog_new_with_buttons(\n l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALL_PROMPT_TITLE).c_str(),\n parent,\n GTK_DIALOG_MODAL,\n NULL);\n GtkWidget* close_button = gtk_dialog_add_button(GTK_DIALOG(dialog),\n GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE);\n gtk_dialog_add_button(GTK_DIALOG(dialog),\n l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_INSTALL_BUTTON).c_str(),\n GTK_RESPONSE_ACCEPT);\n gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);\n\n \/\/ Create a two column layout.\n GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;\n gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);\n\n GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing);\n gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0);\n\n \/\/ Resize the icon if necessary.\n SkBitmap scaled_icon = *skia_icon;\n if (scaled_icon.width() > kImageSize || scaled_icon.height() > kImageSize) {\n scaled_icon = skia::ImageOperations::Resize(scaled_icon,\n skia::ImageOperations::RESIZE_LANCZOS3,\n kImageSize, kImageSize);\n }\n\n \/\/ Put Icon in the left column.\n GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&scaled_icon);\n GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf);\n g_object_unref(pixbuf);\n gtk_box_pack_start(GTK_BOX(icon_hbox), icon, FALSE, FALSE, 0);\n \/\/ Top justify the image.\n gtk_misc_set_alignment(GTK_MISC(icon), 0.5, 0.0);\n\n \/\/ Create a new vbox for the right column.\n GtkWidget* right_column_area = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0);\n\n std::string heading_text = l10n_util::GetStringFUTF8(\n IDS_EXTENSION_INSTALL_PROMPT_HEADING, UTF8ToUTF16(extension->name()));\n GtkWidget* heading_label = MakeMarkupLabel(\"%s<\/span>\",\n heading_text);\n gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5);\n bool show_permissions = !permissions.empty();\n \/\/ If we are not going to show the permissions, vertically center the title.\n gtk_box_pack_start(GTK_BOX(right_column_area), heading_label,\n !show_permissions, !show_permissions, 0);\n\n if (show_permissions) {\n GtkWidget* warning_label = gtk_label_new(l10n_util::GetStringUTF8(\n IDS_EXTENSION_PROMPT2_WILL_HAVE_ACCESS_TO).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(warning_label), TRUE);\n gtk_widget_set_size_request(warning_label, kRightColumnWidth, -1);\n gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5);\n gtk_box_pack_start(GTK_BOX(right_column_area), warning_label,\n FALSE, FALSE, 0);\n\n GtkWidget* frame = gtk_frame_new(NULL);\n gtk_box_pack_start(GTK_BOX(right_column_area), frame, FALSE, FALSE, 0);\n\n GtkWidget* table = gtk_table_new(permissions.size(), 1, false);\n gtk_container_add(GTK_CONTAINER(frame), table);\n int row = 0;\n for (std::vector::const_iterator iter = permissions.begin();\n iter != permissions.end(); ++iter) {\n GtkWidget* entry = gtk_entry_new();\n GtkBorder border = { kPermissionsPadding, kPermissionsPadding,\n row == 0 ? kPermissionsPadding : 0,\n kPermissionsPadding };\n gtk_entry_set_inner_border(GTK_ENTRY(entry), &border);\n gtk_entry_set_text(GTK_ENTRY(entry), UTF16ToUTF8(*iter).c_str());\n gtk_entry_set_editable(GTK_ENTRY(entry), FALSE);\n gtk_entry_set_has_frame(GTK_ENTRY(entry), FALSE);\n\n gtk_table_attach_defaults(GTK_TABLE(table), entry,\n 0, 1, row, row + 1);\n ++row;\n }\n }\n\n g_signal_connect(dialog, \"response\", G_CALLBACK(OnDialogResponse), delegate);\n gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);\n\n gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE);\n gtk_widget_show_all(dialog);\n gtk_widget_grab_focus(close_button);\n}\n\n} \/\/ namespace\n\nvoid ExtensionInstallUI::ShowExtensionInstallUIPrompt2Impl(\n Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,\n const std::vector& permissions) {\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile);\n if (!browser) {\n delegate->InstallUIAbort();\n return;\n }\n\n BrowserWindowGtk* browser_window = static_cast(\n browser->window());\n if (!browser_window) {\n delegate->InstallUIAbort();\n return;\n }\n\n ShowInstallPromptDialog2(browser_window->window(), icon, extension,\n delegate, permissions);\n}\nGTK: let the extension install prompt permissions line wrap.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/generated_resources.h\"\n#include \"skia\/ext\/image_operations.h\"\n\nclass Profile;\n\nnamespace {\n\nconst int kRightColumnWidth = 290;\n\nconst int kImageSize = 69;\n\n\/\/ Padding on all sides of each permission in the permissions list.\nconst int kPermissionsPadding = 8;\n\n\/\/ Make a GtkLabel with |str| as its text, using the formatting in |format|.\nGtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {\n GtkWidget* label = gtk_label_new(NULL);\n char* markup = g_markup_printf_escaped(format, str.c_str());\n gtk_label_set_markup(GTK_LABEL(label), markup);\n g_free(markup);\n\n \/\/ Left align it.\n gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);\n\n return label;\n}\n\nvoid OnDialogResponse(GtkDialog* dialog, int response_id,\n ExtensionInstallUI::Delegate* delegate) {\n if (response_id == GTK_RESPONSE_ACCEPT) {\n delegate->InstallUIProceed(false);\n } else {\n delegate->InstallUIAbort();\n }\n\n gtk_widget_destroy(GTK_WIDGET(dialog));\n}\n\nvoid ShowInstallPromptDialog2(GtkWindow* parent, SkBitmap* skia_icon,\n Extension* extension,\n ExtensionInstallUI::Delegate *delegate,\n const std::vector& permissions) {\n \/\/ Build the dialog.\n GtkWidget* dialog = gtk_dialog_new_with_buttons(\n l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALL_PROMPT_TITLE).c_str(),\n parent,\n GTK_DIALOG_MODAL,\n NULL);\n GtkWidget* close_button = gtk_dialog_add_button(GTK_DIALOG(dialog),\n GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE);\n gtk_dialog_add_button(GTK_DIALOG(dialog),\n l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_INSTALL_BUTTON).c_str(),\n GTK_RESPONSE_ACCEPT);\n gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);\n\n \/\/ Create a two column layout.\n GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;\n gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);\n\n GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing);\n gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0);\n\n \/\/ Resize the icon if necessary.\n SkBitmap scaled_icon = *skia_icon;\n if (scaled_icon.width() > kImageSize || scaled_icon.height() > kImageSize) {\n scaled_icon = skia::ImageOperations::Resize(scaled_icon,\n skia::ImageOperations::RESIZE_LANCZOS3,\n kImageSize, kImageSize);\n }\n\n \/\/ Put Icon in the left column.\n GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&scaled_icon);\n GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf);\n g_object_unref(pixbuf);\n gtk_box_pack_start(GTK_BOX(icon_hbox), icon, FALSE, FALSE, 0);\n \/\/ Top justify the image.\n gtk_misc_set_alignment(GTK_MISC(icon), 0.5, 0.0);\n\n \/\/ Create a new vbox for the right column.\n GtkWidget* right_column_area = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0);\n\n std::string heading_text = l10n_util::GetStringFUTF8(\n IDS_EXTENSION_INSTALL_PROMPT_HEADING, UTF8ToUTF16(extension->name()));\n GtkWidget* heading_label = MakeMarkupLabel(\"%s<\/span>\",\n heading_text);\n gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5);\n bool show_permissions = !permissions.empty();\n \/\/ If we are not going to show the permissions, vertically center the title.\n gtk_box_pack_start(GTK_BOX(right_column_area), heading_label,\n !show_permissions, !show_permissions, 0);\n\n if (show_permissions) {\n GtkWidget* warning_label = gtk_label_new(l10n_util::GetStringUTF8(\n IDS_EXTENSION_PROMPT2_WILL_HAVE_ACCESS_TO).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(warning_label), TRUE);\n gtk_widget_set_size_request(warning_label, kRightColumnWidth, -1);\n gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5);\n gtk_box_pack_start(GTK_BOX(right_column_area), warning_label,\n FALSE, FALSE, 0);\n\n GtkWidget* frame = gtk_frame_new(NULL);\n gtk_box_pack_start(GTK_BOX(right_column_area), frame, FALSE, FALSE, 0);\n\n GtkWidget* text_view = gtk_text_view_new();\n gtk_container_add(GTK_CONTAINER(frame), text_view);\n gtk_text_view_set_editable(GTK_TEXT_VIEW(text_view), FALSE);\n gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_view),\n kPermissionsPadding);\n gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text_view),\n kPermissionsPadding);\n gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_view), GTK_WRAP_WORD);\n GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view));\n GtkTextTagTable* tag_table = gtk_text_buffer_get_tag_table(buffer);\n\n GtkTextTag* padding_below_tag = gtk_text_tag_new(NULL);\n g_object_set(G_OBJECT(padding_below_tag), \"pixels-below-lines\",\n kPermissionsPadding, NULL);\n g_object_set(G_OBJECT(padding_below_tag), \"pixels-below-lines-set\",\n TRUE, NULL);\n gtk_text_tag_table_add(tag_table, padding_below_tag);\n g_object_unref(padding_below_tag);\n GtkTextTag* padding_above_tag = gtk_text_tag_new(NULL);\n g_object_set(G_OBJECT(padding_above_tag), \"pixels-above-lines\",\n kPermissionsPadding, NULL);\n g_object_set(G_OBJECT(padding_above_tag), \"pixels-above-lines-set\",\n TRUE, NULL);\n gtk_text_tag_table_add(tag_table, padding_above_tag);\n g_object_unref(padding_above_tag);\n\n GtkTextIter end_iter;\n gtk_text_buffer_get_end_iter(buffer, &end_iter);\n for (std::vector::const_iterator iter = permissions.begin();\n iter != permissions.end(); ++iter) {\n if (iter != permissions.begin())\n gtk_text_buffer_insert(buffer, &end_iter, \"\\n\", -1);\n gtk_text_buffer_insert_with_tags(\n buffer, &end_iter, UTF16ToUTF8(*iter).c_str(), -1,\n padding_below_tag,\n iter == permissions.begin() ? padding_above_tag : NULL,\n NULL);\n }\n }\n\n g_signal_connect(dialog, \"response\", G_CALLBACK(OnDialogResponse), delegate);\n gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);\n\n gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE);\n gtk_widget_show_all(dialog);\n gtk_widget_grab_focus(close_button);\n}\n\n} \/\/ namespace\n\nvoid ExtensionInstallUI::ShowExtensionInstallUIPrompt2Impl(\n Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,\n const std::vector& permissions) {\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile);\n if (!browser) {\n delegate->InstallUIAbort();\n return;\n }\n\n BrowserWindowGtk* browser_window = static_cast(\n browser->window());\n if (!browser_window) {\n delegate->InstallUIAbort();\n return;\n }\n\n ShowInstallPromptDialog2(browser_window->window(), icon, extension,\n delegate, permissions);\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_ENGINE_NormalsFromPoints_INL\n#define SOFA_COMPONENT_ENGINE_NormalsFromPoints_INL\n\n#if !defined(__GNUC__) || (__GNUC__ > 3 || (_GNUC__ == 3 && __GNUC_MINOR__ > 3))\n#pragma once\n#endif\n\n#include \"NormalsFromPoints.h\"\n#include \n#include \n#include \n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace engine\n{\n\nusing namespace sofa::helper;\nusing namespace sofa::defaulttype;\nusing namespace core::objectmodel;\n\ntemplate \nNormalsFromPoints::NormalsFromPoints()\n : position(initData(&position,\"position\",\"Vertices of the mesh\"))\n , triangles(initData(&triangles,\"triangles\",\"Triangles of the mesh\"))\n , quads(initData(&quads,\"quads\",\"Quads of the mesh\"))\n , normals(initData(&normals,\"normals\",\"Computed vertex normals of the mesh\"))\n , invertNormals( initData (&invertNormals, false, \"invertNormals\", \"Swap normals\") )\n , useAngles( initData (&useAngles, false, \"useAngles\", \"Use incident angles to weight faces normal contributions at each vertex\") )\n\n{\n}\n\ntemplate \nvoid NormalsFromPoints::init()\n{\n mstate = dynamic_cast< MechanicalState* >(getContext()->getMechanicalState());\n addInput(&position);\n addInput(&triangles);\n addInput(&quads);\n addInput(&invertNormals);\n addInput(&useAngles);\n addOutput(&normals);\n setDirtyValue();\n}\n\ntemplate \nvoid NormalsFromPoints::reinit()\n{\n update();\n}\n\ntemplate \nvoid NormalsFromPoints::update()\n{\n cleanDirty();\n\n helper::ReadAccessor > raPositions = position;\n helper::ReadAccessor > > > raTriangles = triangles;\n helper::ReadAccessor > > > raQuads = quads;\n helper::WriteAccessor > waNormals = normals;\n const bool useAngles = this->useAngles.getValue();\n const bool invertNormals = this->invertNormals.getValue();\n\n waNormals.resize(raPositions.size());\n\n for (unsigned int i = 0; i < raTriangles.size() ; i++)\n {\n const Coord v1 = raPositions[raTriangles[i][0]];\n const Coord v2 = raPositions[raTriangles[i][1]];\n const Coord v3 = raPositions[raTriangles[i][2]];\n Coord n = cross(v2-v1, v3-v1);\n if (useAngles)\n {\n Real nnorm = n.norm();\n Coord e12 = v2-v1; Real e12norm = e12.norm();\n Coord e23 = v3-v2; Real e23norm = e23.norm();\n Coord e31 = v3-v1; Real e31norm = e31.norm();\n waNormals[raTriangles[i][0]] += n * (acos(-(e31*e12)\/(e31norm*e12norm))\/nnorm);\n waNormals[raTriangles[i][1]] += n * (acos(-(e12*e23)\/(e12norm*e23norm))\/nnorm);\n waNormals[raTriangles[i][2]] += n * (acos(-(e23*e31)\/(e23norm*e31norm))\/nnorm);\n }\n else\n {\n n.normalize();\n waNormals[raTriangles[i][0]] += n;\n waNormals[raTriangles[i][1]] += n;\n waNormals[raTriangles[i][2]] += n;\n }\n }\n for (unsigned int i = 0; i < raQuads.size() ; i++)\n {\n const Coord & v1 = raPositions[raQuads[i][0]];\n const Coord & v2 = raPositions[raQuads[i][1]];\n const Coord & v3 = raPositions[raQuads[i][2]];\n const Coord & v4 = raPositions[raQuads[i][3]];\n Coord n1 = cross(v2-v1, v4-v1); Real n1norm = n1.norm();\n Coord n2 = cross(v3-v2, v1-v2); Real n2norm = n2.norm();\n Coord n3 = cross(v4-v3, v2-v3); Real n3norm = n3.norm();\n Coord n4 = cross(v1-v4, v3-v4); Real n4norm = n4.norm();\n if (useAngles)\n {\n Coord e12 = v2-v1; Real e12norm = e12.norm();\n Coord e23 = v3-v2; Real e23norm = e23.norm();\n Coord e34 = v4-v3; Real e34norm = e34.norm();\n Coord e41 = v1-v4; Real e41norm = e41.norm();\n waNormals[raQuads[i][0]] += n1 * (acos(-(e41*e12)\/(e41norm*e12norm))\/n1norm);\n waNormals[raQuads[i][1]] += n2 * (acos(-(e12*e23)\/(e12norm*e23norm))\/n2norm);\n waNormals[raQuads[i][2]] += n3 * (acos(-(e23*e34)\/(e23norm*e34norm))\/n3norm);\n waNormals[raQuads[i][3]] += n4 * (acos(-(e34*e41)\/(e34norm*e41norm))\/n3norm);\n }\n else\n {\n waNormals[raQuads[i][0]] += n1 \/ n1norm;\n waNormals[raQuads[i][1]] += n2 \/ n2norm;\n waNormals[raQuads[i][2]] += n3 \/ n3norm;\n waNormals[raQuads[i][3]] += n4 \/ n4norm;\n }\n }\n\n if(invertNormals)\n for (unsigned int i = 0; i < waNormals.size(); i++)\n waNormals[i]=-waNormals[i];\n\n for (unsigned int i = 0; i < waNormals.size(); i++)\n waNormals[i].normalize();\n}\n\n} \/\/ namespace engine\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\nr12665\/sofa-dev : FIX: sign error\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_ENGINE_NormalsFromPoints_INL\n#define SOFA_COMPONENT_ENGINE_NormalsFromPoints_INL\n\n#if !defined(__GNUC__) || (__GNUC__ > 3 || (_GNUC__ == 3 && __GNUC_MINOR__ > 3))\n#pragma once\n#endif\n\n#include \"NormalsFromPoints.h\"\n#include \n#include \n#include \n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace engine\n{\n\nusing namespace sofa::helper;\nusing namespace sofa::defaulttype;\nusing namespace core::objectmodel;\n\ntemplate \nNormalsFromPoints::NormalsFromPoints()\n : position(initData(&position,\"position\",\"Vertices of the mesh\"))\n , triangles(initData(&triangles,\"triangles\",\"Triangles of the mesh\"))\n , quads(initData(&quads,\"quads\",\"Quads of the mesh\"))\n , normals(initData(&normals,\"normals\",\"Computed vertex normals of the mesh\"))\n , invertNormals( initData (&invertNormals, false, \"invertNormals\", \"Swap normals\") )\n , useAngles( initData (&useAngles, false, \"useAngles\", \"Use incident angles to weight faces normal contributions at each vertex\") )\n\n{\n}\n\ntemplate \nvoid NormalsFromPoints::init()\n{\n mstate = dynamic_cast< MechanicalState* >(getContext()->getMechanicalState());\n addInput(&position);\n addInput(&triangles);\n addInput(&quads);\n addInput(&invertNormals);\n addInput(&useAngles);\n addOutput(&normals);\n setDirtyValue();\n}\n\ntemplate \nvoid NormalsFromPoints::reinit()\n{\n update();\n}\n\ntemplate \nvoid NormalsFromPoints::update()\n{\n cleanDirty();\n\n helper::ReadAccessor > raPositions = position;\n helper::ReadAccessor > > > raTriangles = triangles;\n helper::ReadAccessor > > > raQuads = quads;\n helper::WriteAccessor > waNormals = normals;\n const bool useAngles = this->useAngles.getValue();\n const bool invertNormals = this->invertNormals.getValue();\n\n waNormals.resize(raPositions.size());\n\n for (unsigned int i = 0; i < raTriangles.size() ; i++)\n {\n const Coord v1 = raPositions[raTriangles[i][0]];\n const Coord v2 = raPositions[raTriangles[i][1]];\n const Coord v3 = raPositions[raTriangles[i][2]];\n Coord n = cross(v2-v1, v3-v1);\n if (useAngles)\n {\n Real nnorm = n.norm();\n Coord e12 = v2-v1; Real e12norm = e12.norm();\n Coord e23 = v3-v2; Real e23norm = e23.norm();\n Coord e31 = v1-v3; Real e31norm = e31.norm();\n waNormals[raTriangles[i][0]] += n * (acos(-(e31*e12)\/(e31norm*e12norm))\/nnorm);\n waNormals[raTriangles[i][1]] += n * (acos(-(e12*e23)\/(e12norm*e23norm))\/nnorm);\n waNormals[raTriangles[i][2]] += n * (acos(-(e23*e31)\/(e23norm*e31norm))\/nnorm);\n }\n else\n {\n n.normalize();\n waNormals[raTriangles[i][0]] += n;\n waNormals[raTriangles[i][1]] += n;\n waNormals[raTriangles[i][2]] += n;\n }\n }\n for (unsigned int i = 0; i < raQuads.size() ; i++)\n {\n const Coord & v1 = raPositions[raQuads[i][0]];\n const Coord & v2 = raPositions[raQuads[i][1]];\n const Coord & v3 = raPositions[raQuads[i][2]];\n const Coord & v4 = raPositions[raQuads[i][3]];\n Coord n1 = cross(v2-v1, v4-v1); Real n1norm = n1.norm();\n Coord n2 = cross(v3-v2, v1-v2); Real n2norm = n2.norm();\n Coord n3 = cross(v4-v3, v2-v3); Real n3norm = n3.norm();\n Coord n4 = cross(v1-v4, v3-v4); Real n4norm = n4.norm();\n if (useAngles)\n {\n Coord e12 = v2-v1; Real e12norm = e12.norm();\n Coord e23 = v3-v2; Real e23norm = e23.norm();\n Coord e34 = v4-v3; Real e34norm = e34.norm();\n Coord e41 = v1-v4; Real e41norm = e41.norm();\n waNormals[raQuads[i][0]] += n1 * (acos(-(e41*e12)\/(e41norm*e12norm))\/n1norm);\n waNormals[raQuads[i][1]] += n2 * (acos(-(e12*e23)\/(e12norm*e23norm))\/n2norm);\n waNormals[raQuads[i][2]] += n3 * (acos(-(e23*e34)\/(e23norm*e34norm))\/n3norm);\n waNormals[raQuads[i][3]] += n4 * (acos(-(e34*e41)\/(e34norm*e41norm))\/n3norm);\n }\n else\n {\n waNormals[raQuads[i][0]] += n1 \/ n1norm;\n waNormals[raQuads[i][1]] += n2 \/ n2norm;\n waNormals[raQuads[i][2]] += n3 \/ n3norm;\n waNormals[raQuads[i][3]] += n4 \/ n4norm;\n }\n }\n\n if(invertNormals)\n for (unsigned int i = 0; i < waNormals.size(); i++)\n waNormals[i]=-waNormals[i];\n\n for (unsigned int i = 0; i < waNormals.size(); i++)\n waNormals[i].normalize();\n}\n\n} \/\/ namespace engine\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/history\/in_memory_history_backend.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/histogram.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/history\/history_notifications.h\"\n#include \"chrome\/browser\/history\/in_memory_database.h\"\n#include \"chrome\/browser\/history\/in_memory_url_index.h\"\n#include \"chrome\/browser\/history\/url_database.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nnamespace history {\n\n\/\/ If a page becomes starred we use this id in place of the real starred id.\n\/\/ See note in OnURLsStarred.\nstatic const StarID kBogusStarredID = 0x0FFFFFFF;\n\nInMemoryHistoryBackend::InMemoryHistoryBackend()\n : profile_(NULL) {\n}\n\nInMemoryHistoryBackend::~InMemoryHistoryBackend() {\n}\n\nbool InMemoryHistoryBackend::Init(const FilePath& history_filename,\n URLDatabase* db,\n const std::string& languages) {\n db_.reset(new InMemoryDatabase);\n bool success = db_->InitFromDisk(history_filename);\n if (!CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDisableHistoryQuickProvider)) {\n index_.reset(new InMemoryURLIndex());\n base::TimeTicks beginning_time = base::TimeTicks::Now();\n index_->Init(db, languages);\n UMA_HISTOGRAM_TIMES(\"Autocomplete.HistoryDatabaseIndexingTime\",\n base::TimeTicks::Now() - beginning_time);\n }\n return success;\n}\n\nvoid InMemoryHistoryBackend::AttachToHistoryService(Profile* profile) {\n if (!db_.get()) {\n NOTREACHED();\n return;\n }\n\n profile_ = profile;\n\n \/\/ TODO(evanm): this is currently necessitated by generate_profile, which\n \/\/ runs without a browser process. generate_profile should really create\n \/\/ a browser process, at which point this check can then be nuked.\n if (!g_browser_process)\n return;\n\n \/\/ Register for the notifications we care about.\n \/\/ We only want notifications for the associated profile.\n Source source(profile_);\n registrar_.Add(this, NotificationType::HISTORY_URL_VISITED, source);\n registrar_.Add(this, NotificationType::HISTORY_TYPED_URLS_MODIFIED, source);\n registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED, source);\n}\n\nvoid InMemoryHistoryBackend::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::HISTORY_URL_VISITED: {\n Details visited_details(details);\n if (visited_details->row.typed_count() > 0) {\n URLsModifiedDetails modified_details;\n modified_details.changed_urls.push_back(visited_details->row);\n OnTypedURLsModified(modified_details);\n }\n break;\n }\n case NotificationType::HISTORY_TYPED_URLS_MODIFIED:\n OnTypedURLsModified(\n *Details(details).ptr());\n break;\n case NotificationType::HISTORY_URLS_DELETED:\n OnURLsDeleted(*Details(details).ptr());\n break;\n default:\n \/\/ For simplicity, the unit tests send us all notifications, even when\n \/\/ we haven't registered for them, so don't assert here.\n break;\n }\n}\n\nvoid InMemoryHistoryBackend::OnTypedURLsModified(\n const URLsModifiedDetails& details) {\n DCHECK(db_.get());\n\n \/\/ Add or update the URLs.\n \/\/\n \/\/ TODO(brettw) currently the rows in the in-memory database don't match the\n \/\/ IDs in the main database. This sucks. Instead of Add and Remove, we should\n \/\/ have Sync(), which would take the ID if it's given and add it.\n std::vector::const_iterator i;\n for (i = details.changed_urls.begin();\n i != details.changed_urls.end(); i++) {\n URLID id = db_->GetRowForURL(i->url(), NULL);\n if (id)\n db_->UpdateURLRow(id, *i);\n else\n db_->AddURL(*i);\n }\n}\n\nvoid InMemoryHistoryBackend::OnURLsDeleted(const URLsDeletedDetails& details) {\n DCHECK(db_.get());\n\n if (details.all_history) {\n \/\/ When all history is deleted, the individual URLs won't be listed. Just\n \/\/ create a new database to quickly clear everything out.\n db_.reset(new InMemoryDatabase);\n if (!db_->InitFromScratch())\n db_.reset();\n return;\n }\n\n \/\/ Delete all matching URLs in our database.\n for (std::set::const_iterator i = details.urls.begin();\n i != details.urls.end(); ++i) {\n URLID id = db_->GetRowForURL(*i, NULL);\n if (id) {\n \/\/ We typically won't have most of them since we only have a subset of\n \/\/ history, so ignore errors.\n db_->DeleteURLRow(id);\n }\n }\n}\n\n} \/\/ namespace history\nTemporarily disable the HistoryQuickProvider and InMemoryURLIndex to see if it is causing a slowdown at startup.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/history\/in_memory_history_backend.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/histogram.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/history\/history_notifications.h\"\n#include \"chrome\/browser\/history\/in_memory_database.h\"\n#include \"chrome\/browser\/history\/in_memory_url_index.h\"\n#include \"chrome\/browser\/history\/url_database.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nnamespace history {\n\n\/\/ If a page becomes starred we use this id in place of the real starred id.\n\/\/ See note in OnURLsStarred.\nstatic const StarID kBogusStarredID = 0x0FFFFFFF;\n\nInMemoryHistoryBackend::InMemoryHistoryBackend()\n : profile_(NULL) {\n}\n\nInMemoryHistoryBackend::~InMemoryHistoryBackend() {\n}\n\nbool InMemoryHistoryBackend::Init(const FilePath& history_filename,\n URLDatabase* db,\n const std::string& languages) {\n db_.reset(new InMemoryDatabase);\n bool success = db_->InitFromDisk(history_filename);\n#if 0\n \/\/ TODO(mrossetti): Temporary removal to help determine if the\n \/\/ InMemoryURLIndex is contributing to a startup slowdown.\n if (!CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDisableHistoryQuickProvider)) {\n index_.reset(new InMemoryURLIndex());\n base::TimeTicks beginning_time = base::TimeTicks::Now();\n index_->Init(db, languages);\n UMA_HISTOGRAM_TIMES(\"Autocomplete.HistoryDatabaseIndexingTime\",\n base::TimeTicks::Now() - beginning_time);\n }\n#endif\n return success;\n}\n\nvoid InMemoryHistoryBackend::AttachToHistoryService(Profile* profile) {\n if (!db_.get()) {\n NOTREACHED();\n return;\n }\n\n profile_ = profile;\n\n \/\/ TODO(evanm): this is currently necessitated by generate_profile, which\n \/\/ runs without a browser process. generate_profile should really create\n \/\/ a browser process, at which point this check can then be nuked.\n if (!g_browser_process)\n return;\n\n \/\/ Register for the notifications we care about.\n \/\/ We only want notifications for the associated profile.\n Source source(profile_);\n registrar_.Add(this, NotificationType::HISTORY_URL_VISITED, source);\n registrar_.Add(this, NotificationType::HISTORY_TYPED_URLS_MODIFIED, source);\n registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED, source);\n}\n\nvoid InMemoryHistoryBackend::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::HISTORY_URL_VISITED: {\n Details visited_details(details);\n if (visited_details->row.typed_count() > 0) {\n URLsModifiedDetails modified_details;\n modified_details.changed_urls.push_back(visited_details->row);\n OnTypedURLsModified(modified_details);\n }\n break;\n }\n case NotificationType::HISTORY_TYPED_URLS_MODIFIED:\n OnTypedURLsModified(\n *Details(details).ptr());\n break;\n case NotificationType::HISTORY_URLS_DELETED:\n OnURLsDeleted(*Details(details).ptr());\n break;\n default:\n \/\/ For simplicity, the unit tests send us all notifications, even when\n \/\/ we haven't registered for them, so don't assert here.\n break;\n }\n}\n\nvoid InMemoryHistoryBackend::OnTypedURLsModified(\n const URLsModifiedDetails& details) {\n DCHECK(db_.get());\n\n \/\/ Add or update the URLs.\n \/\/\n \/\/ TODO(brettw) currently the rows in the in-memory database don't match the\n \/\/ IDs in the main database. This sucks. Instead of Add and Remove, we should\n \/\/ have Sync(), which would take the ID if it's given and add it.\n std::vector::const_iterator i;\n for (i = details.changed_urls.begin();\n i != details.changed_urls.end(); i++) {\n URLID id = db_->GetRowForURL(i->url(), NULL);\n if (id)\n db_->UpdateURLRow(id, *i);\n else\n db_->AddURL(*i);\n }\n}\n\nvoid InMemoryHistoryBackend::OnURLsDeleted(const URLsDeletedDetails& details) {\n DCHECK(db_.get());\n\n if (details.all_history) {\n \/\/ When all history is deleted, the individual URLs won't be listed. Just\n \/\/ create a new database to quickly clear everything out.\n db_.reset(new InMemoryDatabase);\n if (!db_->InitFromScratch())\n db_.reset();\n return;\n }\n\n \/\/ Delete all matching URLs in our database.\n for (std::set::const_iterator i = details.urls.begin();\n i != details.urls.end(); ++i) {\n URLID id = db_->GetRowForURL(*i, NULL);\n if (id) {\n \/\/ We typically won't have most of them since we only have a subset of\n \/\/ history, so ignore errors.\n db_->DeleteURLRow(id);\n }\n }\n}\n\n} \/\/ namespace history\n<|endoftext|>"} {"text":"#include \"omp.h\"\n\n inline\n kth_cv_omp::kth_cv_omp(const std::string in_path,\n\t\tconst std::string in_actionNames, \n\t\tconst field in_all_people,\n\t\tconst int in_scale_factor, \n\t\tconst int in_shift,\n\t\tconst int in_scene, \/\/only for kth\n\t\tconst int in_segment_length,\n\t\tconst int in_dim \n ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)\n {\n actions.load( actionNames ); \n \n \n }\n \n \n \/\/ Log-Euclidean Distance\n inline\n void\n kth_cv_omp::logEucl()\n {\n \n int n_actions = actions.n_rows;\n int n_peo = all_people.n_rows;\n \n \n \/\/No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels\n float acc;\n acc = 0;\n \n \/\/int n_test = n_peo*n_actions*total_scenes - 1; \/\/ - person13_handclapping_d3\n int n_test = n_peo*n_actions*total_scenes; \/\/ - person13_handclapping_d3\n \n vec real_labels;\n vec est_labels;\n field test_video_list(n_test);\n \n \n real_labels.zeros(n_test);\n est_labels.zeros(n_test);\n \n int k=0;\n int sc = 1; \/\/ = total scenes\n \n\n \n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act( n_actions );\n\t \n\t \/\/ Esto es lo que deberia hacerse en paralelo?? Piensa Piensa piensa\n\t wall_clock timer;\n\t timer.tic();\n\t \n\t \n\t \/\/#pragma omp parallel for \n\t for (int s=0; s test_video_list(n_test);\n \n \n real_labels.zeros(n_test);\n est_labels.zeros(n_test);\n \n int k=0;\n \n \n for (int sc = 1; sc<=total_scenes; ++sc) \/\/scene\n {\n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act( n_actions );\n\t \n\t for (int s=0; sRun in parallel. Classification#include \"omp.h\"\n\n inline\n kth_cv_omp::kth_cv_omp(const std::string in_path,\n\t\tconst std::string in_actionNames, \n\t\tconst field in_all_people,\n\t\tconst int in_scale_factor, \n\t\tconst int in_shift,\n\t\tconst int in_scene, \/\/only for kth\n\t\tconst int in_segment_length,\n\t\tconst int in_dim \n ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)\n {\n actions.load( actionNames ); \n \n \n }\n \n \n \/\/ Log-Euclidean Distance\n inline\n void\n kth_cv_omp::logEucl()\n {\n \n int n_actions = actions.n_rows;\n int n_peo = all_people.n_rows;\n \n \n \/\/No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels\n float acc;\n acc = 0;\n \n \/\/int n_test = n_peo*n_actions*total_scenes - 1; \/\/ - person13_handclapping_d3\n int n_test = n_peo*n_actions*total_scenes; \/\/ - person13_handclapping_d3\n \n vec real_labels;\n vec est_labels;\n field test_video_list(n_test);\n \n \n real_labels.zeros(n_test);\n est_labels.zeros(n_test);\n \n int k=0;\n int sc = 1; \/\/ = total scenes\n \n\n \n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act( n_actions );\n\t \n\t \/\/ Esto es lo que deberia hacerse en paralelo?? Piensa Piensa piensa\n\t wall_clock timer;\n\t timer.tic();\n\t \n\t \n\t #pragma omp parallel for \n\t for (int s=0; s test_video_list(n_test);\n \n \n real_labels.zeros(n_test);\n est_labels.zeros(n_test);\n \n int k=0;\n \n \n for (int sc = 1; sc<=total_scenes; ++sc) \/\/scene\n {\n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act( n_actions );\n\t \n\t for (int s=0; s"} {"text":"#include \"stdafx.h\"\n#include \"CoreJobTest.h\"\n#include \"CoreJob.h\"\n#include \"move_only.h\"\n#include \n\nTEST_F(CoreJobTest, VerifySimpleProperties) {\n AutoRequired jb;\n\n ASSERT_FALSE(m_create->IsInitiated()) << \"CoreJob reported it could receive events before its enclosing context was created\";\n\n \/\/ Create a thread which will delay for acceptance, and then quit:\n boost::thread t([this] {\n m_create->DelayUntilInitiated();\n });\n\n \/\/ Verify that this thread doesn't back out right away:\n ASSERT_FALSE(t.try_join_for(boost::chrono::milliseconds(10))) << \"CoreJob did not block a client who was waiting for its readiness to accept dispatchers\";\n\n \/\/ Now start the context and verify that certain properties changed as anticipated:\n m_create->Initiate();\n ASSERT_TRUE(m_create->DelayUntilInitiated()) << \"CoreJob did not correctly delay for dispatch acceptance\";\n\n \/\/ Verify that the blocked thread has become unblocked and quits properly:\n ASSERT_TRUE(t.try_join_for(boost::chrono::seconds(1))) << \"CoreJob did not correctly signal a blocked thread that it was ready to accept dispatchers\";\n}\n\nTEST_F(CoreJobTest, VerifySimpleSubmission) {\n AutoRequired jb;\n\n auto myFlag = std::make_shared(false);\n *jb += [myFlag] {\n *myFlag = true;\n };\n\n \/\/ Kickoff, signal for a shutdown to take place, and then verify the flag\n AutoCurrentContext ctxt;\n ctxt->Initiate();\n ctxt->SignalShutdown(true);\n ASSERT_TRUE(*myFlag) << \"CoreJob did not properly execute its thread\";\n}\n\nTEST_F(CoreJobTest, VerifyTeardown) {\n AutoRequired job;\n AutoCurrentContext ctxt;\n\n bool check1 = false;\n bool check2 = false;\n bool check3 = false;\n\n *job += [&check1] {\n boost::this_thread::sleep(boost::posix_time::milliseconds(200));\n check1 = true;\n };\n *job += [&check2] {\n boost::this_thread::sleep(boost::posix_time::milliseconds(200));\n check2 = true;\n };\n ctxt->Initiate();\n *job += [&check3] {\n boost::this_thread::sleep(boost::posix_time::milliseconds(100));\n check3 = true;\n };\n\n ctxt->SignalShutdown(true);\n EXPECT_TRUE(check1) << \"Lambda 1 didn't finish\";\n EXPECT_TRUE(check2) << \"Lambda 2 didn't finish\";\n EXPECT_TRUE(check3) << \"Lambda 3 didn't finish\";\n}\n\nstruct SimpleListen:\n virtual EventReceiver\n{\n SimpleListen():\n m_flag(false)\n {}\n\n void SetFlag(){m_flag=true;}\n\n bool m_flag;\n};\n\nTEST_F(CoreJobTest, VerifyNoEventReceivers){\n AutoCreateContext ctxt1;\n CurrentContextPusher pshr1(ctxt1);\n\n AutoFired fire;\n ctxt1->Initiate();\n\n AutoCreateContext ctxt2;\n CurrentContextPusher pshr2(ctxt2);\n\n AutoRequired listener;\n ASSERT_FALSE(listener->m_flag) << \"Flag was initialized improperly\";\n\n fire(&SimpleListen::SetFlag)();\n EXPECT_FALSE(listener->m_flag) << \"Lister recived event event though it wasn't initiated\";\n}\n\nclass CanOnlyMove {\npublic:\n CanOnlyMove(){}\n ~CanOnlyMove(){}\n CanOnlyMove(const CanOnlyMove& derp) = delete;\n CanOnlyMove(CanOnlyMove&& derp){}\n};\n\nTEST_F(CoreJobTest, MoveOnly){\n CanOnlyMove move;\n \/\/CanOnlyMove derp = move; \/\/error\n\n MoveOnly mo(std::move(move));\n\n MoveOnly first = mo;\n \/\/MoveOnly second = mo; \/\/error\n}\n\nTEST_F(CoreJobTest, AbandonedDispatchers) {\n auto v = std::make_shared(false);\n\n AutoRequired cj;\n *cj += [v] { *v = true; };\n\n \/\/ Graceful shutdown on our enclosing context without starting it:\n AutoCurrentContext()->SignalShutdown(true);\n\n \/\/ Verify that all lambdas on the CoreThread got called as expected:\n ASSERT_FALSE(*v) << \"Lambdas attached to a CoreJob should not be executed when the enclosing context is terminated without being started\";\n}\n\nTEST_F(CoreJobTest, RecursiveAdd) {\n bool first = false;\n bool second = false;\n bool third = false;\n \n AutoRequired cj;\n \n AutoCurrentContext()->Initiate();\n \n *cj += [&first,&second,&third, &cj] {\n first = true;\n *cj += [&first,&second,&third,&cj] {\n second = true;\n *cj += [&first,&second,&third,&cj] {\n third = true;\n };\n cj->Stop(true);\n };\n };\n \n cj->Wait();\n \n \/\/ Verify that all lambdas on the CoreThread got called as expected:\n EXPECT_TRUE(first) << \"Appended lambda didn't set value\";\n EXPECT_TRUE(second) << \"Appended lambda didn't set value\";\n EXPECT_TRUE(third) << \"Appended lambda didn't set value\";\n}\n\nTEST_F(CoreJobTest, RaceCondition) {\n \n for (int i=0; i<5; i++) {\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired cj;\n ctxt->Initiate();\n \n bool first = false;\n bool second = false;\n \n *cj += [&first] {\n first = true;\n };\n \n boost::this_thread::sleep(boost::posix_time::milliseconds(i));\n \n *cj += [&second, &cj] {\n second = true;\n };\n \n ctxt->SignalShutdown(true);\n \n ASSERT_TRUE(first) << \"Failed after set value in lambda\";\n ASSERT_TRUE(second) << \"Failed to set value when delayed \" << i << \" milliseconds\";\n }\n}\nAdding a unit test to validate context assignment during lambda execution#include \"stdafx.h\"\n#include \"CoreJobTest.h\"\n#include \"CoreJob.h\"\n#include \"move_only.h\"\n#include \n\nTEST_F(CoreJobTest, VerifySimpleProperties) {\n AutoRequired jb;\n\n ASSERT_FALSE(m_create->IsInitiated()) << \"CoreJob reported it could receive events before its enclosing context was created\";\n\n \/\/ Create a thread which will delay for acceptance, and then quit:\n boost::thread t([this] {\n m_create->DelayUntilInitiated();\n });\n\n \/\/ Verify that this thread doesn't back out right away:\n ASSERT_FALSE(t.try_join_for(boost::chrono::milliseconds(10))) << \"CoreJob did not block a client who was waiting for its readiness to accept dispatchers\";\n\n \/\/ Now start the context and verify that certain properties changed as anticipated:\n m_create->Initiate();\n ASSERT_TRUE(m_create->DelayUntilInitiated()) << \"CoreJob did not correctly delay for dispatch acceptance\";\n\n \/\/ Verify that the blocked thread has become unblocked and quits properly:\n ASSERT_TRUE(t.try_join_for(boost::chrono::seconds(1))) << \"CoreJob did not correctly signal a blocked thread that it was ready to accept dispatchers\";\n}\n\nTEST_F(CoreJobTest, VerifySimpleSubmission) {\n AutoRequired jb;\n\n auto myFlag = std::make_shared(false);\n *jb += [myFlag] {\n *myFlag = true;\n };\n\n \/\/ Kickoff, signal for a shutdown to take place, and then verify the flag\n AutoCurrentContext ctxt;\n ctxt->Initiate();\n ctxt->SignalShutdown(true);\n ASSERT_TRUE(*myFlag) << \"CoreJob did not properly execute its thread\";\n}\n\nTEST_F(CoreJobTest, VerifyTeardown) {\n AutoRequired job;\n AutoCurrentContext ctxt;\n\n bool check1 = false;\n bool check2 = false;\n bool check3 = false;\n\n *job += [&check1] {\n boost::this_thread::sleep(boost::posix_time::milliseconds(200));\n check1 = true;\n };\n *job += [&check2] {\n boost::this_thread::sleep(boost::posix_time::milliseconds(200));\n check2 = true;\n };\n ctxt->Initiate();\n *job += [&check3] {\n boost::this_thread::sleep(boost::posix_time::milliseconds(100));\n check3 = true;\n };\n\n ctxt->SignalShutdown(true);\n EXPECT_TRUE(check1) << \"Lambda 1 didn't finish\";\n EXPECT_TRUE(check2) << \"Lambda 2 didn't finish\";\n EXPECT_TRUE(check3) << \"Lambda 3 didn't finish\";\n}\n\nstruct SimpleListen:\n virtual EventReceiver\n{\n SimpleListen():\n m_flag(false)\n {}\n\n void SetFlag(){m_flag=true;}\n\n bool m_flag;\n};\n\nTEST_F(CoreJobTest, VerifyNoEventReceivers){\n AutoCreateContext ctxt1;\n CurrentContextPusher pshr1(ctxt1);\n\n AutoFired fire;\n ctxt1->Initiate();\n\n AutoCreateContext ctxt2;\n CurrentContextPusher pshr2(ctxt2);\n\n AutoRequired listener;\n ASSERT_FALSE(listener->m_flag) << \"Flag was initialized improperly\";\n\n fire(&SimpleListen::SetFlag)();\n EXPECT_FALSE(listener->m_flag) << \"Lister recived event event though it wasn't initiated\";\n}\n\nclass CanOnlyMove {\npublic:\n CanOnlyMove(){}\n ~CanOnlyMove(){}\n CanOnlyMove(const CanOnlyMove& derp) = delete;\n CanOnlyMove(CanOnlyMove&& derp){}\n};\n\nTEST_F(CoreJobTest, MoveOnly){\n CanOnlyMove move;\n \/\/CanOnlyMove derp = move; \/\/error\n\n MoveOnly mo(std::move(move));\n\n MoveOnly first = mo;\n \/\/MoveOnly second = mo; \/\/error\n}\n\nTEST_F(CoreJobTest, AbandonedDispatchers) {\n auto v = std::make_shared(false);\n\n AutoRequired cj;\n *cj += [v] { *v = true; };\n\n \/\/ Graceful shutdown on our enclosing context without starting it:\n AutoCurrentContext()->SignalShutdown(true);\n\n \/\/ Verify that all lambdas on the CoreThread got called as expected:\n ASSERT_FALSE(*v) << \"Lambdas attached to a CoreJob should not be executed when the enclosing context is terminated without being started\";\n}\n\nTEST_F(CoreJobTest, RecursiveAdd) {\n bool first = false;\n bool second = false;\n bool third = false;\n \n AutoRequired cj;\n \n AutoCurrentContext()->Initiate();\n \n *cj += [&first,&second,&third, &cj] {\n first = true;\n *cj += [&first,&second,&third,&cj] {\n second = true;\n *cj += [&first,&second,&third,&cj] {\n third = true;\n };\n cj->Stop(true);\n };\n };\n \n cj->Wait();\n \n \/\/ Verify that all lambdas on the CoreThread got called as expected:\n EXPECT_TRUE(first) << \"Appended lambda didn't set value\";\n EXPECT_TRUE(second) << \"Appended lambda didn't set value\";\n EXPECT_TRUE(third) << \"Appended lambda didn't set value\";\n}\n\nTEST_F(CoreJobTest, RaceCondition) {\n for (int i=0; i<5; i++) {\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired cj;\n ctxt->Initiate();\n \n bool first = false;\n bool second = false;\n \n *cj += [&first] {\n first = true;\n };\n \n boost::this_thread::sleep(boost::posix_time::milliseconds(i));\n \n *cj += [&second, &cj] {\n second = true;\n };\n \n ctxt->SignalShutdown(true);\n \n ASSERT_TRUE(first) << \"Failed after set value in lambda\";\n ASSERT_TRUE(second) << \"Failed to set value when delayed \" << i << \" milliseconds\";\n }\n}\n\nTEST_F(CoreJobTest, CorrectlyAssignedCurrentContext) {\n AutoCurrentContext()->Initiate();\n AutoRequired job;\n\n std::shared_ptr ctxt;\n *job += [&ctxt] { ctxt = AutoCurrentContext(); };\n *job += [job] { job->Stop(true); };\n ASSERT_TRUE(job->WaitFor(boost::chrono::seconds(5)));\n\n \/\/ Now verify that the job was run in the right thread context:\n ASSERT_EQ(AutoCurrentContext(), ctxt) << \"Job lambda was not run with the correct CoreContext current\";\n}<|endoftext|>"} {"text":"\/\/ Day23.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n\nenum OpCode { hlf, tpl, inc, jmp, jie, jio };\n\nstruct CPUState {\n\tsize_t InstructionPointer;\n\n\tsize_t a;\n\tsize_t b;\n\n\tCPUState()\n\t\t:InstructionPointer(0), a(0), b(0)\n\t{}\n};\n\ntypedef std::function InstructionFunction;\ntypedef std::vector InstructionVector;\ntypedef std::map StringOpCodeMap;\ntypedef std::function RegisterFetchFunction;\ntypedef std::map StringRegisterFetchFunctionMap;\n\n\nstatic CPUState Run(const std::string & InputFile);\nstatic InstructionFunction ParseAssembly(const StringVector & Line);\n\nstatic const StringOpCodeMap StringToOpCodeMap({ { \"hlf\", hlf },{ \"tpl\", tpl },{ \"inc\", inc },{ \"jmp\", jmp },{ \"jie\", jie },{ \"jio\", jio }, });\nstatic const StringRegisterFetchFunctionMap StringToRegisterFetch({ {\"a\", [](CPUState & CPU)->size_t& { return CPU.a; }},{ \"b\", [](CPUState & CPU)->size_t& { return CPU.b; }} });\n\nint main()\n{\n\tCPUState State = Run(\"Input.txt\");\n\n\tstd::cout << \"b: \" << State.b << std::endl;\n\n\tsystem(\"pause\");\n\n\treturn 0;\n}\n\n\nstatic CPUState Run(const std::string & InputFile)\n{\n\tStringVectorVector InputParts = GetFileLineParts(InputFile);\n\tInstructionVector ParsedInstructions(InputParts.size(), nullptr);\n\n\tCPUState CPU;\n\twhile (CPU.InstructionPointer < ParsedInstructions.size())\n\t{\n\t\tif (!ParsedInstructions[CPU.InstructionPointer])\n\t\t{\n\t\t\tParsedInstructions[CPU.InstructionPointer] = ParseAssembly(InputParts[CPU.InstructionPointer]);\n\t\t}\n\n\t\tParsedInstructions[CPU.InstructionPointer](CPU);\n\t}\n\n\treturn CPU;\n}\n\nstatic InstructionFunction ParseAssembly(const StringVector & Line)\n{\n\tconst OpCode Instruction = StringToOpCodeMap.find(Line[0])->second;\n\n\tRegisterFetchFunction RegisterFetch = nullptr;;\n\tswitch (Instruction)\n\t{\n\tcase hlf:\n\tcase tpl:\n\tcase inc:\n\t\tRegisterFetch = StringToRegisterFetch.find(Line[1])->second;\n\t\tbreak;\n\tcase jie:\n\tcase jio:\n\t\tRegisterFetch = StringToRegisterFetch.find(Line[1].substr(0, Line[1].size() - 1))->second;\n\t\tbreak;\n\t}\n\n\tint64_t JumpDistance = 0;\n\tswitch (Instruction)\n\t{\n\tcase jmp:\n\t\tJumpDistance = std::atoi(Line[1].c_str());\n\t\tbreak;\n\tcase jie:\n\tcase jio:\n\t\tJumpDistance = std::atoi(Line[2].c_str());\n\t\tbreak;\n\t}\n\n\tswitch (Instruction)\n\t{\n\tcase hlf:\n\t\treturn [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) \/= 2; ++CPU.InstructionPointer; };\n\tcase tpl:\n\t\treturn [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) *= 3; ++CPU.InstructionPointer; };\n\tcase inc:\n\t\treturn [RegisterFetch](CPUState & CPU) { ++RegisterFetch(CPU); ++CPU.InstructionPointer; };\n\tcase jmp:\n\t\treturn [JumpDistance](CPUState & CPU) { CPU.InstructionPointer += JumpDistance; };\n\tcase jie:\n\t\treturn [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += ((RegisterFetch(CPU) % 2) == 0) ? JumpDistance : 1; };\n\tcase jio:\n\t\treturn [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += (RegisterFetch(CPU) == 1) ? JumpDistance : 1; };\n\t}\n\n\treturn nullptr;\n}\nAdd soltion for Day 23 part two\/\/ Day23.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n\nenum OpCode { hlf, tpl, inc, jmp, jie, jio };\n\nstruct CPUState {\n\tsize_t InstructionPointer;\n\n\tsize_t a;\n\tsize_t b;\n\n\tCPUState()\n\t\t:InstructionPointer(0), a(0), b(0)\n\t{}\n\n\tCPUState(size_t a, size_t b)\n\t\t:InstructionPointer(0), a(a), b(b)\n\t{}\n};\n\ntypedef std::function InstructionFunction;\ntypedef std::vector InstructionVector;\ntypedef std::map StringOpCodeMap;\ntypedef std::function RegisterFetchFunction;\ntypedef std::map StringRegisterFetchFunctionMap;\n\n\nstatic CPUState Run(const std::string & InputFile, CPUState CPU = CPUState());\nstatic InstructionFunction ParseAssembly(const StringVector & Line);\n\nstatic const StringOpCodeMap StringToOpCodeMap({ { \"hlf\", hlf },{ \"tpl\", tpl },{ \"inc\", inc },{ \"jmp\", jmp },{ \"jie\", jie },{ \"jio\", jio }, });\nstatic const StringRegisterFetchFunctionMap StringToRegisterFetch({ {\"a\", [](CPUState & CPU)->size_t& { return CPU.a; }},{ \"b\", [](CPUState & CPU)->size_t& { return CPU.b; }} });\n\nint main()\n{\n\tCPUState PartOne = Run(\"Input.txt\");\n\tCPUState PartTwo = Run(\"Input.txt\", CPUState(1, 0));\n\n\tstd::cout << \"b (Part One): \" << PartOne.b << std::endl;\n\tstd::cout << \"b (Part Two): \" << PartTwo.b << std::endl;\n\n\tsystem(\"pause\");\n\n\treturn 0;\n}\n\n\nstatic CPUState Run(const std::string & InputFile, CPUState CPU)\n{\n\tStringVectorVector InputParts = GetFileLineParts(InputFile);\n\tInstructionVector ParsedInstructions(InputParts.size(), nullptr);\n\n\twhile (CPU.InstructionPointer < ParsedInstructions.size())\n\t{\n\t\tif (!ParsedInstructions[CPU.InstructionPointer])\n\t\t{\n\t\t\tParsedInstructions[CPU.InstructionPointer] = ParseAssembly(InputParts[CPU.InstructionPointer]);\n\t\t}\n\n\t\tParsedInstructions[CPU.InstructionPointer](CPU);\n\t}\n\n\treturn CPU;\n}\n\nstatic InstructionFunction ParseAssembly(const StringVector & Line)\n{\n\tconst OpCode Instruction = StringToOpCodeMap.find(Line[0])->second;\n\n\tRegisterFetchFunction RegisterFetch = nullptr;;\n\tswitch (Instruction)\n\t{\n\tcase hlf:\n\tcase tpl:\n\tcase inc:\n\t\tRegisterFetch = StringToRegisterFetch.find(Line[1])->second;\n\t\tbreak;\n\tcase jie:\n\tcase jio:\n\t\tRegisterFetch = StringToRegisterFetch.find(Line[1].substr(0, Line[1].size() - 1))->second;\n\t\tbreak;\n\t}\n\n\tint64_t JumpDistance = 0;\n\tswitch (Instruction)\n\t{\n\tcase jmp:\n\t\tJumpDistance = std::atoi(Line[1].c_str());\n\t\tbreak;\n\tcase jie:\n\tcase jio:\n\t\tJumpDistance = std::atoi(Line[2].c_str());\n\t\tbreak;\n\t}\n\n\tswitch (Instruction)\n\t{\n\tcase hlf:\n\t\treturn [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) \/= 2; ++CPU.InstructionPointer; };\n\tcase tpl:\n\t\treturn [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) *= 3; ++CPU.InstructionPointer; };\n\tcase inc:\n\t\treturn [RegisterFetch](CPUState & CPU) { ++RegisterFetch(CPU); ++CPU.InstructionPointer; };\n\tcase jmp:\n\t\treturn [JumpDistance](CPUState & CPU) { CPU.InstructionPointer += JumpDistance; };\n\tcase jie:\n\t\treturn [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += ((RegisterFetch(CPU) % 2) == 0) ? JumpDistance : 1; };\n\tcase jio:\n\t\treturn [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += (RegisterFetch(CPU) == 1) ? JumpDistance : 1; };\n\t}\n\n\treturn nullptr;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ash\/first_run\/first_run_helper.h\"\n#include \"ash\/shell.h\"\n#include \"ash\/system\/tray\/system_tray.h\"\n#include \"chrome\/browser\/chromeos\/first_run\/first_run.h\"\n#include \"chrome\/browser\/chromeos\/first_run\/first_run_controller.h\"\n#include \"chrome\/browser\/chromeos\/first_run\/step_names.h\"\n#include \"chrome\/browser\/chromeos\/login\/test\/js_checker.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"content\/public\/test\/test_utils.h\"\n\nnamespace chromeos {\n\nclass FirstRunUIBrowserTest : public InProcessBrowserTest,\n public FirstRunActor::Delegate {\n public:\n FirstRunUIBrowserTest()\n : initialized_(false),\n finalized_(false) {\n }\n\n \/\/ FirstRunActor::Delegate overrides.\n virtual void OnActorInitialized() OVERRIDE {\n initialized_ = true;\n if (!on_initialized_callback_.is_null())\n on_initialized_callback_.Run();\n controller()->OnActorInitialized();\n }\n\n virtual void OnNextButtonClicked(const std::string& step_name) OVERRIDE {\n controller()->OnNextButtonClicked(step_name);\n }\n\n virtual void OnStepShown(const std::string& step_name) OVERRIDE {\n if (!on_step_shown_callback_.is_null())\n on_step_shown_callback_.Run();\n controller()->OnStepShown(step_name);\n }\n\n virtual void OnStepHidden(const std::string& step_name) OVERRIDE {\n controller()->OnStepHidden(step_name);\n }\n\n virtual void OnHelpButtonClicked() OVERRIDE {\n controller()->OnHelpButtonClicked();\n }\n\n virtual void OnActorFinalized() OVERRIDE {\n finalized_ = true;\n if (!on_finalized_callback_.is_null())\n on_finalized_callback_.Run();\n controller()->OnActorFinalized();\n }\n\n virtual void OnActorDestroyed() OVERRIDE {\n controller()->OnActorDestroyed();\n }\n\n void LaunchTutorial() {\n chromeos::first_run::LaunchTutorial();\n EXPECT_TRUE(controller() != NULL);\n \/\/ Replacing delegate to observe all messages coming from WebUI to\n \/\/ controller.\n controller()->actor_->set_delegate(this);\n initialized_ = controller()->actor_->IsInitialized();\n }\n\n void WaitForInitialization() {\n if (initialized_)\n return;\n WaitUntilCalled(&on_initialized_callback_);\n EXPECT_TRUE(initialized_);\n js().set_web_contents(controller()->web_contents_for_tests_);\n }\n\n void WaitForStep(const std::string& step_name) {\n if (GetCurrentStepName() == step_name)\n return;\n WaitUntilCalled(&on_step_shown_callback_);\n EXPECT_EQ(GetCurrentStepName(), step_name);\n }\n\n void AdvanceStep() {\n js().Evaluate(\"cr.FirstRun.currentStep_.nextButton_.click()\");\n }\n\n void WaitForFinalization() {\n if (!finalized_) {\n WaitUntilCalled(&on_finalized_callback_);\n EXPECT_TRUE(finalized_);\n }\n }\n\n void WaitUntilCalled(base::Closure* callback) {\n scoped_refptr runner =\n new content::MessageLoopRunner;\n *callback = runner->QuitClosure();\n runner->Run();\n callback->Reset();\n }\n\n std::string GetCurrentStepName() {\n return js().GetString(\n \"cr.FirstRun.currentStep_ ? cr.FirstRun.currentStep_.getName() : ''\");\n }\n\n test::JSChecker& js() { return js_; }\n\n ash::FirstRunHelper* shell_helper() {\n return controller()->shell_helper_.get();\n }\n\n FirstRunController* controller() {\n return FirstRunController::GetInstanceForTest();\n }\n\n private:\n bool initialized_;\n bool finalized_;\n base::Closure on_initialized_callback_;\n base::Closure on_step_shown_callback_;\n base::Closure on_finalized_callback_;\n test::JSChecker js_;\n};\n\n\/\/ Disabled due to flakiness, see http:\/\/crbug.com\/335280\nIN_PROC_BROWSER_TEST_F(FirstRunUIBrowserTest, DISABLED_FirstRunFlow) {\n LaunchTutorial();\n WaitForInitialization();\n WaitForStep(first_run::kAppListStep);\n EXPECT_FALSE(shell_helper()->IsTrayBubbleOpened());\n AdvanceStep();\n WaitForStep(first_run::kTrayStep);\n EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());\n AdvanceStep();\n WaitForStep(first_run::kHelpStep);\n EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());\n AdvanceStep();\n WaitForFinalization();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(controller(), (void*)NULL);\n \/\/ shell_helper() is destructed already, thats why we call Shell directly.\n EXPECT_FALSE(ash::Shell::GetInstance()->GetPrimarySystemTray()->\n HasSystemBubble());\n}\n\n} \/\/ namespace chromeos\n\nPrevented flakiness in FirstRunUIBrowserTest.FirstRunFlow test.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ash\/first_run\/first_run_helper.h\"\n#include \"ash\/shell.h\"\n#include \"ash\/system\/tray\/system_tray.h\"\n#include \"chrome\/browser\/chromeos\/first_run\/first_run.h\"\n#include \"chrome\/browser\/chromeos\/first_run\/first_run_controller.h\"\n#include \"chrome\/browser\/chromeos\/first_run\/step_names.h\"\n#include \"chrome\/browser\/chromeos\/login\/test\/js_checker.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"content\/public\/test\/test_utils.h\"\n\nnamespace chromeos {\n\nclass FirstRunUIBrowserTest : public InProcessBrowserTest,\n public FirstRunActor::Delegate {\n public:\n FirstRunUIBrowserTest()\n : initialized_(false),\n finalized_(false) {\n }\n\n \/\/ FirstRunActor::Delegate overrides.\n virtual void OnActorInitialized() OVERRIDE {\n initialized_ = true;\n if (!on_initialized_callback_.is_null())\n on_initialized_callback_.Run();\n controller()->OnActorInitialized();\n }\n\n virtual void OnNextButtonClicked(const std::string& step_name) OVERRIDE {\n controller()->OnNextButtonClicked(step_name);\n }\n\n virtual void OnStepShown(const std::string& step_name) OVERRIDE {\n current_step_name_ = step_name;\n if (!on_step_shown_callback_.is_null())\n on_step_shown_callback_.Run();\n controller()->OnStepShown(step_name);\n }\n\n virtual void OnStepHidden(const std::string& step_name) OVERRIDE {\n controller()->OnStepHidden(step_name);\n }\n\n virtual void OnHelpButtonClicked() OVERRIDE {\n controller()->OnHelpButtonClicked();\n }\n\n virtual void OnActorFinalized() OVERRIDE {\n finalized_ = true;\n if (!on_finalized_callback_.is_null())\n on_finalized_callback_.Run();\n controller()->OnActorFinalized();\n }\n\n virtual void OnActorDestroyed() OVERRIDE {\n controller()->OnActorDestroyed();\n }\n\n void LaunchTutorial() {\n chromeos::first_run::LaunchTutorial();\n EXPECT_TRUE(controller() != NULL);\n \/\/ Replacing delegate to observe all messages coming from WebUI to\n \/\/ controller.\n controller()->actor_->set_delegate(this);\n initialized_ = controller()->actor_->IsInitialized();\n }\n\n void WaitForInitialization() {\n if (initialized_)\n return;\n WaitUntilCalled(&on_initialized_callback_);\n EXPECT_TRUE(initialized_);\n js().set_web_contents(controller()->web_contents_for_tests_);\n }\n\n void WaitForStep(const std::string& step_name) {\n if (current_step_name_ == step_name)\n return;\n WaitUntilCalled(&on_step_shown_callback_);\n EXPECT_EQ(current_step_name_, step_name);\n }\n\n void AdvanceStep() {\n js().Evaluate(\"cr.FirstRun.currentStep_.nextButton_.click()\");\n }\n\n void WaitForFinalization() {\n if (!finalized_) {\n WaitUntilCalled(&on_finalized_callback_);\n EXPECT_TRUE(finalized_);\n }\n }\n\n void WaitUntilCalled(base::Closure* callback) {\n scoped_refptr runner =\n new content::MessageLoopRunner;\n *callback = runner->QuitClosure();\n runner->Run();\n callback->Reset();\n }\n\n test::JSChecker& js() { return js_; }\n\n ash::FirstRunHelper* shell_helper() {\n return controller()->shell_helper_.get();\n }\n\n FirstRunController* controller() {\n return FirstRunController::GetInstanceForTest();\n }\n\n private:\n std::string current_step_name_;\n bool initialized_;\n bool finalized_;\n base::Closure on_initialized_callback_;\n base::Closure on_step_shown_callback_;\n base::Closure on_finalized_callback_;\n test::JSChecker js_;\n};\n\nIN_PROC_BROWSER_TEST_F(FirstRunUIBrowserTest, FirstRunFlow) {\n LaunchTutorial();\n WaitForInitialization();\n WaitForStep(first_run::kAppListStep);\n EXPECT_FALSE(shell_helper()->IsTrayBubbleOpened());\n AdvanceStep();\n WaitForStep(first_run::kTrayStep);\n EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());\n AdvanceStep();\n WaitForStep(first_run::kHelpStep);\n EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());\n AdvanceStep();\n WaitForFinalization();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(controller(), (void*)NULL);\n \/\/ shell_helper() is destructed already, thats why we call Shell directly.\n EXPECT_FALSE(ash::Shell::GetInstance()->GetPrimarySystemTray()->\n HasSystemBubble());\n}\n\n} \/\/ namespace chromeos\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/input_method\/xkeyboard.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chromeos\/input_method\/input_method_util.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n\n#if defined(TOUCH_UI)\n\/\/ Since TOUCH_UI build only supports a few keyboard layouts, we skip the tests\n\/\/ for now.\n#define TestCreateFullXkbLayoutNameKeepAlt \\\n DISABLED_TestCreateFullXkbLayoutNameKeepAlt\n#define TestCreateFullXkbLayoutNameKeepCapsLock \\\n DISABLED_TestCreateFullXkbLayoutNameKeepCapsLock\n#endif \/\/ TOUCH_UI\n\nnamespace chromeos {\nnamespace input_method {\n\nnamespace {\n\nclass TestableXKeyboard : public XKeyboard {\n public:\n explicit TestableXKeyboard(const InputMethodUtil& util) : XKeyboard(util) {\n }\n\n \/\/ Change access rights.\n using XKeyboard::CreateFullXkbLayoutName;\n using XKeyboard::ContainsModifierKeyAsReplacement;\n};\n\nclass Testee {\n public:\n Testee() : util_(), xkey_(util_) {\n }\n\n InputMethodUtil util_;\n TestableXKeyboard xkey_;\n};\n\n\/\/ Returns a ModifierMap object that contains the following mapping:\n\/\/ - kSearchKey is mapped to |search|.\n\/\/ - kLeftControl key is mapped to |control|.\n\/\/ - kLeftAlt key is mapped to |alt|.\nModifierMap GetMap(ModifierKey search, ModifierKey control, ModifierKey alt) {\n ModifierMap modifier_key;\n \/\/ Use the Search key as |search|.\n modifier_key.push_back(ModifierKeyPair(kSearchKey, search));\n modifier_key.push_back(ModifierKeyPair(kLeftControlKey, control));\n modifier_key.push_back(ModifierKeyPair(kLeftAltKey, alt));\n return modifier_key;\n}\n\n\/\/ Checks |modifier_map| and returns true if the following conditions are met:\n\/\/ - kSearchKey is mapped to |search|.\n\/\/ - kLeftControl key is mapped to |control|.\n\/\/ - kLeftAlt key is mapped to |alt|.\nbool CheckMap(const ModifierMap& modifier_map,\n ModifierKey search, ModifierKey control, ModifierKey alt) {\n ModifierMap::const_iterator begin = modifier_map.begin();\n ModifierMap::const_iterator end = modifier_map.end();\n if ((std::count(begin, end, ModifierKeyPair(kSearchKey, search)) == 1) &&\n (std::count(begin, end,\n ModifierKeyPair(kLeftControlKey, control)) == 1) &&\n (std::count(begin, end, ModifierKeyPair(kLeftAltKey, alt)) == 1)) {\n return true;\n }\n return false;\n}\n\n\/\/ Returns true if X display is available.\nbool DisplayAvailable() {\n return ui::GetXDisplay() ? true : false;\n}\n\n} \/\/ namespace\n\n\/\/ Tests CreateFullXkbLayoutName() function.\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameBasic) {\n Testee testee;\n\n \/\/ CreateFullXkbLayoutName should not accept an empty |layout_name|.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept an empty ModifierMap.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"us\", ModifierMap()).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept an incomplete ModifierMap.\n ModifierMap tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.pop_back();\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept redundant ModifierMaps.\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kSearchKey, kVoidKey)); \/\/ two search maps\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kLeftControlKey, kVoidKey)); \/\/ two ctrls\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kLeftAltKey, kVoidKey)); \/\/ two alts.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept invalid ModifierMaps.\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kVoidKey, kSearchKey)); \/\/ can't remap void\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kCapsLockKey, kSearchKey)); \/\/ ditto\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n\n \/\/ CreateFullXkbLayoutName can remap Search\/Ctrl\/Alt to CapsLock.\n EXPECT_STREQ(\"us+chromeos(capslock_disabled_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us\",\n GetMap(kCapsLockKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"us+chromeos(disabled_capslock_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us\",\n GetMap(kVoidKey, kCapsLockKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"us+chromeos(disabled_disabled_capslock)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us\",\n GetMap(kVoidKey, kVoidKey, kCapsLockKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept non-alphanumeric characters\n \/\/ except \"()-_\".\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"us!\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"us; \/bin\/sh\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"ab-c_12+chromeos(disabled_disabled_disabled),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"ab-c_12\",\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept upper-case ascii characters.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"US\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should accept lower-case ascii characters.\n for (int c = 'a'; c <= 'z'; ++c) {\n EXPECT_STRNE(\"\", testee.xkey_.CreateFullXkbLayoutName(\n std::string(3, c),\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n }\n\n \/\/ CreateFullXkbLayoutName should accept numbers.\n for (int c = '0'; c <= '9'; ++c) {\n EXPECT_STRNE(\"\", testee.xkey_.CreateFullXkbLayoutName(\n std::string(3, c),\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n }\n\n \/\/ CreateFullXkbLayoutName should accept a layout with a variant name.\n EXPECT_STREQ(\"us(dvorak)+chromeos(disabled_disabled_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us(dvorak)\",\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"gb(extd)+chromeos(disabled_disabled_disabled_keepralt),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"gb(extd)\",\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"jp+chromeos(disabled_disabled_disabled),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"jp\", \/\/ does not use AltGr, therefore no _keepralt.\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ When the layout name is not \"us\", the second layout should be added.\n EXPECT_EQ(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"us\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n EXPECT_EQ(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"us(dvorak)\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n EXPECT_NE(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"gb(extd)\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n EXPECT_NE(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"jp\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n}\n\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameKeepCapsLock) {\n Testee testee;\n\n EXPECT_STREQ(\"us(colemak)+chromeos(search_disabled_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us(colemak)\",\n \/\/ The 1st kVoidKey should be ignored.\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"de(neo)+\"\n \"chromeos(search_leftcontrol_leftcontrol_keepralt),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \/\/ The 1st kLeftControlKey should be ignored.\n \"de(neo)\", GetMap(kLeftControlKey,\n kLeftControlKey,\n kLeftControlKey)).c_str());\n}\n\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameKeepAlt) {\n Testee testee;\n\n EXPECT_STREQ(\"us(intl)+chromeos(disabled_disabled_disabled_keepralt)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us(intl)\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"kr(kr104)+\"\n \"chromeos(leftcontrol_leftcontrol_leftcontrol_keepralt),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"kr(kr104)\", GetMap(kLeftControlKey,\n kLeftControlKey,\n kLeftControlKey)).c_str());\n}\n\n\/\/ Tests if CreateFullXkbLayoutName and ExtractLayoutNameFromFullXkbLayoutName\n\/\/ functions could handle all combinations of modifier remapping.\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameModifierKeys) {\n Testee testee;\n\n std::set layouts;\n for (int i = 0; i < static_cast(kNumModifierKeys); ++i) {\n for (int j = 0; j < static_cast(kNumModifierKeys); ++j) {\n for (int k = 0; k < static_cast(kNumModifierKeys); ++k) {\n const std::string layout = testee.xkey_.CreateFullXkbLayoutName(\n \"us\", GetMap(ModifierKey(i), ModifierKey(j), ModifierKey(k)));\n \/\/ CreateFullXkbLayoutName should succeed (i.e. should not return \"\".)\n EXPECT_STREQ(\"us+\", layout.substr(0, 3).c_str())\n << \"layout: \" << layout;\n \/\/ All 4*3*3 layouts should be different.\n EXPECT_TRUE(layouts.insert(layout).second) << \"layout: \" << layout;\n }\n }\n }\n}\n\nTEST(XKeyboardTest, TestSetCapsLockIsEnabled) {\n if (!DisplayAvailable()) {\n return;\n }\n const bool initial_lock_state = XKeyboard::CapsLockIsEnabled();\n XKeyboard::SetCapsLockEnabled(true);\n EXPECT_TRUE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(false);\n EXPECT_FALSE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(true);\n EXPECT_TRUE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(false);\n EXPECT_FALSE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(initial_lock_state);\n}\n\nTEST(XKeyboardTest, TestContainsModifierKeyAsReplacement) {\n EXPECT_FALSE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kVoidKey, kVoidKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kCapsLockKey, kVoidKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kVoidKey, kCapsLockKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kVoidKey, kVoidKey, kCapsLockKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kCapsLockKey, kCapsLockKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kCapsLockKey, kCapsLockKey, kCapsLockKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kSearchKey, kVoidKey, kVoidKey), kSearchKey));\n}\n\n} \/\/ namespace input_method\n} \/\/ namespace chromeos\nFix unit_tests break on TOUCH_UI build.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/input_method\/xkeyboard.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chromeos\/input_method\/input_method_util.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n\n#if defined(TOUCH_UI)\n\/\/ Since TOUCH_UI build only supports a few keyboard layouts, we skip the tests\n\/\/ for now.\n#define TestCreateFullXkbLayoutNameKeepAlt \\\n DISABLED_TestCreateFullXkbLayoutNameKeepAlt\n#define TestCreateFullXkbLayoutNameKeepCapsLock \\\n DISABLED_TestCreateFullXkbLayoutNameKeepCapsLock\n#endif \/\/ TOUCH_UI\n\nnamespace chromeos {\nnamespace input_method {\n\nnamespace {\n\nclass TestableXKeyboard : public XKeyboard {\n public:\n explicit TestableXKeyboard(const InputMethodUtil& util) : XKeyboard(util) {\n }\n\n \/\/ Change access rights.\n using XKeyboard::CreateFullXkbLayoutName;\n using XKeyboard::ContainsModifierKeyAsReplacement;\n};\n\nclass Testee {\n public:\n Testee() : util_(), xkey_(util_) {\n }\n\n InputMethodUtil util_;\n TestableXKeyboard xkey_;\n};\n\n\/\/ Returns a ModifierMap object that contains the following mapping:\n\/\/ - kSearchKey is mapped to |search|.\n\/\/ - kLeftControl key is mapped to |control|.\n\/\/ - kLeftAlt key is mapped to |alt|.\nModifierMap GetMap(ModifierKey search, ModifierKey control, ModifierKey alt) {\n ModifierMap modifier_key;\n \/\/ Use the Search key as |search|.\n modifier_key.push_back(ModifierKeyPair(kSearchKey, search));\n modifier_key.push_back(ModifierKeyPair(kLeftControlKey, control));\n modifier_key.push_back(ModifierKeyPair(kLeftAltKey, alt));\n return modifier_key;\n}\n\n\/\/ Checks |modifier_map| and returns true if the following conditions are met:\n\/\/ - kSearchKey is mapped to |search|.\n\/\/ - kLeftControl key is mapped to |control|.\n\/\/ - kLeftAlt key is mapped to |alt|.\nbool CheckMap(const ModifierMap& modifier_map,\n ModifierKey search, ModifierKey control, ModifierKey alt) {\n ModifierMap::const_iterator begin = modifier_map.begin();\n ModifierMap::const_iterator end = modifier_map.end();\n if ((std::count(begin, end, ModifierKeyPair(kSearchKey, search)) == 1) &&\n (std::count(begin, end,\n ModifierKeyPair(kLeftControlKey, control)) == 1) &&\n (std::count(begin, end, ModifierKeyPair(kLeftAltKey, alt)) == 1)) {\n return true;\n }\n return false;\n}\n\n\/\/ Returns true if X display is available.\nbool DisplayAvailable() {\n return ui::GetXDisplay() ? true : false;\n}\n\n} \/\/ namespace\n\n\/\/ Tests CreateFullXkbLayoutName() function.\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameBasic) {\n Testee testee;\n\n \/\/ CreateFullXkbLayoutName should not accept an empty |layout_name|.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept an empty ModifierMap.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"us\", ModifierMap()).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept an incomplete ModifierMap.\n ModifierMap tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.pop_back();\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept redundant ModifierMaps.\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kSearchKey, kVoidKey)); \/\/ two search maps\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kLeftControlKey, kVoidKey)); \/\/ two ctrls\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kLeftAltKey, kVoidKey)); \/\/ two alts.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept invalid ModifierMaps.\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kVoidKey, kSearchKey)); \/\/ can't remap void\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n tmp_map = GetMap(kVoidKey, kVoidKey, kVoidKey);\n tmp_map.push_back(ModifierKeyPair(kCapsLockKey, kSearchKey)); \/\/ ditto\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\"us\", tmp_map).c_str());\n\n \/\/ CreateFullXkbLayoutName can remap Search\/Ctrl\/Alt to CapsLock.\n EXPECT_STREQ(\"us+chromeos(capslock_disabled_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us\",\n GetMap(kCapsLockKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"us+chromeos(disabled_capslock_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us\",\n GetMap(kVoidKey, kCapsLockKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"us+chromeos(disabled_disabled_capslock)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us\",\n GetMap(kVoidKey, kVoidKey, kCapsLockKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept non-alphanumeric characters\n \/\/ except \"()-_\".\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"us!\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"us; \/bin\/sh\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"ab-c_12+chromeos(disabled_disabled_disabled),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"ab-c_12\",\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should not accept upper-case ascii characters.\n EXPECT_STREQ(\"\", testee.xkey_.CreateFullXkbLayoutName(\n \"US\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ CreateFullXkbLayoutName should accept lower-case ascii characters.\n for (int c = 'a'; c <= 'z'; ++c) {\n EXPECT_STRNE(\"\", testee.xkey_.CreateFullXkbLayoutName(\n std::string(3, c),\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n }\n\n \/\/ CreateFullXkbLayoutName should accept numbers.\n for (int c = '0'; c <= '9'; ++c) {\n EXPECT_STRNE(\"\", testee.xkey_.CreateFullXkbLayoutName(\n std::string(3, c),\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n }\n\n \/\/ CreateFullXkbLayoutName should accept a layout with a variant name.\n EXPECT_STREQ(\"us(dvorak)+chromeos(disabled_disabled_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us(dvorak)\",\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"jp+chromeos(disabled_disabled_disabled),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"jp\", \/\/ does not use AltGr, therefore no _keepralt.\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n\n \/\/ When the layout name is not \"us\", the second layout should be added.\n EXPECT_EQ(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"us\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n EXPECT_EQ(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"us(dvorak)\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n EXPECT_NE(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"gb(extd)\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n EXPECT_NE(std::string::npos, testee.xkey_.CreateFullXkbLayoutName(\n \"jp\", GetMap(kVoidKey, kVoidKey, kVoidKey)).find(\",us\"));\n}\n\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameKeepCapsLock) {\n Testee testee;\n\n EXPECT_STREQ(\"us(colemak)+chromeos(search_disabled_disabled)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us(colemak)\",\n \/\/ The 1st kVoidKey should be ignored.\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"de(neo)+\"\n \"chromeos(search_leftcontrol_leftcontrol_keepralt),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \/\/ The 1st kLeftControlKey should be ignored.\n \"de(neo)\", GetMap(kLeftControlKey,\n kLeftControlKey,\n kLeftControlKey)).c_str());\n EXPECT_STREQ(\"gb(extd)+chromeos(disabled_disabled_disabled_keepralt),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"gb(extd)\",\n GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n}\n\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameKeepAlt) {\n Testee testee;\n\n EXPECT_STREQ(\"us(intl)+chromeos(disabled_disabled_disabled_keepralt)\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"us(intl)\", GetMap(kVoidKey, kVoidKey, kVoidKey)).c_str());\n EXPECT_STREQ(\"kr(kr104)+\"\n \"chromeos(leftcontrol_leftcontrol_leftcontrol_keepralt),us\",\n testee.xkey_.CreateFullXkbLayoutName(\n \"kr(kr104)\", GetMap(kLeftControlKey,\n kLeftControlKey,\n kLeftControlKey)).c_str());\n}\n\n\/\/ Tests if CreateFullXkbLayoutName and ExtractLayoutNameFromFullXkbLayoutName\n\/\/ functions could handle all combinations of modifier remapping.\nTEST(XKeyboardTest, TestCreateFullXkbLayoutNameModifierKeys) {\n Testee testee;\n\n std::set layouts;\n for (int i = 0; i < static_cast(kNumModifierKeys); ++i) {\n for (int j = 0; j < static_cast(kNumModifierKeys); ++j) {\n for (int k = 0; k < static_cast(kNumModifierKeys); ++k) {\n const std::string layout = testee.xkey_.CreateFullXkbLayoutName(\n \"us\", GetMap(ModifierKey(i), ModifierKey(j), ModifierKey(k)));\n \/\/ CreateFullXkbLayoutName should succeed (i.e. should not return \"\".)\n EXPECT_STREQ(\"us+\", layout.substr(0, 3).c_str())\n << \"layout: \" << layout;\n \/\/ All 4*3*3 layouts should be different.\n EXPECT_TRUE(layouts.insert(layout).second) << \"layout: \" << layout;\n }\n }\n }\n}\n\nTEST(XKeyboardTest, TestSetCapsLockIsEnabled) {\n if (!DisplayAvailable()) {\n return;\n }\n const bool initial_lock_state = XKeyboard::CapsLockIsEnabled();\n XKeyboard::SetCapsLockEnabled(true);\n EXPECT_TRUE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(false);\n EXPECT_FALSE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(true);\n EXPECT_TRUE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(false);\n EXPECT_FALSE(XKeyboard::CapsLockIsEnabled());\n XKeyboard::SetCapsLockEnabled(initial_lock_state);\n}\n\nTEST(XKeyboardTest, TestContainsModifierKeyAsReplacement) {\n EXPECT_FALSE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kVoidKey, kVoidKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kCapsLockKey, kVoidKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kVoidKey, kCapsLockKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kVoidKey, kVoidKey, kCapsLockKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kCapsLockKey, kCapsLockKey, kVoidKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kCapsLockKey, kCapsLockKey, kCapsLockKey), kCapsLockKey));\n EXPECT_TRUE(TestableXKeyboard::ContainsModifierKeyAsReplacement(\n GetMap(kSearchKey, kVoidKey, kVoidKey), kSearchKey));\n}\n\n} \/\/ namespace input_method\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds;\n tester->GetChildWidget()->GetBounds(&lock_bounds, true);\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n app::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\nMark ScreenLockerTest.TestBasic flaky.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\n\/\/ PulseAudioMixer sometimes crashes at exit. See http:\/\/crosbug.om\/9303\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds;\n tester->GetChildWidget()->GetBounds(&lock_bounds, true);\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n app::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_interceptor.h\"\n\n#include \n\n#include \"base\/callback.h\"\n#include \"base\/file_path.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/test\/test_server.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass PrerenderInterceptorTest : public testing::Test {\n public:\n PrerenderInterceptorTest();\n\n void MakeTestUrl(const std::string& base);\n virtual void SetUp();\n\n net::TestServer test_server_;\n GURL gurl_;\n GURL last_intercepted_gurl_;\n scoped_ptr req_;\n private:\n void SetLastInterceptedGurl(const GURL& url);\n\n PrerenderInterceptor prerender_interceptor_;\n MessageLoopForIO io_loop_;\n scoped_refptr io_message_loop_proxy_;\n BrowserThread ui_thread_;\n};\n\nPrerenderInterceptorTest::PrerenderInterceptorTest()\n : test_server_(net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))),\n last_intercepted_gurl_(\"http:\/\/not.initialized\/\"),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n prerender_interceptor_(\n NewCallback(this,\n &PrerenderInterceptorTest::SetLastInterceptedGurl))),\n ui_thread_(BrowserThread::UI, &io_loop_) {\n}\n\nvoid PrerenderInterceptorTest::SetUp() {\n testing::Test::SetUp();\n last_intercepted_gurl_ = GURL(\"http:\/\/nothing.intercepted\/\");\n\n io_message_loop_proxy_ = base::MessageLoopProxy::CreateForCurrentThread();\n ASSERT_TRUE(test_server_.Start());\n}\n\nvoid PrerenderInterceptorTest::MakeTestUrl(const std::string& base) {\n gurl_ = test_server_.GetURL(base);\n req_.reset(new TestURLRequest(gurl_, new TestDelegate()));\n}\n\nvoid PrerenderInterceptorTest::SetLastInterceptedGurl(const GURL& url) {\n last_intercepted_gurl_ = url;\n}\n\nTEST_F(PrerenderInterceptorTest, Interception) {\n MakeTestUrl(\"files\/prerender\/doc1.html\");\n req_->set_load_flags(req_->load_flags() | net::LOAD_PREFETCH);\n req_->Start();\n\n MessageLoop::current()->Run();\n EXPECT_EQ(URLRequestStatus::SUCCESS, req_->status().status());\n EXPECT_EQ(gurl_, last_intercepted_gurl_);\n}\n\nTEST_F(PrerenderInterceptorTest, NotAPrefetch) {\n MakeTestUrl(\"files\/prerender\/doc2.html\");\n req_->set_load_flags(req_->load_flags() & ~net::LOAD_PREFETCH);\n req_->Start();\n\n MessageLoop::current()->Run();\n EXPECT_EQ(URLRequestStatus::SUCCESS, req_->status().status());\n EXPECT_NE(gurl_, last_intercepted_gurl_);\n}\n\nTEST_F(PrerenderInterceptorTest, WrongMimeType) {\n MakeTestUrl(\"files\/prerender\/image.jpeg\");\n req_->set_load_flags(req_->load_flags() | net::LOAD_PREFETCH);\n req_->Start();\n\n MessageLoop::current()->Run();\n EXPECT_EQ(URLRequestStatus::SUCCESS, req_->status().status());\n EXPECT_NE(gurl_, last_intercepted_gurl_);\n}\n\nDisabling PrerenderInterceptorTests's due to memory leaks.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_interceptor.h\"\n\n#include \n\n#include \"base\/callback.h\"\n#include \"base\/file_path.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/test\/test_server.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass PrerenderInterceptorTest : public testing::Test {\n public:\n PrerenderInterceptorTest();\n\n void MakeTestUrl(const std::string& base);\n virtual void SetUp();\n\n net::TestServer test_server_;\n GURL gurl_;\n GURL last_intercepted_gurl_;\n scoped_ptr req_;\n private:\n void SetLastInterceptedGurl(const GURL& url);\n\n PrerenderInterceptor prerender_interceptor_;\n MessageLoopForIO io_loop_;\n scoped_refptr io_message_loop_proxy_;\n BrowserThread ui_thread_;\n};\n\nPrerenderInterceptorTest::PrerenderInterceptorTest()\n : test_server_(net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))),\n last_intercepted_gurl_(\"http:\/\/not.initialized\/\"),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n prerender_interceptor_(\n NewCallback(this,\n &PrerenderInterceptorTest::SetLastInterceptedGurl))),\n ui_thread_(BrowserThread::UI, &io_loop_) {\n}\n\nvoid PrerenderInterceptorTest::SetUp() {\n testing::Test::SetUp();\n last_intercepted_gurl_ = GURL(\"http:\/\/nothing.intercepted\/\");\n\n io_message_loop_proxy_ = base::MessageLoopProxy::CreateForCurrentThread();\n ASSERT_TRUE(test_server_.Start());\n}\n\nvoid PrerenderInterceptorTest::MakeTestUrl(const std::string& base) {\n gurl_ = test_server_.GetURL(base);\n req_.reset(new TestURLRequest(gurl_, new TestDelegate()));\n}\n\nvoid PrerenderInterceptorTest::SetLastInterceptedGurl(const GURL& url) {\n last_intercepted_gurl_ = url;\n}\n\n\/\/ Temporarily disabling PrerenderInterceptorTest's due to a leak.\n\/\/ I have a fix, but will land in the morning.\n\/\/ http:\/\/crbug.com\/65993\nTEST_F(PrerenderInterceptorTest, DISABLED_Interception) {\n MakeTestUrl(\"files\/prerender\/doc1.html\");\n req_->set_load_flags(req_->load_flags() | net::LOAD_PREFETCH);\n req_->Start();\n\n MessageLoop::current()->Run();\n EXPECT_EQ(URLRequestStatus::SUCCESS, req_->status().status());\n EXPECT_EQ(gurl_, last_intercepted_gurl_);\n}\n\nTEST_F(PrerenderInterceptorTest, DISABLED_NotAPrefetch) {\n MakeTestUrl(\"files\/prerender\/doc2.html\");\n req_->set_load_flags(req_->load_flags() & ~net::LOAD_PREFETCH);\n req_->Start();\n\n MessageLoop::current()->Run();\n EXPECT_EQ(URLRequestStatus::SUCCESS, req_->status().status());\n EXPECT_NE(gurl_, last_intercepted_gurl_);\n}\n\nTEST_F(PrerenderInterceptorTest, DISABLED_WrongMimeType) {\n MakeTestUrl(\"files\/prerender\/image.jpeg\");\n req_->set_load_flags(req_->load_flags() | net::LOAD_PREFETCH);\n req_->Start();\n\n MessageLoop::current()->Run();\n EXPECT_EQ(URLRequestStatus::SUCCESS, req_->status().status());\n EXPECT_NE(gurl_, last_intercepted_gurl_);\n}\n\n<|endoftext|>"} {"text":"\/*\n * ProbingPT.cpp\n *\n * Created on: 3 Nov 2015\n * Author: hieu\n *\/\n#include \n#include \"ProbingPT.h\"\n#include \"..\/System.h\"\n#include \"..\/Scores.h\"\n#include \"..\/Phrase.h\"\n#include \"..\/legacy\/InputFileStream.h\"\n#include \"..\/legacy\/ProbingPT\/probing_hash_utils.hh\"\n#include \"..\/FF\/FeatureFunctions.h\"\n#include \"..\/Search\/Manager.h\"\n#include \"..\/legacy\/FactorCollection.h\"\n#include \"..\/legacy\/ProbingPT\/quering.hh\"\n#include \"..\/legacy\/Util2.h\"\n\nusing namespace std;\n\nnamespace Moses2\n{\n\nProbingPT::ProbingPT(size_t startInd, const std::string &line)\n:PhraseTable(startInd, line)\n{\n\t ReadParameters();\n}\n\nProbingPT::~ProbingPT()\n{\n delete m_engine;\n}\n\nvoid ProbingPT::Load(System &system)\n{\n m_engine = new QueryEngine(m_path.c_str());\n\n m_unkId = 456456546456;\n\n FactorCollection &vocab = system.GetVocab();\n\n \/\/ source vocab\n const std::map &sourceVocab = m_engine->getSourceVocab();\n std::map::const_iterator iterSource;\n for (iterSource = sourceVocab.begin(); iterSource != sourceVocab.end(); ++iterSource) {\n\tconst string &wordStr = iterSource->second;\n\tconst Factor *factor = vocab.AddFactor(wordStr, system);\n\n\tuint64_t probingId = iterSource->first;\n\tsize_t factorId = factor->GetId();\n\n\tif (factorId >= m_sourceVocab.size()) {\n\t\tm_sourceVocab.resize(factorId + 1, m_unkId);\n\t}\n\tm_sourceVocab[factorId] = probingId;\n }\n\n \/\/ target vocab\n InputFileStream targetVocabStrme(m_path + \"\/TargetVocab.dat\");\n string line;\n while (getline(targetVocabStrme, line)) {\n\t vector toks = Tokenize(line, \"\\t\");\n\t assert(toks.size());\n \t const Factor *factor = vocab.AddFactor(toks[0], system);\n \t uint32_t probingId = Scan(toks[1]);\n\n \t if (probingId >= m_targetVocab.size()) {\n \t\tm_targetVocab.resize(probingId + 1, NULL);\n \t }\n \t m_targetVocab[probingId] = factor;\n }\n\n \/\/ memory mapped file to tps\n string filePath = m_path + \"\/TargetColl.dat\";\n file.open(filePath.c_str());\n if (!file.is_open()) {\n throw \"Couldn't open file \";\n }\n\n data = file.data();\n\n size_t size = file.size();\n\n \/\/ cache\n CreateCache(system);\n}\n\nvoid ProbingPT::Lookup(const Manager &mgr, InputPaths &inputPaths) const\n{\n BOOST_FOREACH(InputPath *path, inputPaths) {\n\tTargetPhrases *tpsPtr;\n\ttpsPtr = Lookup(mgr, mgr.GetPool(), *path);\n\tpath->AddTargetPhrases(*this, tpsPtr);\n }\n}\n\nTargetPhrases* ProbingPT::Lookup(const Manager &mgr,\n\t\tMemPool &pool,\n\t\tInputPath &inputPath) const\n{\n\t\/*\n\tif (inputPath.prefixPath && inputPath.prefixPath->GetTargetPhrases(*this) == NULL) {\n\t\t\/\/ assume all paths have prefixes, except rules with 1 word source\n\t\treturn NULL;\n\t}\n\telse {\n\t\tconst Phrase &sourcePhrase = inputPath.subPhrase;\n\t\tstd::pair tpsAndKey = CreateTargetPhrase(pool, mgr.system, sourcePhrase);\n\t\treturn tpsAndKey.first;\n\t}\n\t*\/\n\tconst Phrase &sourcePhrase = inputPath.subPhrase;\n\n\t\/\/ get hash for source phrase\n\tstd::pair keyStruct = GetSourceProbingId(sourcePhrase);\n\tif (!keyStruct.first) {\n\t return NULL;\n\t}\n\n\t\/\/ check in cache\n\tCache::const_iterator iter = m_cache.find(keyStruct.second);\n\tif (iter != m_cache.end()) {\n \t cerr << \"cache 1\\n\";\n\t\tTargetPhrases *tps = iter->second;\n\t\treturn tps;\n\t}\n else {\n cerr << \"cache 0\\n\";\n }\n\n\t\/\/ query pt\n\tTargetPhrases *tps = CreateTargetPhrase(pool, mgr.system, sourcePhrase, keyStruct.second);\n\treturn tps;\n}\n\nstd::pair ProbingPT::GetSourceProbingId(const Phrase &sourcePhrase) const\n{\n std::pair ret;\n\n \/\/ create a target phrase from the 1st word of the source, prefix with 'ProbingPT:'\n size_t sourceSize = sourcePhrase.GetSize();\n assert(sourceSize);\n\n uint64_t probingSource[sourceSize];\n ConvertToProbingSourcePhrase(sourcePhrase, ret.first, probingSource);\n if (!ret.first) {\n\t\/\/ source phrase contains a word unknown in the pt.\n\t\/\/ We know immediately there's no translation for it\n }\n else {\n\t ret.second = m_engine->getKey(probingSource, sourceSize);\n }\n\n return ret;\n\n}\n\nTargetPhrases *ProbingPT::CreateTargetPhrase(\n\t\t MemPool &pool,\n\t\t const System &system,\n\t\t const Phrase &sourcePhrase,\n\t\t uint64_t key) const\n{\n TargetPhrases *tps = NULL;\n\n \/\/Actual lookup\n std::pair query_result; \/\/ 1st=found, 2nd=target file offset\n query_result = m_engine->query(key);\n\n if (query_result.first) {\n\t const char *offset = data + query_result.second;\n\t uint64_t *numTP = (uint64_t*) offset;\n\n\t tps = new (pool.Allocate()) TargetPhrases(pool, *numTP);\n\n\t offset += sizeof(uint64_t);\n\t for (size_t i = 0; i < *numTP; ++i) {\n\t\t TargetPhrase *tp = CreateTargetPhrase(pool, system, offset);\n\t\t assert(tp);\n\t\t const FeatureFunctions &ffs = system.featureFunctions;\n\t\t ffs.EvaluateInIsolation(pool, system, sourcePhrase, *tp);\n\n\t\t tps->AddTargetPhrase(*tp);\n\n\t }\n\n\t tps->SortAndPrune(m_tableLimit);\n\t system.featureFunctions.EvaluateAfterTablePruning(pool, *tps, sourcePhrase);\n\t \/\/cerr << *tps << endl;\n }\n\n return tps;\n}\n\nTargetPhrase *ProbingPT::CreateTargetPhrase(\n\t\t MemPool &pool,\n\t\t const System &system,\n\t\t const char *&offset) const\n{\n\tTargetPhraseInfo *tpInfo = (TargetPhraseInfo*) offset;\n TargetPhrase *tp = new (pool.Allocate()) TargetPhrase(pool, *this, system, tpInfo->numWords);\n\n\toffset += sizeof(TargetPhraseInfo);\n\n\t\/\/ scores\n\tSCORE *scores = (SCORE*) offset;\n\n size_t totalNumScores = m_engine->num_scores + m_engine->num_lex_scores;\n\n if (m_engine->logProb) {\n\t \/\/ set pt score for rule\n\t tp->GetScores().PlusEquals(system, *this, scores);\n\n\t \/\/ save scores for other FF, eg. lex RO. Just give the offset\n\t if (m_engine->num_lex_scores) {\n\t\t tp->scoreProperties = scores + m_engine->num_scores;\n\t }\n }\n else {\n\t \/\/ log score 1st\n\t SCORE logScores[totalNumScores];\n\t for (size_t i = 0; i < totalNumScores; ++i) {\n\t\t logScores[i] = FloorScore(TransformScore(scores[i]));\n\t }\n\n \/\/ set pt score for rule\n\t tp->GetScores().PlusEquals(system, *this, logScores);\n\n \/\/ save scores for other FF, eg. lex RO.\n\t tp->scoreProperties = pool.Allocate(m_engine->num_lex_scores);\n\t for (size_t i = 0; i < m_engine->num_lex_scores; ++i) {\n\t\t tp->scoreProperties[i] = logScores[i + m_engine->num_scores];\n\t }\n }\n\n offset += sizeof(SCORE) * totalNumScores;\n\n \/\/ words\n for (size_t i = 0; i < tpInfo->numWords; ++i) {\n\t uint32_t *probingId = (uint32_t*) offset;\n\n\t const Factor *factor = GetTargetFactor(*probingId);\n\t assert(factor);\n\n\t Word &word = (*tp)[i];\n\t word[0] = factor;\n\n\t offset += sizeof(uint32_t);\n }\n\n \/\/ properties TODO\n\n return tp;\n}\n\nvoid ProbingPT::ConvertToProbingSourcePhrase(const Phrase &sourcePhrase, bool &ok, uint64_t probingSource[]) const\n{\n\n size_t size = sourcePhrase.GetSize();\n for (size_t i = 0; i < size; ++i) {\n const Factor *factor = sourcePhrase[i][0];\n uint64_t probingId = GetSourceProbingId(factor);\n if (probingId == m_unkId) {\n ok = false;\n return;\n } else {\n probingSource[i] = probingId;\n }\n }\n\n ok = true;\n}\n\nvoid ProbingPT::CreateCache(System &system)\n{\n\tif (m_maxCacheSize == 0) {\n\t\treturn;\n\t}\n\n\tstring filePath = m_path + \"\/cache\";\n\tInputFileStream strme(filePath);\n\n\tstring line;\n\tgetline(strme, line);\n\t\/\/float totalCount = Scan(line);\n\n\tMemPool &pool = system.GetSystemPool();\n\tFactorCollection &vocab = system.GetVocab();\n\n\tsize_t lineCount = 0;\n\twhile (getline(strme, line) && lineCount < m_maxCacheSize) {\n\t\tvector toks = Tokenize(line, \"\\t\");\n\t\tassert(toks.size() == 2);\n\t\tPhraseImpl *sourcePhrase = PhraseImpl::CreateFromString(pool, vocab, system, toks[1]);\n\n\t\tstd::pair retStruct = GetSourceProbingId(*sourcePhrase);\n\t\tif (!retStruct.first) {\n\t\t return;\n\t\t}\n\n\t\tTargetPhrases *tps = CreateTargetPhrase(pool, system, *sourcePhrase, retStruct.second);\n\t\tassert(tps);\n\n\t\tm_cache[retStruct.second] = tps;\n\n\t\t++lineCount;\n\t}\n\n\n}\n\n}\n\nRevert \"debug cache\"\/*\n * ProbingPT.cpp\n *\n * Created on: 3 Nov 2015\n * Author: hieu\n *\/\n#include \n#include \"ProbingPT.h\"\n#include \"..\/System.h\"\n#include \"..\/Scores.h\"\n#include \"..\/Phrase.h\"\n#include \"..\/legacy\/InputFileStream.h\"\n#include \"..\/legacy\/ProbingPT\/probing_hash_utils.hh\"\n#include \"..\/FF\/FeatureFunctions.h\"\n#include \"..\/Search\/Manager.h\"\n#include \"..\/legacy\/FactorCollection.h\"\n#include \"..\/legacy\/ProbingPT\/quering.hh\"\n#include \"..\/legacy\/Util2.h\"\n\nusing namespace std;\n\nnamespace Moses2\n{\n\nProbingPT::ProbingPT(size_t startInd, const std::string &line)\n:PhraseTable(startInd, line)\n{\n\t ReadParameters();\n}\n\nProbingPT::~ProbingPT()\n{\n delete m_engine;\n}\n\nvoid ProbingPT::Load(System &system)\n{\n m_engine = new QueryEngine(m_path.c_str());\n\n m_unkId = 456456546456;\n\n FactorCollection &vocab = system.GetVocab();\n\n \/\/ source vocab\n const std::map &sourceVocab = m_engine->getSourceVocab();\n std::map::const_iterator iterSource;\n for (iterSource = sourceVocab.begin(); iterSource != sourceVocab.end(); ++iterSource) {\n\tconst string &wordStr = iterSource->second;\n\tconst Factor *factor = vocab.AddFactor(wordStr, system);\n\n\tuint64_t probingId = iterSource->first;\n\tsize_t factorId = factor->GetId();\n\n\tif (factorId >= m_sourceVocab.size()) {\n\t\tm_sourceVocab.resize(factorId + 1, m_unkId);\n\t}\n\tm_sourceVocab[factorId] = probingId;\n }\n\n \/\/ target vocab\n InputFileStream targetVocabStrme(m_path + \"\/TargetVocab.dat\");\n string line;\n while (getline(targetVocabStrme, line)) {\n\t vector toks = Tokenize(line, \"\\t\");\n\t assert(toks.size());\n \t const Factor *factor = vocab.AddFactor(toks[0], system);\n \t uint32_t probingId = Scan(toks[1]);\n\n \t if (probingId >= m_targetVocab.size()) {\n \t\tm_targetVocab.resize(probingId + 1, NULL);\n \t }\n \t m_targetVocab[probingId] = factor;\n }\n\n \/\/ memory mapped file to tps\n string filePath = m_path + \"\/TargetColl.dat\";\n file.open(filePath.c_str());\n if (!file.is_open()) {\n throw \"Couldn't open file \";\n }\n\n data = file.data();\n\n size_t size = file.size();\n\n \/\/ cache\n CreateCache(system);\n}\n\nvoid ProbingPT::Lookup(const Manager &mgr, InputPaths &inputPaths) const\n{\n BOOST_FOREACH(InputPath *path, inputPaths) {\n\tTargetPhrases *tpsPtr;\n\ttpsPtr = Lookup(mgr, mgr.GetPool(), *path);\n\tpath->AddTargetPhrases(*this, tpsPtr);\n }\n}\n\nTargetPhrases* ProbingPT::Lookup(const Manager &mgr,\n\t\tMemPool &pool,\n\t\tInputPath &inputPath) const\n{\n\t\/*\n\tif (inputPath.prefixPath && inputPath.prefixPath->GetTargetPhrases(*this) == NULL) {\n\t\t\/\/ assume all paths have prefixes, except rules with 1 word source\n\t\treturn NULL;\n\t}\n\telse {\n\t\tconst Phrase &sourcePhrase = inputPath.subPhrase;\n\t\tstd::pair tpsAndKey = CreateTargetPhrase(pool, mgr.system, sourcePhrase);\n\t\treturn tpsAndKey.first;\n\t}\n\t*\/\n\tconst Phrase &sourcePhrase = inputPath.subPhrase;\n\n\t\/\/ get hash for source phrase\n\tstd::pair keyStruct = GetSourceProbingId(sourcePhrase);\n\tif (!keyStruct.first) {\n\t return NULL;\n\t}\n\n\t\/\/ check in cache\n\tCache::const_iterator iter = m_cache.find(keyStruct.second);\n\tif (iter != m_cache.end()) {\n\t\tTargetPhrases *tps = iter->second;\n\t\treturn tps;\n\t}\n\n\t\/\/ query pt\n\tTargetPhrases *tps = CreateTargetPhrase(pool, mgr.system, sourcePhrase, keyStruct.second);\n\treturn tps;\n}\n\nstd::pair ProbingPT::GetSourceProbingId(const Phrase &sourcePhrase) const\n{\n std::pair ret;\n\n \/\/ create a target phrase from the 1st word of the source, prefix with 'ProbingPT:'\n size_t sourceSize = sourcePhrase.GetSize();\n assert(sourceSize);\n\n uint64_t probingSource[sourceSize];\n ConvertToProbingSourcePhrase(sourcePhrase, ret.first, probingSource);\n if (!ret.first) {\n\t\/\/ source phrase contains a word unknown in the pt.\n\t\/\/ We know immediately there's no translation for it\n }\n else {\n\t ret.second = m_engine->getKey(probingSource, sourceSize);\n }\n\n return ret;\n\n}\n\nTargetPhrases *ProbingPT::CreateTargetPhrase(\n\t\t MemPool &pool,\n\t\t const System &system,\n\t\t const Phrase &sourcePhrase,\n\t\t uint64_t key) const\n{\n TargetPhrases *tps = NULL;\n\n \/\/Actual lookup\n std::pair query_result; \/\/ 1st=found, 2nd=target file offset\n query_result = m_engine->query(key);\n\n if (query_result.first) {\n\t const char *offset = data + query_result.second;\n\t uint64_t *numTP = (uint64_t*) offset;\n\n\t tps = new (pool.Allocate()) TargetPhrases(pool, *numTP);\n\n\t offset += sizeof(uint64_t);\n\t for (size_t i = 0; i < *numTP; ++i) {\n\t\t TargetPhrase *tp = CreateTargetPhrase(pool, system, offset);\n\t\t assert(tp);\n\t\t const FeatureFunctions &ffs = system.featureFunctions;\n\t\t ffs.EvaluateInIsolation(pool, system, sourcePhrase, *tp);\n\n\t\t tps->AddTargetPhrase(*tp);\n\n\t }\n\n\t tps->SortAndPrune(m_tableLimit);\n\t system.featureFunctions.EvaluateAfterTablePruning(pool, *tps, sourcePhrase);\n\t \/\/cerr << *tps << endl;\n }\n\n return tps;\n}\n\nTargetPhrase *ProbingPT::CreateTargetPhrase(\n\t\t MemPool &pool,\n\t\t const System &system,\n\t\t const char *&offset) const\n{\n\tTargetPhraseInfo *tpInfo = (TargetPhraseInfo*) offset;\n TargetPhrase *tp = new (pool.Allocate()) TargetPhrase(pool, *this, system, tpInfo->numWords);\n\n\toffset += sizeof(TargetPhraseInfo);\n\n\t\/\/ scores\n\tSCORE *scores = (SCORE*) offset;\n\n size_t totalNumScores = m_engine->num_scores + m_engine->num_lex_scores;\n\n if (m_engine->logProb) {\n\t \/\/ set pt score for rule\n\t tp->GetScores().PlusEquals(system, *this, scores);\n\n\t \/\/ save scores for other FF, eg. lex RO. Just give the offset\n\t if (m_engine->num_lex_scores) {\n\t\t tp->scoreProperties = scores + m_engine->num_scores;\n\t }\n }\n else {\n\t \/\/ log score 1st\n\t SCORE logScores[totalNumScores];\n\t for (size_t i = 0; i < totalNumScores; ++i) {\n\t\t logScores[i] = FloorScore(TransformScore(scores[i]));\n\t }\n\n \/\/ set pt score for rule\n\t tp->GetScores().PlusEquals(system, *this, logScores);\n\n \/\/ save scores for other FF, eg. lex RO.\n\t tp->scoreProperties = pool.Allocate(m_engine->num_lex_scores);\n\t for (size_t i = 0; i < m_engine->num_lex_scores; ++i) {\n\t\t tp->scoreProperties[i] = logScores[i + m_engine->num_scores];\n\t }\n }\n\n offset += sizeof(SCORE) * totalNumScores;\n\n \/\/ words\n for (size_t i = 0; i < tpInfo->numWords; ++i) {\n\t uint32_t *probingId = (uint32_t*) offset;\n\n\t const Factor *factor = GetTargetFactor(*probingId);\n\t assert(factor);\n\n\t Word &word = (*tp)[i];\n\t word[0] = factor;\n\n\t offset += sizeof(uint32_t);\n }\n\n \/\/ properties TODO\n\n return tp;\n}\n\nvoid ProbingPT::ConvertToProbingSourcePhrase(const Phrase &sourcePhrase, bool &ok, uint64_t probingSource[]) const\n{\n\n size_t size = sourcePhrase.GetSize();\n for (size_t i = 0; i < size; ++i) {\n const Factor *factor = sourcePhrase[i][0];\n uint64_t probingId = GetSourceProbingId(factor);\n if (probingId == m_unkId) {\n ok = false;\n return;\n } else {\n probingSource[i] = probingId;\n }\n }\n\n ok = true;\n}\n\nvoid ProbingPT::CreateCache(System &system)\n{\n\tif (m_maxCacheSize == 0) {\n\t\treturn;\n\t}\n\n\tstring filePath = m_path + \"\/cache\";\n\tInputFileStream strme(filePath);\n\n\tstring line;\n\tgetline(strme, line);\n\t\/\/float totalCount = Scan(line);\n\n\tMemPool &pool = system.GetSystemPool();\n\tFactorCollection &vocab = system.GetVocab();\n\n\tsize_t lineCount = 0;\n\twhile (getline(strme, line) && lineCount < m_maxCacheSize) {\n\t\tvector toks = Tokenize(line, \"\\t\");\n\t\tassert(toks.size() == 2);\n\t\tPhraseImpl *sourcePhrase = PhraseImpl::CreateFromString(pool, vocab, system, toks[1]);\n\n\t\tstd::pair retStruct = GetSourceProbingId(*sourcePhrase);\n\t\tif (!retStruct.first) {\n\t\t return;\n\t\t}\n\n\t\tTargetPhrases *tps = CreateTargetPhrase(pool, system, *sourcePhrase, retStruct.second);\n\t\tassert(tps);\n\n\t\tm_cache[retStruct.second] = tps;\n\n\t\t++lineCount;\n\t}\n\n\n}\n\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2002 - present, H. Hernan Saez\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Rendering\/Compositions\/TonemappingComposition.hpp\"\n\n#include \"Rendering\/CommandBuffer.hpp\"\n#include \"Rendering\/DescriptorSet.hpp\"\n#include \"Rendering\/Pipeline.hpp\"\n#include \"Rendering\/RenderPass.hpp\"\n#include \"Rendering\/Sampler.hpp\"\n#include \"Rendering\/ShaderProgram.hpp\"\n#include \"Rendering\/Texture.hpp\"\n#include \"Rendering\/UniformBuffer.hpp\"\n#include \"Simulation\/AssetManager.hpp\"\n\nusing namespace crimild;\nusing namespace crimild::compositions;\n\nComposition crimild::compositions::tonemapping( Composition cmp, crimild::Real32 exposure ) noexcept\n{\n auto renderPass = cmp.create< RenderPass >();\n renderPass->attachments = {\n [ & ] {\n auto att = cmp.createAttachment( \"tonemapping\" );\n att->usage = Attachment::Usage::COLOR_ATTACHMENT;\n att->format = Format::R8G8B8A8_UNORM;\n att->imageView = crimild::alloc< ImageView >();\n att->imageView->image = crimild::alloc< Image >();\n return crimild::retain( att );\n }(),\n };\n\n renderPass->setDescriptors(\n [ & ] {\n auto descriptorSet = crimild::alloc< DescriptorSet >();\n descriptorSet->descriptors = {\n {\n .descriptorType = DescriptorType::UNIFORM_BUFFER,\n .obj = crimild::alloc< UniformBuffer >( exposure ),\n },\n {\n .descriptorType = DescriptorType::TEXTURE,\n .obj = [ & ] {\n auto texture = crimild::alloc< Texture >();\n texture->imageView = cmp.getOutput()->imageView;\n texture->sampler = [] {\n auto sampler = crimild::alloc< Sampler >();\n sampler->setMinFilter( Sampler::Filter::NEAREST );\n sampler->setMagFilter( Sampler::Filter::NEAREST );\n return sampler;\n }();\n return texture;\n }(),\n },\n };\n return descriptorSet;\n }() );\n\n renderPass->setGraphicsPipeline(\n [] {\n auto pipeline = crimild::alloc< GraphicsPipeline >();\n pipeline->setProgram(\n [] {\n auto program = crimild::alloc< ShaderProgram >(\n Array< SharedPointer< Shader > > {\n crimild::alloc< Shader >(\n Shader::Stage::VERTEX,\n CRIMILD_TO_STRING(\n vec2 positions[ 6 ] = vec2[](\n vec2( -1.0, 1.0 ),\n vec2( -1.0, -1.0 ),\n vec2( 1.0, -1.0 ),\n\n vec2( -1.0, 1.0 ),\n vec2( 1.0, -1.0 ),\n vec2( 1.0, 1.0 ) );\n\n vec2 texCoords[ 6 ] = vec2[](\n vec2( 0.0, 0.0 ),\n vec2( 0.0, 1.0 ),\n vec2( 1.0, 1.0 ),\n\n vec2( 0.0, 0.0 ),\n vec2( 1.0, 1.0 ),\n vec2( 1.0, 0.0 ) );\n\n layout( location = 0 ) out vec2 outTexCoord;\n\n void main() {\n gl_Position = vec4( positions[ gl_VertexIndex ], 0.0, 1.0 );\n outTexCoord = texCoords[ gl_VertexIndex ];\n } ) ),\n crimild::alloc< Shader >(\n Shader::Stage::FRAGMENT,\n CRIMILD_TO_STRING(\n layout( location = 0 ) in vec2 inTexCoord;\n\n layout( set = 0, binding = 0 ) uniform Uniforms {\n float exposure;\n };\n\n layout( set = 0, binding = 1 ) uniform sampler2D uHDRMap;\n\n layout( location = 0 ) out vec4 outColor;\n\n void main() {\n const float gamma = 2.2;\n\n \/\/ Reinhard tone mapping\n vec3 hdrColor = texture( uHDRMap, inTexCoord ).rgb;\n vec3 mapped = vec3( 1.0 ) - exp( -hdrColor * exposure );\n\n \/\/ Gamma correction\n mapped = pow( mapped, vec3( 1.0 \/ gamma ) );\n\n outColor = vec4( mapped, 1.0 );\n } ) ),\n } );\n program->descriptorSetLayouts = {\n [] {\n auto layout = crimild::alloc< DescriptorSetLayout >();\n layout->bindings = {\n {\n .descriptorType = DescriptorType::UNIFORM_BUFFER,\n .stage = Shader::Stage::FRAGMENT,\n },\n {\n .descriptorType = DescriptorType::TEXTURE,\n .stage = Shader::Stage::FRAGMENT,\n },\n };\n return layout;\n }(),\n };\n return program;\n }() );\n pipeline->viewport = { .scalingMode = ScalingMode::DYNAMIC };\n pipeline->scissor = { .scalingMode = ScalingMode::DYNAMIC };\n return pipeline;\n }() );\n\n renderPass->commands = [ & ] {\n auto commandBuffer = crimild::alloc< CommandBuffer >();\n commandBuffer->bindGraphicsPipeline( renderPass->getGraphicsPipeline() );\n commandBuffer->bindDescriptorSet( renderPass->getDescriptors() );\n commandBuffer->draw( 6 );\n return commandBuffer;\n }();\n\n cmp.setOutput( crimild::get_ptr( renderPass->attachments[ 0 ] ) );\n\n return cmp;\n}\nFix viewport dimensions in tonemapping composition\/*\n * Copyright (c) 2002 - present, H. Hernan Saez\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Rendering\/Compositions\/TonemappingComposition.hpp\"\n\n#include \"Rendering\/CommandBuffer.hpp\"\n#include \"Rendering\/DescriptorSet.hpp\"\n#include \"Rendering\/Pipeline.hpp\"\n#include \"Rendering\/RenderPass.hpp\"\n#include \"Rendering\/Sampler.hpp\"\n#include \"Rendering\/ShaderProgram.hpp\"\n#include \"Rendering\/Texture.hpp\"\n#include \"Rendering\/UniformBuffer.hpp\"\n#include \"Simulation\/AssetManager.hpp\"\n\nusing namespace crimild;\nusing namespace crimild::compositions;\n\nComposition crimild::compositions::tonemapping( Composition cmp, crimild::Real32 exposure ) noexcept\n{\n auto renderPass = cmp.create< RenderPass >();\n renderPass->attachments = {\n [ & ] {\n auto att = cmp.createAttachment( \"tonemapping\" );\n att->usage = Attachment::Usage::COLOR_ATTACHMENT;\n att->format = Format::R8G8B8A8_UNORM;\n att->imageView = crimild::alloc< ImageView >();\n att->imageView->image = crimild::alloc< Image >();\n return crimild::retain( att );\n }(),\n };\n\n renderPass->setDescriptors(\n [ & ] {\n auto descriptorSet = crimild::alloc< DescriptorSet >();\n descriptorSet->descriptors = {\n {\n .descriptorType = DescriptorType::UNIFORM_BUFFER,\n .obj = crimild::alloc< UniformBuffer >( exposure ),\n },\n {\n .descriptorType = DescriptorType::TEXTURE,\n .obj = [ & ] {\n auto texture = crimild::alloc< Texture >();\n texture->imageView = cmp.getOutput()->imageView;\n texture->sampler = [] {\n auto sampler = crimild::alloc< Sampler >();\n sampler->setMinFilter( Sampler::Filter::NEAREST );\n sampler->setMagFilter( Sampler::Filter::NEAREST );\n return sampler;\n }();\n return texture;\n }(),\n },\n };\n return descriptorSet;\n }() );\n\n renderPass->setGraphicsPipeline(\n [] {\n auto pipeline = crimild::alloc< GraphicsPipeline >();\n pipeline->setProgram(\n [] {\n auto program = crimild::alloc< ShaderProgram >(\n Array< SharedPointer< Shader > > {\n crimild::alloc< Shader >(\n Shader::Stage::VERTEX,\n CRIMILD_TO_STRING(\n vec2 positions[ 6 ] = vec2[](\n vec2( -1.0, 1.0 ),\n vec2( -1.0, -1.0 ),\n vec2( 1.0, -1.0 ),\n\n vec2( -1.0, 1.0 ),\n vec2( 1.0, -1.0 ),\n vec2( 1.0, 1.0 ) );\n\n vec2 texCoords[ 6 ] = vec2[](\n vec2( 0.0, 0.0 ),\n vec2( 0.0, 1.0 ),\n vec2( 1.0, 1.0 ),\n\n vec2( 0.0, 0.0 ),\n vec2( 1.0, 1.0 ),\n vec2( 1.0, 0.0 ) );\n\n layout( location = 0 ) out vec2 outTexCoord;\n\n void main() {\n gl_Position = vec4( positions[ gl_VertexIndex ], 0.0, 1.0 );\n outTexCoord = texCoords[ gl_VertexIndex ];\n } ) ),\n crimild::alloc< Shader >(\n Shader::Stage::FRAGMENT,\n CRIMILD_TO_STRING(\n layout( location = 0 ) in vec2 inTexCoord;\n\n layout( set = 0, binding = 0 ) uniform Uniforms {\n float exposure;\n };\n\n layout( set = 0, binding = 1 ) uniform sampler2D uHDRMap;\n\n layout( location = 0 ) out vec4 outColor;\n\n void main() {\n const float gamma = 2.2;\n\n \/\/ Reinhard tone mapping\n vec3 hdrColor = texture( uHDRMap, inTexCoord ).rgb;\n vec3 mapped = vec3( 1.0 ) - exp( -hdrColor * exposure );\n\n \/\/ Gamma correction\n mapped = pow( mapped, vec3( 1.0 \/ gamma ) );\n\n outColor = vec4( mapped, 1.0 );\n } ) ),\n } );\n program->descriptorSetLayouts = {\n [] {\n auto layout = crimild::alloc< DescriptorSetLayout >();\n layout->bindings = {\n {\n .descriptorType = DescriptorType::UNIFORM_BUFFER,\n .stage = Shader::Stage::FRAGMENT,\n },\n {\n .descriptorType = DescriptorType::TEXTURE,\n .stage = Shader::Stage::FRAGMENT,\n },\n };\n return layout;\n }(),\n };\n return program;\n }() );\n pipeline->viewport = { .scalingMode = ScalingMode::DYNAMIC };\n pipeline->scissor = { .scalingMode = ScalingMode::DYNAMIC };\n return pipeline;\n }() );\n\n auto viewport = ViewportDimensions {\n .scalingMode = ScalingMode::RELATIVE,\n };\n\n renderPass->commands = [ & ] {\n auto commandBuffer = crimild::alloc< CommandBuffer >();\n commandBuffer->setViewport( viewport );\n commandBuffer->setScissor( viewport );\n commandBuffer->bindGraphicsPipeline( renderPass->getGraphicsPipeline() );\n commandBuffer->bindDescriptorSet( renderPass->getDescriptors() );\n commandBuffer->draw( 6 );\n return commandBuffer;\n }();\n\n cmp.setOutput( crimild::get_ptr( renderPass->attachments[ 0 ] ) );\n\n return cmp;\n}\n<|endoftext|>"} {"text":"#include \"EventDialog.h\"\n#include \"ui_EventDialog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ TODO Get the columns from the Database class\nenum EventColumn {\n IDColumn = 0,\n TypeColumn = 1,\n ConversationColumn = 2,\n CharacterColumn = 3,\n AudioFileColumn = 4,\n TextColumn = 5\n};\n\nEventDialog::EventDialog(QWidget *parent) :\n QDialog(parent), ui(new Ui::EventDialog), m_row(0), m_result(0), m_delegate(new QSqlRelationalDelegate(this))\n{\n ui->setupUi(this);\n\n m_columnToComboBoxMap.insert(TypeColumn, ui->typeComboBox);\n m_columnToComboBoxMap.insert(ConversationColumn, ui->conversationComboBox);\n m_columnToComboBoxMap.insert(CharacterColumn, ui->characterComboBox);\n m_columnToComboBoxMap.insert(AudioFileColumn, ui->audioFileComboBox);\n\n connect(ui->typeComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(changedEventType(QString)));\n\n foreach(QComboBox *comboBox, m_columnToComboBoxMap) {\n connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkWriteReady()));\n connect(comboBox, SIGNAL(editTextChanged(QString)), this, SLOT(checkWriteReady()));\n }\n connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(checkWriteReady()));\n\n checkWriteReady();\n}\n\nvoid EventDialog::changedEventType(const QString &eventType)\n{\n \/\/ TODO Maybe change the event entry box depending event type?\n ui->eventTypeGroupBox->setTitle(eventType);\n}\n\nvoid EventDialog::accept()\n{\n \/\/ Manually set the result first so it's propogated to the delegate before closing\n setResult(QDialog::Accepted);\n done(QDialog::Accepted);\n}\n\nEventDialog::~EventDialog()\n{\n delete ui;\n}\n\nvoid EventDialog::setModelRow(QSqlRelationalTableModel *model, int row) {\n m_row = row;\n m_model = model;\n\n foreach(QComboBox *comboBox, m_columnToComboBoxMap)\n setupComboBox(comboBox);\n\n setupTextEdit(ui->textEdit);\n}\n\nvoid EventDialog::writeToModel() {\n foreach(QComboBox *comboBox, m_columnToComboBoxMap)\n writeComboBox(comboBox);\n\n writeTextEdit(ui->textEdit);\n}\n\nvoid EventDialog::setupComboBox(QComboBox *comboBox) {\n Q_ASSERT(comboBox);\n if (!comboBox)\n return;\n\n const int comboBoxColumn = m_columnToComboBoxMap.key(comboBox);\n const QModelIndex index = m_model->index(m_row, comboBoxColumn);\n QWidget *delegateWidget = m_delegate->createEditor(this, QStyleOptionViewItem(), index);\n QComboBox *delegateComboBox = qobject_cast(delegateWidget);\n Q_ASSERT(delegateComboBox);\n if (!delegateComboBox)\n return;\n m_delegate->setEditorData(delegateComboBox, index);\n\n QAbstractItemModel *abstractModel = delegateComboBox->model();\n QSqlTableModel *model = qobject_cast(abstractModel);\n Q_ASSERT(model);\n if (!model)\n return;\n\n model->setEditStrategy(QSqlTableModel::OnManualSubmit);\n comboBox->setModel(model);\n comboBox->setModelColumn(delegateComboBox->modelColumn());\n comboBox->setCurrentIndex(delegateComboBox->currentIndex());\n\n delete delegateComboBox;\n}\n\nvoid EventDialog::setupTextEdit(QTextEdit *textEdit) {\n const QModelIndex index = m_model->index(m_row, TextColumn);\n QWidget *delegateWidget = m_delegate->createEditor(this, QStyleOptionViewItem(), index);\n QLineEdit *delegateLineEdit = qobject_cast(delegateWidget);\n Q_ASSERT(delegateLineEdit);\n if (!delegateLineEdit)\n return;\n m_delegate->setEditorData(delegateLineEdit, index);\n\n textEdit->setText(delegateLineEdit->text());\n\n delete delegateLineEdit;\n}\n\nvoid EventDialog::writeComboBox(QComboBox *comboBox) {\n Q_ASSERT(comboBox);\n if (!comboBox)\n return;\n\n QSqlTableModel *relationModel = qobject_cast(comboBox->model());\n Q_ASSERT(relationModel);\n if (!relationModel)\n return;\n\n \/\/ Need to get text before writing new items as the combobox\n \/\/ index can be reset afterwards.\n const QString &comboBoxText = comboBox->currentText();\n relationModel->submitAll();\n const int comboBoxRow = comboBox->findText(comboBoxText);\n comboBox->setCurrentIndex(comboBoxRow);\n\n \/\/ A hacky but successful way to clear the model's relation cache.\n const QSqlTableModel::EditStrategy editStrategy = m_model->editStrategy();\n Q_ASSERT(editStrategy != QSqlTableModel::OnManualSubmit);\n m_model->setEditStrategy(QSqlTableModel::OnManualSubmit);\n m_model->submitAll();\n m_model->setEditStrategy(editStrategy);\n\n const int comboBoxColumn = m_columnToComboBoxMap.key(comboBox);\n const QModelIndex index = m_model->index(m_row, comboBoxColumn);\n m_delegate->setModelData(comboBox, m_model, index);\n}\n\nvoid EventDialog::writeTextEdit(QTextEdit *textEdit) {\n QLineEdit *lineEdit = new QLineEdit(textEdit->toPlainText(), this);\n const QModelIndex index = m_model->index(m_row, TextColumn);\n m_delegate->setModelData(lineEdit, m_model, index);\n delete lineEdit;\n}\n\nvoid EventDialog::checkWriteReady() {\n bool isReadyToWrite = true;\n\n foreach(QComboBox *comboBox, m_columnToComboBoxMap)\n if (comboBox->currentIndex() == -1 || comboBox->currentText().isEmpty()) {\n isReadyToWrite = false;\n break;\n }\n\n if (isReadyToWrite && ui->textEdit->toPlainText().isEmpty())\n isReadyToWrite = false;\n\n QPushButton *ok = ui->buttonBox->button(QDialogButtonBox::Ok);\n Q_ASSERT(ok);\n if (ok)\n ok->setEnabled(isReadyToWrite);\n}\nFix adding new events.#include \"EventDialog.h\"\n#include \"ui_EventDialog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ TODO Get the columns from the Database class\nenum EventColumn {\n IDColumn = 0,\n TypeColumn = 1,\n ConversationColumn = 2,\n CharacterColumn = 3,\n AudioFileColumn = 4,\n TextColumn = 5\n};\n\nEventDialog::EventDialog(QWidget *parent) :\n QDialog(parent), ui(new Ui::EventDialog), m_row(0), m_result(0), m_delegate(new QSqlRelationalDelegate(this))\n{\n ui->setupUi(this);\n\n m_columnToComboBoxMap.insert(TypeColumn, ui->typeComboBox);\n m_columnToComboBoxMap.insert(ConversationColumn, ui->conversationComboBox);\n m_columnToComboBoxMap.insert(CharacterColumn, ui->characterComboBox);\n m_columnToComboBoxMap.insert(AudioFileColumn, ui->audioFileComboBox);\n\n connect(ui->typeComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(changedEventType(QString)));\n\n foreach(QComboBox *comboBox, m_columnToComboBoxMap) {\n connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkWriteReady()));\n connect(comboBox, SIGNAL(editTextChanged(QString)), this, SLOT(checkWriteReady()));\n }\n connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(checkWriteReady()));\n\n checkWriteReady();\n}\n\nvoid EventDialog::changedEventType(const QString &eventType)\n{\n \/\/ TODO Maybe change the event entry box depending event type?\n ui->eventTypeGroupBox->setTitle(eventType);\n}\n\nvoid EventDialog::accept()\n{\n \/\/ Manually set the result first so it's propogated to the delegate before closing\n setResult(QDialog::Accepted);\n done(QDialog::Accepted);\n}\n\nEventDialog::~EventDialog()\n{\n delete ui;\n}\n\nvoid EventDialog::setModelRow(QSqlRelationalTableModel *model, int row) {\n m_row = row;\n m_model = model;\n\n foreach(QComboBox *comboBox, m_columnToComboBoxMap)\n setupComboBox(comboBox);\n\n setupTextEdit(ui->textEdit);\n}\n\nvoid EventDialog::writeToModel() {\n foreach(QComboBox *comboBox, m_columnToComboBoxMap)\n writeComboBox(comboBox);\n\n writeTextEdit(ui->textEdit);\n}\n\nvoid EventDialog::setupComboBox(QComboBox *comboBox) {\n Q_ASSERT(comboBox);\n if (!comboBox)\n return;\n\n const int comboBoxColumn = m_columnToComboBoxMap.key(comboBox);\n QModelIndex index = m_model->index(m_row, comboBoxColumn);\n if (!index.isValid()) {\n \/\/ If this index is invalid, we're probably creating new\n \/\/ data so try the previous row\n index = m_model->index(m_row-1, comboBoxColumn);\n Q_ASSERT(index.isValid());\n if (!index.isValid())\n return;\n }\n QWidget *delegateWidget = m_delegate->createEditor(this, QStyleOptionViewItem(), index);\n QComboBox *delegateComboBox = qobject_cast(delegateWidget);\n Q_ASSERT(delegateComboBox);\n if (!delegateComboBox)\n return;\n m_delegate->setEditorData(delegateComboBox, index);\n\n QAbstractItemModel *abstractModel = delegateComboBox->model();\n QSqlTableModel *model = qobject_cast(abstractModel);\n Q_ASSERT(model);\n if (!model)\n return;\n\n model->setEditStrategy(QSqlTableModel::OnManualSubmit);\n comboBox->setModel(model);\n comboBox->setModelColumn(delegateComboBox->modelColumn());\n comboBox->setCurrentIndex(delegateComboBox->currentIndex());\n\n delete delegateComboBox;\n}\n\nvoid EventDialog::setupTextEdit(QTextEdit *textEdit) {\n QModelIndex index = m_model->index(m_row, TextColumn);\n if (!index.isValid())\n return;\n QWidget *delegateWidget = m_delegate->createEditor(this, QStyleOptionViewItem(), index);\n QLineEdit *delegateLineEdit = qobject_cast(delegateWidget);\n Q_ASSERT(delegateLineEdit);\n if (!delegateLineEdit)\n return;\n m_delegate->setEditorData(delegateLineEdit, index);\n\n textEdit->setText(delegateLineEdit->text());\n\n delete delegateLineEdit;\n}\n\nvoid EventDialog::writeComboBox(QComboBox *comboBox) {\n Q_ASSERT(comboBox);\n if (!comboBox)\n return;\n\n QSqlTableModel *relationModel = qobject_cast(comboBox->model());\n Q_ASSERT(relationModel);\n if (!relationModel)\n return;\n\n \/\/ Need to get text before writing new items as the combobox\n \/\/ index can be reset afterwards.\n const QString &comboBoxText = comboBox->currentText();\n relationModel->submitAll();\n const int comboBoxRow = comboBox->findText(comboBoxText);\n comboBox->setCurrentIndex(comboBoxRow);\n\n \/\/ A hacky but successful way to clear the model's relation cache.\n const QSqlTableModel::EditStrategy editStrategy = m_model->editStrategy();\n Q_ASSERT(editStrategy != QSqlTableModel::OnManualSubmit);\n m_model->setEditStrategy(QSqlTableModel::OnManualSubmit);\n m_model->submitAll();\n m_model->setEditStrategy(editStrategy);\n\n const int comboBoxColumn = m_columnToComboBoxMap.key(comboBox);\n const QModelIndex index = m_model->index(m_row, comboBoxColumn);\n m_delegate->setModelData(comboBox, m_model, index);\n}\n\nvoid EventDialog::writeTextEdit(QTextEdit *textEdit) {\n QLineEdit *lineEdit = new QLineEdit(textEdit->toPlainText(), this);\n const QModelIndex index = m_model->index(m_row, TextColumn);\n m_delegate->setModelData(lineEdit, m_model, index);\n delete lineEdit;\n}\n\nvoid EventDialog::checkWriteReady() {\n bool isReadyToWrite = true;\n\n foreach(QComboBox *comboBox, m_columnToComboBoxMap)\n if (comboBox->currentIndex() == -1 || comboBox->currentText().isEmpty()) {\n isReadyToWrite = false;\n break;\n }\n\n if (isReadyToWrite && ui->textEdit->toPlainText().isEmpty())\n isReadyToWrite = false;\n\n QPushButton *ok = ui->buttonBox->button(QDialogButtonBox::Ok);\n Q_ASSERT(ok);\n if (ok)\n ok->setEnabled(isReadyToWrite);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Exponent.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Exponential.h\"\n\n\nExponential::Exponential(Expression* base, Rational* exponent){\n this->type = \"exponential\";\n this->base = base;\n this->exponent = exponent;\n this->exde = new Integer(exponent->getDenominator());\n if (exde->getValue() != 1) {\n \t\/\/if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1\n \tInteger* baseAsInteger = (Integer *) base;\n base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);\n Integer* one = new Integer(1);\n exponent->setDenominator(one);\n }\n this->exnu = new Integer(exponent->getNumerator());\n if (canExponentiate()) {\n \texponentiate();\n }\n}\nExponential::~Exponential(){\n\n}\n\nbool Exponential::canExponentiate() {\n if(base->type == \"euler\"){\n return false;\n\n }else if(base->type == \"exponential\"){\n\tExponential* ex = (Exponential *) base;\n\tthis->exponent->multiply(ex->getExponent());\n\tInteger* numSum = new Integer (1);\n\tex->getExponent()->setNumerator(numSum);\n return false;\n \/\/ false is returned because the base itself would have already been exponentiated if it were possible\n\n }else if(base->type == \"integer\"){\n return true;\n\n\n }else if(base->type == \"logarithm\"){\n return false;\n\n }else if(base->type == \"nthRoot\"){\n\tnthRoot* nr = (nthRoot *) base;\n\tRational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());\n\t\/\/makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one\n\tthis->exponent = r;\n\tnr->setRoot(1);\n\treturn false;\n\n }else if(base->type == \"pi\"){\n return false;\n\n }else if(base->type == \"rational\"){\n Rational* r = (Rational *) base;\n if (r->geteNumerator()->type == \"integer\" && r->geteDenominator()->type == \"integer\") {\n Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);\n r->setNumerator(nu);\n Exponential* de = new Exponential(r->geteDenominator(), this->exponent);\n r->setDenominator(de);\n }\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return false;\n}\n\nvoid Exponential::exponentiate(){\n\tInteger* one = new Integer(1);\n Rational* oneRat = new Rational(1, 1);\n\tif (this->base->type == \"rational\") {\n\t\tRational* ratBase = (Rational *) this->base;\n\t\tExponential* numAsExponential = new Exponential (ratBase->geteNumerator(), this->exponent); \/\/no matching constructor for exponential\n\t\tExponential* denAsExponential = new Exponential (ratBase->geteDenominator(), this->exponent); \/\/same error\n\t\tthis->exponent = oneRat;\n\t}\n\telse {\n\n if (this->exponent->getNumerator()==0) {\n \n this->exponent=oneRat;\n this->base=one;\n\n }\n bool toFlip = false;\n if (exnu->getValue()<0) {\n\t exnu->setValue(exnu->getValue()*-1);\n toFlip = true;\n \/\/handles negative exponents\n }\n Expression* constantBase = 0;\n if (base->type == \"integer\") { \/\/fixed the problem for integers but nothing else\n Integer *a = (Integer *)base;\n constantBase = new Integer(a->getValue());\n }\n\n\n while (exponent->getNumerator()>1)\n \t{\n base->multiply(constantBase);\n exponent->setNumerator(exponent->geteNumerator()->subtract(one));\n }\n if (toFlip) {\n Integer* one = new Integer(1);\n Rational* mouse = new Rational(one, base);\n \tbase = mouse;\n }\n \n\t}\n\n}\n\nExpression* Exponential::add(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* two = new Integer(2);\n\t\t\tthis->multiply(two);\n\t\t}\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::subtract(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* zero = new Integer(0);\n\t\t\tthis->multiply(zero);\n\t\t}\n\t}\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::multiply(Expression* a){\n\tif(a->type == \"euler\"){\n \t\tif (this->base->type == \"euler\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t\t\n \t}\n\n }else if(a->type == \"exponential\"){\n\t\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->add(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* numToSet = r->geteNumerator();\n\tnumToSet->multiply(this);\n\tr->setNumerator(numToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::divide(Expression* a){\n\tif(a->type == \"euler\"){\n\t\tif (this->base->type == \"euler\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->subtract(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* denToSet = r->geteDenominator();\n\tdenToSet->multiply(this);\n\tr->setDenominator(denToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\n\nRational* Exponential::getExponent() {\n return exponent;\n}\n\nExpression* Exponential::getBase() {\n return base;\n}\n\nInteger* Exponential::getExnu() {\n\treturn exnu;\n}\n\nInteger* Exponential::getExde() {\n\treturn exde;\n}\n\nvoid Exponential::setExnu(Integer* n) {\n\texnu = n;\n}\n\nvoid Exponential::setExde(Integer* n) {\n\texde = n;\n}\n\nvoid Exponential::setExponent(Rational* e) {\n exponent = e;\n}\n\nvoid Exponential::setBase(Expression* e) {\n base = e;\n}\n\nstring Exponential::toString() {\n stringstream str;\n if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){\n str << *base;\n }\n else if(exponent->getDenominator() == 1){\n str << *base << \"^\" << *exponent->geteNumerator();\n }else{\n str << *base << \"^\" << *exponent;\n }\n return str.str();\n}\n\n\nostream& Exponential::print(std::ostream& output) const{\n Exponential *a = (Exponential *)this;\n output << a->toString();\n return output;\n}\n\n\n\nbool Exponential::canAdd(Expression* b){ \/\/use \"this\" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)\n \n if (this->type == b->type && this->type != \"logarithm\") {\n if (this->type == \"nthRoot\") {\n }\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canSubtract(Expression* b){\n if (this->type == b->type) {\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canMultiply(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if(this->type == \"integer\" && b->type == \"rational\") return true;\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n \n}\nbool Exponential::canDivide(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if(this->type == \"integer\"){\n if( b->type == \"rational\") return true;\n }\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nFixed errors\/\/\n\/\/ Exponent.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Exponential.h\"\n\n\nExponential::Exponential(Expression* base, Rational* exponent){\n this->type = \"exponential\";\n this->base = base;\n this->exponent = exponent;\n this->exde = new Integer(exponent->getDenominator());\n if (exde->getValue() != 1) {\n \t\/\/if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1\n \tInteger* baseAsInteger = (Integer *) base;\n base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);\n Integer* one = new Integer(1);\n exponent->setDenominator(one);\n }\n this->exnu = new Integer(exponent->getNumerator());\n if (canExponentiate()) {\n \texponentiate();\n }\n}\nExponential::~Exponential(){\n\n}\n\nbool Exponential::canExponentiate() {\n if(base->type == \"euler\"){\n return false;\n\n }else if(base->type == \"exponential\"){\n\tExponential* ex = (Exponential *) base;\n\tthis->exponent->multiply(ex->getExponent());\n\tInteger* numSum = new Integer (1);\n\tex->getExponent()->setNumerator(numSum);\n return false;\n \/\/ false is returned because the base itself would have already been exponentiated if it were possible\n\n }else if(base->type == \"integer\"){\n return true;\n\n\n }else if(base->type == \"logarithm\"){\n return false;\n\n }else if(base->type == \"nthRoot\"){\n\tnthRoot* nr = (nthRoot *) base;\n\tRational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());\n\t\/\/makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one\n\tthis->exponent = r;\n\tnr->setRoot(1);\n\treturn false;\n\n }else if(base->type == \"pi\"){\n return false;\n\n }else if(base->type == \"rational\"){\n Rational* r = (Rational *) base;\n if (r->geteNumerator()->type == \"integer\" && r->geteDenominator()->type == \"integer\") {\n Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);\n r->setNumerator(nu);\n Exponential* de = new Exponential(r->geteDenominator(), this->exponent);\n r->setDenominator(de);\n }\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return false;\n}\n\nvoid Exponential::exponentiate(){\n\tInteger* one = new Integer(1);\n Rational* oneRat = new Rational(1, 1);\n\tif (this->base->type == \"rational\") {\n\t\tRational* ratBase = (Rational *) this->base;\n\t\tExponential* numAsExponential = new Exponential (&(ratBase->geteNumerator()), &(this->exponent)); \/\/no matching constructor for exponential\n\t\tExponential* denAsExponential = new Exponential (&(ratBase->geteDenominator()), &(this->exponent)); \/\/same error\n\t\tRational* newRatBase = new Rational(numAsExponential, denAsExponential);\n\t\tthis->base = newRatBase;\n\t\tthis->exponent = oneRat;\n\t}\n\telse {\n\n if (this->exponent->getNumerator()==0) {\n \n this->exponent=oneRat;\n this->base=one;\n\n }\n bool toFlip = false;\n if (exnu->getValue()<0) {\n\t exnu->setValue(exnu->getValue()*-1);\n toFlip = true;\n \/\/handles negative exponents\n }\n Expression* constantBase = 0;\n if (base->type == \"integer\") { \/\/fixed the problem for integers but nothing else\n Integer *a = (Integer *)base;\n constantBase = new Integer(a->getValue());\n }\n\n\n while (exponent->getNumerator()>1)\n \t{\n base->multiply(constantBase);\n exponent->setNumerator(exponent->geteNumerator()->subtract(one));\n }\n if (toFlip) {\n Integer* one = new Integer(1);\n Rational* mouse = new Rational(one, base);\n \tbase = mouse;\n }\n \n\t}\n\n}\n\nExpression* Exponential::add(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* two = new Integer(2);\n\t\t\tthis->multiply(two);\n\t\t}\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::subtract(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* zero = new Integer(0);\n\t\t\tthis->multiply(zero);\n\t\t}\n\t}\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::multiply(Expression* a){\n\tif(a->type == \"euler\"){\n \t\tif (this->base->type == \"euler\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t\t\n \t}\n\n }else if(a->type == \"exponential\"){\n\t\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->add(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* numToSet = r->geteNumerator();\n\tnumToSet->multiply(this);\n\tr->setNumerator(numToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::divide(Expression* a){\n\tif(a->type == \"euler\"){\n\t\tif (this->base->type == \"euler\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->subtract(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* denToSet = r->geteDenominator();\n\tdenToSet->multiply(this);\n\tr->setDenominator(denToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\n\nRational* Exponential::getExponent() {\n return exponent;\n}\n\nExpression* Exponential::getBase() {\n return base;\n}\n\nInteger* Exponential::getExnu() {\n\treturn exnu;\n}\n\nInteger* Exponential::getExde() {\n\treturn exde;\n}\n\nvoid Exponential::setExnu(Integer* n) {\n\texnu = n;\n}\n\nvoid Exponential::setExde(Integer* n) {\n\texde = n;\n}\n\nvoid Exponential::setExponent(Rational* e) {\n exponent = e;\n}\n\nvoid Exponential::setBase(Expression* e) {\n base = e;\n}\n\nstring Exponential::toString() {\n stringstream str;\n if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){\n str << *base;\n }\n else if(exponent->getDenominator() == 1){\n str << *base << \"^\" << *exponent->geteNumerator();\n }else{\n str << *base << \"^\" << *exponent;\n }\n return str.str();\n}\n\n\nostream& Exponential::print(std::ostream& output) const{\n Exponential *a = (Exponential *)this;\n output << a->toString();\n return output;\n}\n\n\n\nbool Exponential::canAdd(Expression* b){ \/\/use \"this\" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)\n \n if (this->type == b->type && this->type != \"logarithm\") {\n if (this->type == \"nthRoot\") {\n }\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canSubtract(Expression* b){\n if (this->type == b->type) {\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canMultiply(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if(this->type == \"integer\" && b->type == \"rational\") return true;\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n \n}\nbool Exponential::canDivide(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if(this->type == \"integer\"){\n if( b->type == \"rational\") return true;\n }\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\n<|endoftext|>"} {"text":"\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\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 * #L%\n *\/\n\n#include \"libjoynrclustercontroller\/mqtt\/MosquittoConnection.h\"\n\n#include \"joynr\/ClusterControllerSettings.h\"\n#include \"joynr\/MessagingSettings.h\"\n#include \"joynr\/Util.h\"\n#include \"joynr\/exceptions\/JoynrException.h\"\n\nnamespace joynr\n{\n\nMosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings,\n const ClusterControllerSettings& ccSettings,\n const std::string& clientId)\n : mosquittopp(clientId.c_str(), false),\n messagingSettings(messagingSettings),\n host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()),\n port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()),\n channelId(),\n subscribeChannelMid(),\n topic(),\n additionalTopics(),\n additionalTopicsMutex(),\n isConnected(false),\n isRunning(false),\n isChannelIdRegistered(false),\n subscribedToChannelTopic(false),\n readyToSend(false),\n onMessageReceived(),\n onReadyToSendChangedMutex(),\n onReadyToSendChanged()\n{\n JOYNR_LOG_INFO(logger(), \"Init mosquitto connection using MQTT client ID: {}\", clientId);\n mosqpp::lib_init();\n\n if (ccSettings.isMqttTlsEnabled()) {\n const std::string mqttCertificateAuthorityPemFilename =\n ccSettings.getMqttCertificateAuthorityPemFilename();\n const std::string mqttCertificateAuthorityCertificateFolderPath =\n ccSettings.getMqttCertificateAuthorityCertificateFolderPath();\n\n const char* mqttCertificateAuthorityPemFilename_cstr = nullptr;\n if (!mqttCertificateAuthorityPemFilename.empty()) {\n mqttCertificateAuthorityPemFilename_cstr = mqttCertificateAuthorityPemFilename.c_str();\n }\n\n const char* mqttCertificateAuthorityCertificateFolderPath_cstr = nullptr;\n if (!mqttCertificateAuthorityCertificateFolderPath.empty()) {\n mqttCertificateAuthorityCertificateFolderPath_cstr =\n mqttCertificateAuthorityCertificateFolderPath.c_str();\n }\n\n int rc = tls_set(mqttCertificateAuthorityPemFilename_cstr,\n mqttCertificateAuthorityCertificateFolderPath_cstr,\n ccSettings.getMqttCertificatePemFilename().c_str(),\n ccSettings.getMqttPrivateKeyPemFilename().c_str());\n\n if (rc != MOSQ_ERR_SUCCESS) {\n const std::string errorString(getErrorString(rc));\n mosqpp::lib_cleanup();\n JOYNR_LOG_FATAL(\n logger(), \"fatal failure to initialize TLS connection - {}\", errorString);\n }\n } else {\n JOYNR_LOG_DEBUG(logger(), \"MQTT connection not encrypted\");\n }\n}\n\nMosquittoConnection::~MosquittoConnection()\n{\n stop();\n stopLoop(true);\n\n mosqpp::lib_cleanup();\n}\n\nstd::string MosquittoConnection::getErrorString(int rc)\n{\n \/\/ Do not use mosq::strerror() in case of MOSQ_ERR_ERRNO\n \/\/ since it calls the MT-unsafe API strerror()\n if (rc != MOSQ_ERR_ERRNO) {\n return std::string(mosqpp::strerror(rc));\n }\n\n const int storedErrno = errno;\n return joynr::util::getErrorString(storedErrno);\n}\n\nvoid MosquittoConnection::on_disconnect(int rc)\n{\n const std::string errorString(getErrorString(rc));\n setReadyToSend(false);\n if (!isConnected) {\n \/\/ In case we didn't connect yet\n JOYNR_LOG_ERROR(\n logger(), \"Not yet connected to tcp:\/\/{}:{}, error: {}\", host, port, errorString);\n return;\n }\n\n \/\/ There was indeed a disconnect...set connect to false\n isConnected = false;\n\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Disconnected from tcp:\/\/{}:{}\", host, port);\n stopLoop();\n } else {\n JOYNR_LOG_ERROR(logger(),\n \"Unexpectedly disconnected from tcp:\/\/{}:{}, error: {}\",\n host,\n port,\n errorString);\n reconnect();\n }\n}\n\nvoid MosquittoConnection::on_log(int level, const char* str)\n{\n if (level == MOSQ_LOG_ERR) {\n JOYNR_LOG_ERROR(logger(), \"Mosquitto Log: {}\", str);\n } else if (level == MOSQ_LOG_WARNING) {\n JOYNR_LOG_WARN(logger(), \"Mosquitto Log: {}\", str);\n } else if (level == MOSQ_LOG_INFO) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto Log: {}\", str);\n } else {\n \/\/ MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level\n JOYNR_LOG_DEBUG(logger(), \"Mosquitto Log: {}\", str);\n }\n}\n\nstd::uint16_t MosquittoConnection::getMqttQos() const\n{\n return mqttQos;\n}\n\nstd::string MosquittoConnection::getMqttPrio() const\n{\n static const std::string value(\"low\");\n return value;\n}\n\nbool MosquittoConnection::isMqttRetain() const\n{\n return mqttRetain;\n}\n\nvoid MosquittoConnection::start()\n{\n JOYNR_LOG_TRACE(\n logger(), \"Start called with isRunning: {}, isConnected: {}\", isRunning, isConnected);\n\n JOYNR_LOG_INFO(logger(), \"Try to connect to tcp:\/\/{}:{}\", host, port);\n connect_async(host.c_str(), port, messagingSettings.getMqttKeepAliveTimeSeconds().count());\n\n reconnect_delay_set(messagingSettings.getMqttReconnectDelayTimeSeconds().count(),\n messagingSettings.getMqttReconnectMaxDelayTimeSeconds().count(),\n messagingSettings.getMqttExponentialBackoffEnabled());\n\n startLoop();\n}\n\nvoid MosquittoConnection::startLoop()\n{\n int rc = loop_start();\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto loop started\");\n isRunning = true;\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Mosquitto loop start failed: error: {} ({})\",\n std::to_string(rc),\n errorString);\n }\n}\n\nvoid MosquittoConnection::stop()\n{\n if (isConnected) {\n int rc = disconnect();\n\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto Connection disconnected\");\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Mosquitto disconnect failed: error: {} ({})\",\n std::to_string(rc),\n errorString);\n stopLoop(true);\n }\n } else if (isRunning) {\n stopLoop(true);\n }\n setReadyToSend(false);\n}\n\nvoid MosquittoConnection::stopLoop(bool force)\n{\n int rc = loop_stop(force);\n\n if (rc == MOSQ_ERR_SUCCESS) {\n isRunning = false;\n JOYNR_LOG_INFO(logger(), \"Mosquitto loop stopped\");\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Mosquitto loop stop failed: error: {} ({})\",\n std::to_string(rc),\n errorString);\n }\n}\n\nvoid MosquittoConnection::on_connect(int rc)\n{\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto Connection established\");\n isConnected = true;\n\n createSubscriptions();\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(\n logger(), \"Mosquitto Connection Error: {} ({})\", std::to_string(rc), errorString);\n }\n}\n\nvoid MosquittoConnection::createSubscriptions()\n{\n while (!isChannelIdRegistered && isRunning) {\n std::this_thread::sleep_for(std::chrono::milliseconds(25));\n }\n try {\n subscribeToTopicInternal(topic, true);\n std::lock_guard lock(additionalTopicsMutex);\n for (const std::string& additionalTopic : additionalTopics) {\n subscribeToTopicInternal(additionalTopic);\n }\n } catch (const exceptions::JoynrRuntimeException& error) {\n JOYNR_LOG_ERROR(logger(), \"Error subscribing to Mqtt topic, error: \", error.getMessage());\n }\n}\n\nvoid MosquittoConnection::subscribeToTopicInternal(const std::string& topic,\n const bool isChannelTopic)\n{\n int* mid = nullptr;\n if (isChannelTopic) {\n mid = &subscribeChannelMid;\n }\n int rc = subscribe(mid, topic.c_str(), getMqttQos());\n switch (rc) {\n case (MOSQ_ERR_SUCCESS):\n JOYNR_LOG_INFO(logger(), \"Subscribed to {}\", topic);\n break;\n case (MOSQ_ERR_NO_CONN): {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_DEBUG(logger(),\n \"Subscription to {} failed: error: {} ({}). \"\n \"Subscription will be restored on connect.\",\n topic,\n std::to_string(rc),\n errorString);\n break;\n }\n default: {\n \/\/ MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM\n const std::string errorString(getErrorString(rc));\n std::string errorMsg = \"Subscription to \" + topic + \" failed: error: \" +\n std::to_string(rc) + \" (\" + errorString + \")\";\n throw exceptions::JoynrRuntimeException(errorMsg);\n }\n }\n}\n\nvoid MosquittoConnection::subscribeToTopic(const std::string& topic)\n{\n if (!isChannelIdRegistered) {\n std::string errorMsg = \"No channelId registered, cannot subscribe to topic \" + topic;\n throw exceptions::JoynrRuntimeException(errorMsg);\n }\n\n {\n std::lock_guard lock(additionalTopicsMutex);\n if (additionalTopics.find(topic) != additionalTopics.end()) {\n JOYNR_LOG_DEBUG(logger(), \"Already subscribed to topic {}\", topic);\n return;\n }\n\n subscribeToTopicInternal(topic);\n\n additionalTopics.insert(topic);\n }\n}\n\nvoid MosquittoConnection::unsubscribeFromTopic(const std::string& topic)\n{\n if (isChannelIdRegistered) {\n std::lock_guard lock(additionalTopicsMutex);\n if (additionalTopics.find(topic) == additionalTopics.end()) {\n JOYNR_LOG_DEBUG(logger(), \"Unsubscribe called for non existing topic {}\", topic);\n return;\n }\n additionalTopics.erase(topic);\n if (isConnected && isRunning) {\n int rc = unsubscribe(nullptr, topic.c_str());\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Unsubscribed from {}\", topic);\n } else {\n \/\/ MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Unsubscribe from {} failed: error: {} ({})\",\n topic,\n std::to_string(rc),\n errorString);\n }\n }\n }\n}\n\nvoid MosquittoConnection::publishMessage(\n const std::string& topic,\n const int qosLevel,\n const std::function& onFailure,\n uint32_t payloadlen = 0,\n const void* payload = nullptr)\n{\n JOYNR_LOG_DEBUG(logger(), \"Publish message of length {} to {}\", payloadlen, topic);\n\n int mid;\n int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain());\n if (!(rc == MOSQ_ERR_SUCCESS)) {\n const std::string errorString(getErrorString(rc));\n if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) {\n onFailure(exceptions::JoynrMessageNotSentException(\n \"message could not be sent: mid (mqtt message id): \" + std::to_string(mid) +\n \", error: \" + std::to_string(rc) + \" (\" + errorString + \")\"));\n return;\n }\n \/\/ MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors\n onFailure(exceptions::JoynrDelayMessageException(\n \"error sending message: mid (mqtt message id): \" + std::to_string(mid) +\n \", error: \" + std::to_string(rc) + \" (\" + errorString + \")\"));\n return;\n }\n JOYNR_LOG_TRACE(logger(), \"published message with mqtt message id {}\", std::to_string(mid));\n}\n\nvoid MosquittoConnection::registerChannelId(const std::string& channelId)\n{\n this->channelId = channelId;\n topic = channelId + \"\/\" + getMqttPrio() + \"\/\" + \"#\";\n isChannelIdRegistered = true;\n}\n\nvoid MosquittoConnection::registerReceiveCallback(\n std::function onMessageReceived)\n{\n this->onMessageReceived = onMessageReceived;\n}\n\nvoid MosquittoConnection::registerReadyToSendChangedCallback(\n std::function onReadyToSendChanged)\n{\n std::lock_guard lock(onReadyToSendChangedMutex);\n this->onReadyToSendChanged = std::move(onReadyToSendChanged);\n}\n\nbool MosquittoConnection::isSubscribedToChannelTopic() const\n{\n return subscribedToChannelTopic;\n}\n\nbool MosquittoConnection::isReadyToSend() const\n{\n return readyToSend;\n}\n\nvoid MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos)\n{\n JOYNR_LOG_DEBUG(logger(), \"Subscribed (mid: {} with granted QOS {}\", mid, granted_qos[0]);\n\n for (int i = 1; i < qos_count; i++) {\n JOYNR_LOG_DEBUG(logger(), \"QOS: {} granted {}\", i, granted_qos[i]);\n }\n\n if (mid == subscribeChannelMid) {\n subscribedToChannelTopic = true;\n setReadyToSend(isConnected);\n }\n}\n\nvoid MosquittoConnection::on_message(const mosquitto_message* message)\n{\n if (!onMessageReceived) {\n JOYNR_LOG_ERROR(logger(),\n \"Discarding received message, since onMessageReceived callback is empty.\");\n return;\n }\n\n if (!message || message->payloadlen <= 0) {\n JOYNR_LOG_ERROR(\n logger(),\n \"Discarding received message: invalid message or non-positive payload's length.\");\n return;\n }\n\n std::uint8_t* data = static_cast(message->payload);\n\n \/\/ convert address of data into integral type\n std::uintptr_t integralAddress = reinterpret_cast(data);\n const bool overflow =\n joynr::util::isAdditionOnPointerSafe(integralAddress, message->payloadlen);\n if (overflow) {\n JOYNR_LOG_ERROR(logger(), \"Discarding received message, since there is an overflow.\");\n return;\n }\n\n smrf::ByteVector rawMessage(data, data + message->payloadlen);\n onMessageReceived(std::move(rawMessage));\n}\n\nvoid MosquittoConnection::on_publish(int mid)\n{\n JOYNR_LOG_TRACE(logger(), \"published message with mid {}\", std::to_string(mid));\n}\n\nvoid MosquittoConnection::setReadyToSend(bool readyToSend)\n{\n if (this->readyToSend != readyToSend) {\n this->readyToSend = readyToSend;\n\n std::lock_guard lock(onReadyToSendChangedMutex);\n if (onReadyToSendChanged) {\n onReadyToSendChanged(readyToSend);\n }\n }\n}\n\n} \/\/ namespace joynr\n[C++] MosquittoConnection stop() calls stopLoop() when connected\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\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 * #L%\n *\/\n\n#include \"libjoynrclustercontroller\/mqtt\/MosquittoConnection.h\"\n\n#include \"joynr\/ClusterControllerSettings.h\"\n#include \"joynr\/MessagingSettings.h\"\n#include \"joynr\/Util.h\"\n#include \"joynr\/exceptions\/JoynrException.h\"\n\nnamespace joynr\n{\n\nMosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings,\n const ClusterControllerSettings& ccSettings,\n const std::string& clientId)\n : mosquittopp(clientId.c_str(), false),\n messagingSettings(messagingSettings),\n host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()),\n port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()),\n channelId(),\n subscribeChannelMid(),\n topic(),\n additionalTopics(),\n additionalTopicsMutex(),\n isConnected(false),\n isRunning(false),\n isChannelIdRegistered(false),\n subscribedToChannelTopic(false),\n readyToSend(false),\n onMessageReceived(),\n onReadyToSendChangedMutex(),\n onReadyToSendChanged()\n{\n JOYNR_LOG_INFO(logger(), \"Init mosquitto connection using MQTT client ID: {}\", clientId);\n mosqpp::lib_init();\n\n if (ccSettings.isMqttTlsEnabled()) {\n const std::string mqttCertificateAuthorityPemFilename =\n ccSettings.getMqttCertificateAuthorityPemFilename();\n const std::string mqttCertificateAuthorityCertificateFolderPath =\n ccSettings.getMqttCertificateAuthorityCertificateFolderPath();\n\n const char* mqttCertificateAuthorityPemFilename_cstr = nullptr;\n if (!mqttCertificateAuthorityPemFilename.empty()) {\n mqttCertificateAuthorityPemFilename_cstr = mqttCertificateAuthorityPemFilename.c_str();\n }\n\n const char* mqttCertificateAuthorityCertificateFolderPath_cstr = nullptr;\n if (!mqttCertificateAuthorityCertificateFolderPath.empty()) {\n mqttCertificateAuthorityCertificateFolderPath_cstr =\n mqttCertificateAuthorityCertificateFolderPath.c_str();\n }\n\n int rc = tls_set(mqttCertificateAuthorityPemFilename_cstr,\n mqttCertificateAuthorityCertificateFolderPath_cstr,\n ccSettings.getMqttCertificatePemFilename().c_str(),\n ccSettings.getMqttPrivateKeyPemFilename().c_str());\n\n if (rc != MOSQ_ERR_SUCCESS) {\n const std::string errorString(getErrorString(rc));\n mosqpp::lib_cleanup();\n JOYNR_LOG_FATAL(\n logger(), \"fatal failure to initialize TLS connection - {}\", errorString);\n }\n } else {\n JOYNR_LOG_DEBUG(logger(), \"MQTT connection not encrypted\");\n }\n}\n\nMosquittoConnection::~MosquittoConnection()\n{\n stop();\n stopLoop(true);\n\n mosqpp::lib_cleanup();\n}\n\nstd::string MosquittoConnection::getErrorString(int rc)\n{\n \/\/ Do not use mosq::strerror() in case of MOSQ_ERR_ERRNO\n \/\/ since it calls the MT-unsafe API strerror()\n if (rc != MOSQ_ERR_ERRNO) {\n return std::string(mosqpp::strerror(rc));\n }\n\n const int storedErrno = errno;\n return joynr::util::getErrorString(storedErrno);\n}\n\nvoid MosquittoConnection::on_disconnect(int rc)\n{\n const std::string errorString(getErrorString(rc));\n setReadyToSend(false);\n if (!isConnected) {\n \/\/ In case we didn't connect yet\n JOYNR_LOG_ERROR(\n logger(), \"Not yet connected to tcp:\/\/{}:{}, error: {}\", host, port, errorString);\n return;\n }\n\n \/\/ There was indeed a disconnect...set connect to false\n isConnected = false;\n\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Disconnected from tcp:\/\/{}:{}\", host, port);\n stopLoop();\n } else {\n JOYNR_LOG_ERROR(logger(),\n \"Unexpectedly disconnected from tcp:\/\/{}:{}, error: {}\",\n host,\n port,\n errorString);\n reconnect();\n }\n}\n\nvoid MosquittoConnection::on_log(int level, const char* str)\n{\n if (level == MOSQ_LOG_ERR) {\n JOYNR_LOG_ERROR(logger(), \"Mosquitto Log: {}\", str);\n } else if (level == MOSQ_LOG_WARNING) {\n JOYNR_LOG_WARN(logger(), \"Mosquitto Log: {}\", str);\n } else if (level == MOSQ_LOG_INFO) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto Log: {}\", str);\n } else {\n \/\/ MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level\n JOYNR_LOG_DEBUG(logger(), \"Mosquitto Log: {}\", str);\n }\n}\n\nstd::uint16_t MosquittoConnection::getMqttQos() const\n{\n return mqttQos;\n}\n\nstd::string MosquittoConnection::getMqttPrio() const\n{\n static const std::string value(\"low\");\n return value;\n}\n\nbool MosquittoConnection::isMqttRetain() const\n{\n return mqttRetain;\n}\n\nvoid MosquittoConnection::start()\n{\n JOYNR_LOG_TRACE(\n logger(), \"Start called with isRunning: {}, isConnected: {}\", isRunning, isConnected);\n\n JOYNR_LOG_INFO(logger(), \"Try to connect to tcp:\/\/{}:{}\", host, port);\n connect_async(host.c_str(), port, messagingSettings.getMqttKeepAliveTimeSeconds().count());\n\n reconnect_delay_set(messagingSettings.getMqttReconnectDelayTimeSeconds().count(),\n messagingSettings.getMqttReconnectMaxDelayTimeSeconds().count(),\n messagingSettings.getMqttExponentialBackoffEnabled());\n\n startLoop();\n}\n\nvoid MosquittoConnection::startLoop()\n{\n int rc = loop_start();\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto loop started\");\n isRunning = true;\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Mosquitto loop start failed: error: {} ({})\",\n std::to_string(rc),\n errorString);\n }\n}\n\nvoid MosquittoConnection::stop()\n{\n if (isConnected) {\n int rc = disconnect();\n\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto Connection disconnected\");\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Mosquitto disconnect failed: error: {} ({})\",\n std::to_string(rc),\n errorString);\n }\n stopLoop(true);\n } else if (isRunning) {\n stopLoop(true);\n }\n setReadyToSend(false);\n}\n\nvoid MosquittoConnection::stopLoop(bool force)\n{\n int rc = loop_stop(force);\n\n if (rc == MOSQ_ERR_SUCCESS) {\n isRunning = false;\n JOYNR_LOG_INFO(logger(), \"Mosquitto loop stopped\");\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Mosquitto loop stop failed: error: {} ({})\",\n std::to_string(rc),\n errorString);\n }\n}\n\nvoid MosquittoConnection::on_connect(int rc)\n{\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Mosquitto Connection established\");\n isConnected = true;\n\n createSubscriptions();\n } else {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(\n logger(), \"Mosquitto Connection Error: {} ({})\", std::to_string(rc), errorString);\n }\n}\n\nvoid MosquittoConnection::createSubscriptions()\n{\n while (!isChannelIdRegistered && isRunning) {\n std::this_thread::sleep_for(std::chrono::milliseconds(25));\n }\n try {\n subscribeToTopicInternal(topic, true);\n std::lock_guard lock(additionalTopicsMutex);\n for (const std::string& additionalTopic : additionalTopics) {\n subscribeToTopicInternal(additionalTopic);\n }\n } catch (const exceptions::JoynrRuntimeException& error) {\n JOYNR_LOG_ERROR(logger(), \"Error subscribing to Mqtt topic, error: \", error.getMessage());\n }\n}\n\nvoid MosquittoConnection::subscribeToTopicInternal(const std::string& topic,\n const bool isChannelTopic)\n{\n int* mid = nullptr;\n if (isChannelTopic) {\n mid = &subscribeChannelMid;\n }\n int rc = subscribe(mid, topic.c_str(), getMqttQos());\n switch (rc) {\n case (MOSQ_ERR_SUCCESS):\n JOYNR_LOG_INFO(logger(), \"Subscribed to {}\", topic);\n break;\n case (MOSQ_ERR_NO_CONN): {\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_DEBUG(logger(),\n \"Subscription to {} failed: error: {} ({}). \"\n \"Subscription will be restored on connect.\",\n topic,\n std::to_string(rc),\n errorString);\n break;\n }\n default: {\n \/\/ MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM\n const std::string errorString(getErrorString(rc));\n std::string errorMsg = \"Subscription to \" + topic + \" failed: error: \" +\n std::to_string(rc) + \" (\" + errorString + \")\";\n throw exceptions::JoynrRuntimeException(errorMsg);\n }\n }\n}\n\nvoid MosquittoConnection::subscribeToTopic(const std::string& topic)\n{\n if (!isChannelIdRegistered) {\n std::string errorMsg = \"No channelId registered, cannot subscribe to topic \" + topic;\n throw exceptions::JoynrRuntimeException(errorMsg);\n }\n\n {\n std::lock_guard lock(additionalTopicsMutex);\n if (additionalTopics.find(topic) != additionalTopics.end()) {\n JOYNR_LOG_DEBUG(logger(), \"Already subscribed to topic {}\", topic);\n return;\n }\n\n subscribeToTopicInternal(topic);\n\n additionalTopics.insert(topic);\n }\n}\n\nvoid MosquittoConnection::unsubscribeFromTopic(const std::string& topic)\n{\n if (isChannelIdRegistered) {\n std::lock_guard lock(additionalTopicsMutex);\n if (additionalTopics.find(topic) == additionalTopics.end()) {\n JOYNR_LOG_DEBUG(logger(), \"Unsubscribe called for non existing topic {}\", topic);\n return;\n }\n additionalTopics.erase(topic);\n if (isConnected && isRunning) {\n int rc = unsubscribe(nullptr, topic.c_str());\n if (rc == MOSQ_ERR_SUCCESS) {\n JOYNR_LOG_INFO(logger(), \"Unsubscribed from {}\", topic);\n } else {\n \/\/ MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN\n const std::string errorString(getErrorString(rc));\n JOYNR_LOG_ERROR(logger(),\n \"Unsubscribe from {} failed: error: {} ({})\",\n topic,\n std::to_string(rc),\n errorString);\n }\n }\n }\n}\n\nvoid MosquittoConnection::publishMessage(\n const std::string& topic,\n const int qosLevel,\n const std::function& onFailure,\n uint32_t payloadlen = 0,\n const void* payload = nullptr)\n{\n JOYNR_LOG_DEBUG(logger(), \"Publish message of length {} to {}\", payloadlen, topic);\n\n int mid;\n int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain());\n if (!(rc == MOSQ_ERR_SUCCESS)) {\n const std::string errorString(getErrorString(rc));\n if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) {\n onFailure(exceptions::JoynrMessageNotSentException(\n \"message could not be sent: mid (mqtt message id): \" + std::to_string(mid) +\n \", error: \" + std::to_string(rc) + \" (\" + errorString + \")\"));\n return;\n }\n \/\/ MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors\n onFailure(exceptions::JoynrDelayMessageException(\n \"error sending message: mid (mqtt message id): \" + std::to_string(mid) +\n \", error: \" + std::to_string(rc) + \" (\" + errorString + \")\"));\n return;\n }\n JOYNR_LOG_TRACE(logger(), \"published message with mqtt message id {}\", std::to_string(mid));\n}\n\nvoid MosquittoConnection::registerChannelId(const std::string& channelId)\n{\n this->channelId = channelId;\n topic = channelId + \"\/\" + getMqttPrio() + \"\/\" + \"#\";\n isChannelIdRegistered = true;\n}\n\nvoid MosquittoConnection::registerReceiveCallback(\n std::function onMessageReceived)\n{\n this->onMessageReceived = onMessageReceived;\n}\n\nvoid MosquittoConnection::registerReadyToSendChangedCallback(\n std::function onReadyToSendChanged)\n{\n std::lock_guard lock(onReadyToSendChangedMutex);\n this->onReadyToSendChanged = std::move(onReadyToSendChanged);\n}\n\nbool MosquittoConnection::isSubscribedToChannelTopic() const\n{\n return subscribedToChannelTopic;\n}\n\nbool MosquittoConnection::isReadyToSend() const\n{\n return readyToSend;\n}\n\nvoid MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos)\n{\n JOYNR_LOG_DEBUG(logger(), \"Subscribed (mid: {} with granted QOS {}\", mid, granted_qos[0]);\n\n for (int i = 1; i < qos_count; i++) {\n JOYNR_LOG_DEBUG(logger(), \"QOS: {} granted {}\", i, granted_qos[i]);\n }\n\n if (mid == subscribeChannelMid) {\n subscribedToChannelTopic = true;\n setReadyToSend(isConnected);\n }\n}\n\nvoid MosquittoConnection::on_message(const mosquitto_message* message)\n{\n if (!onMessageReceived) {\n JOYNR_LOG_ERROR(logger(),\n \"Discarding received message, since onMessageReceived callback is empty.\");\n return;\n }\n\n if (!message || message->payloadlen <= 0) {\n JOYNR_LOG_ERROR(\n logger(),\n \"Discarding received message: invalid message or non-positive payload's length.\");\n return;\n }\n\n std::uint8_t* data = static_cast(message->payload);\n\n \/\/ convert address of data into integral type\n std::uintptr_t integralAddress = reinterpret_cast(data);\n const bool overflow =\n joynr::util::isAdditionOnPointerSafe(integralAddress, message->payloadlen);\n if (overflow) {\n JOYNR_LOG_ERROR(logger(), \"Discarding received message, since there is an overflow.\");\n return;\n }\n\n smrf::ByteVector rawMessage(data, data + message->payloadlen);\n onMessageReceived(std::move(rawMessage));\n}\n\nvoid MosquittoConnection::on_publish(int mid)\n{\n JOYNR_LOG_TRACE(logger(), \"published message with mid {}\", std::to_string(mid));\n}\n\nvoid MosquittoConnection::setReadyToSend(bool readyToSend)\n{\n if (this->readyToSend != readyToSend) {\n this->readyToSend = readyToSend;\n\n std::lock_guard lock(onReadyToSendChangedMutex);\n if (onReadyToSendChanged) {\n onReadyToSendChanged(readyToSend);\n }\n }\n}\n\n} \/\/ namespace joynr\n<|endoftext|>"} {"text":"ugly hack for NS_ooxml::LN_CT_Style_type being the first attribute processed<|endoftext|>"} {"text":"\/*\n\/\/ $ g++ -O3 -o createdSortedJaccsFile createdSortedJaccsFile.cpp\n\/\/ $ .\/createdSortedJaccsFile network.pairs network.jaccs threshDensity.csv\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ for pairs\n#include \/\/ for swap\n#define MIN_DIFF_BW_JACCS 0.0001\nusing namespace std;\n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 3){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" network.jaccs sortedjaccs.csv\" << endl;\n exit(1);\n }\n \/\/************* got the args\n clock_t begin = clock(); \n ifstream jaccFile; \n jaccFile.open( argv[1] );\n if (!jaccFile) {\n cout << \"ERROR: unable to open jaccards file\" << endl;\n exit(1); \/\/ terminate with error\n }\n int edgeId1,edgeId2; \n float jacc;\n set thresholdSet;\n while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) {\n if(thresholdSet.count(jacc) == 0)\n thresholdSet.insert(jacc);\n }\n jaccFile.close();jaccFile.clear();\n cout << \"Done with thresholdSet creation.\" << endl;\n \/\/ create the file\n \/\/ if exists then overwrite everything\n FILE * sortedJaccsFile = fopen( argv[2], \"w\" );\n fclose(sortedJaccsFile);\n for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){\n threshold = *thIt;\n sortedJaccsFile = fopen( argv[2], \"a\" );\n fprintf( sortedJaccsFile, \"%.6f \\n\", threshold, D);\n fclose(sortedJaccsFile);\n }\n thresholdSet.clear();\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\nFixed errors\/*\n\/\/ $ g++ -O3 -o createdSortedJaccsFile createdSortedJaccsFile.cpp\n\/\/ $ .\/createdSortedJaccsFile network.pairs network.jaccs threshDensity.csv\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ for pairs\n#include \/\/ for swap\n#define MIN_DIFF_BW_JACCS 0.0001\nusing namespace std;\n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 3){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" network.jaccs sortedjaccs.csv\" << endl;\n exit(1);\n }\n \/\/************* got the args\n clock_t begin = clock(); \n ifstream jaccFile; \n jaccFile.open( argv[1] );\n if (!jaccFile) {\n cout << \"ERROR: unable to open jaccards file\" << endl;\n exit(1); \/\/ terminate with error\n }\n int edgeId1,edgeId2; \n float jacc;\n set thresholdSet;\n set ::reverse_iterator thIt;\n \/\/ read each line from the jacc file\n while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) {\n \/\/ if this value of jacc does exists\n \/\/ then add inser the value\n if(thresholdSet.count(jacc) == 0)\n thresholdSet.insert(jacc);\n }\n jaccFile.close();jaccFile.clear();\n cout << \"Done with thresholdSet creation. total unique jaccs:\" << thresholdSet.size() << endl;\n \/\/ create the file\n \/\/ if exists then overwrite everything\n FILE * sortedJaccsFile = fopen( argv[2], \"w\" );\n fclose(sortedJaccsFile);\n for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){\n jacc = *thIt;\n \/\/ open the file\n sortedJaccsFile = fopen( argv[2], \"a\" );\n fprintf( sortedJaccsFile, \"%.6f \\n\", jacc);\n fclose(sortedJaccsFile);\n }\n thresholdSet.clear();\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \"..\/..\/..\/shared\/generated\/cpp\/AudioCaptureBase.h\"\n#include \"AudioCapture.h\"\n\nnamespace rho {\n\tusing namespace apiGenerator;\n\tusing namespace common;\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"AudioCapture\"\n\nclass CAudioCaptureImpl: public IRhoExtension, public CAudioCaptureBase\n{\n\tCAudioCapture *pAudio;\npublic:\n CAudioCaptureImpl(const rho::String& strID): CAudioCaptureBase()\n {\n\t\tpAudio = NULL;\n\t\tpAudio = new CAudioCapture(true);\n }\n\n\t~CAudioCaptureImpl()\n\t{\n\t\tLOG(INFO) + \"Shutting down Audio Capture \"; \n\t\tif (pAudio){\n\t\t\tdelete pAudio;\n\t\t\tpAudio = NULL;\t\n\t\t}\n\t}\n\t\n\tvirtual void start( const rho::Hashtable& props, rho::apiGenerator::CMethodResult& oResult){\n\t\tif (!pAudio) {return;}\n\t\tpAudio->SetCallback(NULL);\t\t\n\t\tif (oResult.hasCallback()){\n\t\t\tDEBUGMSG(true, (L\"Callback\"));\n\t\t\tpAudio->SetCallback(&oResult);\n\t\t\tCMethodResult oRes;\n\t\t\tsetProperties(props, oRes);\n\t\t\tpAudio->Start();\n\t\t}\n\t\telse{\n\t\t\tLOG(INFO) + L\"Could not start Audio Capture. Callback is Mandatory.\";\n\t\t\treturn;\n\t\t}\n }\n\t\n virtual void stop( rho::apiGenerator::CMethodResult& oResult) {\n\t\tif (!pAudio) {return;}\n\t\tpAudio->Stop();\n }\n\n\tvirtual void cancel(rho::apiGenerator::CMethodResult& oResult) {\n\t\tif (!pAudio) {return;}\n\t\tpAudio->Cancel();\n }\n\t\n virtual void onBeforeNavigate(const wchar_t* szUrlBeingNavigatedTo, const CRhoExtData& oExtData)\n\t{\n\t\tif (!pAudio){return;}\n\t\tpAudio->Cancel();\n\t}\n\n\tvirtual void OnAppActivate(bool bActivate, const CRhoExtData& oExtData)\n\t{\n\t\tif (!pAudio) {return;}\n\t\tpAudio->ApplicationFocusChange(bActivate);\n\t}\n\n\tvirtual void setProperty( const rho::String& propertyName, const rho::String& propertyValue, CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\tLOG(INFO) + L\"Setting Property \" + propertyName.c_str() + \" to \" + propertyValue.c_str();\t\t\n\t\tBOOL bRet = pAudio->SetPropertyOrMethod(convertToStringW(propertyName).c_str(), convertToStringW(propertyValue).c_str());\n\t\toResult.set(bRet == TRUE);\n\t}\n\n virtual void setProperties( const rho::Hashtable& propertyMap, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Set multiple properties\n\t\tif (!pAudio) {return;}\n\t\ttypedef std::map::const_iterator it_type;\n\t\tfor (it_type iterator = propertyMap.begin(); iterator != propertyMap.end(); iterator++)\n\t\t{\n\t\t\tLOG(INFO) + L\"Setting Property \" + iterator->first.c_str() + \" to \" + iterator->second.c_str();\t\t\t\n\t\t\tpAudio->SetPropertyOrMethod(convertToStringW(iterator->first).c_str(), convertToStringW(iterator->second).c_str());\n\t\t}\n\t\toResult.set(true);\n\t}\n\n\tvirtual void getProperty( const rho::String& propertyName, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\tif (m_hashProps.containsKey(propertyName))\n\t\t\toResult.set(m_hashProps.get(propertyName));\n\t\telse\n\t\t{\t\t\t\n\t\t\tWCHAR szValue[MAX_PATH];\n\t\t\tBOOL bResult = pAudio->RetrieveProperty(convertToStringW(propertyName).c_str(), szValue);\n\t\t\tLOG(INFO) + L\"Getting Property \" + convertToStringW(propertyName).c_str() + \" as \" + szValue;\n\t\t\tif (szValue && (bResult == TRUE))\n\t\t\t{\n\t\t\t\trho::StringW szStringValue;\n\t\t\t\tszStringValue.insert(0, szValue);\n\t\t\t\toResult.set(szStringValue);\n\t\t\t}\t\t\t\n\t\t\telse\n\t\t\t{\n\t\t\t\toResult.set(L\"Unavailable\");\n\t\t\t}\n\t\t}\n\t}\n\n virtual void getProperties( const rho::Vector& arrayofNames, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\trho::Hashtable propsHash;\n\t\tCMethodResult oRes;\n\t\ttypedef std::vector::const_iterator it_type;\n\t\tfor (it_type iterator = arrayofNames.begin(); iterator != arrayofNames.end(); iterator++)\n\t\t{\n\t\t\tgetProperty(*iterator, oRes);\n\t\t\tpropsHash.put(*iterator, convertToStringA(oRes.toString()));\n\t\t}\n\t\toResult.set(propsHash);\n\t}\n\n virtual void getAllProperties(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\trho::Hashtable propsHash;\n\t\tCMethodResult oRes;\n\t\trho::Vector arrayofNames;\n\t\tarrayofNames.push_back(\"fileName\");\n\t\tarrayofNames.push_back(\"duration\");\t\n\t\ttypedef std::vector::const_iterator it_type;\n\t\tfor (it_type iterator = arrayofNames.begin(); iterator != arrayofNames.end(); iterator++)\n\t\t{\n\t\t\tgetProperty(*iterator, oRes);\t\t\t\n\t\t\tpropsHash.put(*iterator, convertToStringA(oRes.toString()));\n\t\t}\n\t\toResult.set(propsHash);\t\t\n\t}\n};\n\nclass CAudioCaptureSingleton: public CAudioCaptureSingletonBase\n{\n ~CAudioCaptureSingleton(){}\n virtual rho::String getInitialDefaultID();\n virtual void enumerate(CMethodResult& oResult);\n};\n\nclass CAudioCaptureFactory: public CAudioCaptureFactoryBase\n{\n ~CAudioCaptureFactory(){}\n virtual IAudioCaptureSingleton* createModuleSingleton();\n virtual IAudioCapture* createModuleByID(const rho::String& strID);\n};\n\nextern \"C\" void Init_AudioCapture_extension()\n{\n CAudioCaptureFactory::setInstance( new CAudioCaptureFactory() );\n Init_AudioCapture_API();\n}\n\nIAudioCapture* CAudioCaptureFactory::createModuleByID(const rho::String& strID)\n{\n return new CAudioCaptureImpl(strID);\n}\n\nIAudioCaptureSingleton* CAudioCaptureFactory::createModuleSingleton()\n{\n return new CAudioCaptureSingleton();\n}\n\nvoid CAudioCaptureSingleton::enumerate(CMethodResult& oResult)\n{\n rho::Vector arIDs;\n arIDs.addElement(\"SC1\");\n arIDs.addElement(\"SC2\");\n\n oResult.set(arIDs);\n}\n\nrho::String CAudioCaptureSingleton::getInitialDefaultID()\n{\n CMethodResult oRes;\n enumerate(oRes);\n\n rho::Vector& arIDs = oRes.getStringArray();\n \n return arIDs[0];\n}\n\n}Registering the extension#include \n#include \"..\/..\/..\/shared\/generated\/cpp\/AudioCaptureBase.h\"\n#include \"AudioCapture.h\"\n\nnamespace rho {\n\tusing namespace apiGenerator;\n\tusing namespace common;\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"AudioCapture\"\n\nclass CAudioCaptureImpl: public IRhoExtension, public CAudioCaptureBase\n{\n\tCAudioCapture *pAudio;\npublic:\n CAudioCaptureImpl(const rho::String& strID): CAudioCaptureBase()\n {\n\t\t\/\/Is this the AudioCapture instance ID?\n\t\tm_hashProps.put( \"ID\", strID);\n\t\t\n\t\tLOG(INFO) + \"Initialising interface for AudioCapture \" + strID; \n\t\tRHODESAPP().getExtManager().registerExtension(strID, this );\n\n\t\tpAudio = NULL;\n\t\tpAudio = new CAudioCapture(true);\n }\n\n\t~CAudioCaptureImpl()\n\t{\n\t\tLOG(INFO) + \"Shutting down Audio Capture \"; \n\t\tif (pAudio){\n\t\t\tdelete pAudio;\n\t\t\tpAudio = NULL;\t\n\t\t}\n\t}\n\t\n\tvirtual void start( const rho::Hashtable& props, rho::apiGenerator::CMethodResult& oResult){\n\t\tif (!pAudio) {return;}\n\t\tpAudio->SetCallback(NULL);\t\t\n\t\tif (oResult.hasCallback()){\n\t\t\tDEBUGMSG(true, (L\"Callback\"));\n\t\t\tpAudio->SetCallback(&oResult);\n\t\t\tCMethodResult oRes;\n\t\t\tsetProperties(props, oRes);\n\t\t\tpAudio->Start();\n\t\t}\n\t\telse{\n\t\t\tLOG(INFO) + L\"Could not start Audio Capture. Callback is Mandatory.\";\n\t\t\treturn;\n\t\t}\n }\n\t\n virtual void stop( rho::apiGenerator::CMethodResult& oResult) {\n\t\tif (!pAudio) {return;}\n\t\tpAudio->Stop();\n }\n\n\tvirtual void cancel(rho::apiGenerator::CMethodResult& oResult) {\n\t\tif (!pAudio) {return;}\n\t\tpAudio->Cancel();\n }\n\t\n virtual void onBeforeNavigate(const wchar_t* szUrlBeingNavigatedTo, const CRhoExtData& oExtData)\n\t{\n\t\tif (!pAudio){return;}\n\t\tpAudio->Cancel();\n\t}\n\n\tvirtual void OnAppActivate(bool bActivate, const CRhoExtData& oExtData)\n\t{\n\t\tif (!pAudio) {return;}\n\t\tpAudio->ApplicationFocusChange(bActivate);\n\t}\n\n\tvirtual void setProperty( const rho::String& propertyName, const rho::String& propertyValue, CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\tLOG(INFO) + L\"Setting Property \" + propertyName.c_str() + \" to \" + propertyValue.c_str();\t\t\n\t\tBOOL bRet = pAudio->SetPropertyOrMethod(convertToStringW(propertyName).c_str(), convertToStringW(propertyValue).c_str());\n\t\toResult.set(bRet == TRUE);\n\t}\n\n virtual void setProperties( const rho::Hashtable& propertyMap, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Set multiple properties\n\t\tif (!pAudio) {return;}\n\t\ttypedef std::map::const_iterator it_type;\n\t\tfor (it_type iterator = propertyMap.begin(); iterator != propertyMap.end(); iterator++)\n\t\t{\n\t\t\tLOG(INFO) + L\"Setting Property \" + iterator->first.c_str() + \" to \" + iterator->second.c_str();\t\t\t\n\t\t\tpAudio->SetPropertyOrMethod(convertToStringW(iterator->first).c_str(), convertToStringW(iterator->second).c_str());\n\t\t}\n\t\toResult.set(true);\n\t}\n\n\tvirtual void getProperty( const rho::String& propertyName, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\tif (m_hashProps.containsKey(propertyName))\n\t\t\toResult.set(m_hashProps.get(propertyName));\n\t\telse\n\t\t{\t\t\t\n\t\t\tWCHAR szValue[MAX_PATH];\n\t\t\tBOOL bResult = pAudio->RetrieveProperty(convertToStringW(propertyName).c_str(), szValue);\n\t\t\tLOG(INFO) + L\"Getting Property \" + convertToStringW(propertyName).c_str() + \" as \" + szValue;\n\t\t\tif (szValue && (bResult == TRUE))\n\t\t\t{\n\t\t\t\trho::StringW szStringValue;\n\t\t\t\tszStringValue.insert(0, szValue);\n\t\t\t\toResult.set(szStringValue);\n\t\t\t}\t\t\t\n\t\t\telse\n\t\t\t{\n\t\t\t\toResult.set(L\"Unavailable\");\n\t\t\t}\n\t\t}\n\t}\n\n virtual void getProperties( const rho::Vector& arrayofNames, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\trho::Hashtable propsHash;\n\t\tCMethodResult oRes;\n\t\ttypedef std::vector::const_iterator it_type;\n\t\tfor (it_type iterator = arrayofNames.begin(); iterator != arrayofNames.end(); iterator++)\n\t\t{\n\t\t\tgetProperty(*iterator, oRes);\n\t\t\tpropsHash.put(*iterator, convertToStringA(oRes.toString()));\n\t\t}\n\t\toResult.set(propsHash);\n\t}\n\n virtual void getAllProperties(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\tif (!pAudio) {return;}\n\t\trho::Hashtable propsHash;\n\t\tCMethodResult oRes;\n\t\trho::Vector arrayofNames;\n\t\tarrayofNames.push_back(\"fileName\");\n\t\tarrayofNames.push_back(\"duration\");\t\n\t\ttypedef std::vector::const_iterator it_type;\n\t\tfor (it_type iterator = arrayofNames.begin(); iterator != arrayofNames.end(); iterator++)\n\t\t{\n\t\t\tgetProperty(*iterator, oRes);\t\t\t\n\t\t\tpropsHash.put(*iterator, convertToStringA(oRes.toString()));\n\t\t}\n\t\toResult.set(propsHash);\t\t\n\t}\n};\n\nclass CAudioCaptureSingleton: public CAudioCaptureSingletonBase\n{\n ~CAudioCaptureSingleton(){}\n virtual rho::String getInitialDefaultID();\n virtual void enumerate(CMethodResult& oResult);\n};\n\nclass CAudioCaptureFactory: public CAudioCaptureFactoryBase\n{\n ~CAudioCaptureFactory(){}\n virtual IAudioCaptureSingleton* createModuleSingleton();\n virtual IAudioCapture* createModuleByID(const rho::String& strID);\n};\n\nextern \"C\" void Init_AudioCapture_extension()\n{\n CAudioCaptureFactory::setInstance( new CAudioCaptureFactory() );\n Init_AudioCapture_API();\n}\n\nIAudioCapture* CAudioCaptureFactory::createModuleByID(const rho::String& strID)\n{\n return new CAudioCaptureImpl(strID);\n}\n\nIAudioCaptureSingleton* CAudioCaptureFactory::createModuleSingleton()\n{\n return new CAudioCaptureSingleton();\n}\n\nvoid CAudioCaptureSingleton::enumerate(CMethodResult& oResult)\n{\n rho::Vector arIDs;\n arIDs.addElement(\"AudioCapture\");\n oResult.set(arIDs);\n}\n\nrho::String CAudioCaptureSingleton::getInitialDefaultID()\n{\n CMethodResult oRes;\n enumerate(oRes);\n\n rho::Vector& arIDs = oRes.getStringArray();\n \n return arIDs[0];\n}\n\n}<|endoftext|>"} {"text":"\/\/\n\/\/ TapePRG.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/08\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Storage_Tape_PRG_hpp\n#define Storage_Tape_PRG_hpp\n\n#include \"..\/Tape.hpp\"\n#include \"..\/..\/FileHolder.hpp\"\n#include \n\nnamespace Storage {\nnamespace Tape {\n\n\/*!\n\tProvides a @c Tape containing a .PRG, which is a direct local file.\n*\/\nclass PRG: public Tape, public Storage::FileHolder {\n\tpublic:\n\t\t\/*!\n\t\t\tConstructs a @c T64 containing content from the file with name @c file_name, of type @c type.\n\n\t\t\t@param file_name The name of the file to load.\n\t\t\t@param type The type of data the file should contain.\n\t\t\t@throws ErrorBadFormat if this file could not be opened and recognised as the specified type.\n\t\t*\/\n\t\tPRG(const char *file_name);\n\n\t\tenum {\n\t\t\tErrorBadFormat\n\t\t};\n\n\t\t\/\/ implemented to satisfy @c Tape\n\t\tbool is_at_end();\n\n\tprivate:\n\t\tPulse virtual_get_next_pulse();\n\t\tvoid virtual_reset();\n\n\t\tuint16_t load_address_;\n\t\tuint16_t length_;\n\n\t\tenum FilePhase {\n\t\t\tFilePhaseLeadIn,\n\t\t\tFilePhaseHeader,\n\t\t\tFilePhaseHeaderDataGap,\n\t\t\tFilePhaseData,\n\t\t\tFilePhaseAtEnd\n\t\t} file_phase_;\n\t\tint phase_offset_;\n\n\t\tint bit_phase_;\n\t\tenum OutputToken {\n\t\t\tLeader,\n\t\t\tZero,\n\t\t\tOne,\n\t\t\tWordMarker,\n\t\t\tEndOfBlock,\n\t\t\tSilence\n\t\t} output_token_;\n\t\tvoid get_next_output_token();\n\t\tuint8_t output_byte_;\n\t\tuint8_t check_digit_;\n\t\tuint8_t copy_mask_;\n};\n\n}\n}\n\n#endif \/* T64_hpp *\/\nRemoved reference to a parameter long-since dead.\/\/\n\/\/ TapePRG.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/08\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Storage_Tape_PRG_hpp\n#define Storage_Tape_PRG_hpp\n\n#include \"..\/Tape.hpp\"\n#include \"..\/..\/FileHolder.hpp\"\n#include \n\nnamespace Storage {\nnamespace Tape {\n\n\/*!\n\tProvides a @c Tape containing a .PRG, which is a direct local file.\n*\/\nclass PRG: public Tape, public Storage::FileHolder {\n\tpublic:\n\t\t\/*!\n\t\t\tConstructs a @c T64 containing content from the file with name @c file_name, of type @c type.\n\n\t\t\t@param file_name The name of the file to load.\n\t\t\t@throws ErrorBadFormat if this file could not be opened and recognised as the specified type.\n\t\t*\/\n\t\tPRG(const char *file_name);\n\n\t\tenum {\n\t\t\tErrorBadFormat\n\t\t};\n\n\t\t\/\/ implemented to satisfy @c Tape\n\t\tbool is_at_end();\n\n\tprivate:\n\t\tPulse virtual_get_next_pulse();\n\t\tvoid virtual_reset();\n\n\t\tuint16_t load_address_;\n\t\tuint16_t length_;\n\n\t\tenum FilePhase {\n\t\t\tFilePhaseLeadIn,\n\t\t\tFilePhaseHeader,\n\t\t\tFilePhaseHeaderDataGap,\n\t\t\tFilePhaseData,\n\t\t\tFilePhaseAtEnd\n\t\t} file_phase_;\n\t\tint phase_offset_;\n\n\t\tint bit_phase_;\n\t\tenum OutputToken {\n\t\t\tLeader,\n\t\t\tZero,\n\t\t\tOne,\n\t\t\tWordMarker,\n\t\t\tEndOfBlock,\n\t\t\tSilence\n\t\t} output_token_;\n\t\tvoid get_next_output_token();\n\t\tuint8_t output_byte_;\n\t\tuint8_t check_digit_;\n\t\tuint8_t copy_mask_;\n};\n\n}\n}\n\n#endif \/* T64_hpp *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2018, University of Edinburgh\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \n\n#include \n#include \n\nnamespace exotica\n{\ntemplate \nOMPLSolver::OMPLSolver() = default;\n\ntemplate \nOMPLSolver::~OMPLSolver() = default;\n\ntemplate \nvoid OMPLSolver::SpecifyProblem(PlanningProblemPtr pointer)\n{\n MotionSolver::SpecifyProblem(pointer);\n prob_ = std::static_pointer_cast(pointer);\n if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FIXED)\n state_space_.reset(new OMPLRNStateSpace(init_));\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::PLANAR)\n {\n if (init_.IsDubinsStateSpace)\n state_space_.reset(new OMPLDubinsRNStateSpace(init_));\n else\n state_space_.reset(new OMPLRNStateSpace(init_)); \/\/ NB: We have a dedicated OMPLSE2RNStateSpace, however, for now we cannot set orientation bounds on it - as thus we are using the RN here. Cf. issue #629.\n }\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FLOATING)\n state_space_.reset(new OMPLSE3RNStateSpace(init_));\n else\n ThrowNamed(\"Unsupported base type \" << prob_->GetScene()->GetKinematicTree().GetControlledBaseType());\n ompl_simple_setup_.reset(new ompl::geometric::SimpleSetup(state_space_));\n ompl_simple_setup_->setStateValidityChecker(ompl::base::StateValidityCheckerPtr(new OMPLStateValidityChecker(ompl_simple_setup_->getSpaceInformation(), prob_)));\n ompl_simple_setup_->setPlannerAllocator(boost::bind(planner_allocator_, _1, algorithm_));\n\n if (init_.Projection.rows() > 0)\n {\n std::vector project_vars(init_.Projection.rows());\n for (int i = 0; i < init_.Projection.rows(); ++i)\n {\n project_vars[i] = (int)init_.Projection(i);\n if (project_vars[i] < 0 || project_vars[i] >= prob_->N) ThrowNamed(\"Invalid projection index! \" << project_vars[i]);\n }\n if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FIXED)\n ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLRNProjection(state_space_, project_vars)));\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::PLANAR)\n ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE2RNProjection(state_space_, project_vars)));\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FLOATING)\n ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE3RNProjection(state_space_, project_vars)));\n }\n}\n\ntemplate \nint OMPLSolver::GetRandomSeed() const\n{\n return ompl::RNG::getSeed();\n}\n\ntemplate \nvoid OMPLSolver::PreSolve()\n{\n \/\/ Clear previously computed solutions\n if (!multi_query_)\n {\n ompl_simple_setup_->getProblemDefinition()->clearSolutionPaths();\n const ompl::base::PlannerPtr planner = ompl_simple_setup_->getPlanner();\n if (planner)\n planner->clear();\n ompl_simple_setup_->getPlanner()->setProblemDefinition(ompl_simple_setup_->getProblemDefinition());\n }\n ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->resetMotionCounter();\n}\n\ntemplate \nvoid OMPLSolver::PostSolve()\n{\n ompl_simple_setup_->clearStartStates();\n int v = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getValidMotionCount();\n int iv = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getInvalidMotionCount();\n if (debug_) CONSOLE_BRIDGE_logDebug(\"There were %d valid motions and %d invalid motions.\", v, iv);\n\n if (ompl_simple_setup_->getProblemDefinition()->hasApproximateSolution())\n CONSOLE_BRIDGE_logWarn(\"Computed solution is approximate\");\n}\n\ntemplate \nvoid OMPLSolver::SetGoalState(Eigen::VectorXdRefConst qT, const double eps)\n{\n ompl::base::ScopedState<> gs(state_space_);\n state_space_->as()->ExoticaToOMPLState(qT, gs.get());\n if (!ompl_simple_setup_->getStateValidityChecker()->isValid(gs.get()))\n {\n ThrowNamed(\"Goal state is not valid!\");\n }\n\n if (!ompl_simple_setup_->getSpaceInformation()->satisfiesBounds(gs.get()))\n {\n state_space_->as()->StateDebug(qT);\n\n \/\/ Debug state and bounds\n auto bounds = prob_->GetBounds();\n std::string out_of_bounds_joint_ids = \"\";\n for (int i = 0; i < qT.rows(); ++i)\n if (qT(i) < bounds[i] || qT(i) > bounds[i + qT.rows()])\n out_of_bounds_joint_ids += \"[j\" + std::to_string(i) + \"=\" + std::to_string(qT(i)) + \", ll=\" + std::to_string(bounds[i]) + \", ul=\" + std::to_string(bounds[i + qT.rows()]) + \"]\\n\";\n\n ThrowNamed(\"Invalid goal state [Invalid joint bounds for joint indices: \\n\"\n << out_of_bounds_joint_ids << \"]\");\n }\n ompl_simple_setup_->setGoalState(gs, eps);\n}\n\ntemplate \nvoid OMPLSolver::GetPath(Eigen::MatrixXd &traj, ompl::base::PlannerTerminationCondition &ptc)\n{\n ompl::geometric::PathSimplifierPtr psf = ompl_simple_setup_->getPathSimplifier();\n const ompl::base::SpaceInformationPtr &si = ompl_simple_setup_->getSpaceInformation();\n\n ompl::geometric::PathGeometric pg = ompl_simple_setup_->getSolutionPath();\n if (init_.Smooth)\n {\n bool try_more = true;\n int times = 0;\n while (init_.ReduceVertices && times < init_.SimplifyTryCnt && try_more && ptc == false)\n {\n pg.interpolate(init_.SimplifyInterpolationLength);\n try_more = psf->reduceVertices(pg, 0, 0, init_.RangeRatio);\n ++times;\n }\n if (init_.ShortcutPath && si->getStateSpace()->isMetricSpace())\n {\n times = 0;\n while (times < init_.SimplifyTryCnt && try_more && ptc == false)\n {\n pg.interpolate(init_.SimplifyInterpolationLength);\n try_more = psf->shortcutPath(pg, 0, 0, init_.RangeRatio, init_.SnapToVertex);\n ++times;\n }\n }\n }\n std::vector &states = pg.getStates();\n unsigned int length = 0;\n if (init_.FinalInterpolationLength > 3)\n {\n length = init_.FinalInterpolationLength;\n }\n else\n {\n const int n1 = states.size() - 1;\n for (int i = 0; i < n1; ++i)\n length += si->getStateSpace()->validSegmentCount(states[i], states[i + 1]);\n }\n pg.interpolate(int(length * init_.SmoothnessFactor));\n\n traj.resize(pg.getStateCount(), prob_->GetSpaceDim());\n Eigen::VectorXd tmp(prob_->GetSpaceDim());\n\n for (int i = 0; i < static_cast(pg.getStateCount()); ++i)\n {\n state_space_->as()->OMPLToExoticaState(pg.getState(i), tmp);\n traj.row(i) = tmp.transpose();\n }\n}\n\ntemplate \nvoid OMPLSolver::Solve(Eigen::MatrixXd &solution)\n{\n \/\/ Set log level\n ompl::msg::setLogLevel(debug_ ? ompl::msg::LogLevel::LOG_DEBUG : ompl::msg::LogLevel::LOG_WARN);\n\n Eigen::VectorXd q0 = prob_->ApplyStartState();\n\n \/\/ check joint limits\n const std::vector bounds = prob_->GetBounds();\n for (const double l : bounds)\n {\n if (!std::isfinite(l))\n {\n std::cerr << \"Detected non-finite joint limits:\" << std::endl;\n const size_t nlim = bounds.size() \/ 2;\n for (uint i = 0; i < nlim; ++i)\n {\n std::cout << bounds[i] << \", \" << bounds[nlim + i] << std::endl;\n }\n throw std::runtime_error(\"All joint limits need to be finite!\");\n }\n }\n\n if (!state_space_->as()->isLocked())\n {\n state_space_->as()->SetBounds(prob_);\n bounds_ = prob_->GetBounds();\n }\n else if (!bounds_.empty() && bounds_ != prob_->GetBounds())\n {\n ThrowPretty(\"Cannot set new bounds on locked state space!\");\n }\n\n ompl_simple_setup_->getSpaceInformation()->setup();\n\n ompl_simple_setup_->setup();\n\n if (ompl_simple_setup_->getPlanner()->params().hasParam(\"Range\"))\n ompl_simple_setup_->getPlanner()->params().setParam(\"Range\", init_.Range);\n if (ompl_simple_setup_->getPlanner()->params().hasParam(\"GoalBias\"))\n ompl_simple_setup_->getPlanner()->params().setParam(\"GoalBias\", init_.GoalBias);\n\n if (init_.RandomSeed > -1)\n {\n HIGHLIGHT_NAMED(algorithm_, \"Setting random seed to \" << init_.RandomSeed);\n ompl::RNG::setSeed(static_cast(init_.RandomSeed));\n }\n\n SetGoalState(prob_->GetGoalState(), init_.Epsilon);\n\n ompl::base::ScopedState<> ompl_start_state(state_space_);\n\n state_space_->as()->ExoticaToOMPLState(q0, ompl_start_state.get());\n ompl_simple_setup_->setStartState(ompl_start_state);\n\n PreSolve();\n ompl::time::point start = ompl::time::now();\n ompl::base::PlannerTerminationCondition ptc = ompl::base::timedPlannerTerminationCondition(init_.Timeout - ompl::time::seconds(ompl::time::now() - start));\n\n Timer t;\n if (ompl_simple_setup_->solve(ptc) == ompl::base::PlannerStatus::EXACT_SOLUTION && ompl_simple_setup_->haveSolutionPath())\n {\n GetPath(solution, ptc);\n }\n std::cout << \"Finished simple setup solve\" << std::endl;\n planning_time_ = t.GetDuration();\n PostSolve();\n}\n\ntemplate class OMPLSolver;\n}\n[exotica_ompl_solver] Remove extraneous debug\/\/\n\/\/ Copyright (c) 2018, University of Edinburgh\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \n\n#include \n#include \n\nnamespace exotica\n{\ntemplate \nOMPLSolver::OMPLSolver() = default;\n\ntemplate \nOMPLSolver::~OMPLSolver() = default;\n\ntemplate \nvoid OMPLSolver::SpecifyProblem(PlanningProblemPtr pointer)\n{\n MotionSolver::SpecifyProblem(pointer);\n prob_ = std::static_pointer_cast(pointer);\n if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FIXED)\n state_space_.reset(new OMPLRNStateSpace(init_));\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::PLANAR)\n {\n if (init_.IsDubinsStateSpace)\n state_space_.reset(new OMPLDubinsRNStateSpace(init_));\n else\n state_space_.reset(new OMPLRNStateSpace(init_)); \/\/ NB: We have a dedicated OMPLSE2RNStateSpace, however, for now we cannot set orientation bounds on it - as thus we are using the RN here. Cf. issue #629.\n }\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FLOATING)\n state_space_.reset(new OMPLSE3RNStateSpace(init_));\n else\n ThrowNamed(\"Unsupported base type \" << prob_->GetScene()->GetKinematicTree().GetControlledBaseType());\n ompl_simple_setup_.reset(new ompl::geometric::SimpleSetup(state_space_));\n ompl_simple_setup_->setStateValidityChecker(ompl::base::StateValidityCheckerPtr(new OMPLStateValidityChecker(ompl_simple_setup_->getSpaceInformation(), prob_)));\n ompl_simple_setup_->setPlannerAllocator(boost::bind(planner_allocator_, _1, algorithm_));\n\n if (init_.Projection.rows() > 0)\n {\n std::vector project_vars(init_.Projection.rows());\n for (int i = 0; i < init_.Projection.rows(); ++i)\n {\n project_vars[i] = (int)init_.Projection(i);\n if (project_vars[i] < 0 || project_vars[i] >= prob_->N) ThrowNamed(\"Invalid projection index! \" << project_vars[i]);\n }\n if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FIXED)\n ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLRNProjection(state_space_, project_vars)));\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::PLANAR)\n ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE2RNProjection(state_space_, project_vars)));\n else if (prob_->GetScene()->GetKinematicTree().GetControlledBaseType() == BaseType::FLOATING)\n ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE3RNProjection(state_space_, project_vars)));\n }\n}\n\ntemplate \nint OMPLSolver::GetRandomSeed() const\n{\n return ompl::RNG::getSeed();\n}\n\ntemplate \nvoid OMPLSolver::PreSolve()\n{\n \/\/ Clear previously computed solutions\n if (!multi_query_)\n {\n ompl_simple_setup_->getProblemDefinition()->clearSolutionPaths();\n const ompl::base::PlannerPtr planner = ompl_simple_setup_->getPlanner();\n if (planner)\n planner->clear();\n ompl_simple_setup_->getPlanner()->setProblemDefinition(ompl_simple_setup_->getProblemDefinition());\n }\n ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->resetMotionCounter();\n}\n\ntemplate \nvoid OMPLSolver::PostSolve()\n{\n ompl_simple_setup_->clearStartStates();\n int v = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getValidMotionCount();\n int iv = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getInvalidMotionCount();\n if (debug_) CONSOLE_BRIDGE_logDebug(\"There were %d valid motions and %d invalid motions.\", v, iv);\n\n if (ompl_simple_setup_->getProblemDefinition()->hasApproximateSolution())\n CONSOLE_BRIDGE_logWarn(\"Computed solution is approximate\");\n}\n\ntemplate \nvoid OMPLSolver::SetGoalState(Eigen::VectorXdRefConst qT, const double eps)\n{\n ompl::base::ScopedState<> gs(state_space_);\n state_space_->as()->ExoticaToOMPLState(qT, gs.get());\n if (!ompl_simple_setup_->getStateValidityChecker()->isValid(gs.get()))\n {\n ThrowNamed(\"Goal state is not valid!\");\n }\n\n if (!ompl_simple_setup_->getSpaceInformation()->satisfiesBounds(gs.get()))\n {\n state_space_->as()->StateDebug(qT);\n\n \/\/ Debug state and bounds\n auto bounds = prob_->GetBounds();\n std::string out_of_bounds_joint_ids = \"\";\n for (int i = 0; i < qT.rows(); ++i)\n if (qT(i) < bounds[i] || qT(i) > bounds[i + qT.rows()])\n out_of_bounds_joint_ids += \"[j\" + std::to_string(i) + \"=\" + std::to_string(qT(i)) + \", ll=\" + std::to_string(bounds[i]) + \", ul=\" + std::to_string(bounds[i + qT.rows()]) + \"]\\n\";\n\n ThrowNamed(\"Invalid goal state [Invalid joint bounds for joint indices: \\n\"\n << out_of_bounds_joint_ids << \"]\");\n }\n ompl_simple_setup_->setGoalState(gs, eps);\n}\n\ntemplate \nvoid OMPLSolver::GetPath(Eigen::MatrixXd &traj, ompl::base::PlannerTerminationCondition &ptc)\n{\n ompl::geometric::PathSimplifierPtr psf = ompl_simple_setup_->getPathSimplifier();\n const ompl::base::SpaceInformationPtr &si = ompl_simple_setup_->getSpaceInformation();\n\n ompl::geometric::PathGeometric pg = ompl_simple_setup_->getSolutionPath();\n if (init_.Smooth)\n {\n bool try_more = true;\n int times = 0;\n while (init_.ReduceVertices && times < init_.SimplifyTryCnt && try_more && ptc == false)\n {\n pg.interpolate(init_.SimplifyInterpolationLength);\n try_more = psf->reduceVertices(pg, 0, 0, init_.RangeRatio);\n ++times;\n }\n if (init_.ShortcutPath && si->getStateSpace()->isMetricSpace())\n {\n times = 0;\n while (times < init_.SimplifyTryCnt && try_more && ptc == false)\n {\n pg.interpolate(init_.SimplifyInterpolationLength);\n try_more = psf->shortcutPath(pg, 0, 0, init_.RangeRatio, init_.SnapToVertex);\n ++times;\n }\n }\n }\n std::vector &states = pg.getStates();\n unsigned int length = 0;\n if (init_.FinalInterpolationLength > 3)\n {\n length = init_.FinalInterpolationLength;\n }\n else\n {\n const int n1 = states.size() - 1;\n for (int i = 0; i < n1; ++i)\n length += si->getStateSpace()->validSegmentCount(states[i], states[i + 1]);\n }\n pg.interpolate(int(length * init_.SmoothnessFactor));\n\n traj.resize(pg.getStateCount(), prob_->GetSpaceDim());\n Eigen::VectorXd tmp(prob_->GetSpaceDim());\n\n for (int i = 0; i < static_cast(pg.getStateCount()); ++i)\n {\n state_space_->as()->OMPLToExoticaState(pg.getState(i), tmp);\n traj.row(i) = tmp.transpose();\n }\n}\n\ntemplate \nvoid OMPLSolver::Solve(Eigen::MatrixXd &solution)\n{\n \/\/ Set log level\n ompl::msg::setLogLevel(debug_ ? ompl::msg::LogLevel::LOG_DEBUG : ompl::msg::LogLevel::LOG_WARN);\n\n Eigen::VectorXd q0 = prob_->ApplyStartState();\n\n \/\/ check joint limits\n const std::vector bounds = prob_->GetBounds();\n for (const double l : bounds)\n {\n if (!std::isfinite(l))\n {\n std::cerr << \"Detected non-finite joint limits:\" << std::endl;\n const size_t nlim = bounds.size() \/ 2;\n for (uint i = 0; i < nlim; ++i)\n {\n std::cout << bounds[i] << \", \" << bounds[nlim + i] << std::endl;\n }\n throw std::runtime_error(\"All joint limits need to be finite!\");\n }\n }\n\n if (!state_space_->as()->isLocked())\n {\n state_space_->as()->SetBounds(prob_);\n bounds_ = prob_->GetBounds();\n }\n else if (!bounds_.empty() && bounds_ != prob_->GetBounds())\n {\n ThrowPretty(\"Cannot set new bounds on locked state space!\");\n }\n\n ompl_simple_setup_->getSpaceInformation()->setup();\n\n ompl_simple_setup_->setup();\n\n if (ompl_simple_setup_->getPlanner()->params().hasParam(\"Range\"))\n ompl_simple_setup_->getPlanner()->params().setParam(\"Range\", init_.Range);\n if (ompl_simple_setup_->getPlanner()->params().hasParam(\"GoalBias\"))\n ompl_simple_setup_->getPlanner()->params().setParam(\"GoalBias\", init_.GoalBias);\n\n if (init_.RandomSeed > -1)\n {\n HIGHLIGHT_NAMED(algorithm_, \"Setting random seed to \" << init_.RandomSeed);\n ompl::RNG::setSeed(static_cast(init_.RandomSeed));\n }\n\n SetGoalState(prob_->GetGoalState(), init_.Epsilon);\n\n ompl::base::ScopedState<> ompl_start_state(state_space_);\n\n state_space_->as()->ExoticaToOMPLState(q0, ompl_start_state.get());\n ompl_simple_setup_->setStartState(ompl_start_state);\n\n PreSolve();\n ompl::time::point start = ompl::time::now();\n ompl::base::PlannerTerminationCondition ptc = ompl::base::timedPlannerTerminationCondition(init_.Timeout - ompl::time::seconds(ompl::time::now() - start));\n\n Timer t;\n if (ompl_simple_setup_->solve(ptc) == ompl::base::PlannerStatus::EXACT_SOLUTION && ompl_simple_setup_->haveSolutionPath())\n {\n GetPath(solution, ptc);\n }\n planning_time_ = t.GetDuration();\n PostSolve();\n}\n\ntemplate class OMPLSolver;\n}\n<|endoftext|>"} {"text":"\/* rbOOmit: An implementation of the Certified Reduced Basis method. *\/\n\/* Copyright (C) 2009, 2010 David J. Knezevic *\/\n\/* This file is part of rbOOmit. *\/\n\n\/* rbOOmit is free software; you can redistribute it and\/or *\/\n\/* modify it under the terms of the GNU Lesser General Public *\/\n\/* License as published by the Free Software Foundation; either *\/\n\/* version 2.1 of the License, or (at your option) any later version. *\/\n \n\/* rbOOmit 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, MA 02111-1307 USA *\/\n\n\/\/

Reduced Basis: Example 5 - Reduced Basis Cantilever<\/h1>\n\/\/ 3D cantilever beam using the Reduced Basis Method\n\/\/ David Knezevic, Kyung Hoon Lee\n\/\/\n\/\/ We consider four parameters in this problem:\n\/\/ x_scaling: scales the length of the cantilever\n\/\/ load_Fx: the traction in the x-direction on the right boundary of the cantilever\n\/\/ load_Fy: the traction in the y-direction on the right boundary of the cantilever\n\/\/ load_Fz: the traction in the z-direction on the right boundary of the cantilever\n\n\/\/ C++ include files that we need\n#include \n#include \n#include \n#include \n\n\/\/ Basic include file needed for the mesh functionality.\n#include \"libmesh.h\"\n#include \"mesh.h\"\n#include \"mesh_generation.h\"\n#include \"exodusII_io.h\"\n#include \"equation_systems.h\"\n#include \"dof_map.h\"\n#include \"getpot.h\"\n#include \"elem.h\"\n\n\/\/ local includes\n#include \"rb_classes.h\"\n#include \"assembly.h\"\n\n\/\/ Bring in everything from the libMesh namespace\nusing namespace libMesh;\n\n\/\/ Define a function to scale the mesh according to the parameter.\nvoid scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename);\n\n\/\/ The main program.\nint main(int argc, char** argv) {\n\t\/\/ Initialize libMesh.\n\tLibMeshInit init (argc, argv);\n\n#if !defined(LIBMESH_HAVE_XDR)\n \/\/ We need XDR support to write out reduced bases\n libmesh_example_assert(false, \"--enable-xdr\");\n#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)\n \/\/ XDR binary support requires double precision\n libmesh_example_assert(false, \"--disable-singleprecision\");\n#endif\n\n \/\/ This example only works if libMesh was compiled for 3D\n const unsigned int dim = 3;\n libmesh_example_assert(dim == LIBMESH_DIM, \"3D support\");\n\n\tstd::string parameters_filename = \"reduced_basis_ex5.in\";\n\tGetPot infile(parameters_filename);\n\n unsigned int n_elem_x = infile(\"n_elem_x\",0);\n unsigned int n_elem_y = infile(\"n_elem_y\",0);\n unsigned int n_elem_z = infile(\"n_elem_z\",0);\n Real x_size = infile(\"x_size\", 0.);\n Real y_size = infile(\"y_size\", 0.);\n Real z_size = infile(\"z_size\", 0.);\n\n\tbool store_basis_functions = infile(\"store_basis_functions\", true);\n\n\t\/\/ Read the \"online_mode\" flag from the command line\n\tGetPot command_line(argc, argv);\n\tint online_mode = 0;\n\tif ( command_line.search(1, \"-online_mode\") ) {\n\t\tonline_mode = command_line.next(online_mode);\t\t\n\t}\n\n\n Mesh mesh (dim);\n MeshTools::Generation::build_cube (mesh,\n n_elem_x,\n n_elem_y,\n n_elem_z,\n 0., x_size,\n 0., y_size,\n 0., z_size,\n HEX8);\n\t mesh.print_info();\n\n\t\/\/ Create an equation systems object.\n\tEquationSystems equation_systems(mesh);\n\n\t\/\/ We override RBConstruction with ElasticityRBConstruction in order to\n\t\/\/ specialize a few functions for this particular problem.\n\tElasticityRBConstruction& rb_con =\n\t\tequation_systems.add_system(\"RBElasticity\");\n\n\t\/\/ Initialize the data structures for the equation system.\n\tequation_systems.init ();\n equation_systems.print_info();\n\n\t\/\/ Build a new RBEvaluation object which will be used to perform\n\t\/\/ Reduced Basis calculations. This is required in both the\n\t\/\/ \"Offline\" and \"Online\" stages.\n\tElasticityRBEvaluation rb_eval;\n\n\t\/\/ We need to give the RBConstruction object a pointer to\n\t\/\/ our RBEvaluation object\n\trb_con.set_rb_evaluation(rb_eval);\n\n\tif(!online_mode) \/\/ Perform the Offline stage of the RB method\n\t{\n\t\t\/\/ Read in the data that defines this problem from the specified text file\n\t\trb_con.process_parameters_file(parameters_filename);\n\n\t\t\/\/ Print out info that describes the current setup of rb_con\n\t\trb_con.print_info();\n\n\t\t\/\/ Prepare rb_con for the Construction stage of the RB method.\n\t\t\/\/ This sets up the necessary data structures and performs\n\t\t\/\/ initial assembly of the \"truth\" affine expansion of the PDE.\n\t\trb_con.initialize_rb_construction();\n\n\t\t\/\/ Compute the reduced basis space by computing \"snapshots\", i.e.\n\t\t\/\/ \"truth\" solves, at well-chosen parameter values and employing\n\t\t\/\/ these snapshots as basis functions.\n\t\trb_con.train_reduced_basis();\n\n\t\t\/\/ Write out the data that will subsequently be required for the Evaluation stage\n\t\trb_con.get_rb_evaluation().write_offline_data_to_files();\n\t\t\n\t\t\/\/ If requested, write out the RB basis functions for visualization purposes\n\t\tif(store_basis_functions)\n\t\t{\n\t\t\t\/\/ Write out the basis functions\n\t\t\trb_con.get_rb_evaluation().write_out_basis_functions(rb_con);\n\t\t}\n\t}\n\telse \/\/ Perform the Online stage of the RB method\n\t{\n\t\t\/\/ Read in the reduced basis data\n\t\trb_eval.read_offline_data_from_files();\n\n\t\t\/\/ Iinitialize online parameters\n\t\tReal online_x_scaling = infile(\"online_x_scaling\", 0.);\n\t\tReal online_load_Fx = infile(\"online_load_Fx\", 0.);\n\t\tReal online_load_Fy = infile(\"online_load_Fy\", 0.);\n\t\tReal online_load_Fz = infile(\"online_load_Fz\", 0.);\n\t\tRBParameters online_mu;\n\t\tonline_mu.set_value(\"x_scaling\", online_x_scaling);\n\t\tonline_mu.set_value(\"load_Fx\", online_load_Fx);\n\t\tonline_mu.set_value(\"load_Fy\", online_load_Fy);\n\t\tonline_mu.set_value(\"load_Fz\", online_load_Fz);\n\t\trb_eval.set_parameters(online_mu);\n\t\trb_eval.print_parameters();\n\t\t\n\t\t\/\/ Now do the Online solve using the precomputed reduced basis\n\t\trb_eval.rb_solve( rb_eval.get_n_basis_functions() );\n\n\t\tif(store_basis_functions)\n\t\t{\n\t\t\t\/\/ Read in the basis functions\n\t\t\trb_eval.read_in_basis_functions(rb_con);\n\n\t\t\t\/\/ Plot the solution\n\t\t\trb_con.load_rb_solution();\n\n\t\t\tconst RBParameters& rb_eval_params = rb_eval.get_parameters();\n\t\t\tscale_mesh_and_plot(equation_systems, rb_eval_params, \"RB_sol.e\");\n\t\t}\t\t\n\t}\n\n\treturn 0;\n}\n\nvoid scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename)\n{\n const Real x_scaling = mu.get_value(\"x_scaling\");\n \n \/\/ Loop over the mesh nodes and move them!\n MeshBase& mesh = es.get_mesh();\n\n MeshBase::node_iterator node_it = mesh.nodes_begin();\n const MeshBase::node_iterator node_end = mesh.nodes_end();\n\n for( ; node_it != node_end; node_it++)\n {\n Node* node = *node_it;\n\n (*node)(0) *= mu.get_value(\"x_scaling\");\n }\n\n#ifdef LIBMESH_HAVE_EXODUS_API\n ExodusII_IO (mesh).write_equation_systems (filename, es);\n#endif\n\n \/\/ Loop over the mesh nodes and move them!\n node_it = mesh.nodes_begin();\n\n for( ; node_it != node_end; node_it++)\n {\n Node* node = *node_it;\n\n (*node)(0) \/= mu.get_value(\"x_scaling\");\n }\n}\ncorrected K's name in the example\/* rbOOmit: An implementation of the Certified Reduced Basis method. *\/\n\/* Copyright (C) 2009, 2010 David J. Knezevic *\/\n\/* This file is part of rbOOmit. *\/\n\n\/* rbOOmit is free software; you can redistribute it and\/or *\/\n\/* modify it under the terms of the GNU Lesser General Public *\/\n\/* License as published by the Free Software Foundation; either *\/\n\/* version 2.1 of the License, or (at your option) any later version. *\/\n \n\/* rbOOmit 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, MA 02111-1307 USA *\/\n\n\/\/

Reduced Basis: Example 5 - Reduced Basis Cantilever<\/h1>\n\/\/ 3D cantilever beam using the Reduced Basis Method\n\/\/ David Knezevic, Kyunghoon \"K\" Lee\n\/\/\n\/\/ We consider four parameters in this problem:\n\/\/ x_scaling: scales the length of the cantilever\n\/\/ load_Fx: the traction in the x-direction on the right boundary of the cantilever\n\/\/ load_Fy: the traction in the y-direction on the right boundary of the cantilever\n\/\/ load_Fz: the traction in the z-direction on the right boundary of the cantilever\n\n\/\/ C++ include files that we need\n#include \n#include \n#include \n#include \n\n\/\/ Basic include file needed for the mesh functionality.\n#include \"libmesh.h\"\n#include \"mesh.h\"\n#include \"mesh_generation.h\"\n#include \"exodusII_io.h\"\n#include \"equation_systems.h\"\n#include \"dof_map.h\"\n#include \"getpot.h\"\n#include \"elem.h\"\n\n\/\/ local includes\n#include \"rb_classes.h\"\n#include \"assembly.h\"\n\n\/\/ Bring in everything from the libMesh namespace\nusing namespace libMesh;\n\n\/\/ Define a function to scale the mesh according to the parameter.\nvoid scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename);\n\n\/\/ The main program.\nint main(int argc, char** argv) {\n\t\/\/ Initialize libMesh.\n\tLibMeshInit init (argc, argv);\n\n#if !defined(LIBMESH_HAVE_XDR)\n \/\/ We need XDR support to write out reduced bases\n libmesh_example_assert(false, \"--enable-xdr\");\n#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)\n \/\/ XDR binary support requires double precision\n libmesh_example_assert(false, \"--disable-singleprecision\");\n#endif\n\n \/\/ This example only works if libMesh was compiled for 3D\n const unsigned int dim = 3;\n libmesh_example_assert(dim == LIBMESH_DIM, \"3D support\");\n\n\tstd::string parameters_filename = \"reduced_basis_ex5.in\";\n\tGetPot infile(parameters_filename);\n\n unsigned int n_elem_x = infile(\"n_elem_x\",0);\n unsigned int n_elem_y = infile(\"n_elem_y\",0);\n unsigned int n_elem_z = infile(\"n_elem_z\",0);\n Real x_size = infile(\"x_size\", 0.);\n Real y_size = infile(\"y_size\", 0.);\n Real z_size = infile(\"z_size\", 0.);\n\n\tbool store_basis_functions = infile(\"store_basis_functions\", true);\n\n\t\/\/ Read the \"online_mode\" flag from the command line\n\tGetPot command_line(argc, argv);\n\tint online_mode = 0;\n\tif ( command_line.search(1, \"-online_mode\") ) {\n\t\tonline_mode = command_line.next(online_mode);\t\t\n\t}\n\n\n Mesh mesh (dim);\n MeshTools::Generation::build_cube (mesh,\n n_elem_x,\n n_elem_y,\n n_elem_z,\n 0., x_size,\n 0., y_size,\n 0., z_size,\n HEX8);\n\t mesh.print_info();\n\n\t\/\/ Create an equation systems object.\n\tEquationSystems equation_systems(mesh);\n\n\t\/\/ We override RBConstruction with ElasticityRBConstruction in order to\n\t\/\/ specialize a few functions for this particular problem.\n\tElasticityRBConstruction& rb_con =\n\t\tequation_systems.add_system(\"RBElasticity\");\n\n\t\/\/ Initialize the data structures for the equation system.\n\tequation_systems.init ();\n equation_systems.print_info();\n\n\t\/\/ Build a new RBEvaluation object which will be used to perform\n\t\/\/ Reduced Basis calculations. This is required in both the\n\t\/\/ \"Offline\" and \"Online\" stages.\n\tElasticityRBEvaluation rb_eval;\n\n\t\/\/ We need to give the RBConstruction object a pointer to\n\t\/\/ our RBEvaluation object\n\trb_con.set_rb_evaluation(rb_eval);\n\n\tif(!online_mode) \/\/ Perform the Offline stage of the RB method\n\t{\n\t\t\/\/ Read in the data that defines this problem from the specified text file\n\t\trb_con.process_parameters_file(parameters_filename);\n\n\t\t\/\/ Print out info that describes the current setup of rb_con\n\t\trb_con.print_info();\n\n\t\t\/\/ Prepare rb_con for the Construction stage of the RB method.\n\t\t\/\/ This sets up the necessary data structures and performs\n\t\t\/\/ initial assembly of the \"truth\" affine expansion of the PDE.\n\t\trb_con.initialize_rb_construction();\n\n\t\t\/\/ Compute the reduced basis space by computing \"snapshots\", i.e.\n\t\t\/\/ \"truth\" solves, at well-chosen parameter values and employing\n\t\t\/\/ these snapshots as basis functions.\n\t\trb_con.train_reduced_basis();\n\n\t\t\/\/ Write out the data that will subsequently be required for the Evaluation stage\n\t\trb_con.get_rb_evaluation().write_offline_data_to_files();\n\t\t\n\t\t\/\/ If requested, write out the RB basis functions for visualization purposes\n\t\tif(store_basis_functions)\n\t\t{\n\t\t\t\/\/ Write out the basis functions\n\t\t\trb_con.get_rb_evaluation().write_out_basis_functions(rb_con);\n\t\t}\n\t}\n\telse \/\/ Perform the Online stage of the RB method\n\t{\n\t\t\/\/ Read in the reduced basis data\n\t\trb_eval.read_offline_data_from_files();\n\n\t\t\/\/ Iinitialize online parameters\n\t\tReal online_x_scaling = infile(\"online_x_scaling\", 0.);\n\t\tReal online_load_Fx = infile(\"online_load_Fx\", 0.);\n\t\tReal online_load_Fy = infile(\"online_load_Fy\", 0.);\n\t\tReal online_load_Fz = infile(\"online_load_Fz\", 0.);\n\t\tRBParameters online_mu;\n\t\tonline_mu.set_value(\"x_scaling\", online_x_scaling);\n\t\tonline_mu.set_value(\"load_Fx\", online_load_Fx);\n\t\tonline_mu.set_value(\"load_Fy\", online_load_Fy);\n\t\tonline_mu.set_value(\"load_Fz\", online_load_Fz);\n\t\trb_eval.set_parameters(online_mu);\n\t\trb_eval.print_parameters();\n\t\t\n\t\t\/\/ Now do the Online solve using the precomputed reduced basis\n\t\trb_eval.rb_solve( rb_eval.get_n_basis_functions() );\n\n\t\tif(store_basis_functions)\n\t\t{\n\t\t\t\/\/ Read in the basis functions\n\t\t\trb_eval.read_in_basis_functions(rb_con);\n\n\t\t\t\/\/ Plot the solution\n\t\t\trb_con.load_rb_solution();\n\n\t\t\tconst RBParameters& rb_eval_params = rb_eval.get_parameters();\n\t\t\tscale_mesh_and_plot(equation_systems, rb_eval_params, \"RB_sol.e\");\n\t\t}\t\t\n\t}\n\n\treturn 0;\n}\n\nvoid scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename)\n{\n const Real x_scaling = mu.get_value(\"x_scaling\");\n \n \/\/ Loop over the mesh nodes and move them!\n MeshBase& mesh = es.get_mesh();\n\n MeshBase::node_iterator node_it = mesh.nodes_begin();\n const MeshBase::node_iterator node_end = mesh.nodes_end();\n\n for( ; node_it != node_end; node_it++)\n {\n Node* node = *node_it;\n\n (*node)(0) *= mu.get_value(\"x_scaling\");\n }\n\n#ifdef LIBMESH_HAVE_EXODUS_API\n ExodusII_IO (mesh).write_equation_systems (filename, es);\n#endif\n\n \/\/ Loop over the mesh nodes and move them!\n node_it = mesh.nodes_begin();\n\n for( ; node_it != node_end; node_it++)\n {\n Node* node = *node_it;\n\n (*node)(0) \/= mu.get_value(\"x_scaling\");\n }\n}\n<|endoftext|>"} {"text":"#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP\n#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP\n\n#include \"internal\/common.hpp\"\n#include \"Singleton.hpp\"\n\n#include \n#include \n#include \n\nnamespace cutehmi {\n\n\/**\n * Internationalization singleton.\n *\/\nclass CUTEHMI_API Internationalizer:\n\tpublic QObject,\n\tpublic Singleton\n{\n\t\tQ_OBJECT\n\n\t\tfriend class Singleton;\n\t\tfriend class test_Internationalizer;\n\n\tpublic:\n\t\t\/**\n\t\t User interface language.\n\t\t *\/\n\t\tQ_PROPERTY(QString uiLanguage READ uiLanguage WRITE setUILanguage NOTIFY uiLanguageChanged)\n\n\t\t\/**\n\t\t * Get user interface language.\n\t\t * @return currently used user interface language.\n\t\t *\/\n\t\tQString uiLanguage() const;\n\n\t\t\/**\n\t\t * Set user interface language.\n\t\t * @param uiLanguage language to be currently used.\n\t\t *\/\n\t\tvoid setUILanguage(const QString & uiLanguage);\n\n\t\t\/**\n\t\t * Load Qt translation.\n\t\t *\/\n\t\tQ_INVOKABLE void loadQtTranslation();\n\n\t\t\/**\n\t\t * Unload Qt translation.\n\t\t *\/\n\t\tQ_INVOKABLE void unloadQtTranslation();\n\n\t\t\/**\n\t\t * Load translation of %CuteHMI product. Typically product is an extension, but the function can be also used to load\n\t\t * translation of a tool or even a test.\n\t\t *\n\t\t * In order to load a translation function looks at various directories as returned by standardTranslationDirectories()\n\t\t * function. The directories are searched in the same order as they appear in the list. Additional directories can be\n\t\t * specified by setAdditionalTranslationDirectories() function. Additional directories take precedence over standard ones.\n\t\t *\n\t\t * To obtain the stem of the translation file, product name is lowercased and all the dots are replaced with hyphens, thus\n\t\t * for example @p CuteHMI.2 becomes @p cutehmi-2. After that several file suffixes are tested in each of the translation\n\t\t * directories as specified by QTranslator::load() function and \"_qt.qm\" suffix is used to satisfy KDE internationalization\n\t\t * framework convention. For example, for @p CuteHMI.2 product any of the following translation files will match @p en-US\n\t\t * translation: @p cutehmi-2.qm, @p cutehmi-2_en.qm, @p cutehmi-2_en_US.qm, @p cutehmi-2.en.qm, @p cutehmi-2.en_US.qm,\n\t\t * @p cutehmi-2_qt.qm, @p cutehmi-2_en_qt.qm, @p cutehmi-2_en_US_qt.qm, @p cutehmi-2.en_qt.qm, @p cutehmi-2.en_US_qt.qm.\n\t\t *\n\t\t * @param product product name.\n\t\t * @param dependencies denotes if translations of product dependencies should be loaded as well. Dependency information is\n\t\t * retrieved from metadata, so it is important to specify appropriate dependencies in Qbs file.\n\t\t *\/\n\t\tQ_INVOKABLE void loadTranslation(const QString & product, bool dependencies = true);\n\n\t\t\/**\n\t\t * Unload translations of a specific product.\n\t\t * @param product product name.\n\t\t *\/\n\t\tQ_INVOKABLE void unloadTranslation(const QString & product);\n\n\t\t\/**\n\t\t * Unload loaded translations. Function unloads any previously loaded translation of a product and optionally Qt\n\t\t * translation.\n\t\t * @param qt whether to unload Qt translation. If set to @p true, Qt translation will be unloaded.\n\t\t *\/\n\t\tQ_INVOKABLE void unloadTranslations(bool qt = true);\n\n\t\t\/**\n\t\t * Get standard translation directories. The list is composed of following entries:\n\t\t * - CuteHMI-specific \"translations\" subdirectory.\n\t\t * - In an attempt to satisfy gettext convention, path specified by LOCPATH environmental variable followed by\n\t\t * {langdir}\/LC_MESSAGES<\/tt> is used. The @p {langdir} subdirectory is obtained from \\ref uiLanguage passed through\n\t\t * QLocale::uiLanguages() function. Hyphens are replaced by underscores, so that en-US<\/tt> becomes en_US<\/tt>.\n\t\t * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_HOME environmental variable followed by\n\t\t * \/locale\/{langdir}\/LC_MESSAGES<\/tt> are used. If XDG_DATA_HOME has not been set,\n\t\t * HOME\/.local\/share<\/tt> is being used. The @p {langdir} subdirectory is obtained in the same way as above.\n\t\t * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_DIRS environmental variable followed by\n\t\t * \/locale\/{langdir}\/LC_MESSAGES<\/tt> are used. If XDG_DATA_DIRS has not been set, usr\/local\/share\/<\/tt> and\n\t\t * \/usr\/share\/<\/tt> are used. The @p {langdir} subdirectory is obtained in the same way as above.\n\t\t * @return list of standard translation directories.\n\t\t * - Directories returned by QLibraryInfo::location(QLibraryInfo::TranslationsPath) are ued.\n\t\t *\n\t\t * @see additionalTranslationDirectories().\n\t\t *\/\n\t\tQ_INVOKABLE QStringList standardTranslationDirectories() const;\n\n\t\t\/**\n\t\t * Get additional translation directories.\n\t\t * @return list of additional translation directories. By default this list is empty.\n\t\t *\n\t\t * @see setAdditionalTranslationDirectories().\n\t\t *\/\n\t\tQ_INVOKABLE QStringList additionalTranslationDirectories() const;\n\n\t\t\/**\n\t\t * Set additional translation directories.\n\t\t * @param additionalDirectories additional directories, where translation files may reside.\n\t\t *\n\t\t * @see additionalTranslationDirectories(), standardTranslationDirectories().\n\t\t *\/\n\t\tQ_INVOKABLE void setAdditionalTranslationDirectories(const QStringList & additionalDirectories);\n\n\tsignals:\n\t\t\/**\n\t\t * User interface language has changed.\n\t\t *\/\n\t\tvoid uiLanguageChanged();\n\n\tprivate:\n\t\ttypedef QMap TranslatorsContainer;\n\n\t\t\/**\n\t\t * Default constructor.\n\t\t * @param parent parent object.\n\t\t *\/\n\t\texplicit Internationalizer(QObject * parent = nullptr);\n\n\t\tvoid updateTranslation(QTranslator & translator, const QString & product, const QStringList & directories);\n\n\t\tvoid updateQtTranslation(QTranslator & translator);\n\n\t\tQString translationFileStem(const QString & product);\n\n\t\tQStringList translationDirectories() const;\n\n\t\tstruct Members\n\t\t{\n\t\t\tQLocale uiLanguage;\n\t\t\tTranslatorsContainer translators;\n\t\t\tQTranslator * qtTranslator = nullptr;\n\t\t\tQStringList additionalTranslationDirectories;\n\t\t};\n\n\t\tMPtr m;\n};\n\n}\n\n#endif\n\n\/\/(c)C: Copyright © 2020, Michał Policht . All rights reserved.\n\/\/(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI is free software: you can redistribute it and\/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\/\/(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see .\n\/\/(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.\n\/\/(c)C: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\/\/(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\/\/(c)C: THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\nFix a typo#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP\n#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP\n\n#include \"internal\/common.hpp\"\n#include \"Singleton.hpp\"\n\n#include \n#include \n#include \n\nnamespace cutehmi {\n\n\/**\n * Internationalization singleton.\n *\/\nclass CUTEHMI_API Internationalizer:\n\tpublic QObject,\n\tpublic Singleton\n{\n\t\tQ_OBJECT\n\n\t\tfriend class Singleton;\n\t\tfriend class test_Internationalizer;\n\n\tpublic:\n\t\t\/**\n\t\t User interface language.\n\t\t *\/\n\t\tQ_PROPERTY(QString uiLanguage READ uiLanguage WRITE setUILanguage NOTIFY uiLanguageChanged)\n\n\t\t\/**\n\t\t * Get user interface language.\n\t\t * @return currently used user interface language.\n\t\t *\/\n\t\tQString uiLanguage() const;\n\n\t\t\/**\n\t\t * Set user interface language.\n\t\t * @param uiLanguage language to be currently used.\n\t\t *\/\n\t\tvoid setUILanguage(const QString & uiLanguage);\n\n\t\t\/**\n\t\t * Load Qt translation.\n\t\t *\/\n\t\tQ_INVOKABLE void loadQtTranslation();\n\n\t\t\/**\n\t\t * Unload Qt translation.\n\t\t *\/\n\t\tQ_INVOKABLE void unloadQtTranslation();\n\n\t\t\/**\n\t\t * Load translation of %CuteHMI product. Typically product is an extension, but the function can be also used to load\n\t\t * translation of a tool or even a test.\n\t\t *\n\t\t * In order to load a translation function looks at various directories as returned by standardTranslationDirectories()\n\t\t * function. The directories are searched in the same order as they appear in the list. Additional directories can be\n\t\t * specified by setAdditionalTranslationDirectories() function. Additional directories take precedence over standard ones.\n\t\t *\n\t\t * To obtain the stem of the translation file, product name is lowercased and all the dots are replaced with hyphens, thus\n\t\t * for example @p CuteHMI.2 becomes @p cutehmi-2. After that several file suffixes are tested in each of the translation\n\t\t * directories as specified by QTranslator::load() function and \"_qt.qm\" suffix is used to satisfy KDE internationalization\n\t\t * framework convention. For example, for @p CuteHMI.2 product any of the following translation files will match @p en-US\n\t\t * translation: @p cutehmi-2.qm, @p cutehmi-2_en.qm, @p cutehmi-2_en_US.qm, @p cutehmi-2.en.qm, @p cutehmi-2.en_US.qm,\n\t\t * @p cutehmi-2_qt.qm, @p cutehmi-2_en_qt.qm, @p cutehmi-2_en_US_qt.qm, @p cutehmi-2.en_qt.qm, @p cutehmi-2.en_US_qt.qm.\n\t\t *\n\t\t * @param product product name.\n\t\t * @param dependencies denotes if translations of product dependencies should be loaded as well. Dependency information is\n\t\t * retrieved from metadata, so it is important to specify appropriate dependencies in Qbs file.\n\t\t *\/\n\t\tQ_INVOKABLE void loadTranslation(const QString & product, bool dependencies = true);\n\n\t\t\/**\n\t\t * Unload translations of a specific product.\n\t\t * @param product product name.\n\t\t *\/\n\t\tQ_INVOKABLE void unloadTranslation(const QString & product);\n\n\t\t\/**\n\t\t * Unload loaded translations. Function unloads any previously loaded translation of a product and optionally Qt\n\t\t * translation.\n\t\t * @param qt whether to unload Qt translation. If set to @p true, Qt translation will be unloaded.\n\t\t *\/\n\t\tQ_INVOKABLE void unloadTranslations(bool qt = true);\n\n\t\t\/**\n\t\t * Get standard translation directories. The list is composed of following entries:\n\t\t * - CuteHMI-specific \"translations\" subdirectory.\n\t\t * - In an attempt to satisfy gettext convention, path specified by LOCPATH environmental variable followed by\n\t\t * {langdir}\/LC_MESSAGES<\/tt> is used. The @p {langdir} subdirectory is obtained from \\ref uiLanguage passed through\n\t\t * QLocale::uiLanguages() function. Hyphens are replaced by underscores, so that en-US<\/tt> becomes en_US<\/tt>.\n\t\t * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_HOME environmental variable followed by\n\t\t * \/locale\/{langdir}\/LC_MESSAGES<\/tt> are used. If XDG_DATA_HOME has not been set,\n\t\t * HOME\/.local\/share<\/tt> is being used. The @p {langdir} subdirectory is obtained in the same way as above.\n\t\t * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_DIRS environmental variable followed by\n\t\t * \/locale\/{langdir}\/LC_MESSAGES<\/tt> are used. If XDG_DATA_DIRS has not been set, usr\/local\/share\/<\/tt> and\n\t\t * \/usr\/share\/<\/tt> are used. The @p {langdir} subdirectory is obtained in the same way as above.\n\t\t * @return list of standard translation directories.\n\t\t * - Directories returned by QLibraryInfo::location(QLibraryInfo::TranslationsPath) are used.\n\t\t *\n\t\t * @see additionalTranslationDirectories().\n\t\t *\/\n\t\tQ_INVOKABLE QStringList standardTranslationDirectories() const;\n\n\t\t\/**\n\t\t * Get additional translation directories.\n\t\t * @return list of additional translation directories. By default this list is empty.\n\t\t *\n\t\t * @see setAdditionalTranslationDirectories().\n\t\t *\/\n\t\tQ_INVOKABLE QStringList additionalTranslationDirectories() const;\n\n\t\t\/**\n\t\t * Set additional translation directories.\n\t\t * @param additionalDirectories additional directories, where translation files may reside.\n\t\t *\n\t\t * @see additionalTranslationDirectories(), standardTranslationDirectories().\n\t\t *\/\n\t\tQ_INVOKABLE void setAdditionalTranslationDirectories(const QStringList & additionalDirectories);\n\n\tsignals:\n\t\t\/**\n\t\t * User interface language has changed.\n\t\t *\/\n\t\tvoid uiLanguageChanged();\n\n\tprivate:\n\t\ttypedef QMap TranslatorsContainer;\n\n\t\t\/**\n\t\t * Default constructor.\n\t\t * @param parent parent object.\n\t\t *\/\n\t\texplicit Internationalizer(QObject * parent = nullptr);\n\n\t\tvoid updateTranslation(QTranslator & translator, const QString & product, const QStringList & directories);\n\n\t\tvoid updateQtTranslation(QTranslator & translator);\n\n\t\tQString translationFileStem(const QString & product);\n\n\t\tQStringList translationDirectories() const;\n\n\t\tstruct Members\n\t\t{\n\t\t\tQLocale uiLanguage;\n\t\t\tTranslatorsContainer translators;\n\t\t\tQTranslator * qtTranslator = nullptr;\n\t\t\tQStringList additionalTranslationDirectories;\n\t\t};\n\n\t\tMPtr m;\n};\n\n}\n\n#endif\n\n\/\/(c)C: Copyright © 2020, Michał Policht . All rights reserved.\n\/\/(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI is free software: you can redistribute it and\/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\/\/(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see .\n\/\/(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.\n\/\/(c)C: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\/\/(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\/\/(c)C: THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define lli long long int\n\nusing namespace std;\n\nint main()\n{\n int a,b;\n cin >> a >> b;\n cout << a+a+b+b << endl;\n\treturn 0;\n}\nUpdate A_Accepted.cpp#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main()\n{\n int a,b;\n cin >> a >> b;\n cout << a+a+b+b << endl;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/**\n* @license Apache-2.0\n*\n* Copyright (c) 2018 The Stdlib Authors.\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 \"stdlib\/strided_binary.h\"\n#include \"stdlib\/ndarray\/base\/bytes_per_element.h\"\n#include \"stdlib\/ndarray\/dtypes.h\"\n#include \n#include \n#include \n#include \n\n\/**\n* Add-on namespace.\n*\/\nnamespace addon_strided_add {\n\n\t\/**\n\t* Adds two doubles.\n\t*\n\t* @private\n\t* @param x first double\n\t* @param y second double\n\t* @return sum\n\t*\/\n\tdouble add( double x, double y ) {\n\t\treturn x + y;\n\t}\n\n\t\/**\n\t* Returns a typed array data type.\n\t*\n\t* @private\n\t* @param vtype typed array type\n\t* @return data type\n\t*\/\n\tenum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {\n\t\tif ( vtype == napi_float64_array ) {\n\t\t\treturn STDLIB_NDARRAY_FLOAT64;\n\t\t}\n\t\tif ( vtype == napi_float32_array ) {\n\t\t\treturn STDLIB_NDARRAY_FLOAT32;\n\t\t}\n\t\tif ( vtype == napi_int32_array ) {\n\t\t\treturn STDLIB_NDARRAY_INT32;\n\t\t}\n\t\tif ( vtype == napi_uint32_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT32;\n\t\t}\n\t\tif ( vtype == napi_int16_array ) {\n\t\t\treturn STDLIB_NDARRAY_INT16;\n\t\t}\n\t\tif ( vtype == napi_uint16_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT16;\n\t\t}\n\t\tif ( vtype == napi_int8_array ) {\n\t\t\treturn STDLIB_NDARRAY_INT8;\n\t\t}\n\t\tif ( vtype == napi_uint8_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT8;\n\t\t}\n\t\tif ( vtype == napi_uint8_clamped_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT8;\n\t\t}\n\t\t\/\/ FIXME: handle BigInt64Array and BigUint64Array\n\t}\n\n\t\/**\n\t* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.\n\t*\n\t* ## Notes\n\t*\n\t* - The function assumes the following argument order:\n\t*\n\t* ```text\n\t* [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]\n\t* ```\n\t*\n\t* where\n\t*\n\t* - `N` is the number of elements over which to iterate\n\t* - `ia#` is an input strided array\n\t* - `is#` is a corresponding input strided array stride (in units of elements)\n\t* - `oa#` is an output strided array\n\t* - `os#` is a corresponding output strided array stride (in units of elements)\n\t*\n\t* - We **assume** no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).\n\t*\n\t* @private\n\t* @param env environment\n\t* @param info arguments\n\t* @param nargs total number of expected arguments\n\t* @param nin number of input strided array arguments\n\t* @param nout number of output strided array arguments\n\t* @param arrays destination array containing pointers to both input and output strided byte arrays\n\t* @param shape destination array containing the array shape (dimensions)\n\t* @param strides destination array containing array strides (in bytes) for each strided array\n\t* @param types destination array containing strided array argument data types\n\t* @throws must provide expected number of input arguments\n\t* @throws stride arguments must be numbers\n\t* @throws input strided array arguments must be either typed arrays or scalars\n\t* @throws output strided array arguments must be typed arrays\n\t* @throws must provide at least one input strided array\n\t* @return number of scalar strided \"array\" arguments\n\t*\/\n\tint64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {\n\t\tnapi_status status;\n\t\tint64_t i;\n\t\tint64_t j;\n\n\t\t\/\/ Compute the index of the first output strided array argument:\n\t\tint64_t iout = ( nin*2 ) + 1;\n\n\t\t\/\/ Initialize variables used to track scalar input arguments:\n\t\tint64_t nsargs = 0;\n\t\tint64_t sargs = 0;\n\n\t\t\/\/ Get callback arguments:\n\t\tsize_t argc = 7;\n\t\tnapi_value argv[ 7 ];\n\t\tstatus = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );\n\t\tassert( status == napi_ok );\n\n\t\tif ( (int64_t)argc != nargs ) {\n\t\t\tnapi_throw_error( env, nullptr, \"invalid invocation. Incorrect number of arguments.\" );\n\t\t\treturn -1;\n\t\t}\n\n\t\t\/\/ The first argument is always the number of elements over which to iterate...\n\t\tnapi_valuetype vtype0;\n\t\tstatus = napi_typeof( env, argv[ 0 ], &vtype0 );\n\t\tassert( status == napi_ok );\n\t\tif ( vtype0 != napi_number ) {\n\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. First argument must be a number.\" );\n\t\t\treturn -1;\n\t\t}\n\n\t\t\/\/ Retrieve the number of elements:\n\t\tint64_t N;\n\t\tstatus = napi_get_value_int64( env, argv[ 0 ], &N );\n\t\tassert( status == napi_ok );\n\n\t\tshape[ 0 ] = N;\n\n\t\t\/\/ Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...\n\t\tfor ( i = 2; i < nargs; i += 2 ) {\n\t\t\tnapi_valuetype vtype;\n\t\t\tstatus = napi_typeof( env, argv[ i ], &vtype );\n\t\t\tassert( status == napi_ok );\n\t\t\tif ( vtype != napi_number ) {\n\t\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. Stride argument must be a number.\" );\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tint64_t stride;\n\t\t\tstatus = napi_get_value_int64( env, argv[ i ], &stride );\n\t\t\tassert( status == napi_ok );\n\n\t\t\tj = ( i-2 ) \/ 2;\n\t\t\tstrides[ j ] = stride;\n\t\t}\n\n\t\t\/\/ Input strided array arguments are every other argument beginning from the second argument...\n\t\tfor ( i = 1; i < iout; i += 2 ) {\n\t\t\tj = ( i-1 ) \/ 2;\n\n\t\t\tbool res;\n\t\t\tstatus = napi_is_typedarray( env, argv[ i ], &res );\n\t\t\tassert( status == napi_ok );\n\t\t\tif ( res == true ) {\n\t\t\t\tnapi_typedarray_type vtype;\n\t\t\t\tsize_t len;\n\t\t\t\tvoid *TypedArray;\n\t\t\t\tstatus = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );\n\t\t\t\tassert( status == napi_ok );\n\t\t\t\tif ( (N-1)*llabs(strides[j]) > (int64_t)len ) {\n\t\t\t\t\tnapi_throw_range_error( env, nullptr, \"invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements.\" );\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tarrays[ j ] = (uint8_t *)TypedArray;\n\t\t\t\ttypes[ j ] = typed_array_data_type( vtype );\n\t\t\t\tstrides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );\n\t\t\t} else {\n\t\t\t\tdouble v;\n\t\t\t\tstatus = napi_get_value_double( env, argv[ i ], &v );\n\t\t\t\tif ( status != napi_ok ) {\n\t\t\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. Input strided array argument must be a typed array or scalar.\" );\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tsargs |= (1< (int64_t)len ) {\n\t\t\t\t\tnapi_throw_range_error( env, nullptr, \"invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements.\" );\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tarrays[ j ] = (uint8_t *)TypedArray;\n\t\t\t\ttypes[ j ] = typed_array_data_type( vtype );\n\t\t\t\tstrides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );\n\t\t\t} else {\n\t\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. Output strided array arguments must be typed arrays.\" );\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Check if we have been provided only scalar input arguments...\n\t\tif ( nin > 0 && nsargs == nin ) {\n\t\t\tnapi_throw_type_error( env, nullptr, \"invalid arguments. Must provide at least one input strided array argument.\" );\n\t\t\treturn -1;\n\t\t}\n\t\treturn nsargs;\n\t}\n\n\t\/**\n\t* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.\n\t*\n\t* ## Notes\n\t*\n\t* - When called from JavaScript, the function expects the following arguments:\n\t*\n\t* - `N`: number of indexed elements\n\t* - `X`: input array (or scalar constant)\n\t* - `strideX`: `X` stride length\n\t* - `Y`: input array (or scalar constant)\n\t* - `strideY`: `Y` stride length\n\t* - `Z`: destination array\n\t* - `strideZ`: `Z` stride length\n\t*\/\n\tnapi_value node_add( napi_env env, napi_callback_info info ) {\n\t\tenum STDLIB_NDARRAY_DTYPE types[ 3 ];\n\t\tuint8_t *arrays[ 3 ];\n\t\tint64_t strides[ 3 ];\n\t\tint64_t shape[ 1 ];\n\t\tint64_t nsargs;\n\t\tint64_t nargs;\n\t\tint64_t nout;\n\t\tint64_t nin;\n\n\t\t\/\/ Total number of input arguments:\n\t\tnargs = 7;\n\n\t\t\/\/ Number of input and output strided array arguments:\n\t\tnin = 2;\n\t\tnout = 1;\n\n\t\t\/\/ Process the provided arguments:\n\t\tnsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );\n\t\tif ( nsargs < 0 ) {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t\/\/ Broadcasting of scalar arguments...\n\t\tif ( nsargs > 0 ) {\n\t\t\t\/\/ Create an array having the closest \"compatible\" type...\n\t\t\t\/\/ arrays[ 0 ] = broadcast( static_cast( info[ 1 ]->NumberValue() ), types[ 0 ] );\n\t\t}\n\n\t\t\/\/ Perform addition:\n\t\tstdlib_strided_dd_d( arrays, shape, strides, (void *)add );\n\n\t\treturn nullptr;\n\t}\n\n\tnapi_value Init( napi_env env, napi_value exports ) {\n\t\tnapi_status status;\n\t\tnapi_value fcn;\n\t\tstatus = napi_create_function( env, \"exports\", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );\n\t\tassert( status == napi_ok );\n\t\treturn fcn;\n\t}\n\n\tNAPI_MODULE( NODE_GYP_MODULE_NAME, Init )\n} \/\/ end namespace addon_strided_add\nAdd FIXMEs\/**\n* @license Apache-2.0\n*\n* Copyright (c) 2018 The Stdlib Authors.\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 \"stdlib\/strided_binary.h\"\n#include \"stdlib\/ndarray\/base\/bytes_per_element.h\"\n#include \"stdlib\/ndarray\/dtypes.h\"\n#include \n#include \n#include \n#include \n\n\/**\n* Add-on namespace.\n*\/\nnamespace addon_strided_add {\n\n\t\/**\n\t* Adds two doubles.\n\t*\n\t* @private\n\t* @param x first double\n\t* @param y second double\n\t* @return sum\n\t*\/\n\tdouble add( double x, double y ) {\n\t\treturn x + y;\n\t}\n\n\t\/**\n\t* Returns a typed array data type.\n\t*\n\t* @private\n\t* @param vtype typed array type\n\t* @return data type\n\t*\/\n\tenum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {\n\t\tif ( vtype == napi_float64_array ) {\n\t\t\treturn STDLIB_NDARRAY_FLOAT64;\n\t\t}\n\t\tif ( vtype == napi_float32_array ) {\n\t\t\treturn STDLIB_NDARRAY_FLOAT32;\n\t\t}\n\t\tif ( vtype == napi_int32_array ) {\n\t\t\treturn STDLIB_NDARRAY_INT32;\n\t\t}\n\t\tif ( vtype == napi_uint32_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT32;\n\t\t}\n\t\tif ( vtype == napi_int16_array ) {\n\t\t\treturn STDLIB_NDARRAY_INT16;\n\t\t}\n\t\tif ( vtype == napi_uint16_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT16;\n\t\t}\n\t\tif ( vtype == napi_int8_array ) {\n\t\t\treturn STDLIB_NDARRAY_INT8;\n\t\t}\n\t\tif ( vtype == napi_uint8_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT8;\n\t\t}\n\t\tif ( vtype == napi_uint8_clamped_array ) {\n\t\t\treturn STDLIB_NDARRAY_UINT8;\n\t\t}\n\t\t\/\/ FIXME: handle BigInt64Array and BigUint64Array\n\t}\n\n\t\/**\n\t* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.\n\t*\n\t* ## Notes\n\t*\n\t* - The function assumes the following argument order:\n\t*\n\t* ```text\n\t* [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]\n\t* ```\n\t*\n\t* where\n\t*\n\t* - `N` is the number of elements over which to iterate\n\t* - `ia#` is an input strided array\n\t* - `is#` is a corresponding input strided array stride (in units of elements)\n\t* - `oa#` is an output strided array\n\t* - `os#` is a corresponding output strided array stride (in units of elements)\n\t*\n\t* - We **assume** (due to use of bit flags for keeping track of scalar arguments) no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).\n\t*\n\t* @private\n\t* @param env environment\n\t* @param info arguments\n\t* @param nargs total number of expected arguments\n\t* @param nin number of input strided array arguments\n\t* @param nout number of output strided array arguments\n\t* @param arrays destination array containing pointers to both input and output strided byte arrays\n\t* @param shape destination array containing the array shape (dimensions)\n\t* @param strides destination array containing array strides (in bytes) for each strided array\n\t* @param types destination array containing strided array argument data types\n\t* @throws must provide expected number of input arguments\n\t* @throws stride arguments must be numbers\n\t* @throws input strided array arguments must be either typed arrays or scalars\n\t* @throws output strided array arguments must be typed arrays\n\t* @throws must provide at least one input strided array\n\t* @return number of scalar strided \"array\" arguments\n\t*\/\n\tint64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {\n\t\tnapi_status status;\n\t\tint64_t i;\n\t\tint64_t j;\n\n\t\t\/\/ Compute the index of the first output strided array argument:\n\t\tint64_t iout = ( nin*2 ) + 1;\n\n\t\t\/\/ Initialize variables used to track scalar input arguments:\n\t\tint64_t nsargs = 0;\n\t\tint64_t sargs = 0;\n\n\t\t\/\/ Get callback arguments:\n\t\tsize_t argc = 7;\n\t\tnapi_value argv[ 7 ];\n\t\tstatus = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );\n\t\tassert( status == napi_ok );\n\n\t\tif ( (int64_t)argc != nargs ) {\n\t\t\tnapi_throw_error( env, nullptr, \"invalid invocation. Incorrect number of arguments.\" );\n\t\t\treturn -1;\n\t\t}\n\n\t\t\/\/ The first argument is always the number of elements over which to iterate...\n\t\tnapi_valuetype vtype0;\n\t\tstatus = napi_typeof( env, argv[ 0 ], &vtype0 );\n\t\tassert( status == napi_ok );\n\t\tif ( vtype0 != napi_number ) {\n\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. First argument must be a number.\" );\n\t\t\treturn -1;\n\t\t}\n\n\t\t\/\/ Retrieve the number of elements:\n\t\tint64_t N;\n\t\tstatus = napi_get_value_int64( env, argv[ 0 ], &N );\n\t\tassert( status == napi_ok );\n\n\t\tshape[ 0 ] = N;\n\n\t\t\/\/ Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...\n\t\tfor ( i = 2; i < nargs; i += 2 ) {\n\t\t\tnapi_valuetype vtype;\n\t\t\tstatus = napi_typeof( env, argv[ i ], &vtype );\n\t\t\tassert( status == napi_ok );\n\t\t\tif ( vtype != napi_number ) {\n\t\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. Stride argument must be a number.\" );\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tint64_t stride;\n\t\t\tstatus = napi_get_value_int64( env, argv[ i ], &stride );\n\t\t\tassert( status == napi_ok );\n\n\t\t\tj = ( i-2 ) \/ 2;\n\t\t\tstrides[ j ] = stride;\n\t\t}\n\n\t\t\/\/ Input strided array arguments are every other argument beginning from the second argument...\n\t\tfor ( i = 1; i < iout; i += 2 ) {\n\t\t\tj = ( i-1 ) \/ 2;\n\n\t\t\tbool res;\n\t\t\tstatus = napi_is_typedarray( env, argv[ i ], &res );\n\t\t\tassert( status == napi_ok );\n\t\t\tif ( res == true ) {\n\t\t\t\tnapi_typedarray_type vtype;\n\t\t\t\tsize_t len;\n\t\t\t\tvoid *TypedArray;\n\t\t\t\tstatus = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );\n\t\t\t\tassert( status == napi_ok );\n\t\t\t\tif ( (N-1)*llabs(strides[j]) > (int64_t)len ) {\n\t\t\t\t\tnapi_throw_range_error( env, nullptr, \"invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements.\" );\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tarrays[ j ] = (uint8_t *)TypedArray;\n\t\t\t\ttypes[ j ] = typed_array_data_type( vtype );\n\t\t\t\tstrides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );\n\t\t\t} else {\n\t\t\t\tdouble v;\n\t\t\t\tstatus = napi_get_value_double( env, argv[ i ], &v );\n\t\t\t\tif ( status != napi_ok ) {\n\t\t\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. Input strided array argument must be a typed array or scalar.\" );\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tsargs |= (1< (int64_t)len ) {\n\t\t\t\t\tnapi_throw_range_error( env, nullptr, \"invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements.\" );\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tarrays[ j ] = (uint8_t *)TypedArray;\n\t\t\t\ttypes[ j ] = typed_array_data_type( vtype );\n\t\t\t\tstrides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );\n\t\t\t} else {\n\t\t\t\tnapi_throw_type_error( env, nullptr, \"invalid argument. Output strided array arguments must be typed arrays.\" );\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Check if we have been provided only scalar input arguments...\n\t\tif ( nin > 0 && nsargs == nin ) {\n\t\t\tnapi_throw_type_error( env, nullptr, \"invalid arguments. Must provide at least one input strided array argument.\" );\n\t\t\treturn -1;\n\t\t}\n\t\treturn nsargs;\n\t}\n\n\t\/**\n\t* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.\n\t*\n\t* ## Notes\n\t*\n\t* - When called from JavaScript, the function expects the following arguments:\n\t*\n\t* - `N`: number of indexed elements\n\t* - `X`: input array (or scalar constant)\n\t* - `strideX`: `X` stride length\n\t* - `Y`: input array (or scalar constant)\n\t* - `strideY`: `Y` stride length\n\t* - `Z`: destination array\n\t* - `strideZ`: `Z` stride length\n\t*\/\n\tnapi_value node_add( napi_env env, napi_callback_info info ) {\n\t\tenum STDLIB_NDARRAY_DTYPE types[ 3 ];\n\t\tuint8_t *arrays[ 3 ];\n\t\tint64_t strides[ 3 ];\n\t\tint64_t shape[ 1 ];\n\t\tint64_t nsargs;\n\t\tint64_t nargs;\n\t\tint64_t nout;\n\t\tint64_t nin;\n\n\t\t\/\/ Total number of input arguments:\n\t\tnargs = 7;\n\n\t\t\/\/ Number of input and output strided array arguments:\n\t\tnin = 2;\n\t\tnout = 1;\n\n\t\t\/\/ Process the provided arguments:\n\t\tnsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );\n\t\tif ( nsargs < 0 ) {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t\/\/ Broadcasting of scalar arguments...\n\t\tif ( nsargs > 0 ) {\n\t\t\t\/\/ FIXME\n\t\t\t\/\/ Create an array having the closest \"compatible\" type...\n\t\t\t\/\/ arrays[ 0 ] = broadcast( static_cast( info[ 1 ]->NumberValue() ), types[ 0 ] );\n\t\t}\n\n\t\t\/\/ Perform addition (NOTE: this currently assumes Float64Array input and output strided array arguments!!!):\n\t\tstdlib_strided_dd_d( arrays, shape, strides, (void *)add );\n\n\t\treturn nullptr;\n\t}\n\n\tnapi_value Init( napi_env env, napi_value exports ) {\n\t\tnapi_status status;\n\t\tnapi_value fcn;\n\t\tstatus = napi_create_function( env, \"exports\", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );\n\t\tassert( status == napi_ok );\n\t\treturn fcn;\n\t}\n\n\tNAPI_MODULE( NODE_GYP_MODULE_NAME, Init )\n} \/\/ end namespace addon_strided_add\n<|endoftext|>"} {"text":"\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \r\n\r\n#include \r\n\r\n#include \"CoreStdIncludes.h\"\r\n#include \"Core.h\"\r\n#include \"Foundation.h\"\r\n#include \"ServiceInterfaces.h\"\r\n#include \"StaticModuleDefinitions.h\"\r\n\r\n#include \"ConsoleModuleApi.h\"\r\n#include \"ConsoleModule.h\"\r\n#include \"ConsoleManager.h\"\r\n#include \"OgreOverlay.h\"\r\n\r\n#include \"InputEvents.h\"\r\n\r\n\/\/! Unit test for framework\r\nBOOST_AUTO_TEST_SUITE(test_suite_support_modules)\r\n\r\n\r\nFoundation::Framework &CreateFramework()\r\n{\r\n static Foundation::Framework fw;\r\n return fw;\r\n}\r\n\r\nstruct TestA\r\n{\r\n Console::CommandResult TestCallbackSuccess(const Core::StringVector ¶ms)\r\n {\r\n BOOST_CHECK_EQUAL(params[0], \"paramA\");\r\n BOOST_CHECK_EQUAL(params[1], \"paramB\");\r\n\r\n return Console::ResultSuccess(\"Success\");\r\n }\r\n Console::CommandResult TestCallbackFailure(const Core::StringVector ¶ms)\r\n {\r\n BOOST_CHECK_EQUAL(params.size(), 0);\r\n\r\n return Console::ResultFailure();\r\n }\r\n};\r\n\r\nstruct TestB\r\n{\r\n Console::CommandResult TestCallbackThreaded(const Core::StringVector ¶ms)\r\n {\r\n test_var_ = 1;\r\n return Console::ResultSuccess();\r\n }\r\n\r\n void operator()()\r\n {\r\n test_var_ = 0;\r\n Console::CommandService *console = fw_->GetService\r\n (Foundation::Service::ST_ConsoleCommand);\r\n\r\n console->RegisterCommand(Console::CreateCommand(\"Test CommandC\", \"Test command threaded\", Console::Bind(this, &TestB::TestCallbackThreaded), true));\r\n\r\n console->Update();\r\n boost::optional result;\r\n while ( !(result = console->Poll(\"Test CommandC\")) )\r\n console->Update();\r\n \r\n BOOST_CHECK_EQUAL (result->success_, true);\r\n }\r\n Foundation::Framework *fw_;\r\n int test_var_;\r\n};\r\n\r\nBOOST_AUTO_TEST_CASE( support_modules_console_commands )\r\n{\r\n Foundation::Framework &fw = CreateFramework();\r\n\r\n fw.GetModuleManager()->ExcludeModule(\"StaticModuleTest\");\r\n\r\n \/\/! \\todo Gtk seems to cause problems with unit tests, so excluded for now\r\n \/\/! \\bug Re-creating Gtk::Main when running unit tests in debug mode causes a crash. \r\n \/\/! It should have been destroyed properly though, and unloading\/loading GtkmmUI\r\n \/\/! module at runtime works just fine.\r\n fw.GetModuleManager()->ExcludeModule(\"GtkmmUI\");\r\n\r\n Test::StaticModuleDefinitions static_test;\r\n static_test(&fw);\r\n fw.GetModuleManager()->PreInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());\r\n fw.GetModuleManager()->InitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());\r\n fw.GetModuleManager()->PostInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());\r\n\r\n fw.GetModuleManager()->LoadModuleByName(\"SupportModules\", \"ConsoleModule\");\r\n BOOST_CHECK (fw.GetModuleManager()->HasModule(Foundation::Module::MT_Console));\r\n \r\n Console::CommandService *console = fw.GetService\r\n (Foundation::Service::ST_ConsoleCommand);\r\n\r\n TestA test_class;\r\n console->RegisterCommand(Console::CreateCommand(\"Test_CommandA\", \"Test command Success\", Console::Bind(&test_class, &TestA::TestCallbackSuccess)));\r\n console->RegisterCommand(Console::CreateCommand(\"Test_CommandB\", \"Test command Failure\", Console::Bind(&test_class, &TestA::TestCallbackFailure)));\r\n \r\n\r\n Console::CommandResult result = console->ExecuteCommand(\"Test_CommandA (paramA, paramB )\");\r\n BOOST_CHECK_EQUAL (result.success_, true);\r\n BOOST_CHECK_EQUAL (result.why_, \"Success\");\r\n\r\n result = console->ExecuteCommand(\"Test_CommandB\");\r\n BOOST_CHECK_EQUAL (result.success_, false);\r\n BOOST_CHECK_EQUAL (result.why_.size(), 0);\r\n\r\n TestB testb;\r\n testb.fw_ = &fw;\r\n\r\n Core::Thread thread(boost::ref(testb));\r\n console->QueueCommand(\"Test CommandC\");\r\n thread.join();\r\n \r\n BOOST_CHECK_EQUAL (testb.test_var_, 1);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( support_modules_console_ogre )\r\n{\r\n Foundation::Framework &fw = CreateFramework();\r\n\r\n Console::ConsoleManager *console_manager = checked_static_cast(fw.GetService\r\n (Foundation::Service::ST_Console));\r\n\r\n Console::ConsolePtr ogre_console = console_manager->GetOgre();\r\n Console::OgreOverlay *overlay = checked_static_cast(ogre_console.get());\r\n \r\n overlay->SetVisible(true);\r\n BOOST_CHECK_EQUAL(overlay->IsVisible(), true);\r\n overlay->Update(60); \/\/ fast-forward one minute\r\n BOOST_CHECK_EQUAL(overlay->IsVisible(), true);\r\n BOOST_CHECK_EQUAL(overlay->IsActive(), true);\r\n\r\n \r\n overlay->Scroll(30000);\r\n overlay->Scroll(-30000);\r\n overlay->Scroll(300000);\r\n overlay->Scroll(-2);\r\n overlay->Scroll(1);\r\n overlay->Clear();\r\n overlay->Scroll(5);\r\n overlay->Scroll(-5);\r\n overlay->Print(\"Test message A\");\r\n overlay->Print(\"Test message B\");\r\n overlay->Print(\"Test message C\");\r\n BOOST_CHECK_EQUAL(overlay->GetLine(0), std::string(\"Test message C\"));\r\n BOOST_CHECK_EQUAL(overlay->GetLine(1), std::string(\"Test message B\"));\r\n BOOST_CHECK_EQUAL(overlay->GetLine(2), std::string(\"Test message A\"));\r\n\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"\"));\r\n\r\n overlay->HandleKeyDown(OIS::KC_A, 65);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"A\"));\r\n overlay->HandleKeyDown(OIS::KC_B, 66);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"AB\"));\r\n overlay->HandleKeyDown(OIS::KC_BACK, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"A\"));\r\n overlay->HandleKeyDown(OIS::KC_C, 67);\r\n overlay->HandleKeyDown(OIS::KC_RIGHT, 0);\r\n overlay->HandleKeyDown(OIS::KC_LEFT, 0);\r\n overlay->HandleKeyDown(OIS::KC_BACK, 0);\r\n overlay->HandleKeyDown(OIS::KC_DELETE, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"\"));\r\n\r\n overlay->HandleKeyDown(OIS::KC_A, 65);\r\n overlay->HandleKeyDown(OIS::KC_RETURN, 0);\r\n overlay->HandleKeyDown(OIS::KC_B, 66);\r\n overlay->HandleKeyDown(OIS::KC_RETURN, 0);\r\n overlay->HandleKeyDown(OIS::KC_C, 67);\r\n overlay->HandleKeyDown(OIS::KC_RETURN, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"\"));\r\n\r\n overlay->HandleKeyDown(OIS::KC_DOWN, 0);\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"C\"));\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"A\"));\r\n overlay->HandleKeyDown(OIS::KC_DOWN, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"B\"));\r\n\r\n\r\n overlay->SetVisible(false);\r\n BOOST_CHECK_EQUAL(overlay->IsActive(), false);\r\n\r\n\r\n ogre_console.reset();\r\n fw.GetModuleManager()->UninitializeModules();\r\n fw.GetModuleManager()->UnloadModules();\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\nFixed comment.\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \r\n\r\n#include \r\n\r\n#include \"CoreStdIncludes.h\"\r\n#include \"Core.h\"\r\n#include \"Foundation.h\"\r\n#include \"ServiceInterfaces.h\"\r\n#include \"StaticModuleDefinitions.h\"\r\n\r\n#include \"ConsoleModuleApi.h\"\r\n#include \"ConsoleModule.h\"\r\n#include \"ConsoleManager.h\"\r\n#include \"OgreOverlay.h\"\r\n\r\n#include \"InputEvents.h\"\r\n\r\n\/\/! Unit test for framework\r\nBOOST_AUTO_TEST_SUITE(test_suite_support_modules)\r\n\r\n\r\nFoundation::Framework &CreateFramework()\r\n{\r\n static Foundation::Framework fw;\r\n return fw;\r\n}\r\n\r\nstruct TestA\r\n{\r\n Console::CommandResult TestCallbackSuccess(const Core::StringVector ¶ms)\r\n {\r\n BOOST_CHECK_EQUAL(params[0], \"paramA\");\r\n BOOST_CHECK_EQUAL(params[1], \"paramB\");\r\n\r\n return Console::ResultSuccess(\"Success\");\r\n }\r\n Console::CommandResult TestCallbackFailure(const Core::StringVector ¶ms)\r\n {\r\n BOOST_CHECK_EQUAL(params.size(), 0);\r\n\r\n return Console::ResultFailure();\r\n }\r\n};\r\n\r\nstruct TestB\r\n{\r\n Console::CommandResult TestCallbackThreaded(const Core::StringVector ¶ms)\r\n {\r\n test_var_ = 1;\r\n return Console::ResultSuccess();\r\n }\r\n\r\n void operator()()\r\n {\r\n test_var_ = 0;\r\n Console::CommandService *console = fw_->GetService\r\n (Foundation::Service::ST_ConsoleCommand);\r\n\r\n console->RegisterCommand(Console::CreateCommand(\"Test CommandC\", \"Test command threaded\", Console::Bind(this, &TestB::TestCallbackThreaded), true));\r\n\r\n console->Update();\r\n boost::optional result;\r\n while ( !(result = console->Poll(\"Test CommandC\")) )\r\n console->Update();\r\n \r\n BOOST_CHECK_EQUAL (result->success_, true);\r\n }\r\n Foundation::Framework *fw_;\r\n int test_var_;\r\n};\r\n\r\nBOOST_AUTO_TEST_CASE( support_modules_console_commands )\r\n{\r\n Foundation::Framework &fw = CreateFramework();\r\n\r\n fw.GetModuleManager()->ExcludeModule(\"StaticModuleTest\");\r\n\r\n \/\/! \\todo Gtk seems to cause problems with unit tests, so excluded for now\r\n \/\/! \\bug Re-creating Gtk::Main when running unit tests in debug mode causes a crash. \r\n \/\/! It should have been destroyed properly though, and unloading\/loading GtkmmUI\r\n \/\/! module at runtime works just fine. The problem seems to be confined to\r\n \/\/! unit tests in debug mode (run outside of the debugger).\r\n fw.GetModuleManager()->ExcludeModule(\"GtkmmUI\");\r\n\r\n Test::StaticModuleDefinitions static_test;\r\n static_test(&fw);\r\n fw.GetModuleManager()->PreInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());\r\n fw.GetModuleManager()->InitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());\r\n fw.GetModuleManager()->PostInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());\r\n\r\n fw.GetModuleManager()->LoadModuleByName(\"SupportModules\", \"ConsoleModule\");\r\n BOOST_CHECK (fw.GetModuleManager()->HasModule(Foundation::Module::MT_Console));\r\n \r\n Console::CommandService *console = fw.GetService\r\n (Foundation::Service::ST_ConsoleCommand);\r\n\r\n TestA test_class;\r\n console->RegisterCommand(Console::CreateCommand(\"Test_CommandA\", \"Test command Success\", Console::Bind(&test_class, &TestA::TestCallbackSuccess)));\r\n console->RegisterCommand(Console::CreateCommand(\"Test_CommandB\", \"Test command Failure\", Console::Bind(&test_class, &TestA::TestCallbackFailure)));\r\n \r\n\r\n Console::CommandResult result = console->ExecuteCommand(\"Test_CommandA (paramA, paramB )\");\r\n BOOST_CHECK_EQUAL (result.success_, true);\r\n BOOST_CHECK_EQUAL (result.why_, \"Success\");\r\n\r\n result = console->ExecuteCommand(\"Test_CommandB\");\r\n BOOST_CHECK_EQUAL (result.success_, false);\r\n BOOST_CHECK_EQUAL (result.why_.size(), 0);\r\n\r\n TestB testb;\r\n testb.fw_ = &fw;\r\n\r\n Core::Thread thread(boost::ref(testb));\r\n console->QueueCommand(\"Test CommandC\");\r\n thread.join();\r\n \r\n BOOST_CHECK_EQUAL (testb.test_var_, 1);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( support_modules_console_ogre )\r\n{\r\n Foundation::Framework &fw = CreateFramework();\r\n\r\n Console::ConsoleManager *console_manager = checked_static_cast(fw.GetService\r\n (Foundation::Service::ST_Console));\r\n\r\n Console::ConsolePtr ogre_console = console_manager->GetOgre();\r\n Console::OgreOverlay *overlay = checked_static_cast(ogre_console.get());\r\n \r\n overlay->SetVisible(true);\r\n BOOST_CHECK_EQUAL(overlay->IsVisible(), true);\r\n overlay->Update(60); \/\/ fast-forward one minute\r\n BOOST_CHECK_EQUAL(overlay->IsVisible(), true);\r\n BOOST_CHECK_EQUAL(overlay->IsActive(), true);\r\n\r\n \r\n overlay->Scroll(30000);\r\n overlay->Scroll(-30000);\r\n overlay->Scroll(300000);\r\n overlay->Scroll(-2);\r\n overlay->Scroll(1);\r\n overlay->Clear();\r\n overlay->Scroll(5);\r\n overlay->Scroll(-5);\r\n overlay->Print(\"Test message A\");\r\n overlay->Print(\"Test message B\");\r\n overlay->Print(\"Test message C\");\r\n BOOST_CHECK_EQUAL(overlay->GetLine(0), std::string(\"Test message C\"));\r\n BOOST_CHECK_EQUAL(overlay->GetLine(1), std::string(\"Test message B\"));\r\n BOOST_CHECK_EQUAL(overlay->GetLine(2), std::string(\"Test message A\"));\r\n\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"\"));\r\n\r\n overlay->HandleKeyDown(OIS::KC_A, 65);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"A\"));\r\n overlay->HandleKeyDown(OIS::KC_B, 66);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"AB\"));\r\n overlay->HandleKeyDown(OIS::KC_BACK, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"A\"));\r\n overlay->HandleKeyDown(OIS::KC_C, 67);\r\n overlay->HandleKeyDown(OIS::KC_RIGHT, 0);\r\n overlay->HandleKeyDown(OIS::KC_LEFT, 0);\r\n overlay->HandleKeyDown(OIS::KC_BACK, 0);\r\n overlay->HandleKeyDown(OIS::KC_DELETE, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"\"));\r\n\r\n overlay->HandleKeyDown(OIS::KC_A, 65);\r\n overlay->HandleKeyDown(OIS::KC_RETURN, 0);\r\n overlay->HandleKeyDown(OIS::KC_B, 66);\r\n overlay->HandleKeyDown(OIS::KC_RETURN, 0);\r\n overlay->HandleKeyDown(OIS::KC_C, 67);\r\n overlay->HandleKeyDown(OIS::KC_RETURN, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"\"));\r\n\r\n overlay->HandleKeyDown(OIS::KC_DOWN, 0);\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"C\"));\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n overlay->HandleKeyDown(OIS::KC_UP, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"A\"));\r\n overlay->HandleKeyDown(OIS::KC_DOWN, 0);\r\n BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(\"B\"));\r\n\r\n\r\n overlay->SetVisible(false);\r\n BOOST_CHECK_EQUAL(overlay->IsActive(), false);\r\n\r\n\r\n ogre_console.reset();\r\n fw.GetModuleManager()->UninitializeModules();\r\n fw.GetModuleManager()->UnloadModules();\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n<|endoftext|>"} {"text":"\/*\n * Copyright 2012 TennenColl\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 \"application_database.h\"\n#include \"application_gamemode_manager_dialog.h\"\n#include \"application_gamemode_manager_team.h\"\n#include \"application_gamemode_dialogdefinitions.h\"\n#include \"application_data_waypoint.h\"\n#include \"application_gamemode_colordefinitions.h\"\n#include \"application_gamemode_role_classes.h\"\n\n#define DIALOG(x) void Dlg##x(Profile& player, bool response, int listitem, const char* inputtext)\n\nDIALOG(SelectTeam) {\n\tif(player.GetTeamFixed() != TeamManager::GetInstance()[inputtext].GetIngameID()) {\n\t\tif(player.GetTeamFixed() != NO_TEAM)\n\t\t\tTeamManager::GetInstance()[TeamManager::GetInstance().GetNameByID(player.GetTeamFixed())].Quit(player);\n\t\tTeamManager::GetInstance()[inputtext].Join(player);\n\t}\n\tShowPlayerDialog(player.GetId(), DIALOG_ROLE_SELECT, DIALOG_STYLE_LIST, \"ѡְҵ\",\n\t\t\"Assault\\nMedic\\nMechanic\\nEngineer\", \"ȷ\", \"\");\n}\n\nDIALOG(SelectRole) {\n\tswitch(listitem) {\n\tcase 0:\n\t\tplayer.SetRole(Profile::RolePtr(new Assault(player)));\n\t\tbreak;\n\n\tcase 1:\n\t\tplayer.SetRole(Profile::RolePtr(new Medic(player)));\n\t\tbreak;\n\n\tcase 2:\n\t\tplayer.SetRole(Profile::RolePtr(new Mechanic(player)));\n\t\tbreak;\n\n\tcase 3:\n\t\tplayer.SetRole(Profile::RolePtr(new Engineer(player)));\n\t\tbreak;\n\t}\n\tplayer.Spawn();\n}\n\nDIALOG(Register) {\n\tif(inputtext[0] == 0) throw std::runtime_error(\"벻Ϊ\");\n\ttry {\n\t\tplayer.Create(player.GetName(), inputtext);\n\t\tplayer.SendChatMessage(COLOR_SUCC, \"עɹ\");\n\t\tplayer.SetSignedIn(true);\n\t} catch(std::runtime_error) {\n\t\tthrow;\n\t} catch(...) {\n\t\tthrow std::runtime_error(\"עʧ\");\n\t}\n}\n\nDIALOG(Login) {\n\tif(!player.AuthPassword(inputtext)) throw std::runtime_error(\"\");\n\tplayer.SetSignedIn(true);\n\tplayer.ApplyDataToPlayer();\n\tplayer.SendChatMessage(COLOR_SUCC, \"¼ɹ\");\n}\n\n#define REGDLG(x, y) DlgMgr.Add(x, y)\n\nbool RegisterPlayerDlgs() {\n\tDialogManager& DlgMgr = DialogManager::GetInstance();\n\tREGDLG(DIALOG_TEAM_SELECT,\t\t\tDlgSelectTeam);\n\tREGDLG(DIALOG_ROLE_SELECT,\t\t\tDlgSelectRole);\n\tREGDLG(DIALOG_PROFILE_REGISTER,\t\tDlgRegister);\n\tREGDLG(DIALOG_PROFILE_LOGIN,\t\tDlgLogin);\n\treturn true;\n}\n\n#undef REGDLG\n\nvoid* PlayerDlgInit((void*)RegisterPlayerDlgs());\n修正注册登录若失败不会重新ShowDialog的问题\/*\n * Copyright 2012 TennenColl\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 \"application_database.h\"\n#include \"application_gamemode_manager_dialog.h\"\n#include \"application_gamemode_manager_team.h\"\n#include \"application_gamemode_dialogdefinitions.h\"\n#include \"application_data_waypoint.h\"\n#include \"application_gamemode_colordefinitions.h\"\n#include \"application_gamemode_role_classes.h\"\n\n#define DIALOG(x) void Dlg##x(Profile& player, bool response, int listitem, const char* inputtext)\n\nDIALOG(SelectTeam) {\n\tif(player.GetTeamFixed() != TeamManager::GetInstance()[inputtext].GetIngameID()) {\n\t\tif(player.GetTeamFixed() != NO_TEAM)\n\t\t\tTeamManager::GetInstance()[TeamManager::GetInstance().GetNameByID(player.GetTeamFixed())].Quit(player);\n\t\tTeamManager::GetInstance()[inputtext].Join(player);\n\t}\n\tShowPlayerDialog(player.GetId(), DIALOG_ROLE_SELECT, DIALOG_STYLE_LIST, \"ѡְҵ\",\n\t\t\"Assault\\nMedic\\nMechanic\\nEngineer\", \"ȷ\", \"\");\n}\n\nDIALOG(SelectRole) {\n\tswitch(listitem) {\n\tcase 0:\n\t\tplayer.SetRole(Profile::RolePtr(new Assault(player)));\n\t\tbreak;\n\n\tcase 1:\n\t\tplayer.SetRole(Profile::RolePtr(new Medic(player)));\n\t\tbreak;\n\n\tcase 2:\n\t\tplayer.SetRole(Profile::RolePtr(new Mechanic(player)));\n\t\tbreak;\n\n\tcase 3:\n\t\tplayer.SetRole(Profile::RolePtr(new Engineer(player)));\n\t\tbreak;\n\t}\n\tplayer.Spawn();\n}\n\nDIALOG(Register) {\n\tif(inputtext[0] == 0) {\n\t\tplayer.SendChatMessage(COLOR_ERROR, \"벻Ϊ\");\n\t} else {\n\t\ttry {\n\t\t\tplayer.Create(player.GetName(), inputtext);\n\t\t\tplayer.SendChatMessage(COLOR_SUCC, \"עɹ\");\n\t\t\tplayer.SetSignedIn(true);\n\t\t\treturn;\n\t\t} catch(std::runtime_error& e) {\n\t\t\tplayer.SendChatMessage(COLOR_ERROR, e.what());\n\t\t} catch(...) {\n\t\t\tplayer.SendChatMessage(COLOR_ERROR, \"δ֪ԭעʧ, ϵԱ\");\n\t\t}\n\t}\n\tShowPlayerDialog(player.GetId(), DIALOG_PROFILE_REGISTER, DIALOG_STYLE_INPUT, \"ע\", \":\", \"ע\", \"\");\n}\n\nDIALOG(Login) {\n\tif(!player.AuthPassword(inputtext)) {\n\t\tShowPlayerDialog(player.GetId(), DIALOG_PROFILE_LOGIN, DIALOG_STYLE_INPUT, \"¼\", \"Ե¼:\", \"¼\", \"\");\n\t\tthrow std::runtime_error(\"\");\n\t}\n\tplayer.SetSignedIn(true);\n\tplayer.ApplyDataToPlayer();\n\tplayer.SendChatMessage(COLOR_SUCC, \"¼ɹ\");\n}\n\n#define REGDLG(x, y) DlgMgr.Add(x, y)\n\nbool RegisterPlayerDlgs() {\n\tDialogManager& DlgMgr = DialogManager::GetInstance();\n\tREGDLG(DIALOG_TEAM_SELECT,\t\t\tDlgSelectTeam);\n\tREGDLG(DIALOG_ROLE_SELECT,\t\t\tDlgSelectRole);\n\tREGDLG(DIALOG_PROFILE_REGISTER,\t\tDlgRegister);\n\tREGDLG(DIALOG_PROFILE_LOGIN,\t\tDlgLogin);\n\treturn true;\n}\n\n#undef REGDLG\n\nvoid* PlayerDlgInit((void*)RegisterPlayerDlgs());\n<|endoftext|>"} {"text":"\/*!\r\n * \\file dcxdivider.cpp\r\n * \\brief blah\r\n *\r\n * blah\r\n *\r\n * \\author David Legault ( clickhere at scriptsdb dot org )\r\n * \\version 1.0\r\n *\r\n * \\b Revisions\r\n *\r\n * ScriptsDB.org - 2006\r\n *\/\r\n\r\n#include \"dcxdivider.h\"\r\n#include \"dcxdialog.h\"\r\n\r\n\/*!\r\n * \\brief Constructor\r\n *\r\n * \\param ID Control ID\r\n * \\param p_Dialog Parent DcxDialog Object\r\n * \\param mParentHwnd Parent Window Handle\r\n * \\param rc Window Rectangle\r\n * \\param styles Window Style Tokenized List\r\n *\/\r\n\r\nDcxDivider::DcxDivider( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )\r\n: DcxControl( ID, p_Dialog )\r\n{\r\n\tLONG Styles = 0, ExStyles = 0;\r\n\tBOOL bNoTheme = FALSE;\r\n\tthis->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );\r\n\r\n\tthis->m_Hwnd = CreateWindowEx(\t\r\n\t\tExStyles | WS_EX_CONTROLPARENT, \r\n\t\tDCX_DIVIDERCLASS, \r\n\t\tNULL,\r\n\t\tWS_CHILD | Styles, \r\n\t\trc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,\r\n\t\tmParentHwnd,\r\n\t\t(HMENU) ID,\r\n\t\tGetModuleHandle(NULL), \r\n\t\tNULL);\r\n\r\n\tif (!IsWindow(this->m_Hwnd))\r\n\t\tthrow \"Unable To Create Window\";\r\n\r\n\tif ( bNoTheme )\r\n\t\tdcxSetWindowTheme( this->m_Hwnd , L\" \", L\" \" );\r\n\r\n\tthis->registreDefaultWindowProc( );\r\n\tSetProp( this->m_Hwnd, \"dcx_cthis\", (HANDLE) this );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nDcxDivider::~DcxDivider( ) {\r\n\r\n this->unregistreDefaultWindowProc( );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nTString DcxDivider::getStyles(void) {\r\n\tTString styles;\r\n\tLONG Styles;\r\n\tStyles = GetWindowLong(this->m_Hwnd, GWL_STYLE);\r\n\tstyles = __super::getStyles();\r\n\tif (Styles & DVS_VERT)\r\n\t\tstyles.addtok(\"vertical\", \" \");\r\n\treturn styles;\r\n}\r\n\r\n\r\nvoid DcxDivider::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {\r\n\r\n\tunsigned int i = 1, numtok = styles.numtok( );\r\n\t*Styles |= DVS_HORZ;\r\n\r\n\twhile ( i <= numtok ) {\r\n\r\n\t\tif ( styles.gettok( i ) == \"vertical\" )\r\n\t\t\t*Styles |= DVS_VERT;\r\n\r\n\t\ti++;\r\n\t}\r\n\tthis->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme );\r\n}\r\n\r\n\/*!\r\n * \\brief $xdid Parsing Function\r\n *\r\n * \\param input [NAME] [ID] [PROP] (OPTIONS)\r\n * \\param szReturnValue mIRC Data Container\r\n *\r\n * \\return > void\r\n *\/\r\n\r\nvoid DcxDivider::parseInfoRequest( TString & input, char * szReturnValue ) {\r\n\r\n \/\/int numtok = input.numtok( );\r\n TString prop = input.gettok(3);\r\n\r\n \/\/ [NAME] [ID] [PROP]\r\n if (prop == \"position\") {\r\n int iDivPos = 0;\r\n\r\n SendMessage(this->m_Hwnd, DV_GETDIVPOS, (WPARAM) NULL, (LPARAM) &iDivPos);\r\n wsprintf(szReturnValue, \"%d\", iDivPos);\r\n return;\r\n }\r\n else if (prop == \"isvertical\") {\r\n wsprintf(szReturnValue, \"%d\", (GetWindowLong(this->m_Hwnd, GWL_STYLE) & DVS_VERT));\r\n return;\r\n }\r\n\r\n if ( this->parseGlobalInfoRequest( input, szReturnValue ) )\r\n return;\r\n \r\n szReturnValue[0] = 0;\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nvoid DcxDivider::parseCommandRequest( TString & input ) {\r\n XSwitchFlags flags(input.gettok(3));\r\n\r\n int numtok = input.numtok( );\r\n\r\n \/\/ xdid -l|r [NAME] [ID] [SWITCH] [MIN] [IDEAL][TAB][ID] [CONTROL] [X] [Y] [W] [H] (OPTIONS)\r\n if ( ( flags['l'] || flags['r'] )&& numtok > 9 ) {\r\n\r\n DVPANEINFO dvpi;\r\n ZeroMemory( &dvpi, sizeof( DVPANEINFO ) );\r\n dvpi.cbSize = sizeof( DVPANEINFO );\r\n\r\n TString data(input.gettok(1, TSTAB).trim());\r\n TString control_data;\r\n\r\n if ( input.numtok( TSTAB ) > 1 )\r\n control_data = input.gettok(2, TSTAB).trim();\r\n\r\n dvpi.fMask = DVPIM_CHILD | DVPIM_MIN | DVPIM_IDEAL;\r\n dvpi.cxMin = data.gettok( 4 ).to_int( );\r\n dvpi.cxIdeal = data.gettok( 5 ).to_int( );\r\n\r\n if ( control_data.numtok( ) > 5 ) {\r\n\r\n UINT ID = mIRC_ID_OFFSET + control_data.gettok( 1 ).to_int( );\r\n\r\n if ( ID > mIRC_ID_OFFSET - 1 && \r\n !IsWindow( GetDlgItem( this->m_pParentDialog->getHwnd( ), ID ) ) && \r\n this->m_pParentDialog->getControlByID( ID ) == NULL ) \r\n {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tDcxControl * p_Control = DcxControl::controlFactory(this->m_pParentDialog,ID,control_data,2,\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_PBAR|CTLF_ALLOW_TRACKBAR|CTLF_ALLOW_COMBOEX|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_COLORCOMBO|CTLF_ALLOW_STATUSBAR|CTLF_ALLOW_TOOLBAR|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_TREEVIEW|CTLF_ALLOW_LISTVIEW|CTLF_ALLOW_REBAR|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_BUTTON|CTLF_ALLOW_RICHEDIT|CTLF_ALLOW_EDIT|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_UPDOWN| CTLF_ALLOW_IPADDRESS|CTLF_ALLOW_WEBCTRL|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_CALANDER|CTLF_ALLOW_DIVIDER|CTLF_ALLOW_PANEL|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_TAB|CTLF_ALLOW_LINE|CTLF_ALLOW_BOX|CTLF_ALLOW_RADIO|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_CHECK|CTLF_ALLOW_TEXT|CTLF_ALLOW_SCROLL|CTLF_ALLOW_LIST|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_LINK|CTLF_ALLOW_IMAGE|CTLF_ALLOW_PAGER|CTLF_ALLOW_DATETIME|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_STACKER|CTLF_ALLOW_DIRECTSHOW\r\n\t\t\t\t\t\t,this->m_Hwnd);\r\n\r\n\t\t\t\t\tif ( p_Control != NULL ) {\r\n\r\n\t\t\t\t\t\tthis->m_pParentDialog->addControl( p_Control );\r\n\r\n\t\t\t\t\t\tdvpi.hChild = p_Control->getHwnd( );\r\n\r\n\t\t\t\t\t\tif ( flags['l'] )\r\n\t\t\t\t\t\t\tthis->setPane( DVF_PANELEFT, &dvpi );\r\n\t\t\t\t\t\telse if ( flags['r'] )\r\n\t\t\t\t\t\t\tthis->setPane( DVF_PANERIGHT, &dvpi );\r\n\r\n\t\t\t\t\t\tthis->redrawWindow( );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch ( char *err ) {\r\n\t\t\t\t\tthis->showErrorEx(NULL, \"-l|r\", \"Unable To Create Control %d (%s)\", ID - mIRC_ID_OFFSET, err);\r\n\t\t\t\t}\r\n }\r\n else\r\n\t\t\t\tthis->showErrorEx(NULL, \"-l|r\", \"Control with ID \\\"%d\\\" already exists\", ID - mIRC_ID_OFFSET );\r\n }\r\n }\r\n \/\/ xdid -v [NAME] [ID] [SWITCH] [POS]\r\n else if (flags['v'] && numtok > 3) {\r\n if (!this->setDivPos(input.gettok(4).to_int())) {\r\n this->showError(NULL, \"-v\", \"Divider position must be between bounds.\");\r\n }\r\n }\r\n else\r\n this->parseGlobalCommandRequest( input, flags );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nLRESULT DcxDivider::setPane( const UINT iPaneId, LPDVPANEINFO lpdvpi ) {\r\n return SendMessage( this->m_Hwnd, DV_SETPANE, (WPARAM) iPaneId, (LPARAM) lpdvpi );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nLRESULT DcxDivider::setDivPos( const UINT iDivPos ) {\r\n return SendMessage( this->m_Hwnd, DV_SETDIVPOS, (WPARAM) 0, (LPARAM) iDivPos );\r\n}\r\n\r\nvoid DcxDivider::toXml(TiXmlElement * xml) {\r\n\t__super::toXml(xml);\r\n\tDVPANEINFO left;\r\n\tDVPANEINFO right;\r\n\tDcxControl * dcxcleft = NULL;\r\n\tDcxControl * dcxcright = NULL;\r\n\tDivider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &left);\r\n\tDivider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &right);\r\n\tif (left.hChild != NULL) {\r\n\t\tdcxcleft = this->m_pParentDialog->getControlByHWND(left.hChild);\r\n\t\tif (dcxcleft != NULL)\r\n\t\t\txml->LinkEndChild(dcxcleft->toXml());\r\n\t\telse\r\n\t\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n\telse {\r\n\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n\tif (right.hChild != NULL) {\r\n\t\tdcxcright = this->m_pParentDialog->getControlByHWND(right.hChild);\r\n\t\tif (dcxcright != NULL)\r\n\t\t\txml->LinkEndChild(dcxcright->toXml());\r\n\t\telse\r\n\t\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n\telse {\r\n\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\nLRESULT DcxDivider::ParentMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {\r\n\treturn 0L;\r\n}\r\n\r\nLRESULT DcxDivider::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {\r\n\r\n\tLRESULT lRes = 0L;\r\n switch( uMsg ) {\r\n\r\n case WM_NOTIFY : \r\n {\r\n LPNMHDR hdr = (LPNMHDR) lParam;\r\n\r\n if (!hdr)\r\n break;\r\n\r\n\t\t\t\tif (IsWindow(hdr->hwndFrom)) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(hdr->hwndFrom,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_HSCROLL: \r\n case WM_VSCROLL: \r\n case WM_COMMAND:\r\n {\r\n\t\t\t\tif (IsWindow((HWND) lParam)) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp((HWND) lParam,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_DELETEITEM:\r\n {\r\n\t\t\t\tDELETEITEMSTRUCT *idata = (DELETEITEMSTRUCT *)lParam;\r\n\t\t\t\tif ((idata != NULL) && (IsWindow(idata->hwndItem))) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_MEASUREITEM:\r\n {\r\n\t\t\t\tHWND cHwnd = GetDlgItem(this->m_Hwnd, wParam);\r\n\t\t\t\tif (IsWindow(cHwnd)) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(cHwnd,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_DRAWITEM:\r\n {\r\n\t\t\t\tDRAWITEMSTRUCT *idata = (DRAWITEMSTRUCT *)lParam;\r\n\t\t\t\tif ((idata != NULL) && (IsWindow(idata->hwndItem))) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_DESTROY:\r\n {\r\n delete this;\r\n bParsed = TRUE;\r\n }\r\n break;\r\n\r\n case DV_CHANGEPOS:\r\n {\r\n int phase = (int) wParam;\r\n LPPOINT pt = (LPPOINT) lParam;\r\n TString tsPhase = (phase == DVNM_DRAG_START ? \"dragbegin\" : (phase == DVNM_DRAG_END ? \"dragfinish\" : \"drag\"));\r\n\r\n this->execAliasEx(\"%s,%d,%d,%d\", tsPhase.to_chr(), this->getUserID(), pt->x, pt->y);\r\n break;\r\n }\r\n\r\n default:\r\n return this->CommonMessage( uMsg, wParam, lParam, bParsed);\r\n break;\r\n }\r\n\r\n return lRes;\r\n}\r\n[divider] - changed some error msgs to use this->getUserID()\/*!\r\n * \\file dcxdivider.cpp\r\n * \\brief blah\r\n *\r\n * blah\r\n *\r\n * \\author David Legault ( clickhere at scriptsdb dot org )\r\n * \\version 1.0\r\n *\r\n * \\b Revisions\r\n *\r\n * ScriptsDB.org - 2006\r\n *\/\r\n\r\n#include \"dcxdivider.h\"\r\n#include \"dcxdialog.h\"\r\n\r\n\/*!\r\n * \\brief Constructor\r\n *\r\n * \\param ID Control ID\r\n * \\param p_Dialog Parent DcxDialog Object\r\n * \\param mParentHwnd Parent Window Handle\r\n * \\param rc Window Rectangle\r\n * \\param styles Window Style Tokenized List\r\n *\/\r\n\r\nDcxDivider::DcxDivider( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )\r\n: DcxControl( ID, p_Dialog )\r\n{\r\n\tLONG Styles = 0, ExStyles = 0;\r\n\tBOOL bNoTheme = FALSE;\r\n\tthis->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );\r\n\r\n\tthis->m_Hwnd = CreateWindowEx(\t\r\n\t\tExStyles | WS_EX_CONTROLPARENT, \r\n\t\tDCX_DIVIDERCLASS, \r\n\t\tNULL,\r\n\t\tWS_CHILD | Styles, \r\n\t\trc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,\r\n\t\tmParentHwnd,\r\n\t\t(HMENU) ID,\r\n\t\tGetModuleHandle(NULL), \r\n\t\tNULL);\r\n\r\n\tif (!IsWindow(this->m_Hwnd))\r\n\t\tthrow \"Unable To Create Window\";\r\n\r\n\tif ( bNoTheme )\r\n\t\tdcxSetWindowTheme( this->m_Hwnd , L\" \", L\" \" );\r\n\r\n\tthis->registreDefaultWindowProc( );\r\n\tSetProp( this->m_Hwnd, \"dcx_cthis\", (HANDLE) this );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nDcxDivider::~DcxDivider( ) {\r\n\r\n this->unregistreDefaultWindowProc( );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nTString DcxDivider::getStyles(void) {\r\n\tTString styles;\r\n\tLONG Styles;\r\n\tStyles = GetWindowLong(this->m_Hwnd, GWL_STYLE);\r\n\tstyles = __super::getStyles();\r\n\tif (Styles & DVS_VERT)\r\n\t\tstyles.addtok(\"vertical\", \" \");\r\n\treturn styles;\r\n}\r\n\r\n\r\nvoid DcxDivider::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {\r\n\r\n\tunsigned int i = 1, numtok = styles.numtok( );\r\n\t*Styles |= DVS_HORZ;\r\n\r\n\twhile ( i <= numtok ) {\r\n\r\n\t\tif ( styles.gettok( i ) == \"vertical\" )\r\n\t\t\t*Styles |= DVS_VERT;\r\n\r\n\t\ti++;\r\n\t}\r\n\tthis->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme );\r\n}\r\n\r\n\/*!\r\n * \\brief $xdid Parsing Function\r\n *\r\n * \\param input [NAME] [ID] [PROP] (OPTIONS)\r\n * \\param szReturnValue mIRC Data Container\r\n *\r\n * \\return > void\r\n *\/\r\n\r\nvoid DcxDivider::parseInfoRequest( TString & input, char * szReturnValue ) {\r\n\r\n \/\/int numtok = input.numtok( );\r\n TString prop = input.gettok(3);\r\n\r\n \/\/ [NAME] [ID] [PROP]\r\n if (prop == \"position\") {\r\n int iDivPos = 0;\r\n\r\n SendMessage(this->m_Hwnd, DV_GETDIVPOS, (WPARAM) NULL, (LPARAM) &iDivPos);\r\n wsprintf(szReturnValue, \"%d\", iDivPos);\r\n return;\r\n }\r\n else if (prop == \"isvertical\") {\r\n wsprintf(szReturnValue, \"%d\", (GetWindowLong(this->m_Hwnd, GWL_STYLE) & DVS_VERT));\r\n return;\r\n }\r\n\r\n if ( this->parseGlobalInfoRequest( input, szReturnValue ) )\r\n return;\r\n \r\n szReturnValue[0] = 0;\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nvoid DcxDivider::parseCommandRequest( TString & input ) {\r\n XSwitchFlags flags(input.gettok(3));\r\n\r\n int numtok = input.numtok( );\r\n\r\n \/\/ xdid -l|r [NAME] [ID] [SWITCH] [MIN] [IDEAL][TAB][ID] [CONTROL] [X] [Y] [W] [H] (OPTIONS)\r\n if ( ( flags['l'] || flags['r'] )&& numtok > 9 ) {\r\n\r\n DVPANEINFO dvpi;\r\n ZeroMemory( &dvpi, sizeof( DVPANEINFO ) );\r\n dvpi.cbSize = sizeof( DVPANEINFO );\r\n\r\n TString data(input.gettok(1, TSTAB).trim());\r\n TString control_data;\r\n\r\n if ( input.numtok( TSTAB ) > 1 )\r\n control_data = input.gettok(2, TSTAB).trim();\r\n\r\n dvpi.fMask = DVPIM_CHILD | DVPIM_MIN | DVPIM_IDEAL;\r\n dvpi.cxMin = data.gettok( 4 ).to_int( );\r\n dvpi.cxIdeal = data.gettok( 5 ).to_int( );\r\n\r\n if ( control_data.numtok( ) > 5 ) {\r\n\r\n UINT ID = mIRC_ID_OFFSET + control_data.gettok( 1 ).to_int( );\r\n\r\n if ( ID > mIRC_ID_OFFSET - 1 && \r\n !IsWindow( GetDlgItem( this->m_pParentDialog->getHwnd( ), ID ) ) && \r\n this->m_pParentDialog->getControlByID( ID ) == NULL ) \r\n {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tDcxControl * p_Control = DcxControl::controlFactory(this->m_pParentDialog,ID,control_data,2,\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_PBAR|CTLF_ALLOW_TRACKBAR|CTLF_ALLOW_COMBOEX|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_COLORCOMBO|CTLF_ALLOW_STATUSBAR|CTLF_ALLOW_TOOLBAR|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_TREEVIEW|CTLF_ALLOW_LISTVIEW|CTLF_ALLOW_REBAR|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_BUTTON|CTLF_ALLOW_RICHEDIT|CTLF_ALLOW_EDIT|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_UPDOWN| CTLF_ALLOW_IPADDRESS|CTLF_ALLOW_WEBCTRL|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_CALANDER|CTLF_ALLOW_DIVIDER|CTLF_ALLOW_PANEL|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_TAB|CTLF_ALLOW_LINE|CTLF_ALLOW_BOX|CTLF_ALLOW_RADIO|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_CHECK|CTLF_ALLOW_TEXT|CTLF_ALLOW_SCROLL|CTLF_ALLOW_LIST|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_LINK|CTLF_ALLOW_IMAGE|CTLF_ALLOW_PAGER|CTLF_ALLOW_DATETIME|\r\n\t\t\t\t\t\t\t\t\t\t CTLF_ALLOW_STACKER|CTLF_ALLOW_DIRECTSHOW\r\n\t\t\t\t\t\t,this->m_Hwnd);\r\n\r\n\t\t\t\t\tif ( p_Control != NULL ) {\r\n\r\n\t\t\t\t\t\tthis->m_pParentDialog->addControl( p_Control );\r\n\r\n\t\t\t\t\t\tdvpi.hChild = p_Control->getHwnd( );\r\n\r\n\t\t\t\t\t\tif ( flags['l'] )\r\n\t\t\t\t\t\t\tthis->setPane( DVF_PANELEFT, &dvpi );\r\n\t\t\t\t\t\telse if ( flags['r'] )\r\n\t\t\t\t\t\t\tthis->setPane( DVF_PANERIGHT, &dvpi );\r\n\r\n\t\t\t\t\t\tthis->redrawWindow( );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch ( char *err ) {\r\n\t\t\t\t\tthis->showErrorEx(NULL, \"-l|r\", \"Unable To Create Control %d (%s)\", this->getUserID(), err);\r\n\t\t\t\t}\r\n }\r\n else\r\n\t\t\t\tthis->showErrorEx(NULL, \"-l|r\", \"Control with ID \\\"%d\\\" already exists\", this->getUserID());\r\n }\r\n }\r\n \/\/ xdid -v [NAME] [ID] [SWITCH] [POS]\r\n else if (flags['v'] && numtok > 3) {\r\n if (!this->setDivPos(input.gettok(4).to_int())) {\r\n this->showError(NULL, \"-v\", \"Divider position must be between bounds.\");\r\n }\r\n }\r\n else\r\n this->parseGlobalCommandRequest( input, flags );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nLRESULT DcxDivider::setPane( const UINT iPaneId, LPDVPANEINFO lpdvpi ) {\r\n return SendMessage( this->m_Hwnd, DV_SETPANE, (WPARAM) iPaneId, (LPARAM) lpdvpi );\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\n\r\nLRESULT DcxDivider::setDivPos( const UINT iDivPos ) {\r\n return SendMessage( this->m_Hwnd, DV_SETDIVPOS, (WPARAM) 0, (LPARAM) iDivPos );\r\n}\r\n\r\nvoid DcxDivider::toXml(TiXmlElement * xml) {\r\n\t__super::toXml(xml);\r\n\tDVPANEINFO left;\r\n\tDVPANEINFO right;\r\n\tDcxControl * dcxcleft = NULL;\r\n\tDcxControl * dcxcright = NULL;\r\n\tDivider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &left);\r\n\tDivider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &right);\r\n\tif (left.hChild != NULL) {\r\n\t\tdcxcleft = this->m_pParentDialog->getControlByHWND(left.hChild);\r\n\t\tif (dcxcleft != NULL)\r\n\t\t\txml->LinkEndChild(dcxcleft->toXml());\r\n\t\telse\r\n\t\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n\telse {\r\n\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n\tif (right.hChild != NULL) {\r\n\t\tdcxcright = this->m_pParentDialog->getControlByHWND(right.hChild);\r\n\t\tif (dcxcright != NULL)\r\n\t\t\txml->LinkEndChild(dcxcright->toXml());\r\n\t\telse\r\n\t\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n\telse {\r\n\t\txml->LinkEndChild(new TiXmlElement(\"control\"));\r\n\t}\r\n}\r\n\r\n\/*!\r\n * \\brief blah\r\n *\r\n * blah\r\n *\/\r\nLRESULT DcxDivider::ParentMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {\r\n\treturn 0L;\r\n}\r\n\r\nLRESULT DcxDivider::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {\r\n\r\n\tLRESULT lRes = 0L;\r\n switch( uMsg ) {\r\n\r\n case WM_NOTIFY : \r\n {\r\n LPNMHDR hdr = (LPNMHDR) lParam;\r\n\r\n if (!hdr)\r\n break;\r\n\r\n\t\t\t\tif (IsWindow(hdr->hwndFrom)) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(hdr->hwndFrom,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_HSCROLL: \r\n case WM_VSCROLL: \r\n case WM_COMMAND:\r\n {\r\n\t\t\t\tif (IsWindow((HWND) lParam)) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp((HWND) lParam,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_DELETEITEM:\r\n {\r\n\t\t\t\tDELETEITEMSTRUCT *idata = (DELETEITEMSTRUCT *)lParam;\r\n\t\t\t\tif ((idata != NULL) && (IsWindow(idata->hwndItem))) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_MEASUREITEM:\r\n {\r\n\t\t\t\tHWND cHwnd = GetDlgItem(this->m_Hwnd, wParam);\r\n\t\t\t\tif (IsWindow(cHwnd)) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(cHwnd,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_DRAWITEM:\r\n {\r\n\t\t\t\tDRAWITEMSTRUCT *idata = (DRAWITEMSTRUCT *)lParam;\r\n\t\t\t\tif ((idata != NULL) && (IsWindow(idata->hwndItem))) {\r\n\t\t\t\t\tDcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,\"dcx_cthis\");\r\n\t\t\t\t\tif (c_this != NULL) {\r\n\t\t\t\t\t\tlRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n }\r\n break;\r\n\r\n case WM_DESTROY:\r\n {\r\n delete this;\r\n bParsed = TRUE;\r\n }\r\n break;\r\n\r\n case DV_CHANGEPOS:\r\n {\r\n int phase = (int) wParam;\r\n LPPOINT pt = (LPPOINT) lParam;\r\n TString tsPhase = (phase == DVNM_DRAG_START ? \"dragbegin\" : (phase == DVNM_DRAG_END ? \"dragfinish\" : \"drag\"));\r\n\r\n this->execAliasEx(\"%s,%d,%d,%d\", tsPhase.to_chr(), this->getUserID(), pt->x, pt->y);\r\n break;\r\n }\r\n\r\n default:\r\n return this->CommonMessage( uMsg, wParam, lParam, bParsed);\r\n break;\r\n }\r\n\r\n return lRes;\r\n}\r\n<|endoftext|>"} {"text":"#include \"LinearImage.h\"\r\n\r\n\r\nLinearImage::LinearImage( const size_t width, const size_t height, const bool hasAlpha, const unsigned char* data, const float gamma )\r\n : mWidth( width ), mHeight( height )\r\n{\r\n InitTables( gamma );\r\n\r\n \/\/ allocate channels\r\n mChannels.resize( hasAlpha ? 4 : 3 );\r\n for( Channel& channel : mChannels )\r\n {\r\n channel.resize( mWidth * mHeight );\r\n }\r\n\r\n if( NULL == data )\r\n {\r\n return;\r\n }\r\n\r\n \/\/ convert to linear color\r\n const size_t srcPitch = mWidth * 3;\r\n const unsigned char* srcBytes = data;\r\n for( size_t y = 0; y < (size_t)mHeight; ++y )\r\n {\r\n const size_t dstRow = y * mWidth;\r\n const unsigned char* srcRow = &srcBytes[ y * srcPitch ];\r\n for( size_t x = 0; x < (size_t)mWidth; ++x )\r\n {\r\n for( size_t c = 0; c < 3; ++c )\r\n {\r\n mChannels[ c ][ dstRow + x ] = mSrgbToLinear[ srcRow[ x * 3 + c ] ];\r\n }\r\n if( hasAlpha )\r\n {\r\n mChannels[ 3 ][ dstRow + x ] = srcRow[ x * 3 + 3 ] * ( 1.0f \/ 255.0f );\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid LinearImage::GetSrgb( std::vector< unsigned char >& color, std::vector< unsigned char >& alpha ) const\r\n{\r\n color.resize( mWidth * mHeight * 3 );\r\n for( size_t i = 0; i < mWidth * mHeight; ++i )\r\n {\r\n for( size_t c = 0; c < 3; ++c )\r\n {\r\n int j = static_cast< int >( mLinearToSrgb.size() * mChannels[ c ][ i ] + 0.5f );\r\n if( j < 0 ) j = 0;\r\n \/\/ TODO: figure out signed issues\r\n if( j >= (int)mLinearToSrgb.size() ) j = (int)( mLinearToSrgb.size() - 1 );\r\n color[ i * 3 + c ] = mLinearToSrgb[ j ];\r\n }\r\n }\r\n\r\n alpha.resize( 0 );\r\n if( mChannels.size() == 4 )\r\n {\r\n alpha.resize( mWidth * mHeight );\r\n for( size_t i = 0; i < mWidth * mHeight; ++i )\r\n {\r\n int j = static_cast< int >( 255.0f * mChannels[ 3 ][ i ] + 0.5f );\r\n if( j < 0 ) j = 0;\r\n if( j >= 255 ) j = 255;\r\n alpha[ i ] = static_cast< unsigned char >( j );\r\n }\r\n }\r\n}\r\n\r\n\r\nconst float* LinearImage::GetRow( const size_t channel, const size_t row ) const\r\n{\r\n if( channel > mChannels.size() || row >= mHeight )\r\n return NULL;\r\n return &mChannels[ channel ][ mWidth * row ];\r\n}\r\n\r\n\r\nfloat* LinearImage::GetRow( const size_t channel, const size_t row )\r\n{\r\n return const_cast< float* >( static_cast< const LinearImage& >( *this ).GetRow( channel, row ) );\r\n}\r\n\r\n\r\nvoid LinearImage::InitTables( const float gamma )\r\n{\r\n mSrgbToLinear.resize( 256 );\r\n for( size_t i = 0; i < mSrgbToLinear.size(); ++i )\r\n {\r\n mSrgbToLinear[ i ] = pow( i \/ 255.0f, gamma );\r\n }\r\n\r\n mLinearToSrgb.resize( 4096 );\r\n const float invSize = 1.0f \/ mLinearToSrgb.size();\r\n const float invGamma = 1.0f \/ gamma;\r\n for( size_t i = 0; i < mLinearToSrgb.size(); ++i )\r\n {\r\n int k = static_cast< int >( 255.0f * pow( i * invSize, invGamma ) + 0.5f );\r\n if( k < 0 ) k = 0;\r\n if( k > 255 ) k = 255;\r\n mLinearToSrgb[ i ] = static_cast< unsigned char >( k );\r\n }\r\n}Add #include \"LinearImage.h\"\r\n#include \r\n\r\nLinearImage::LinearImage( const size_t width, const size_t height, const bool hasAlpha, const unsigned char* data, const float gamma )\r\n : mWidth( width ), mHeight( height )\r\n{\r\n InitTables( gamma );\r\n\r\n \/\/ allocate channels\r\n mChannels.resize( hasAlpha ? 4 : 3 );\r\n for( Channel& channel : mChannels )\r\n {\r\n channel.resize( mWidth * mHeight );\r\n }\r\n\r\n if( NULL == data )\r\n {\r\n return;\r\n }\r\n\r\n \/\/ convert to linear color\r\n const size_t srcPitch = mWidth * 3;\r\n const unsigned char* srcBytes = data;\r\n for( size_t y = 0; y < (size_t)mHeight; ++y )\r\n {\r\n const size_t dstRow = y * mWidth;\r\n const unsigned char* srcRow = &srcBytes[ y * srcPitch ];\r\n for( size_t x = 0; x < (size_t)mWidth; ++x )\r\n {\r\n for( size_t c = 0; c < 3; ++c )\r\n {\r\n mChannels[ c ][ dstRow + x ] = mSrgbToLinear[ srcRow[ x * 3 + c ] ];\r\n }\r\n if( hasAlpha )\r\n {\r\n mChannels[ 3 ][ dstRow + x ] = srcRow[ x * 3 + 3 ] * ( 1.0f \/ 255.0f );\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid LinearImage::GetSrgb( std::vector< unsigned char >& color, std::vector< unsigned char >& alpha ) const\r\n{\r\n color.resize( mWidth * mHeight * 3 );\r\n for( size_t i = 0; i < mWidth * mHeight; ++i )\r\n {\r\n for( size_t c = 0; c < 3; ++c )\r\n {\r\n int j = static_cast< int >( mLinearToSrgb.size() * mChannels[ c ][ i ] + 0.5f );\r\n if( j < 0 ) j = 0;\r\n \/\/ TODO: figure out signed issues\r\n if( j >= (int)mLinearToSrgb.size() ) j = (int)( mLinearToSrgb.size() - 1 );\r\n color[ i * 3 + c ] = mLinearToSrgb[ j ];\r\n }\r\n }\r\n\r\n alpha.resize( 0 );\r\n if( mChannels.size() == 4 )\r\n {\r\n alpha.resize( mWidth * mHeight );\r\n for( size_t i = 0; i < mWidth * mHeight; ++i )\r\n {\r\n int j = static_cast< int >( 255.0f * mChannels[ 3 ][ i ] + 0.5f );\r\n if( j < 0 ) j = 0;\r\n if( j >= 255 ) j = 255;\r\n alpha[ i ] = static_cast< unsigned char >( j );\r\n }\r\n }\r\n}\r\n\r\n\r\nconst float* LinearImage::GetRow( const size_t channel, const size_t row ) const\r\n{\r\n if( channel > mChannels.size() || row >= mHeight )\r\n return NULL;\r\n return &mChannels[ channel ][ mWidth * row ];\r\n}\r\n\r\n\r\nfloat* LinearImage::GetRow( const size_t channel, const size_t row )\r\n{\r\n return const_cast< float* >( static_cast< const LinearImage& >( *this ).GetRow( channel, row ) );\r\n}\r\n\r\n\r\nvoid LinearImage::InitTables( const float gamma )\r\n{\r\n mSrgbToLinear.resize( 256 );\r\n for( size_t i = 0; i < mSrgbToLinear.size(); ++i )\r\n {\r\n mSrgbToLinear[ i ] = pow( i \/ 255.0f, gamma );\r\n }\r\n\r\n mLinearToSrgb.resize( 4096 );\r\n const float invSize = 1.0f \/ mLinearToSrgb.size();\r\n const float invGamma = 1.0f \/ gamma;\r\n for( size_t i = 0; i < mLinearToSrgb.size(); ++i )\r\n {\r\n int k = static_cast< int >( 255.0f * pow( i * invSize, invGamma ) + 0.5f );\r\n if( k < 0 ) k = 0;\r\n if( k > 255 ) k = 255;\r\n mLinearToSrgb[ i ] = static_cast< unsigned char >( k );\r\n }\r\n}\r\n<|endoftext|>"} {"text":"{\n\n cout << \"Loading libraries ...\" << endl;\n gROOT->LoadMacro(\"${ALICE_ROOT}\/MUON\/loadlibs.C\");\n gInterpreter->ProcessLine(\"loadlibs()\");\n \n TString includePath = \"-I${ROOTSYS}\/include \";\n includePath += \"-I${ALICE_ROOT}\/STEER\/STEER \";\n includePath += \"-I${ALICE_ROOT}\/STEER\/STEERBase \";\n includePath += \"-I${ALICE_BUILD}\/include \";\n includePath += \"-I${ALICE_ROOT}\/RAW \";\n includePath += \"-I${ALICE_ROOT}\/FASTSIM \";\n includePath += \"-I${ALICE_ROOT}\/EVGEN \";\n includePath += \"-I${ALICE_ROOT}\/SHUTTLE\/TestShuttle \";\n includePath += \"-I${ALICE_ROOT}\/ITS \";\n includePath += \"-I${ALICE_ROOT}\/MUON \";\n includePath += \"-I${ALICE_ROOT}\/MFT \";\n includePath += \"-I${ALICE_ROOT}\/MUON\/mapping \";\n includePath += \"-I${ALICE_ROOT}\/RAW \";\n includePath += \"-I${ALICE_ROOT}\/CORRFW \";\n includePath += \"-I${ROOTSYS}\/net\/alien\/inc \";\n gSystem->SetIncludePath(includePath.Data());\n \n gSystem->Load(\"libCore.so\"); \n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libPhysics.so\");\n gSystem->Load(\"libSTEERBase\");\n gSystem->Load(\"libESD\");\n gSystem->Load(\"libAOD\");\n gSystem->Load(\"libANALYSIS\") ;\n gSystem->Load(\"libANALYSISalice\") ;\n gSystem->Load(\"libCORRFW\") ;\n gSystem->Load(\"libMFTbase\") ;\n gSystem->Load(\"libMFTsim\") ;\n gSystem->Load(\"libMFTrec\") ;\n \n \/\/================= define the style =================== \/\/\n \n \/\/ divisions: axis marks outside the figure (minus sign)\n gStyle->SetTickLength(-0.03,\"X\"); gStyle->SetTickLength(-0.03,\"Y\"); \n gStyle->SetNdivisions(508,\"X\"); gStyle->SetNdivisions(506,\"Y\"); \/\/ set ndvx (y)\n \n \/\/ dimensions and position of fonts connected to axes \n gStyle->SetLabelSize(0.05,\"X\"); gStyle->SetLabelSize(0.05,\"Y\"); \n gStyle->SetLabelOffset(0.02,\"X\"); gStyle->SetLabelOffset(0.04,\"Y\"); \n \n \/\/ dimension of the canvas and of the figure (pad) inside it\n gStyle->SetCanvasDefW(600); gStyle->SetCanvasDefH(600);\n gStyle->SetPadBottomMargin(0.16); gStyle->SetPadLeftMargin(0.18); \n gStyle->SetPadTopMargin(0.08); gStyle->SetPadRightMargin(0.06); \n gStyle->SetTitleXSize(0.05); gStyle->SetTitleYSize(0.05);\n gStyle->SetTitleXOffset(1.5); gStyle->SetTitleYOffset(1.9);\n gStyle->SetStatW(0.16); gStyle->SetStatH(0.16);\n gStyle->SetFitFormat(\"9.6g\"); \n gStyle->SetCanvasColor(0);\n gStyle->SetCanvasBorderMode(0);\n gStyle->SetPadBorderMode(0);\n gStyle->SetOptTitle(1);\n gStyle->SetOptStat(1110);\n gStyle->SetOptFit(1);\n \n gStyle->SetPalette(1,0); \/\/ rainbow colors\n gStyle->SetHistLineWidth(2); \n \n gStyle->SetFrameBorderMode(0);\n gROOT->ForceStyle();\n \n}\n\nrootlogon.C updated{\n\n TString includePath = \"-I${ROOTSYS}\/include \";\n \n printf(\"\\nLoading ALICE settings...\\n\\n\");\n includePath += \"-I${ALICE_ROOT}\/STEER \";\n includePath += \"-I${ALICE_ROOT}\/STEER\/STEERBase \";\n includePath += \"-I${ALICE_BUILD}\/include \";\n includePath += \"-I${ALICE_ROOT}\/RAW \";\n includePath += \"-I${ALICE_ROOT}\/FASTSIM \";\n includePath += \"-I${ALICE_ROOT}\/EVGEN \";\n includePath += \"-I${ALICE_ROOT}\/SHUTTLE\/TestShuttle \";\n includePath += \"-I${ALICE_ROOT}\/ITS \";\n includePath += \"-I${ALICE_ROOT}\/MFT \";\n includePath += \"-I${ALICE_ROOT}\/MUON \";\n includePath += \"-I${ALICE_ROOT}\/MUON\/mapping \";\n includePath += \"-I${ALICE_ROOT}\/RAW \";\n includePath += \"-I${ALICE_ROOT}\/CORRFW \";\n includePath += \"-I${ROOTSYS}\/net\/alien\/inc \";\n\n gSystem->SetIncludePath(includePath.Data());\n\n gSystem->Load(\"libCore.so\"); \n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libPhysics.so\");\n gSystem->Load(\"libSTEERBase\");\n gSystem->Load(\"libESD\");\n gSystem->Load(\"libAOD\");\n gSystem->Load(\"libANALYSIS\") ;\n gSystem->Load(\"libANALYSISalice\") ;\n gSystem->Load(\"libCORRFW\") ;\n gSystem->Load(\"libMFTbase\") ;\n gSystem->Load(\"libMFTsim\") ;\n gSystem->Load(\"libMFTrec\") ;\n \n \/\/================= define the style =================== \/\/\n \n \/\/ divisions: axis marks outside the figure (minus sign)\n gStyle->SetTickLength(-0.03,\"X\"); gStyle->SetTickLength(-0.03,\"Y\"); \n gStyle->SetNdivisions(508,\"X\"); gStyle->SetNdivisions(506,\"Y\"); \/\/ set ndvx (y)\n \n \/\/ dimensions and position of fonts connected to axes \n gStyle->SetLabelSize(0.05,\"X\"); gStyle->SetLabelSize(0.05,\"Y\"); \n gStyle->SetLabelOffset(0.02,\"X\"); gStyle->SetLabelOffset(0.04,\"Y\"); \n \n \/\/ dimension of the canvas and of the figure (pad) inside it\n gStyle->SetCanvasDefW(600); gStyle->SetCanvasDefH(600);\n gStyle->SetPadBottomMargin(0.16); gStyle->SetPadLeftMargin(0.18); \n gStyle->SetPadTopMargin(0.08); gStyle->SetPadRightMargin(0.06); \n gStyle->SetTitleXSize(0.05); gStyle->SetTitleYSize(0.05);\n gStyle->SetTitleXOffset(1.5); gStyle->SetTitleYOffset(1.9);\n gStyle->SetStatW(0.16); gStyle->SetStatH(0.16);\n gStyle->SetFitFormat(\"9.6g\"); \n gStyle->SetCanvasColor(0);\n gStyle->SetCanvasBorderMode(0);\n gStyle->SetPadBorderMode(0);\n gStyle->SetOptTitle(1);\n gStyle->SetOptStat(1110);\n gStyle->SetOptFit(1);\n \n gStyle->SetPalette(1,0); \/\/ rainbow colors\n gStyle->SetHistLineWidth(2); \n \n gStyle->SetFrameBorderMode(0);\n gROOT->ForceStyle();\n \n}\n\n<|endoftext|>"} {"text":"#include \"Enemies.hpp\"\n#include \n\nEnemies::Enemies(sf::RenderWindow& window)\n\t: m_speedIncreaseMultiplier(0.9)\n\t, m_dropSpeedIncreaseMultiplier(1.1)\n\t, m_speed(40.0)\n\t, m_dropSpeed(0.05)\n\t, m_enemies()\n\t, m_view(window.getView())\n\t, m_reachedBottom(false)\n{\n\tpriv_addEnemies();\n}\n\nvoid Enemies::reset()\n{\n\tm_speed = 40.0;\n\tm_dropSpeed = 0.05;\n\tm_reachedBottom = false;\n\tm_enemies.clear();\n\tpriv_addEnemies();\n}\n\nvoid Enemies::update(double dt)\n{\n\tif (m_reachedBottom)\n\t\treturn;\n\n\tbool requiresDirectionFlipping = false;\n\tfor (auto& enemy : m_enemies)\n\t{\n\t\tif (!enemy.isAlive())\n\t\t\tcontinue;\n\n\t\tif (enemy.isMovingRight())\n\t\t\tenemy.move({ m_speed * dt, m_speed * m_dropSpeed * dt });\n\t\telse\n\t\t\tenemy.move({ -m_speed * dt, m_speed * m_dropSpeed * dt });\n\t\tif (enemy.requiresFlipping())\n\t\t\trequiresDirectionFlipping = true;\n\t\tif (enemy.reachedBottom())\n\t\t\tm_reachedBottom = true;\n\t}\n\tif (requiresDirectionFlipping)\n\t\ttoggleDirection();\n}\n\nvoid Enemies::killEnemy(const unsigned int enemyIndex)\n{\n\tif (enemyIndex < m_enemies.size() && m_enemies[enemyIndex].isAlive())\n\t{\n\t\tm_enemies[enemyIndex].die();\n\n\t\t\/\/ adjust speed following a kill\n\t\tif (getNumberOfEnemiesAlive() > 0)\n\t\t\tm_speed *= m_speedIncreaseMultiplier \/ getNumberOfEnemiesAlive() + 1;\n\t}\n}\n\nvoid Enemies::toggleDirection()\n{\n\tfor (auto& enemy : m_enemies)\n\t\tenemy.flipDirection();\n\tm_dropSpeed *= m_dropSpeedIncreaseMultiplier;\n}\n\nunsigned int Enemies::getNumberOfEnemiesAlive() const\n{\n\tunsigned int total{ 0u };\n\tfor (auto& enemy : m_enemies)\n\t{\n\t\tif (enemy.isAlive())\n\t\t\t++total;\n\t}\n\treturn total;\n}\n\nbool Enemies::getReachedBottom() const\n{\n\treturn m_reachedBottom;\n}\n\nvoid Enemies::priv_addEnemies()\n{\n\tconst unsigned int numberOfEnemies = 40u;\n\tconst unsigned int enemiesPerRow = 8u;\n\tconst double horizontalSpacing = 65.0;\n\tconst double verticalSpacing = 65.0;\n\tconst pl::Vector2d positionOfTopLeft = { 120.0, 180.0 };\n\tfor (unsigned int i = 0; i < numberOfEnemies; ++i)\n\t\tm_enemies.emplace_back(Enemy(m_view, positionOfTopLeft + pl::Vector2d{ horizontalSpacing * (i % enemiesPerRow), verticalSpacing * (i \/ enemiesPerRow) }));\n}\ncorrect Enemy initial position#include \"Enemies.hpp\"\n#include \n\nEnemies::Enemies(sf::RenderWindow& window)\n\t: m_speedIncreaseMultiplier(0.9)\n\t, m_dropSpeedIncreaseMultiplier(1.1)\n\t, m_speed(40.0)\n\t, m_dropSpeed(0.05)\n\t, m_enemies()\n\t, m_view(window.getView())\n\t, m_reachedBottom(false)\n{\n\tpriv_addEnemies();\n}\n\nvoid Enemies::reset()\n{\n\tm_speed = 40.0;\n\tm_dropSpeed = 0.05;\n\tm_reachedBottom = false;\n\tm_enemies.clear();\n\tpriv_addEnemies();\n}\n\nvoid Enemies::update(double dt)\n{\n\tif (m_reachedBottom)\n\t\treturn;\n\n\tbool requiresDirectionFlipping = false;\n\tfor (auto& enemy : m_enemies)\n\t{\n\t\tif (!enemy.isAlive())\n\t\t\tcontinue;\n\n\t\tif (enemy.isMovingRight())\n\t\t\tenemy.move({ m_speed * dt, m_speed * m_dropSpeed * dt });\n\t\telse\n\t\t\tenemy.move({ -m_speed * dt, m_speed * m_dropSpeed * dt });\n\t\tif (enemy.requiresFlipping())\n\t\t\trequiresDirectionFlipping = true;\n\t\tif (enemy.reachedBottom())\n\t\t\tm_reachedBottom = true;\n\t}\n\tif (requiresDirectionFlipping)\n\t\ttoggleDirection();\n}\n\nvoid Enemies::killEnemy(const unsigned int enemyIndex)\n{\n\tif (enemyIndex < m_enemies.size() && m_enemies[enemyIndex].isAlive())\n\t{\n\t\tm_enemies[enemyIndex].die();\n\n\t\t\/\/ adjust speed following a kill\n\t\tif (getNumberOfEnemiesAlive() > 0)\n\t\t\tm_speed *= m_speedIncreaseMultiplier \/ getNumberOfEnemiesAlive() + 1;\n\t}\n}\n\nvoid Enemies::toggleDirection()\n{\n\tfor (auto& enemy : m_enemies)\n\t\tenemy.flipDirection();\n\tm_dropSpeed *= m_dropSpeedIncreaseMultiplier;\n}\n\nunsigned int Enemies::getNumberOfEnemiesAlive() const\n{\n\tunsigned int total{ 0u };\n\tfor (auto& enemy : m_enemies)\n\t{\n\t\tif (enemy.isAlive())\n\t\t\t++total;\n\t}\n\treturn total;\n}\n\nbool Enemies::getReachedBottom() const\n{\n\treturn m_reachedBottom;\n}\n\nvoid Enemies::priv_addEnemies()\n{\n\tconst unsigned int numberOfEnemies = 40u;\n\tconst unsigned int enemiesPerRow = 8u;\n\tconst double horizontalSpacing = 65.0;\n\tconst double verticalSpacing = 65.0;\n\tconst pl::Vector2d positionOfTopLeft = { 120.0, 80.0 };\n\tfor (unsigned int i = 0; i < numberOfEnemies; ++i)\n\t\tm_enemies.emplace_back(Enemy(m_view, positionOfTopLeft + pl::Vector2d{ horizontalSpacing * (i % enemiesPerRow), verticalSpacing * (i \/ enemiesPerRow) }));\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nextern \"C\" {\n#include \n}\n\n#include \n#include \n#include \n\n#include \"Baton.hpp\"\n#include \"Exception.hpp\"\n#include \"Pooling.hpp\"\n#include \"Trampoline.t.hpp\"\n\nextern \"C\" void __pthread_set_self(pthread_t);\n\ntemplate \nstatic void nlset(Type_ &function, struct nlist *nl, size_t index) {\n struct nlist &name(nl[index]);\n uintptr_t value(name.n_value);\n _assert(value != 0);\n if ((name.n_desc & N_ARM_THUMB_DEF) != 0)\n value |= 0x00000001;\n function = value;\n}\n\nvoid InjectLibrary(pid_t pid) {\n \/\/ XXX: break this into the build environment\n const char *library(\"\/usr\/lib\/libcycript.dylib\");\n\n static const size_t Stack_(8 * 1024);\n size_t length(strlen(library) + 1), depth(sizeof(Baton) + length);\n depth = (depth + sizeof(uintptr_t) + 1) \/ sizeof(uintptr_t) * sizeof(uintptr_t);\n\n CYPool pool;\n uint8_t *local(reinterpret_cast(apr_palloc(pool, depth)));\n Baton *baton(reinterpret_cast(local));\n\n uintptr_t set_self_internal;\n uintptr_t set_self_external;\n\n struct nlist nl[3];\n memset(nl, 0, sizeof(nl));\n nl[0].n_un.n_name = (char *) \"__pthread_set_self\";\n nl[1].n_un.n_name = (char *) \"___pthread_set_self\";\n nlist(\"\/usr\/lib\/libSystem.B.dylib\", nl);\n nlset(set_self_internal, nl, 0);\n nlset(set_self_external, nl, 1);\n\n baton->_pthread_set_self = reinterpret_cast(reinterpret_cast(&__pthread_set_self) - set_self_external + set_self_internal);\n\n baton->pthread_create = &pthread_create;\n baton->pthread_join = &pthread_join;\n\n baton->dlopen = &dlopen;\n baton->dlsym = &dlsym;\n\n baton->mach_thread_self = &mach_thread_self;\n baton->thread_terminate = &thread_terminate;\n\n baton->pid = getpid();\n memcpy(baton->library, library, length);\n\n vm_size_t size(depth + Stack_);\n\n mach_port_t self(mach_task_self()), task;\n _krncall(task_for_pid(self, pid, &task));\n\n vm_address_t stack;\n _krncall(vm_allocate(task, &stack, size, true));\n vm_address_t data(stack + Stack_);\n\n vm_write(task, data, reinterpret_cast(baton), depth);\n\n vm_address_t code;\n _krncall(vm_allocate(task, &code, sizeof(Trampoline_), true));\n vm_write(task, code, reinterpret_cast(Trampoline_), sizeof(Trampoline_));\n _krncall(vm_protect(task, code, sizeof(Trampoline_), false, VM_PROT_READ | VM_PROT_EXECUTE));\n\n thread_act_t thread;\n _krncall(thread_create(task, &thread));\n\n thread_state_flavor_t flavor;\n mach_msg_type_number_t count;\n size_t push;\n\n#if defined(__arm__)\n arm_thread_state_t state;\n flavor = ARM_THREAD_STATE;\n count = ARM_THREAD_STATE_COUNT;\n push = 0;\n#elif defined(__i386__)\n i386_thread_state_t state;\n flavor = i386_THREAD_STATE;\n count = i386_THREAD_STATE_COUNT;\n push = 5;\n#else\n #error XXX: implement\n#endif\n\n uintptr_t frame[push];\n if (sizeof(frame) != 0)\n memset(frame, 0, sizeof(frame));\n\n memset(&state, 0, sizeof(state));\n\n mach_msg_type_number_t read(count);\n _krncall(thread_get_state(thread, flavor, reinterpret_cast(&state), &read));\n _assert(count == count);\n\n#if defined(__arm__)\n state.r[0] = data;\n state.sp = stack + Stack_;\n state.pc = code;\n\n if ((state.pc & 0x1) != 0) {\n state.pc &= ~0x1;\n state.cpsr |= 0x20;\n }\n#elif defined(__i386__)\n frame[0] = 0;\n frame[1] = data;\n\n state.__eip = code;\n state.__esp = stack + Stack_ - sizeof(frame);\n#else\n #error XXX: implement\n#endif\n\n if (sizeof(frame) != 0)\n vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast(frame), sizeof(frame));\n\n _krncall(thread_set_state(thread, flavor, reinterpret_cast(&state), count));\n _krncall(thread_resume(thread));\n\n _krncall(mach_port_deallocate(self, task));\n}\nAttempting a silly x64 fix.#include \n#include \n\nextern \"C\" {\n#include \n}\n\n#include \n#include \n#include \n\n#include \"Baton.hpp\"\n#include \"Exception.hpp\"\n#include \"Pooling.hpp\"\n#include \"Trampoline.t.hpp\"\n\nextern \"C\" void __pthread_set_self(pthread_t);\n\ntemplate \nstatic void nlset(Type_ &function, struct nlist *nl, size_t index) {\n struct nlist &name(nl[index]);\n uintptr_t value(name.n_value);\n _assert(value != 0);\n if ((name.n_desc & N_ARM_THUMB_DEF) != 0)\n value |= 0x00000001;\n function = value;\n}\n\nvoid InjectLibrary(pid_t pid) {\n \/\/ XXX: break this into the build environment\n const char *library(\"\/usr\/lib\/libcycript.dylib\");\n\n static const size_t Stack_(8 * 1024);\n size_t length(strlen(library) + 1), depth(sizeof(Baton) + length);\n depth = (depth + sizeof(uintptr_t) + 1) \/ sizeof(uintptr_t) * sizeof(uintptr_t);\n\n CYPool pool;\n uint8_t *local(reinterpret_cast(apr_palloc(pool, depth)));\n Baton *baton(reinterpret_cast(local));\n\n uintptr_t set_self_internal;\n uintptr_t set_self_external;\n\n struct nlist nl[3];\n memset(nl, 0, sizeof(nl));\n nl[0].n_un.n_name = (char *) \"__pthread_set_self\";\n nl[1].n_un.n_name = (char *) \"___pthread_set_self\";\n nlist(\"\/usr\/lib\/libSystem.B.dylib\", nl);\n nlset(set_self_internal, nl, 0);\n nlset(set_self_external, nl, 1);\n\n baton->_pthread_set_self = reinterpret_cast(reinterpret_cast(&__pthread_set_self) - set_self_external + set_self_internal);\n\n baton->pthread_create = &pthread_create;\n baton->pthread_join = &pthread_join;\n\n baton->dlopen = &dlopen;\n baton->dlsym = &dlsym;\n\n baton->mach_thread_self = &mach_thread_self;\n baton->thread_terminate = &thread_terminate;\n\n baton->pid = getpid();\n memcpy(baton->library, library, length);\n\n vm_size_t size(depth + Stack_);\n\n mach_port_t self(mach_task_self()), task;\n _krncall(task_for_pid(self, pid, &task));\n\n vm_address_t stack;\n _krncall(vm_allocate(task, &stack, size, true));\n vm_address_t data(stack + Stack_);\n\n vm_write(task, data, reinterpret_cast(baton), depth);\n\n vm_address_t code;\n _krncall(vm_allocate(task, &code, sizeof(Trampoline_), true));\n vm_write(task, code, reinterpret_cast(Trampoline_), sizeof(Trampoline_));\n _krncall(vm_protect(task, code, sizeof(Trampoline_), false, VM_PROT_READ | VM_PROT_EXECUTE));\n\n thread_act_t thread;\n _krncall(thread_create(task, &thread));\n\n thread_state_flavor_t flavor;\n mach_msg_type_number_t count;\n size_t push;\n\n#if defined(__arm__)\n arm_thread_state_t state;\n flavor = ARM_THREAD_STATE;\n count = ARM_THREAD_STATE_COUNT;\n push = 0;\n#elif defined(__i386__) || defined(__x86_64__)\n i386_thread_state_t state;\n flavor = i386_THREAD_STATE;\n count = i386_THREAD_STATE_COUNT;\n push = 5;\n#else\n #error XXX: implement\n#endif\n\n uintptr_t frame[push];\n if (sizeof(frame) != 0)\n memset(frame, 0, sizeof(frame));\n\n memset(&state, 0, sizeof(state));\n\n mach_msg_type_number_t read(count);\n _krncall(thread_get_state(thread, flavor, reinterpret_cast(&state), &read));\n _assert(count == count);\n\n#if defined(__arm__)\n state.r[0] = data;\n state.sp = stack + Stack_;\n state.pc = code;\n\n if ((state.pc & 0x1) != 0) {\n state.pc &= ~0x1;\n state.cpsr |= 0x20;\n }\n#elif defined(__i386__) || defined(__x86_64__)\n frame[0] = 0;\n frame[1] = data;\n\n state.__eip = code;\n state.__esp = stack + Stack_ - sizeof(frame);\n#else\n #error XXX: implement\n#endif\n\n if (sizeof(frame) != 0)\n vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast(frame), sizeof(frame));\n\n _krncall(thread_set_state(thread, flavor, reinterpret_cast(&state), count));\n _krncall(thread_resume(thread));\n\n _krncall(mach_port_deallocate(self, task));\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/side_pass\/side_pass_stop_on_wait_point.h\"\n\n#include \n#include \n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/speed_profile_generator.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace side_pass {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::PathPoint;\nusing apollo::common::math::Vec2d;\n\nconstexpr double kExtraMarginforStopOnWaitPointStage = 3.0;\n\nStage::StageStatus SidePassStopOnWaitPoint::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n const ReferenceLineInfo& reference_line_info =\n frame->reference_line_info().front();\n const ReferenceLine& reference_line = reference_line_info.reference_line();\n const PathDecision& path_decision = reference_line_info.path_decision();\n\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty.\";\n return Stage::ERROR;\n }\n\n if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {\n return Stage::ERROR;\n }\n\n const auto adc_frenet_frame_point_ =\n reference_line.GetFrenetPoint(frame->PlanningStartPoint());\n\n if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_.s(),\n adc_frenet_frame_point_.l())) {\n return Stage::ERROR;\n }\n\n PathPoint first_path_point =\n GetContext()->path_data_.discretized_path().path_points().front();\n\n PathPoint last_path_point;\n if (!GetMoveForwardLastPathPoint(reference_line, &last_path_point)) {\n AERROR << \"Fail to get move forward last path point.\";\n return Stage::ERROR;\n }\n ADEBUG << \"first_path_point: \" << first_path_point.ShortDebugString();\n ADEBUG << \"last_path_point : \" << first_path_point.ShortDebugString();\n\n double move_forward_distance = last_path_point.s() - first_path_point.s();\n ADEBUG << \"move_forward_distance: \" << move_forward_distance;\n\n if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),\n first_path_point, last_path_point)) {\n \/\/ wait here, do nothing this cycle.\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFallbackSpeedProfile();\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n AINFO << \"waiting until obstacles are far away.\";\n return Stage::RUNNING;\n }\n\n \/\/ (1) call proceed with cautious\n constexpr double kSidePassCreepSpeed = 2.33; \/\/ m\/s\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(\n move_forward_distance, kSidePassCreepSpeed);\n\n \/\/ (2) combine path and speed.\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n constexpr double kBuffer = 0.3;\n if (move_forward_distance < kBuffer) {\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n }\n return Stage::FINISHED;\n}\n\nbool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(\n const ReferenceLine& reference_line,\n const IndexedList& indexed_obstacle_list,\n const PathPoint& first_path_point, const PathPoint& last_path_point) {\n common::SLPoint first_sl_point;\n if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),\n &first_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n common::SLPoint last_sl_point;\n if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),\n &last_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n \/\/ Go through every obstacle, check if there is any in the no_obs_zone,\n \/\/ which will used by the proceed_with_caution movement.\n for (const auto* obstacle : indexed_obstacle_list.Items()) {\n if (obstacle->IsVirtual()) {\n continue;\n }\n \/\/ Check the s-direction.\n double obs_start_s = obstacle->PerceptionSLBoundary().start_s();\n double obs_end_s = obstacle->PerceptionSLBoundary().end_s();\n if (obs_end_s < first_sl_point.s() ||\n obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {\n continue;\n }\n \/\/ Check the l-direction.\n double lane_left_width_at_start_s = 0.0;\n double lane_left_width_at_end_s = 0.0;\n double lane_right_width_at_start_s = 0.0;\n double lane_right_width_at_end_s = 0.0;\n reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,\n &lane_right_width_at_start_s);\n reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,\n &lane_right_width_at_end_s);\n double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),\n std::abs(lane_left_width_at_end_s));\n double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),\n std::abs(lane_right_width_at_end_s));\n double obs_start_l = obstacle->PerceptionSLBoundary().start_l();\n double obs_end_l = obstacle->PerceptionSLBoundary().end_l();\n if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {\n return false;\n }\n }\n return true;\n}\n\nbool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(\n const ReferenceLine& reference_line,\n common::PathPoint* const last_path_point) {\n int count = 0;\n for (const auto& path_point :\n GetContext()->path_data_.discretized_path().path_points()) {\n \/\/ Get the four corner points ABCD of ADC at every path point,\n \/\/ and check if that's within the current lane until it reaches\n \/\/ out of current lane.\n const auto& vehicle_box =\n common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);\n std::vector ABCDpoints = vehicle_box.GetAllCorners();\n bool is_out_of_curr_lane = false;\n for (size_t i = 0; i < ABCDpoints.size(); i++) {\n \/\/ For each corner point, project it onto reference_line\n common::SLPoint curr_point_sl;\n if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {\n AERROR << \"Failed to get the projection from point onto \"\n \"reference_line\";\n return false;\n }\n \/\/ Get the lane width at the current s indicated by path_point\n double curr_point_left_width = 0.0;\n double curr_point_right_width = 0.0;\n reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,\n &curr_point_right_width);\n \/\/ Check if this corner point is within the lane:\n if (curr_point_sl.l() > std::abs(curr_point_left_width) ||\n curr_point_sl.l() < -std::abs(curr_point_right_width)) {\n is_out_of_curr_lane = true;\n break;\n }\n }\n if (is_out_of_curr_lane) {\n if (count == 0) {\n \/\/ The current ADC, without moving at all, is already at least\n \/\/ partially out of the current lane.\n return Stage::FINISHED;\n }\n break;\n } else {\n *last_path_point = path_point;\n }\n \/\/ check if the ego car on path_point will partially go into the\n \/\/ neighbor lane, and retain only those within-lane path-points.\n CHECK_GE(path_point.s(), 0.0);\n ++count;\n }\n return true;\n}\n\n} \/\/ namespace side_pass\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\nplanning: added path check in side pass stop on wait point.\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/side_pass\/side_pass_stop_on_wait_point.h\"\n\n#include \n#include \n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/speed_profile_generator.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace side_pass {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::PathPoint;\nusing apollo::common::math::Vec2d;\n\nconstexpr double kExtraMarginforStopOnWaitPointStage = 3.0;\n\nStage::StageStatus SidePassStopOnWaitPoint::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n const ReferenceLineInfo& reference_line_info =\n frame->reference_line_info().front();\n const ReferenceLine& reference_line = reference_line_info.reference_line();\n const PathDecision& path_decision = reference_line_info.path_decision();\n\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty.\";\n return Stage::ERROR;\n }\n\n if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {\n return Stage::ERROR;\n }\n\n const auto adc_frenet_frame_point_ =\n reference_line.GetFrenetPoint(frame->PlanningStartPoint());\n\n if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_.s(),\n adc_frenet_frame_point_.l())) {\n return Stage::ERROR;\n }\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty after trim.\";\n return Stage::ERROR;\n }\n\n PathPoint first_path_point =\n GetContext()->path_data_.discretized_path().path_points().front();\n\n PathPoint last_path_point;\n if (!GetMoveForwardLastPathPoint(reference_line, &last_path_point)) {\n AERROR << \"Fail to get move forward last path point.\";\n return Stage::ERROR;\n }\n ADEBUG << \"first_path_point: \" << first_path_point.ShortDebugString();\n ADEBUG << \"last_path_point : \" << first_path_point.ShortDebugString();\n\n double move_forward_distance = last_path_point.s() - first_path_point.s();\n ADEBUG << \"move_forward_distance: \" << move_forward_distance;\n\n if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),\n first_path_point, last_path_point)) {\n \/\/ wait here, do nothing this cycle.\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFallbackSpeedProfile();\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n AINFO << \"waiting until obstacles are far away.\";\n return Stage::RUNNING;\n }\n\n \/\/ (1) call proceed with cautious\n constexpr double kSidePassCreepSpeed = 2.33; \/\/ m\/s\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(\n move_forward_distance, kSidePassCreepSpeed);\n\n \/\/ (2) combine path and speed.\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n constexpr double kBuffer = 0.3;\n if (move_forward_distance < kBuffer) {\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n }\n return Stage::FINISHED;\n}\n\nbool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(\n const ReferenceLine& reference_line,\n const IndexedList& indexed_obstacle_list,\n const PathPoint& first_path_point, const PathPoint& last_path_point) {\n common::SLPoint first_sl_point;\n if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),\n &first_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n common::SLPoint last_sl_point;\n if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),\n &last_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n \/\/ Go through every obstacle, check if there is any in the no_obs_zone,\n \/\/ which will used by the proceed_with_caution movement.\n for (const auto* obstacle : indexed_obstacle_list.Items()) {\n if (obstacle->IsVirtual()) {\n continue;\n }\n \/\/ Check the s-direction.\n double obs_start_s = obstacle->PerceptionSLBoundary().start_s();\n double obs_end_s = obstacle->PerceptionSLBoundary().end_s();\n if (obs_end_s < first_sl_point.s() ||\n obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {\n continue;\n }\n \/\/ Check the l-direction.\n double lane_left_width_at_start_s = 0.0;\n double lane_left_width_at_end_s = 0.0;\n double lane_right_width_at_start_s = 0.0;\n double lane_right_width_at_end_s = 0.0;\n reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,\n &lane_right_width_at_start_s);\n reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,\n &lane_right_width_at_end_s);\n double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),\n std::abs(lane_left_width_at_end_s));\n double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),\n std::abs(lane_right_width_at_end_s));\n double obs_start_l = obstacle->PerceptionSLBoundary().start_l();\n double obs_end_l = obstacle->PerceptionSLBoundary().end_l();\n if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {\n return false;\n }\n }\n return true;\n}\n\nbool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(\n const ReferenceLine& reference_line,\n common::PathPoint* const last_path_point) {\n int count = 0;\n for (const auto& path_point :\n GetContext()->path_data_.discretized_path().path_points()) {\n \/\/ Get the four corner points ABCD of ADC at every path point,\n \/\/ and check if that's within the current lane until it reaches\n \/\/ out of current lane.\n const auto& vehicle_box =\n common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);\n std::vector ABCDpoints = vehicle_box.GetAllCorners();\n bool is_out_of_curr_lane = false;\n for (size_t i = 0; i < ABCDpoints.size(); i++) {\n \/\/ For each corner point, project it onto reference_line\n common::SLPoint curr_point_sl;\n if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {\n AERROR << \"Failed to get the projection from point onto \"\n \"reference_line\";\n return false;\n }\n \/\/ Get the lane width at the current s indicated by path_point\n double curr_point_left_width = 0.0;\n double curr_point_right_width = 0.0;\n reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,\n &curr_point_right_width);\n \/\/ Check if this corner point is within the lane:\n if (curr_point_sl.l() > std::abs(curr_point_left_width) ||\n curr_point_sl.l() < -std::abs(curr_point_right_width)) {\n is_out_of_curr_lane = true;\n break;\n }\n }\n if (is_out_of_curr_lane) {\n if (count == 0) {\n \/\/ The current ADC, without moving at all, is already at least\n \/\/ partially out of the current lane.\n return Stage::FINISHED;\n }\n break;\n } else {\n *last_path_point = path_point;\n }\n \/\/ check if the ego car on path_point will partially go into the\n \/\/ neighbor lane, and retain only those within-lane path-points.\n CHECK_GE(path_point.s(), 0.0);\n ++count;\n }\n return true;\n}\n\n} \/\/ namespace side_pass\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/* Siconos-Examples version 3.0.0, Copyright INRIA 2005-2008.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos 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 General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n*\/\n\n\/*!\\file CamFollowerNoXML.cpp\n\\brief \\ref EMCamFollower - C++ input file version - M. di Bernardo, G. Osorio, S. Santini.\n*\/\n\n#include \"SiconosKernel.hpp\"\n#include \"CamState.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n double rpm = 358;\n try\n {\n\n \/\/ ================= Creation of the model =======================\n\n \/\/ User-defined main parameters\n unsigned int dsNumber = 1; \/\/ the Follower and the ground\n unsigned int nDof = 1; \/\/ degrees of freedom for the ball\n double t0 = 0; \/\/ initial computation time\n double T = 1; \/\/ final computation time\n double h = 0.0001; \/\/ time step\n double position_init = 0.;\/\/;40; \/\/ initial position for lowest bead.\n double velocity_init = 0.;\/\/4; \/\/ initial velocity for lowest bead.\n double theta = 0.5; \/\/ theta for Moreau integrator\n \/\/ -------------------------\n \/\/ --- Dynamical systems ---\n \/\/ -------------------------\n\n SP::SimpleMatrix Mass(new SimpleMatrix(nDof, nDof));\n SP::SimpleMatrix K(new SimpleMatrix(nDof, nDof));\n SP::SimpleMatrix C(new SimpleMatrix(nDof, nDof)); \/\/ mass\/rigidity\/viscosity\n (*Mass)(0, 0) = 1.221;\n (*K)(0, 0) = 1430.8;\n\n \/\/ -- Initial positions and velocities --\n vector q0;\n vector velocity0;\n q0.resize(dsNumber);\n velocity0.resize(dsNumber);\n q0[0].reset(new SimpleVector(nDof));\n velocity0[0].reset(new SimpleVector(nDof));\n (*(q0[0]))(0) = position_init;\n (*(velocity0[0]))(0) = velocity_init;\n SP::LagrangianLinearTIDS lds(new LagrangianLinearTIDS(q0[0], velocity0[0], Mass, K, C));\n lds->setComputeFExtFunction(\"FollowerPlugin.so\", \"FollowerFExtR\");\n\n \/\/ Example to set a list of parameters in FExt function.\n \/\/ 1 - Create a simple vector that contains the required parameters.\n SP::SiconosVector param(new SimpleVector(1)); \/\/ Here we only set one parameter, the DS number.\n \/\/ (*param)(0) = vectorDS[0]->getNumber();\n (*param)(0) = rpm;\n \/\/ 2 - Assign this param to the function FExt\n lds->setZPtr(param);\n \/\/ 2 corresponds to the position of FExt in the stl vector of possible parameters. 0 is mass, 1 FInt and so on.\n \/\/ Now the DS number will be available in FExt plugin.\n\n DynamicalSystemsSet allDS;\n allDS.insert(lds);\n\n \/\/ --------------------\n \/\/ --- Interactions ---\n \/\/ --------------------\n\n \/\/ -- nslaw --\n double e = 0.8;\n\n \/\/ Interaction Follower-floor\n \/\/\n SimpleMatrix H(1, nDof);\n H(0, 0) = 1.0;\n SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));\n SP::Relation relation0(new LagrangianLinearTIR(H));\n DynamicalSystemsSet dsConcerned;\n dsConcerned.insert(lds);\n\n SP::Interaction inter(new Interaction(\"Follower-Ground\", dsConcerned, 0, 1, nslaw0, relation0));\n InteractionsSet allInteractions;\n allInteractions.insert(inter);\n\n \/\/ -------------\n \/\/ --- Model ---\n \/\/ -------------\n\n SP::Model Follower(new Model(t0, T, allDS, allInteractions));\n\n \/\/ ----------------\n \/\/ --- Simulation ---\n \/\/ ----------------\n\n \/\/ -- Time discretisation --\n SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n SP::TimeStepping S(new TimeStepping(t));\n\n\n \/\/ -- OneStepIntegrator --\n SP::OneStepIntegrator OSI(new Moreau(lds, theta));\n S->insertIntegrator(OSI);\n\n \/\/ -- OneStepNsProblem --\n IntParameters iparam(5);\n iparam[0] = 101; \/\/ Max number of iteration\n DoubleParameters dparam(5);\n dparam[0] = 1e-5; \/\/ Tolerance\n string solverName = \"QP\" ;\n SP::NonSmoothSolver mySolver(new NonSmoothSolver(solverName, iparam, dparam));\n SP::OneStepNSProblem osnspb(new LCP(mySolver));\n S->insertNonSmoothProblem(osnspb);\n\n cout << \"=== End of model loading === \" << endl;\n \/\/ =========================== End of model definition ===========================\n\n \/\/ ================================= Computation =================================\n\n \/\/ --- Simulation initialization ---\n Follower->initialize(S);\n cout << \"End of model initialisation\" << endl;\n\n\n int k = 0;\n int N = (int)((T - t0) \/ h); \/\/ Number of time steps\n\n\n \/\/ --- Get the values to be plotted ---\n \/\/ -> saved in a matrix dataPlot\n unsigned int outputSize = 8;\n SimpleMatrix DataPlot(N + 1, outputSize);\n \/\/ For the initial time step:\n \/\/ time\n DataPlot(k, 0) = t0;\n DataPlot(k, 1) = (*lds->q())(0);\n DataPlot(k, 2) = (*lds->velocity())(0);\n DataPlot(k, 3) = (*Follower->nonSmoothDynamicalSystem()->topology()->interactions()->getPtr(0)->lambda(1))(0);\n DataPlot(k, 4) = (*lds->fExt())(0);\n\n \/\/ State of the Cam\n \/\/ double rpm=358;\n double CamEqForce, CamPosition, CamVelocity, CamAcceleration;\n\n CamEqForce = CamState(t0, rpm, CamPosition, CamVelocity, CamAcceleration);\n \/\/ Position of the Cam\n DataPlot(k, 5) = CamPosition;\n \/\/ Velocity of the Cam\n DataPlot(k, 6) = CamVelocity;\n \/\/ Acceleration of the Cam\n DataPlot(k, 7) = CamPosition + (*lds->q())(0);\n boost::timer tt;\n tt.restart();\n \/\/ --- Time loop ---\n cout << \"Start computation ... \" << endl;\n while (k < N)\n {\n \/\/ get current time step\n k++;\n \/\/ solve ...\n S->computeOneStep();\n\n \/\/ --- Get values to be plotted ---\n\n DataPlot(k, 0) = S->nextTime();\n DataPlot(k, 1) = (*lds->q())(0);\n DataPlot(k, 2) = (*lds->velocity())(0);\n DataPlot(k, 3) = (*Follower->nonSmoothDynamicalSystem()->topology()->interactions()->getPtr(0)->lambda(1))(0);\n DataPlot(k, 4) = (*lds->fExt())(0);\n\n CamEqForce = CamState(S->nextTime(), rpm, CamPosition, CamVelocity, CamAcceleration);\n DataPlot(k, 5) = CamPosition;\n DataPlot(k, 6) = CamVelocity;\n DataPlot(k, 7) = CamPosition + (*lds->q())(0);\n \/\/ transfer of state i+1 into state i and time incrementation\n S->nextStep();\n }\n \/\/ --- Output files ---\n ioMatrix io(\"result.dat\", \"ascii\");\n io.write(DataPlot, \"noDim\");\n cout << \"time = \" << tt.elapsed() << endl;\n cout << \"End of computation - Number of iterations done: \" << k << endl;\n }\n\n catch (SiconosException e)\n {\n cout << e.report() << endl;\n }\n catch (...)\n {\n cout << \"Exception caught in \\'sample\/CamFollower\\'\" << endl;\n }\n}\nupdate as the bouncing ball\/* Siconos-Examples version 3.0.0, Copyright INRIA 2005-2008.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos 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 General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n*\/\n\n\/*!\\file CamFollowerNoXML.cpp\n\\brief \\ref EMCamFollower - C++ input file version - M. di Bernardo, G. Osorio, S. Santini.\n*\/\n\n#include \"SiconosKernel.hpp\"\n#include \"CamState.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n double rpm = 358;\n try\n {\n\n \/\/ ================= Creation of the model =======================\n\n \/\/ User-defined main parameters\n unsigned int dsNumber = 1; \/\/ the Follower and the ground\n unsigned int nDof = 1; \/\/ degrees of freedom for the ball\n double t0 = 0; \/\/ initial computation time\n double T = 1; \/\/ final computation time\n double h = 0.0001; \/\/ time step\n double position_init = 0.;\/\/;40; \/\/ initial position for lowest bead.\n double velocity_init = 0.;\/\/4; \/\/ initial velocity for lowest bead.\n double theta = 0.5; \/\/ theta for Moreau integrator\n \/\/ -------------------------\n \/\/ --- Dynamical systems ---\n \/\/ -------------------------\n\n SP::SimpleMatrix Mass(new SimpleMatrix(nDof, nDof));\n SP::SimpleMatrix K(new SimpleMatrix(nDof, nDof));\n SP::SimpleMatrix C(new SimpleMatrix(nDof, nDof)); \/\/ mass\/rigidity\/viscosity\n (*Mass)(0, 0) = 1.221;\n (*K)(0, 0) = 1430.8;\n\n \/\/ -- Initial positions and velocities --\n vector q0;\n vector velocity0;\n q0.resize(dsNumber);\n velocity0.resize(dsNumber);\n q0[0].reset(new SimpleVector(nDof));\n velocity0[0].reset(new SimpleVector(nDof));\n (*(q0[0]))(0) = position_init;\n (*(velocity0[0]))(0) = velocity_init;\n SP::LagrangianLinearTIDS lds(new LagrangianLinearTIDS(q0[0], velocity0[0], Mass, K, C));\n lds->setComputeFExtFunction(\"FollowerPlugin.so\", \"FollowerFExtR\");\n\n \/\/ Example to set a list of parameters in FExt function.\n \/\/ 1 - Create a simple vector that contains the required parameters.\n SP::SiconosVector param(new SimpleVector(1)); \/\/ Here we only set one parameter, the DS number.\n \/\/ (*param)(0) = vectorDS[0]->getNumber();\n (*param)(0) = rpm;\n \/\/ 2 - Assign this param to the function FExt\n lds->setZPtr(param);\n \/\/ 2 corresponds to the position of FExt in the stl vector of possible parameters. 0 is mass, 1 FInt and so on.\n \/\/ Now the DS number will be available in FExt plugin.\n\n \/\/ --------------------\n \/\/ --- Interactions ---\n \/\/ --------------------\n\n \/\/ -- nslaw --\n double e = 0.8;\n\n \/\/ Interaction Follower-floor\n \/\/\n SP::SiconosMatrix H(new SimpleMatrix(1, nDof));\n (*H)(0, 0) = 1.0;\n SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));\n SP::Relation relation0(new LagrangianLinearTIR(H));\n SP::Interaction inter(new Interaction(1, nslaw0, relation0));\n\n \/\/ -------------\n \/\/ --- Model ---\n \/\/ -------------\n\n SP::Model Follower(new Model(t0, T));\n\n Follower->nonSmoothDynamicalSystem()->insertDynamicalSystem(lds);\n Follower->nonSmoothDynamicalSystem()->link(inter, lds);\n\n\n \/\/ ----------------\n \/\/ --- Simulation ---\n \/\/ ----------------\n\n \/\/ -- Time discretisation --\n SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n \/\/ -- OneStepIntegrator --\n SP::OneStepIntegrator OSI(new Moreau(lds, theta));\n\n \/\/ -- OneStepNsProblem --\n IntParameters iparam(5);\n iparam[0] = 101; \/\/ Max number of iteration\n DoubleParameters dparam(5);\n dparam[0] = 1e-5; \/\/ Tolerance\n string solverName = \"QP\" ;\n SP::NonSmoothSolver mySolver(new NonSmoothSolver(solverName, iparam, dparam));\n SP::OneStepNSProblem osnspb(new LCP(mySolver));\n\n SP::TimeStepping S(new TimeStepping(t));\n S->insertIntegrator(OSI);\n S->insertNonSmoothProblem(osnspb);\n\n cout << \"=== End of model loading === \" << endl;\n \/\/ =========================== End of model definition ===========================\n\n \/\/ ================================= Computation =================================\n\n \/\/ --- Simulation initialization ---\n Follower->initialize(S);\n cout << \"End of model initialisation\" << endl;\n\n\n int k = 0;\n int N = (int)((T - t0) \/ h); \/\/ Number of time steps\n\n\n \/\/ --- Get the values to be plotted ---\n \/\/ -> saved in a matrix dataPlot\n unsigned int outputSize = 8;\n SimpleMatrix DataPlot(N + 1, outputSize);\n \/\/ For the initial time step:\n \/\/ time\n DataPlot(k, 0) = t0;\n DataPlot(k, 1) = (*lds->q())(0);\n DataPlot(k, 2) = (*lds->velocity())(0);\n DataPlot(k, 3) = (*Follower->nonSmoothDynamicalSystem()->topology()->interactions()->getPtr(0)->lambda(1))(0);\n DataPlot(k, 4) = (*lds->fExt())(0);\n\n \/\/ State of the Cam\n \/\/ double rpm=358;\n double CamEqForce, CamPosition, CamVelocity, CamAcceleration;\n\n CamEqForce = CamState(t0, rpm, CamPosition, CamVelocity, CamAcceleration);\n \/\/ Position of the Cam\n DataPlot(k, 5) = CamPosition;\n \/\/ Velocity of the Cam\n DataPlot(k, 6) = CamVelocity;\n \/\/ Acceleration of the Cam\n DataPlot(k, 7) = CamPosition + (*lds->q())(0);\n boost::timer tt;\n tt.restart();\n \/\/ --- Time loop ---\n cout << \"Start computation ... \" << endl;\n while (k < N)\n {\n \/\/ get current time step\n k++;\n \/\/ solve ...\n S->computeOneStep();\n\n \/\/ --- Get values to be plotted ---\n\n DataPlot(k, 0) = S->nextTime();\n DataPlot(k, 1) = (*lds->q())(0);\n DataPlot(k, 2) = (*lds->velocity())(0);\n DataPlot(k, 3) = (*Follower->nonSmoothDynamicalSystem()->topology()->interactions()->getPtr(0)->lambda(1))(0);\n DataPlot(k, 4) = (*lds->fExt())(0);\n\n CamEqForce = CamState(S->nextTime(), rpm, CamPosition, CamVelocity, CamAcceleration);\n DataPlot(k, 5) = CamPosition;\n DataPlot(k, 6) = CamVelocity;\n DataPlot(k, 7) = CamPosition + (*lds->q())(0);\n \/\/ transfer of state i+1 into state i and time incrementation\n S->nextStep();\n }\n \/\/ --- Output files ---\n ioMatrix io(\"result.dat\", \"ascii\");\n io.write(DataPlot, \"noDim\");\n cout << \"time = \" << tt.elapsed() << endl;\n cout << \"End of computation - Number of iterations done: \" << k << endl;\n }\n\n catch (SiconosException e)\n {\n cout << e.report() << endl;\n }\n catch (...)\n {\n cout << \"Exception caught in \\'sample\/CamFollower\\'\" << endl;\n }\n}\n<|endoftext|>"} {"text":"\/* Siconos-sample , Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos 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 General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n *\/\n\n\/*!\\file BouncingBallNETS.cpp\n \\brief \\ref EMBouncingBall - C++ input file, Time-Stepping version -\n V. Acary, O. Bonnefon.\n\n A Ball bouncing on the ground.\n Direct description of the model without XML input.\n Simulation with a Time-Stepping scheme.\n*\/\n#include \"SphereNEDSPlanR.hpp\"\n#include \"SiconosKernel.hpp\"\n\n\/\/#define WITH_PROJ\n#define WITH_FC3D\nusing namespace std;\n#ifdef WITH_FC3D\n#define R_CLASS NewtonEulerFrom3DLocalFrameR\n#else\n#define R_CLASS NewtonEulerFrom1DLocalFrameR\n#endif\n\nclass my_NewtonEulerR : public R_CLASS\n{\n\n double _sBallRadius ;\n\npublic:\n\n my_NewtonEulerR(double radius): R_CLASS(), _sBallRadius(radius) { };\n\n virtual void computeh(double t, Interaction& inter)\n {\n SP::SiconosVector y = inter.y(0);\n double height = fabs(inter.data(q0)->getValue(0)) - _sBallRadius;\n \/\/ std::cout <<\"my_NewtonEulerR:: computeh _jachq\" << std:: endl;\n \/\/ _jachq->display();\n y->setValue(0, height);\n _Nc->setValue(0, 1);\n _Nc->setValue(1, 0);\n _Nc->setValue(2, 0);\n _Pc1->setValue(0, height);\n _Pc1->setValue(1, inter.data(q0)->getValue(1));\n _Pc1->setValue(2, inter.data(q0)->getValue(2));\n\n \/\/_Pc2->setValue(0,hpc);\n \/\/_Pc2->setValue(1,data[q0]->getValue(1));\n \/\/_Pc2->setValue(2,data[q0]->getValue(2));\n \/\/printf(\"my_NewtonEulerR N, Pc\\n\");\n \/\/_Nc->display();\n \/\/_Pc1->display();\n }\n \/\/ACCEPT_VISITORS();\n};\nTYPEDEF_SPTR(my_NewtonEulerR);\n\n\n\n\n\nint main(int argc, char* argv[])\n{\n try\n {\n\n\n \/\/ ================= Creation of the model =======================\n\n \/\/ User-defined main parameters\n unsigned int nDof = 3; \/\/ degrees of freedom for the ball\n unsigned int qDim = 7; \/\/ degrees of freedom for the ball\n unsigned int nDim = 6; \/\/ degrees of freedom for the ball\n double t0 = 0; \/\/ initial computation time\n double T = 10.0; \/\/ final computation time\n double h = 0.005; \/\/ time step\n double position_init = 1.0; \/\/ initial position for lowest bead.\n double velocity_init = 2.0; \/\/ initial velocity for lowest bead.\n double omega_initx = 0.0;\n double omega_initz = 0.0;\/\/ initial velocity for lowest bead.\n double theta = 0.5; \/\/ theta for Moreau integrator\n double m = 1; \/\/ Ball mass\n double g = 9.81; \/\/ Gravity\n double radius = 0.1;\n \/\/ -------------------------\n \/\/ --- Dynamical systems ---\n \/\/ -------------------------\n\n cout << \"====> Model loading ...\" << endl << endl;\n\n \/\/ -- Initial positions and velocities --\n SP::SiconosVector q0(new SiconosVector(qDim));\n SP::SiconosVector v0(new SiconosVector(nDim));\n SP::SimpleMatrix I(new SimpleMatrix(3, 3));\n v0->zero();\n q0->zero();\n I->eye();\n (*q0)(0) = position_init;\n \/*initial quaternion equal to (1,0,0,0)*\/\n (*q0)(3) = 1.0;\n\n (*v0)(0) = velocity_init;\n (*v0)(3) = omega_initx;\n (*v0)(5) = omega_initz;\n \/\/ -- The dynamical system --\n SP::NewtonEulerDS ball(new NewtonEulerDS(q0, v0, m, I));\n\n \/\/ -- Set external forces (weight) --\n SP::SiconosVector weight(new SiconosVector(nDof));\n (*weight)(0) = -m * g;\n ball->setFExtPtr(weight);\n\n \/\/ --------------------\n \/\/ --- Interactions ---\n \/\/ --------------------\n\n \/\/ -- nslaw --\n double e = 0.9;\n\n \/\/ Interaction ball-floor\n \/\/\n\n \/\/ vector vecMatrix1;\n \/\/ vecMatrix1.push_back(H);\n \/\/ SP::BlockMatrix H_block(new BlockMatrix(vecMatrix1,1,1));\n\n \/\/ SP::SiconosMatrix HT(new SimpleMatrix(1,nDim));\n \/\/ vector vecMatrix2;\n \/\/ vecMatrix2.push_back(HT);\n \/\/ SP::BlockMatrix HT_block(new BlockMatrix(vecMatrix2,1,1));\n\n#ifdef WITH_FC3D\n int nslawsize = 3;\n SP::NonSmoothLaw nslaw0(new NewtonImpactFrictionNSL(e, e, 0.6, 3));\n#else\n int nslawsize = 1;\n SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));\n#endif\n\n\n \/\/ Version with NewtonEulerR()\n \/\/\n \/\/ SP::SimpleMatrix H(new SimpleMatrix(nslawsize,qDim));\n \/\/ H->zero();\n \/\/ (*H)(0,0) = 1.0;\n \/\/ #ifdef WITH_FC3D\n \/\/ (*H)(1,1) = 1.0;\n \/\/ (*H)(2,2) = 1.0;\n \/\/ #endif\n \/\/ \/\/SP::NewtonEulerR relation0(new SphereNEDSPlanR(0.1,1.0,0.0,0.0,0.0));\n \/\/ \/\/SP::NewtonEulerR relation0(new NewtonEulerR());\n \/\/ \/\/relation0->setJachq(H);\n \/\/ \/\/ relation0->setJacQH(H_block);\n \/\/ \/\/ relation0->setJacQHT(HT_block);\n \/\/ \/\/cout<<\"main jacQH\"<jachq()->display();\n\n \/\/ Version with my_NewtonEulerR()\n SP::NewtonEulerR relation0(new my_NewtonEulerR(radius));\n SP::Interaction inter(new Interaction(nslawsize, nslaw0, relation0));\n\n \/\/ -------------\n \/\/ --- Model ---\n \/\/ -------------\n SP::Model bouncingBall(new Model(t0, T));\n \/\/ add the dynamical system in the non smooth dynamical system\n bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball);\n\n \/\/ link the interaction and the dynamical system\n bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball);\n\n \/\/ ------------------\n \/\/ --- Simulation ---\n \/\/ ------------------\n\n \/\/ -- (1) OneStepIntegrators --\n#ifdef WITH_PROJ\n SP::MoreauProjectOnConstraintsOSI OSI(new MoreauProjectOnConstraintsOSI(ball, theta));\n#else\n SP::Moreau OSI(new Moreau(ball, theta));\n#endif\n \/\/ -- (2) Time discretisation --\n SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n \/\/ -- (3) one step non smooth problem\n SP::OneStepNSProblem osnspb(new GenericMechanical());\n#ifdef WITH_PROJ\n SP::OneStepNSProblem osnspb_pos(new MLCPProjectOnConstraints(SICONOS_MLCP_ENUM, 1.0));\n#endif\n \/\/ -- (4) Simulation setup with (1) (2) (3)\n#ifdef WITH_PROJ\n SP::TimeSteppingProjectOnConstraints s(new TimeSteppingProjectOnConstraints(t, OSI, osnspb, osnspb_pos));\n s->setProjectionMaxIteration(20);\n s->setConstraintTolUnilateral(1e-08);\n s->setConstraintTol(1e-08);\n#else\n SP::TimeStepping s(new TimeStepping(t, OSI, osnspb));\n#endif\n s->setNewtonTolerance(1e-4);\n s->setNewtonMaxIteration(10);\n\n \/\/ =========================== End of model definition ===========================\n\n \/\/ ================================= Computation =================================\n\n \/\/ --- Simulation initialization ---\n\n cout << \"====> Initialisation ...\" << endl << endl;\n bouncingBall->initialize(s);\n int N = ceil((T - t0) \/ h); \/\/ Number of time steps\n\n \/\/ --- Get the values to be plotted ---\n \/\/ -> saved in a matrix dataPlot\n unsigned int outputSize = 16;\n SimpleMatrix dataPlot(N + 1, outputSize);\n\n SP::SiconosVector q = ball->q();\n SP::SiconosVector v = ball->velocity();\n SP::SiconosVector p = ball->p(1);\n SP::SiconosVector lambda = inter->lambda(1);\n\n dataPlot(0, 0) = bouncingBall->t0();\n dataPlot(0, 1) = (*q)(0);\n dataPlot(0, 2) = (*v)(0);\n dataPlot(0, 3) = (*p)(0);\n dataPlot(0, 4) = (*lambda)(0);\n dataPlot(0, 5) = acos((*q)(3));\n dataPlot(0, 6) = relation0->contactForce()->norm2();\n dataPlot(0, 7) = (*q)(0);\n dataPlot(0, 8) = (*q)(1);\n dataPlot(0, 9) = (*q)(2);\n dataPlot(0, 10) = (*q)(3);\n dataPlot(0, 11) = (*q)(4);\n dataPlot(0, 12) = (*q)(5);\n dataPlot(0, 13) = (*q)(6);\n dataPlot(0, 14) = (*v)(1);\n dataPlot(0, 15) = (*v)(2);\n\n \/\/ --- Time loop ---\n cout << \"====> Start computation ... \" << endl << endl;\n \/\/ ==== Simulation loop - Writing without explicit event handling =====\n int k = 1;\n boost::progress_display show_progress(N);\n\n boost::timer time;\n time.restart();\n dataPlot(k, 6) = relation0->contactForce()->norm2();\n while (s->hasNextEvent())\n {\n \/\/ s->computeOneStep();\n s->advanceToEvent();\n \/\/ --- Get values to be plotted ---\n dataPlot(k, 0) = s->nextTime();\n dataPlot(k, 1) = (*q)(0);\n dataPlot(k, 2) = (*v)(0);\n dataPlot(k, 3) = (*p)(0);\n dataPlot(k, 4) = (*lambda)(0);\n dataPlot(k, 5) = acos((*q)(3));\n dataPlot(k, 6) = relation0->contactForce()->norm2();\n dataPlot(k, 7) = (*q)(0);\n dataPlot(k, 8) = (*q)(1);\n dataPlot(k, 9) = (*q)(2);\n dataPlot(k, 10) = (*q)(3);\n dataPlot(k, 11) = (*q)(4);\n dataPlot(k, 12) = (*q)(5);\n dataPlot(k, 13) = (*q)(6);\n dataPlot(k, 14) = (*v)(1);\n dataPlot(k, 15) = (*v)(2);\n s->nextStep();\n ++show_progress;\n k++;\n }\n cout << endl << \"End of computation - Number of iterations done: \" << k - 1 << endl;\n cout << \"Computation Time \" << time.elapsed() << endl;\n\n \/\/ --- Output files ---\n cout << \"====> Output file writing ...\" << endl;\n dataPlot.resize(k, outputSize);\n ioMatrix::write(\"result.dat\", \"ascii\", dataPlot, \"noDim\");\n\n \/\/ Comparison with a reference file\n cout << \"====> Comparison with a reference file ...\" << endl;\n SimpleMatrix dataPlotRef(dataPlot);\n dataPlotRef.zero();\n#ifdef WITH_PROJ\n ioMatrix::read(\"resultNETS-WITHPROJ.ref\", \"ascii\", dataPlotRef);\n#else\n ioMatrix::read(\"resultNETS.ref\", \"ascii\", dataPlotRef);\n#endif\n std::cout << \"Error w.r.t reference file = \" << (dataPlot - dataPlotRef).normInf() << std::endl;\n\n if ((dataPlot - dataPlotRef).normInf() > 1e-10)\n {\n std::cout << \"Warning. The results is rather different from the reference file. err = \" << (dataPlot - dataPlotRef).normInf() << std::endl;\n \/\/(dataPlot-dataPlotRef).display();\n\n double maxerror = -1e+24;\n unsigned int imax = -1;\n unsigned int jmax = -1;\n double error;\n for (unsigned int ii = 0; ii < dataPlot.size(0); ii++)\n {\n for (unsigned int jj = 0; jj < dataPlot.size(1); jj++)\n {\n error = std::abs(dataPlot.getValue(ii, jj) - dataPlotRef.getValue(ii, jj)) ;\n if (error > 1e-12)\n {\n\n std::cout << \"error = \" << error << std::endl;\n std::cout << \"ii = \" << ii << \" jj = \" << jmax << std::endl;\n std::cout << \"dataPlot.getValue(ii,jj) = \" << dataPlot.getValue(ii, jj) << std::endl;\n std::cout << \"dataPlotRef.getValue(ii,jj) =\" << dataPlotRef.getValue(ii, jj) << std::endl;\n }\n\n if (error > maxerror)\n {\n maxerror = error ;\n imax = ii;\n jmax = jj;\n }\n }\n }\n std::cout << \"max error = \" << maxerror << std::endl;\n std::cout << \"imax = \" << imax << \" jmax = \" << jmax << std::endl;\n std::cout << \"dataPlot.getValue(imax,jmax) = \" << dataPlot.getValue(imax, jmax) << std::endl;\n std::cout << \"dataPlotRef.getValue(imax,jmax) =\" << dataPlotRef.getValue(imax, jmax) << std::endl;\n\n\n return 1;\n }\n }\n\n catch (SiconosException e)\n {\n cout << e.report() << endl;\n }\n catch (...)\n {\n cout << \"Exception caught in BouncingBallNETS.cpp\" << endl;\n }\n\n}\nfix ref files\/* Siconos-sample , Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos 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 General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n *\/\n\n\/*!\\file BouncingBallNETS.cpp\n \\brief \\ref EMBouncingBall - C++ input file, Time-Stepping version -\n V. Acary, O. Bonnefon.\n\n A Ball bouncing on the ground.\n Direct description of the model without XML input.\n Simulation with a Time-Stepping scheme.\n*\/\n#include \"SphereNEDSPlanR.hpp\"\n#include \"SiconosKernel.hpp\"\n\n#define WITH_PROJ\n#define WITH_FC3D\nusing namespace std;\n#ifdef WITH_FC3D\n#define R_CLASS NewtonEulerFrom3DLocalFrameR\n#else\n#define R_CLASS NewtonEulerFrom1DLocalFrameR\n#endif\n\nclass my_NewtonEulerR : public R_CLASS\n{\n\n double _sBallRadius ;\n\npublic:\n\n my_NewtonEulerR(double radius): R_CLASS(), _sBallRadius(radius) { };\n\n virtual void computeh(double t, Interaction& inter)\n {\n SP::SiconosVector y = inter.y(0);\n double height = fabs(inter.data(q0)->getValue(0)) - _sBallRadius;\n \/\/ std::cout <<\"my_NewtonEulerR:: computeh _jachq\" << std:: endl;\n \/\/ _jachq->display();\n y->setValue(0, height);\n _Nc->setValue(0, 1);\n _Nc->setValue(1, 0);\n _Nc->setValue(2, 0);\n _Pc1->setValue(0, height);\n _Pc1->setValue(1, inter.data(q0)->getValue(1));\n _Pc1->setValue(2, inter.data(q0)->getValue(2));\n\n \/\/_Pc2->setValue(0,hpc);\n \/\/_Pc2->setValue(1,data[q0]->getValue(1));\n \/\/_Pc2->setValue(2,data[q0]->getValue(2));\n \/\/printf(\"my_NewtonEulerR N, Pc\\n\");\n \/\/_Nc->display();\n \/\/_Pc1->display();\n }\n \/\/ACCEPT_VISITORS();\n};\nTYPEDEF_SPTR(my_NewtonEulerR);\n\n\n\n\n\nint main(int argc, char* argv[])\n{\n try\n {\n\n\n \/\/ ================= Creation of the model =======================\n\n \/\/ User-defined main parameters\n unsigned int nDof = 3; \/\/ degrees of freedom for the ball\n unsigned int qDim = 7; \/\/ degrees of freedom for the ball\n unsigned int nDim = 6; \/\/ degrees of freedom for the ball\n double t0 = 0; \/\/ initial computation time\n double T = 10.0; \/\/ final computation time\n double h = 0.005; \/\/ time step\n double position_init = 1.0; \/\/ initial position for lowest bead.\n double velocity_init = 2.0; \/\/ initial velocity for lowest bead.\n double omega_initx = 0.0;\n double omega_initz = 0.0;\/\/ initial velocity for lowest bead.\n double theta = 0.5; \/\/ theta for Moreau integrator\n double m = 1; \/\/ Ball mass\n double g = 9.81; \/\/ Gravity\n double radius = 0.1;\n \/\/ -------------------------\n \/\/ --- Dynamical systems ---\n \/\/ -------------------------\n\n cout << \"====> Model loading ...\" << endl << endl;\n\n \/\/ -- Initial positions and velocities --\n SP::SiconosVector q0(new SiconosVector(qDim));\n SP::SiconosVector v0(new SiconosVector(nDim));\n SP::SimpleMatrix I(new SimpleMatrix(3, 3));\n v0->zero();\n q0->zero();\n I->eye();\n (*q0)(0) = position_init;\n \/*initial quaternion equal to (1,0,0,0)*\/\n (*q0)(3) = 1.0;\n\n (*v0)(0) = velocity_init;\n (*v0)(3) = omega_initx;\n (*v0)(5) = omega_initz;\n \/\/ -- The dynamical system --\n SP::NewtonEulerDS ball(new NewtonEulerDS(q0, v0, m, I));\n\n \/\/ -- Set external forces (weight) --\n SP::SiconosVector weight(new SiconosVector(nDof));\n (*weight)(0) = -m * g;\n ball->setFExtPtr(weight);\n\n \/\/ --------------------\n \/\/ --- Interactions ---\n \/\/ --------------------\n\n \/\/ -- nslaw --\n double e = 0.9;\n\n \/\/ Interaction ball-floor\n \/\/\n\n \/\/ vector vecMatrix1;\n \/\/ vecMatrix1.push_back(H);\n \/\/ SP::BlockMatrix H_block(new BlockMatrix(vecMatrix1,1,1));\n\n \/\/ SP::SiconosMatrix HT(new SimpleMatrix(1,nDim));\n \/\/ vector vecMatrix2;\n \/\/ vecMatrix2.push_back(HT);\n \/\/ SP::BlockMatrix HT_block(new BlockMatrix(vecMatrix2,1,1));\n\n#ifdef WITH_FC3D\n int nslawsize = 3;\n SP::NonSmoothLaw nslaw0(new NewtonImpactFrictionNSL(e, e, 0.6, 3));\n#else\n int nslawsize = 1;\n SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));\n#endif\n\n\n \/\/ Version with NewtonEulerR()\n \/\/\n \/\/ SP::SimpleMatrix H(new SimpleMatrix(nslawsize,qDim));\n \/\/ H->zero();\n \/\/ (*H)(0,0) = 1.0;\n \/\/ #ifdef WITH_FC3D\n \/\/ (*H)(1,1) = 1.0;\n \/\/ (*H)(2,2) = 1.0;\n \/\/ #endif\n \/\/ \/\/SP::NewtonEulerR relation0(new SphereNEDSPlanR(0.1,1.0,0.0,0.0,0.0));\n \/\/ \/\/SP::NewtonEulerR relation0(new NewtonEulerR());\n \/\/ \/\/relation0->setJachq(H);\n \/\/ \/\/ relation0->setJacQH(H_block);\n \/\/ \/\/ relation0->setJacQHT(HT_block);\n \/\/ \/\/cout<<\"main jacQH\"<jachq()->display();\n\n \/\/ Version with my_NewtonEulerR()\n SP::NewtonEulerR relation0(new my_NewtonEulerR(radius));\n SP::Interaction inter(new Interaction(nslawsize, nslaw0, relation0));\n\n \/\/ -------------\n \/\/ --- Model ---\n \/\/ -------------\n SP::Model bouncingBall(new Model(t0, T));\n \/\/ add the dynamical system in the non smooth dynamical system\n bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball);\n\n \/\/ link the interaction and the dynamical system\n bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball);\n\n \/\/ ------------------\n \/\/ --- Simulation ---\n \/\/ ------------------\n\n \/\/ -- (1) OneStepIntegrators --\n#ifdef WITH_PROJ\n SP::MoreauProjectOnConstraintsOSI OSI(new MoreauProjectOnConstraintsOSI(ball, theta));\n#else\n SP::Moreau OSI(new Moreau(ball, theta));\n#endif\n \/\/ -- (2) Time discretisation --\n SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n \/\/ -- (3) one step non smooth problem\n SP::OneStepNSProblem osnspb(new GenericMechanical());\n#ifdef WITH_PROJ\n SP::OneStepNSProblem osnspb_pos(new MLCPProjectOnConstraints(SICONOS_MLCP_ENUM, 1.0));\n#endif\n \/\/ -- (4) Simulation setup with (1) (2) (3)\n#ifdef WITH_PROJ\n SP::TimeSteppingProjectOnConstraints s(new TimeSteppingProjectOnConstraints(t, OSI, osnspb, osnspb_pos));\n s->setProjectionMaxIteration(20);\n s->setConstraintTolUnilateral(1e-08);\n s->setConstraintTol(1e-08);\n#else\n SP::TimeStepping s(new TimeStepping(t, OSI, osnspb));\n#endif\n s->setNewtonTolerance(1e-4);\n s->setNewtonMaxIteration(10);\n\n \/\/ =========================== End of model definition ===========================\n\n \/\/ ================================= Computation =================================\n\n \/\/ --- Simulation initialization ---\n\n cout << \"====> Initialisation ...\" << endl << endl;\n bouncingBall->initialize(s);\n int N = ceil((T - t0) \/ h); \/\/ Number of time steps\n\n \/\/ --- Get the values to be plotted ---\n \/\/ -> saved in a matrix dataPlot\n unsigned int outputSize = 16;\n SimpleMatrix dataPlot(N + 1, outputSize);\n\n SP::SiconosVector q = ball->q();\n SP::SiconosVector v = ball->velocity();\n SP::SiconosVector p = ball->p(1);\n SP::SiconosVector lambda = inter->lambda(1);\n\n dataPlot(0, 0) = bouncingBall->t0();\n dataPlot(0, 1) = (*q)(0);\n dataPlot(0, 2) = (*v)(0);\n dataPlot(0, 3) = (*p)(0);\n dataPlot(0, 4) = (*lambda)(0);\n dataPlot(0, 5) = acos((*q)(3));\n dataPlot(0, 6) = relation0->contactForce()->norm2();\n dataPlot(0, 7) = (*q)(0);\n dataPlot(0, 8) = (*q)(1);\n dataPlot(0, 9) = (*q)(2);\n dataPlot(0, 10) = (*q)(3);\n dataPlot(0, 11) = (*q)(4);\n dataPlot(0, 12) = (*q)(5);\n dataPlot(0, 13) = (*q)(6);\n dataPlot(0, 14) = (*v)(1);\n dataPlot(0, 15) = (*v)(2);\n\n \/\/ --- Time loop ---\n cout << \"====> Start computation ... \" << endl << endl;\n \/\/ ==== Simulation loop - Writing without explicit event handling =====\n int k = 1;\n boost::progress_display show_progress(N);\n\n boost::timer time;\n time.restart();\n dataPlot(k, 6) = relation0->contactForce()->norm2();\n while (s->hasNextEvent())\n {\n \/\/ s->computeOneStep();\n s->advanceToEvent();\n \/\/ --- Get values to be plotted ---\n dataPlot(k, 0) = s->nextTime();\n dataPlot(k, 1) = (*q)(0);\n dataPlot(k, 2) = (*v)(0);\n dataPlot(k, 3) = (*p)(0);\n dataPlot(k, 4) = (*lambda)(0);\n dataPlot(k, 5) = acos((*q)(3));\n dataPlot(k, 6) = relation0->contactForce()->norm2();\n dataPlot(k, 7) = (*q)(0);\n dataPlot(k, 8) = (*q)(1);\n dataPlot(k, 9) = (*q)(2);\n dataPlot(k, 10) = (*q)(3);\n dataPlot(k, 11) = (*q)(4);\n dataPlot(k, 12) = (*q)(5);\n dataPlot(k, 13) = (*q)(6);\n dataPlot(k, 14) = (*v)(1);\n dataPlot(k, 15) = (*v)(2);\n s->nextStep();\n ++show_progress;\n k++;\n }\n cout << endl << \"End of computation - Number of iterations done: \" << k - 1 << endl;\n cout << \"Computation Time \" << time.elapsed() << endl;\n\n \/\/ --- Output files ---\n cout << \"====> Output file writing ...\" << endl;\n dataPlot.resize(k, outputSize);\n ioMatrix::write(\"result.dat\", \"ascii\", dataPlot, \"noDim\");\n\n \/\/ Comparison with a reference file\n cout << \"====> Comparison with a reference file ...\" << endl;\n SimpleMatrix dataPlotRef(dataPlot);\n dataPlotRef.zero();\n#ifdef WITH_PROJ\n ioMatrix::read(\"resultNETS-WITHPROJ.ref\", \"ascii\", dataPlotRef);\n#else\n ioMatrix::read(\"resultNETS.ref\", \"ascii\", dataPlotRef);\n#endif\n std::cout << \"Error w.r.t reference file = \" << (dataPlot - dataPlotRef).normInf() << std::endl;\n\n if ((dataPlot - dataPlotRef).normInf() > 1e-10)\n {\n std::cout << \"Warning. The results is rather different from the reference file. err = \" << (dataPlot - dataPlotRef).normInf() << std::endl;\n \/\/(dataPlot-dataPlotRef).display();\n\n double maxerror = -1e+24;\n unsigned int imax = -1;\n unsigned int jmax = -1;\n double error;\n for (unsigned int ii = 0; ii < dataPlot.size(0); ii++)\n {\n for (unsigned int jj = 0; jj < dataPlot.size(1); jj++)\n {\n error = std::abs(dataPlot.getValue(ii, jj) - dataPlotRef.getValue(ii, jj)) ;\n if (error > 1e-12)\n {\n\n std::cout << \"error = \" << error << std::endl;\n std::cout << \"ii = \" << ii << \" jj = \" << jmax << std::endl;\n std::cout << \"dataPlot.getValue(ii,jj) = \" << dataPlot.getValue(ii, jj) << std::endl;\n std::cout << \"dataPlotRef.getValue(ii,jj) =\" << dataPlotRef.getValue(ii, jj) << std::endl;\n }\n\n if (error > maxerror)\n {\n maxerror = error ;\n imax = ii;\n jmax = jj;\n }\n }\n }\n std::cout << \"max error = \" << maxerror << std::endl;\n std::cout << \"imax = \" << imax << \" jmax = \" << jmax << std::endl;\n std::cout << \"dataPlot.getValue(imax,jmax) = \" << dataPlot.getValue(imax, jmax) << std::endl;\n std::cout << \"dataPlotRef.getValue(imax,jmax) =\" << dataPlotRef.getValue(imax, jmax) << std::endl;\n\n\n return 1;\n }\n }\n\n catch (SiconosException e)\n {\n cout << e.report() << endl;\n }\n catch (...)\n {\n cout << \"Exception caught in BouncingBallNETS.cpp\" << endl;\n }\n\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\/browser\/atom_resource_dispatcher_host_delegate.h\"\n\n#include \"atom\/browser\/login_handler.h\"\n#include \"atom\/browser\/web_contents_permission_helper.h\"\n#include \"atom\/common\/platform_util.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"net\/base\/escape.h\"\n#include \"url\/gurl.h\"\n\nusing content::BrowserThread;\n\nnamespace atom {\n\nnamespace {\n\nvoid OnOpenExternal(const GURL& escaped_url,\n bool allowed) {\n if (allowed)\n platform_util::OpenExternal(escaped_url, true);\n}\n\nvoid HandleExternalProtocolInUI(\n const GURL& url,\n const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,\n bool has_user_gesture) {\n content::WebContents* web_contents = web_contents_getter.Run();\n if (!web_contents)\n return;\n\n GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));\n auto callback = base::Bind(&OnOpenExternal, escaped_url);\n auto permission_helper =\n WebContentsPermissionHelper::FromWebContents(web_contents);\n permission_helper->RequestOpenExternalPermission(callback, has_user_gesture);\n}\n\n} \/\/ namespace\n\nAtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {\n}\n\nbool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(\n const GURL& url,\n int child_id,\n const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,\n bool is_main_frame,\n ui::PageTransition transition,\n bool has_user_gesture) {\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&HandleExternalProtocolInUI,\n url,\n web_contents_getter,\n has_user_gesture));\n return true;\n}\n\ncontent::ResourceDispatcherHostLoginDelegate*\nAtomResourceDispatcherHostDelegate::CreateLoginDelegate(\n net::AuthChallengeInfo* auth_info,\n net::URLRequest* request) {\n return new LoginHandler(auth_info, request);\n}\n\n} \/\/ namespace atom\nfix dereferencing null pointer\/\/ 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\/browser\/atom_resource_dispatcher_host_delegate.h\"\n\n#include \"atom\/browser\/login_handler.h\"\n#include \"atom\/browser\/web_contents_permission_helper.h\"\n#include \"atom\/common\/platform_util.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"net\/base\/escape.h\"\n#include \"url\/gurl.h\"\n\nusing content::BrowserThread;\n\nnamespace atom {\n\nnamespace {\n\nvoid OnOpenExternal(const GURL& escaped_url,\n bool allowed) {\n if (allowed)\n platform_util::OpenExternal(escaped_url, true);\n}\n\nvoid HandleExternalProtocolInUI(\n const GURL& url,\n const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,\n bool has_user_gesture) {\n content::WebContents* web_contents = web_contents_getter.Run();\n if (!web_contents)\n return;\n\n auto permission_helper =\n WebContentsPermissionHelper::FromWebContents(web_contents);\n if (!permission_helper)\n return;\n\n GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));\n auto callback = base::Bind(&OnOpenExternal, escaped_url);\n permission_helper->RequestOpenExternalPermission(callback, has_user_gesture);\n}\n\n} \/\/ namespace\n\nAtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {\n}\n\nbool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(\n const GURL& url,\n int child_id,\n const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,\n bool is_main_frame,\n ui::PageTransition transition,\n bool has_user_gesture) {\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&HandleExternalProtocolInUI,\n url,\n web_contents_getter,\n has_user_gesture));\n return true;\n}\n\ncontent::ResourceDispatcherHostLoginDelegate*\nAtomResourceDispatcherHostDelegate::CreateLoginDelegate(\n net::AuthChallengeInfo* auth_info,\n net::URLRequest* request) {\n return new LoginHandler(auth_info, request);\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\nusing namespace sensor_msgs;\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\nusing namespace pcl::registration;\nusing namespace pcl::visualization;\n\ntypedef PointNormal PointT;\ntypedef PointCloud Cloud;\ntypedef Cloud::Ptr CloudPtr;\ntypedef Cloud::ConstPtr CloudConstPtr;\n\nCloudPtr src, tgt;\n\nbool rejection = true;\nbool visualize = false;\n\nboost::shared_ptr vis;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nfindCorrespondences (const CloudPtr &src,\n const CloudPtr &tgt,\n Correspondences &all_correspondences)\n{\n \/\/CorrespondenceEstimationNormalShooting est;\n \/\/CorrespondenceEstimation est;\n CorrespondenceEstimationBackProjection est;\n est.setInputSource (src);\n est.setInputTarget (tgt);\n \n est.setSourceNormals (src);\n est.setTargetNormals (tgt);\n est.setKSearch (10);\n est.determineCorrespondences (all_correspondences);\n \/\/est.determineReciprocalCorrespondences (all_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nrejectBadCorrespondences (const CorrespondencesPtr &all_correspondences,\n const CloudPtr &src,\n const CloudPtr &tgt,\n Correspondences &remaining_correspondences)\n{\n CorrespondenceRejectorMedianDistance rej;\n rej.setMedianFactor (8.79241104);\n rej.setInputCorrespondences (all_correspondences);\n\n rej.getCorrespondences (remaining_correspondences);\n return;\n \n CorrespondencesPtr remaining_correspondences_temp (new Correspondences);\n rej.getCorrespondences (*remaining_correspondences_temp);\n PCL_DEBUG (\"[rejectBadCorrespondences] Number of correspondences remaining after rejection: %d\\n\", remaining_correspondences_temp->size ());\n\n \/\/ Reject if the angle between the normals is really off\n CorrespondenceRejectorSurfaceNormal rej_normals;\n rej_normals.setThreshold (acos (deg2rad (45.0)));\n rej_normals.initializeDataContainer ();\n rej_normals.setInputCloud (src);\n rej_normals.setInputNormals (src);\n rej_normals.setInputTarget (tgt);\n rej_normals.setTargetNormals (tgt);\n rej_normals.setInputCorrespondences (remaining_correspondences_temp);\n rej_normals.getCorrespondences (remaining_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nfindTransformation (const CloudPtr &src,\n const CloudPtr &tgt,\n const CorrespondencesPtr &correspondences,\n Eigen::Matrix4d &transform)\n{\n TransformationEstimationPointToPlaneLLS trans_est;\n trans_est.estimateRigidTransformation (*src, *tgt, *correspondences, transform);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nview (const CloudConstPtr &src, const CloudConstPtr &tgt, const CorrespondencesPtr &correspondences)\n{\n if (!visualize || !vis) return;\n PointCloudColorHandlerCustom green (tgt, 0, 255, 0);\n if (!vis->updatePointCloud (src, \"source\"))\n {\n vis->addPointCloud (src, \"source\");\n vis->resetCameraViewpoint (\"source\");\n }\n if (!vis->updatePointCloud (tgt, green, \"target\")) vis->addPointCloud (tgt, green, \"target\");\n vis->setPointCloudRenderingProperties (PCL_VISUALIZER_OPACITY, 0.5, \"source\");\n vis->setPointCloudRenderingProperties (PCL_VISUALIZER_OPACITY, 0.7, \"target\");\n vis->setPointCloudRenderingProperties (PCL_VISUALIZER_POINT_SIZE, 6, \"source\");\n TicToc tt;\n tt.tic ();\n if (!vis->updateCorrespondences (src, tgt, *correspondences, 1)) \n vis->addCorrespondences (src, tgt, *correspondences, 1, \"correspondences\");\n tt.toc_print ();\n vis->setShapeRenderingProperties (PCL_VISUALIZER_LINE_WIDTH, 5, \"correspondences\");\n \/\/vis->setShapeRenderingProperties (PCL_VISUALIZER_COLOR, 1.0, 0.0, 0.0, \"correspondences\");\n vis->spin ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nicp (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n Eigen::Matrix4d &transform)\n{\n CorrespondencesPtr all_correspondences (new Correspondences), \n good_correspondences (new Correspondences);\n\n PointCloud::Ptr output (new PointCloud);\n *output = *src;\n\n Eigen::Matrix4d final_transform (Eigen::Matrix4d::Identity ());\n\n int iterations = 0;\n DefaultConvergenceCriteria converged (iterations, transform, *good_correspondences);\n\n \/\/ ICP loop\n do\n {\n \/\/ Find correspondences\n findCorrespondences (output, tgt, *all_correspondences);\n PCL_DEBUG (\"Number of correspondences found: %d\\n\", all_correspondences->size ());\n\n if (rejection)\n {\n \/\/ Reject correspondences\n rejectBadCorrespondences (all_correspondences, output, tgt, *good_correspondences);\n PCL_DEBUG (\"Number of correspondences remaining after rejection: %d\\n\", good_correspondences->size ());\n }\n else\n *good_correspondences = *all_correspondences;\n\n \/\/ Find transformation\n findTransformation (output, tgt, good_correspondences, transform);\n \n \/\/ Obtain the final transformation \n final_transform = transform * final_transform;\n\n \/\/ Transform the data\n transformPointCloudWithNormals (*src, *output, final_transform.cast ());\n\n \/\/ Check if convergence has been reached\n ++iterations;\n \n \/\/ Visualize the results\n view (output, tgt, good_correspondences);\n }\n while (!converged);\n transform = final_transform;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nsaveTransform (const std::string &file, const Eigen::Matrix4d &transform)\n{\n ofstream ofs;\n ofs.open (file.c_str (), ios::trunc | ios::binary);\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n ofs.write (reinterpret_cast(&transform (i, j)), sizeof (double)); \n ofs.close ();\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n \/\/ Check whether we want to enable debug mode\n bool debug = false;\n parse_argument (argc, argv, \"-debug\", debug);\n if (debug)\n setVerbosityLevel (L_DEBUG);\n\n parse_argument (argc, argv, \"-rejection\", rejection);\n parse_argument (argc, argv, \"-visualization\", visualize);\n if (visualize)\n vis.reset (new PCLVisualizer (\"Registration example\"));\n\n \/\/ Parse the command line arguments for .pcd and .transform files\n std::vector p_pcd_file_indices, p_tr_file_indices;\n p_pcd_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_pcd_file_indices.size () != 2)\n {\n print_error (\"Need one input source PCD file and one input target PCD file to continue.\\n\");\n print_error (\"Example: %s source.pcd target.pcd output.transform\\n\", argv[0]);\n return (-1);\n }\n p_tr_file_indices = parse_file_extension_argument (argc, argv, \".transform\");\n if (p_tr_file_indices.size () != 1)\n {\n print_error (\"Need one output transform file to continue.\\n\");\n print_error (\"Example: %s source.pcd target.pcd output.transform\\n\", argv[0]);\n return (-1);\n }\n \n \/\/ Load the files\n print_info (\"Loading %s as source and %s as target...\\n\", argv[p_pcd_file_indices[0]], argv[p_pcd_file_indices[1]]);\n src.reset (new PointCloud);\n tgt.reset (new PointCloud);\n if (loadPCDFile (argv[p_pcd_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_pcd_file_indices[1]], *tgt) == -1)\n {\n print_error (\"Error reading the input files!\\n\");\n return (-1);\n }\n\n \/\/ Compute the best transformtion\n Eigen::Matrix4d transform;\n icp (src, tgt, transform);\n\n saveTransform (argv[p_tr_file_indices[0]], transform);\n\n cerr.precision (15);\n std::cerr << transform << std::endl;\n}\n\/* ]--- *\/\n#include #include #include #include #include #include #include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\nusing namespace sensor_msgs;\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\nusing namespace pcl::registration;\nusing namespace pcl::visualization;\n\ntypedef PointNormal PointT;\ntypedef PointCloud Cloud;\ntypedef Cloud::Ptr CloudPtr;\ntypedef Cloud::ConstPtr CloudConstPtr;\n\nCloudPtr src, tgt;\n\nbool rejection = true;\nbool visualize = false;\n\nboost::shared_ptr vis;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nfindCorrespondences (const CloudPtr &src,\n const CloudPtr &tgt,\n Correspondences &all_correspondences)\n{\n \/\/CorrespondenceEstimationNormalShooting est;\n \/\/CorrespondenceEstimation est;\n CorrespondenceEstimationBackProjection est;\n est.setInputSource (src);\n est.setInputTarget (tgt);\n \n est.setSourceNormals (src);\n est.setTargetNormals (tgt);\n est.setKSearch (10);\n est.determineCorrespondences (all_correspondences);\n \/\/est.determineReciprocalCorrespondences (all_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nrejectBadCorrespondences (const CorrespondencesPtr &all_correspondences,\n const CloudPtr &src,\n const CloudPtr &tgt,\n Correspondences &remaining_correspondences)\n{\n CorrespondenceRejectorMedianDistance rej;\n rej.setMedianFactor (8.79241104);\n rej.setInputCorrespondences (all_correspondences);\n\n rej.getCorrespondences (remaining_correspondences);\n return;\n \n CorrespondencesPtr remaining_correspondences_temp (new Correspondences);\n rej.getCorrespondences (*remaining_correspondences_temp);\n PCL_DEBUG (\"[rejectBadCorrespondences] Number of correspondences remaining after rejection: %d\\n\", remaining_correspondences_temp->size ());\n\n \/\/ Reject if the angle between the normals is really off\n CorrespondenceRejectorSurfaceNormal rej_normals;\n rej_normals.setThreshold (acos (deg2rad (45.0)));\n rej_normals.initializeDataContainer ();\n rej_normals.setInputCloud (src);\n rej_normals.setInputNormals (src);\n rej_normals.setInputTarget (tgt);\n rej_normals.setTargetNormals (tgt);\n rej_normals.setInputCorrespondences (remaining_correspondences_temp);\n rej_normals.getCorrespondences (remaining_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nfindTransformation (const CloudPtr &src,\n const CloudPtr &tgt,\n const CorrespondencesPtr &correspondences,\n Eigen::Matrix4d &transform)\n{\n TransformationEstimationPointToPlaneLLS trans_est;\n trans_est.estimateRigidTransformation (*src, *tgt, *correspondences, transform);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nview (const CloudConstPtr &src, const CloudConstPtr &tgt, const CorrespondencesPtr &correspondences)\n{\n if (!visualize || !vis) return;\n PointCloudColorHandlerCustom green (tgt, 0, 255, 0);\n if (!vis->updatePointCloud (src, \"source\"))\n {\n vis->addPointCloud (src, \"source\");\n vis->resetCameraViewpoint (\"source\");\n }\n if (!vis->updatePointCloud (tgt, green, \"target\")) vis->addPointCloud (tgt, green, \"target\");\n vis->setPointCloudRenderingProperties (PCL_VISUALIZER_OPACITY, 0.5, \"source\");\n vis->setPointCloudRenderingProperties (PCL_VISUALIZER_OPACITY, 0.7, \"target\");\n vis->setPointCloudRenderingProperties (PCL_VISUALIZER_POINT_SIZE, 6, \"source\");\n pcl::console::TicToc tt;\n tt.tic ();\n if (!vis->updateCorrespondences (src, tgt, *correspondences, 1)) \n vis->addCorrespondences (src, tgt, *correspondences, 1, \"correspondences\");\n tt.toc_print ();\n vis->setShapeRenderingProperties (PCL_VISUALIZER_LINE_WIDTH, 5, \"correspondences\");\n \/\/vis->setShapeRenderingProperties (PCL_VISUALIZER_COLOR, 1.0, 0.0, 0.0, \"correspondences\");\n vis->spin ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nicp (const PointCloud::Ptr &src, \n const PointCloud::Ptr &tgt,\n Eigen::Matrix4d &transform)\n{\n CorrespondencesPtr all_correspondences (new Correspondences), \n good_correspondences (new Correspondences);\n\n PointCloud::Ptr output (new PointCloud);\n *output = *src;\n\n Eigen::Matrix4d final_transform (Eigen::Matrix4d::Identity ());\n\n int iterations = 0;\n DefaultConvergenceCriteria converged (iterations, transform, *good_correspondences);\n\n \/\/ ICP loop\n do\n {\n \/\/ Find correspondences\n findCorrespondences (output, tgt, *all_correspondences);\n PCL_DEBUG (\"Number of correspondences found: %d\\n\", all_correspondences->size ());\n\n if (rejection)\n {\n \/\/ Reject correspondences\n rejectBadCorrespondences (all_correspondences, output, tgt, *good_correspondences);\n PCL_DEBUG (\"Number of correspondences remaining after rejection: %d\\n\", good_correspondences->size ());\n }\n else\n *good_correspondences = *all_correspondences;\n\n \/\/ Find transformation\n findTransformation (output, tgt, good_correspondences, transform);\n \n \/\/ Obtain the final transformation \n final_transform = transform * final_transform;\n\n \/\/ Transform the data\n transformPointCloudWithNormals (*src, *output, final_transform.cast ());\n\n \/\/ Check if convergence has been reached\n ++iterations;\n \n \/\/ Visualize the results\n view (output, tgt, good_correspondences);\n }\n while (!converged);\n transform = final_transform;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nsaveTransform (const std::string &file, const Eigen::Matrix4d &transform)\n{\n ofstream ofs;\n ofs.open (file.c_str (), ios::trunc | ios::binary);\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n ofs.write (reinterpret_cast(&transform (i, j)), sizeof (double)); \n ofs.close ();\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n \/\/ Check whether we want to enable debug mode\n bool debug = false;\n parse_argument (argc, argv, \"-debug\", debug);\n if (debug)\n setVerbosityLevel (L_DEBUG);\n\n parse_argument (argc, argv, \"-rejection\", rejection);\n parse_argument (argc, argv, \"-visualization\", visualize);\n if (visualize)\n vis.reset (new PCLVisualizer (\"Registration example\"));\n\n \/\/ Parse the command line arguments for .pcd and .transform files\n std::vector p_pcd_file_indices, p_tr_file_indices;\n p_pcd_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_pcd_file_indices.size () != 2)\n {\n print_error (\"Need one input source PCD file and one input target PCD file to continue.\\n\");\n print_error (\"Example: %s source.pcd target.pcd output.transform\\n\", argv[0]);\n return (-1);\n }\n p_tr_file_indices = parse_file_extension_argument (argc, argv, \".transform\");\n if (p_tr_file_indices.size () != 1)\n {\n print_error (\"Need one output transform file to continue.\\n\");\n print_error (\"Example: %s source.pcd target.pcd output.transform\\n\", argv[0]);\n return (-1);\n }\n \n \/\/ Load the files\n print_info (\"Loading %s as source and %s as target...\\n\", argv[p_pcd_file_indices[0]], argv[p_pcd_file_indices[1]]);\n src.reset (new PointCloud);\n tgt.reset (new PointCloud);\n if (loadPCDFile (argv[p_pcd_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_pcd_file_indices[1]], *tgt) == -1)\n {\n print_error (\"Error reading the input files!\\n\");\n return (-1);\n }\n\n \/\/ Compute the best transformtion\n Eigen::Matrix4d transform;\n icp (src, tgt, transform);\n\n saveTransform (argv[p_tr_file_indices[0]], transform);\n\n cerr.precision (15);\n std::cerr << transform << std::endl;\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/StroikaPreComp.h\"\n\n#include\t\n#include\t\n#include\t\n#include\t\n\n#if\t\tqPlatform_POSIX\n\t#include\t\n\t#include\t\n\t#include\t\n#endif\n\n#include\t\"..\/..\/Foundation\/Characters\/Format.h\"\n#include\t\"..\/..\/Foundation\/Containers\/Common.h\"\n#include\t\"..\/..\/Foundation\/Debug\/Assertions.h\"\n#include\t\"..\/..\/Foundation\/Debug\/Trace.h\"\n#include\t\"..\/..\/Foundation\/Execution\/CommandLine.h\"\n#include\t\"..\/..\/Foundation\/Execution\/Exceptions.h\"\n#include\t\"..\/..\/Foundation\/Execution\/Module.h\"\n#include\t\"..\/..\/Foundation\/Execution\/ThreadAbortException.h\"\n#include\t\"..\/..\/Foundation\/IO\/FileSystem\/FileUtils.h\"\n#include\t\"..\/..\/Foundation\/Memory\/SmallStackBuffer.h\"\n\n#include\t\"Main.h\"\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Containers;\nusing\tnamespace\tStroika::Foundation::Memory;\n\nusing\tnamespace\tStroika::Frameworks;\nusing\tnamespace\tStroika::Frameworks::Service;\n\n\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************************** Service::Main::IRep *****************************\n ********************************************************************************\n *\/\nMain::IRep::IRep ()\n\t: fStopping_ (false)\n\t, fMustReReadConfig (false)\n{\n}\n\nMain::IRep::~IRep ()\n{\n}\n\nvoid\tMain::IRep::OnStartRequest ()\n{\n\t\/\/ This procedure ends when the entire service process ends...\n\tDebug::TraceContextBumper traceCtx (TSTR (\"Stroika::Frameworks::Service::Main::IRep::OnStartRequest\"));\n\tMainLoop ();\n}\n\nvoid\tMain::IRep::OnStopRequest ()\n{\n\t\/\/ default to using thread stuff to send us a signal to abort...\n\tfStopping_ = true;\n}\n\nvoid\tMain::IRep::OnReReadConfigurationRequest ()\n{\n}\n\nString\tMain::IRep::GetServiceStatusMessage () const\n{\n\treturn String (); \n}\n\n#if\t\tqPlatform_POSIX\nString\tMain::IRep::GetPIDFileName () const\n{\n\treturn L\"\/tmp\/\" + GetServiceDescription ().fName + L\".pid\";\n}\n#endif\n\n#if\t\tqPlatform_POSIX\nvoid\tMain::IRep::SignalHandler (int signum)\n{\n\t\/\/ VERY PRIMITIVE IMPL FOR NOW -- LGP 2011-09-24\n\tswitch (signum) {\n\tcase\tSIGTERM:\n\t\tfStopping_ = true;\n\t\tbreak;\n\t#if\t\tqCompilerAndStdLib_Supports_constexpr\n\t\tcase\tkSIG_ReReadConfiguration:\n\t#else\n\t\tcase\tSIGHUP:\n\t#endif\n\t\t\tfMustReReadConfig = true;\n\t\t\tbreak;\n\n\t}\n}\n#endif\n\n\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************************ Service::Main *****************************\n ********************************************************************************\n *\/\n\nconst\twchar_t\tService::Main::CommandNames::kRunAsService[]\t\t=\tL\"Run-As-Service\";\nconst\twchar_t\tService::Main::CommandNames::kStart[]\t\t\t\t=\tL\"Start\";\nconst\twchar_t\tService::Main::CommandNames::kStop[]\t\t\t\t=\tL\"Stop\";\nconst\twchar_t\tService::Main::CommandNames::kKill[]\t\t\t\t=\tL\"Kill\";\nconst\twchar_t\tService::Main::CommandNames::kRestart[]\t\t\t\t=\tL\"Restart\";\nconst\twchar_t\tService::Main::CommandNames::kReloadConfiguration[]\t=\tL\"Reload-Configuration\";\nconst\twchar_t\tService::Main::CommandNames::kPause[]\t\t\t\t=\tL\"Pause\";\nconst\twchar_t\tService::Main::CommandNames::kContinue[]\t\t\t=\tL\"Continue\";\n\nMemory::SharedPtr\tMain::_sRep;\n\nMain::Main (Memory::SharedPtr rep)\n{\n\tEnsure (_sRep.IsNull ());\n\t_sRep = rep;\n\t#if\t\tqPlatform_POSIX\n\t\tSetupSignalHanlders_ ();\n\t#endif\n}\n\n#if\t\tqPlatform_POSIX\nvoid\tMain::SetupSignalHanlders_ ()\n{\n\tsignal (SIGTERM, SignalHandler);\n\tsignal (kSIG_ReReadConfiguration, SignalHandler);\n}\n#endif\n\nMain::State\tMain::GetState () const\n{\n\t#if\t\tqPlatform_POSIX\n\tif (GetServicePID () != 0) {\n\t\treturn eRunning;\n\t}\n\t#endif\n\treturn eStopped;\t\/\/ otherwise (esp on other platforms where not implemtned) must be stopped\n}\n\n#if\t\tqPlatform_POSIX\npid_t\tMain::GetServicePID () const\n{\n\tifstream\tin (_sRep->GetPIDFileName ().AsTString ().c_str ());\n\tif (in) {\n\t\tpid_t\tn = 0;\n\t\tin >> n;\n\t\treturn n;\n\t}\n\treturn 0;\n}\n#endif\n\nString\t\tMain::GetServiceStatusMessage () const\n{\n\tconst\twchar_t\tkTAB[]\t=\tL\" \";\t\/\/ use spaces instead of tab so formatting independent of tabstop settings\n\tServiceDescription\tsvd\t=\tGetServiceDescription ();\n\twstringstream\ttmp;\n\ttmp << L\"Service '\" << svd.fName.As () << \"'\" << endl;\n\tswitch (this->GetState ()) {\n\t\tcase\teStopped:\t\n\t\t\ttmp << kTAB << L\"State: \" << kTAB << kTAB << kTAB << \"STOPPED\" << endl;\n\t\t\tbreak;\n\t\tcase\teRunning:\t\n\t\t\ttmp << kTAB << L\"State: \" << kTAB << kTAB << kTAB << \"Running\" << endl; \n\t\t\t#if\t\tqPlatform_POSIX\n\t\t\t\ttmp << kTAB << L\"PID: \" << kTAB << kTAB << kTAB << GetServicePID () << endl;\n\t\t\t#endif\n\t\t\tbreak;\n\t\tcase\tePaused:\t\n\t\t\ttmp << kTAB << L\"State: \" << kTAB << kTAB << kTAB << \"PAUSED\" << endl; \n\t\t\t#if\t\tqPlatform_POSIX\n\t\t\t\ttmp << kTAB << L\"PID: \" << kTAB<< kTAB << kTAB << GetServicePID () << endl;\n\t\t\t#endif\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tAssertNotReached ();\n\t}\n\ttmp << _sRep->GetServiceStatusMessage ().As ();\n\treturn tmp.str ();\n}\n\nvoid\tMain::RunAsService ()\n{\n\t\/\/ VERY PRIMITIVE IMPL - WE NEED LOCKING on tmpfile stuff - add good tempfile supprot to fileuitls or use existing...\n\n\ttry {\n#if\t\tqPlatform_POSIX\n\t\tofstream\tout (_sRep->GetPIDFileName ().AsTString ().c_str ());\n\t\tout << getpid () << endl;\n#endif\n\t\t_sRep->OnStartRequest ();\n\t}\n\tcatch (const Execution::ThreadAbortException& \/*threadAbort*\/) {\n#if\t\tqPlatform_POSIX\n\t\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n\t\t\/\/ ignore this - just means service ended normally\n\t}\n\tcatch (...) {\n\t\tDbgTrace (TSTR (\"Unexpected exception ended running service\"));\n#if\t\tqPlatform_POSIX\n\t\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n\t\tthrow;\n\t}\n}\n\nvoid\tMain::Start ()\n{\n\t\/\/ Check not already runnig, (someday) and then for and exec the \n\n#if\t\tqPlatform_POSIX\n\t\/\/ REALLY should use GETSTATE - and return state based on if PID file exsits...\n\tif (GetServicePID () != 0) {\n\t\tExecution::DoThrow (Execution::StringException (L\"Cannot Start service because its already running\"));\n\t}\n#endif\n\tCharacters::TString\tthisEXEPath\t=\tExecution::GetEXEPath ();\n#if\t\tqPlatform_POSIX\n\tpid_t\tpid\t=\tfork ();\n\tif (pid == 0) {\n\t\t\/\/ Child - exec -\n\t\t\/\/\t\tTODO:\t\tSHOULD BE CAREFUL ABOUT CLOSING FILE DESCRIPTORS BEFORE THIS ACTION - WE DONT WANT HTEM INHERITED!!!\n\t\t\/\/\t\t\t\t\tBUT DONT DO WILLYNILLY - THINK THROUGH - I CANNNOT RECALL THE EXACT RIGHT ANSWER\n\t\tint\tr\t=\texecl (thisEXEPath.c_str (), thisEXEPath.c_str (), (String (L\"--\") + String (CommandNames::kRunAsService)).AsTString ().c_str (), nullptr);\n\t\texit (-1);\n\t}\n\telse if (pid < 0) {\n\t\t\/\/ failed to fork - serious error\n\t\tExecution::errno_ErrorException::DoThrow (errno);\n\t}\n\telse {\n\t\t\/\/ parent - in this case - no reason to wait - our work is done... Future versions might wait to\n\t\t\/\/ see if the 'pidfile' got created....\n\t\t\/\/\t\t--LGP 2011-09-23\n\t}\n#endif\n}\n\nvoid\tMain::Stop ()\n{\n\t\/\/ Send signal to server to stop\n#if\t\tqPlatform_POSIX\n\tkill (GetServicePID (), SIGTERM);\n#endif\n}\n\nvoid\tMain::Kill ()\n{\n\tStop ();\n\t\/\/ Send signal to server to stop\n#if\t\tqPlatform_POSIX\n\tkill (GetServicePID (), SIGKILL);\n\t\/\/ REALY should WAIT for server to stop and only do this it fails - \n\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n}\n\nvoid\tMain::Restart ()\n{\n\tIgnoreExceptionsForCall (Stop ());\n#if\t\tqPlatform_POSIX\n\t\/\/ REALY should WAIT for server to stop and only do this it fails - \n\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n\tStart ();\n}\n\nvoid\tMain::ReReadConfiguration ()\n{\n\t\/\/ SEND APPROPRIATE SIGNAL\n#if\t\tqPlatform_POSIX\n\tpid_t\tpid\t=\tGetServicePID ();\n\tAssert (pid != 0);\t\/\/ maybe throw if non-zero???\n\tkill (GetServicePID (), kSIG_ReReadConfiguration);\n#endif\n}\n\nvoid\tMain::Pause ()\n{\n\tAssertNotImplemented ();\n}\n\nvoid\tMain::Continue ()\n{\n\tAssertNotImplemented ();\n}\n\nMain::ServiceDescription\tMain::GetServiceDescription () const\n{\n\treturn _sRep->GetServiceDescription ();\n}\n\n#if\t\tqPlatform_POSIX\nvoid\tMain::SignalHandler (int signum)\n{\n\t_sRep->SignalHandler (signum);\n}\n#endif\n\nbool\tMain::_HandleStandardCommandLineArgument (const String& arg)\n{\n\tif (Execution::MatchesCommandLineArgument (arg, CommandNames::kRunAsService)) {\n\t\tRunAsService ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStart)) {\n\t\tStart ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStop)) {\n\t\tStop ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kKill)) {\n\t\tKill ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRestart)) {\n\t\tRestart ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kReloadConfiguration)) {\n\t\tReReadConfiguration ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kPause)) {\n\t\tPause ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kContinue)) {\n\t\tContinue ();\n\t\treturn true;\n\t}\n\t\/\/\/ MANY more neeeded, and fix to use named constants...\n\treturn false;\n}\n\nfixed problems with recent chagne to ErrNoException stuff\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/StroikaPreComp.h\"\n\n#include\t\n#include\t\n#include\t\n#include\t\n\n#if\t\tqPlatform_POSIX\n\t#include\t\n\t#include\t\n\t#include\t\n#endif\n\n#include\t\"..\/..\/Foundation\/Characters\/Format.h\"\n#include\t\"..\/..\/Foundation\/Containers\/Common.h\"\n#include\t\"..\/..\/Foundation\/Debug\/Assertions.h\"\n#include\t\"..\/..\/Foundation\/Debug\/Trace.h\"\n#include\t\"..\/..\/Foundation\/Execution\/CommandLine.h\"\n#include\t\"..\/..\/Foundation\/Execution\/Exceptions.h\"\n#include\t\"..\/..\/Foundation\/Execution\/ErrNoException.h\"\n#include\t\"..\/..\/Foundation\/Execution\/Module.h\"\n#include\t\"..\/..\/Foundation\/Execution\/ThreadAbortException.h\"\n#include\t\"..\/..\/Foundation\/IO\/FileSystem\/FileUtils.h\"\n#include\t\"..\/..\/Foundation\/Memory\/SmallStackBuffer.h\"\n\n#include\t\"Main.h\"\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Containers;\nusing\tnamespace\tStroika::Foundation::Memory;\n\nusing\tnamespace\tStroika::Frameworks;\nusing\tnamespace\tStroika::Frameworks::Service;\n\n\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************************** Service::Main::IRep *****************************\n ********************************************************************************\n *\/\nMain::IRep::IRep ()\n\t: fStopping_ (false)\n\t, fMustReReadConfig (false)\n{\n}\n\nMain::IRep::~IRep ()\n{\n}\n\nvoid\tMain::IRep::OnStartRequest ()\n{\n\t\/\/ This procedure ends when the entire service process ends...\n\tDebug::TraceContextBumper traceCtx (TSTR (\"Stroika::Frameworks::Service::Main::IRep::OnStartRequest\"));\n\tMainLoop ();\n}\n\nvoid\tMain::IRep::OnStopRequest ()\n{\n\t\/\/ default to using thread stuff to send us a signal to abort...\n\tfStopping_ = true;\n}\n\nvoid\tMain::IRep::OnReReadConfigurationRequest ()\n{\n}\n\nString\tMain::IRep::GetServiceStatusMessage () const\n{\n\treturn String (); \n}\n\n#if\t\tqPlatform_POSIX\nString\tMain::IRep::GetPIDFileName () const\n{\n\treturn L\"\/tmp\/\" + GetServiceDescription ().fName + L\".pid\";\n}\n#endif\n\n#if\t\tqPlatform_POSIX\nvoid\tMain::IRep::SignalHandler (int signum)\n{\n\t\/\/ VERY PRIMITIVE IMPL FOR NOW -- LGP 2011-09-24\n\tswitch (signum) {\n\tcase\tSIGTERM:\n\t\tfStopping_ = true;\n\t\tbreak;\n\t#if\t\tqCompilerAndStdLib_Supports_constexpr\n\t\tcase\tkSIG_ReReadConfiguration:\n\t#else\n\t\tcase\tSIGHUP:\n\t#endif\n\t\t\tfMustReReadConfig = true;\n\t\t\tbreak;\n\n\t}\n}\n#endif\n\n\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************************ Service::Main *****************************\n ********************************************************************************\n *\/\n\nconst\twchar_t\tService::Main::CommandNames::kRunAsService[]\t\t=\tL\"Run-As-Service\";\nconst\twchar_t\tService::Main::CommandNames::kStart[]\t\t\t\t=\tL\"Start\";\nconst\twchar_t\tService::Main::CommandNames::kStop[]\t\t\t\t=\tL\"Stop\";\nconst\twchar_t\tService::Main::CommandNames::kKill[]\t\t\t\t=\tL\"Kill\";\nconst\twchar_t\tService::Main::CommandNames::kRestart[]\t\t\t\t=\tL\"Restart\";\nconst\twchar_t\tService::Main::CommandNames::kReloadConfiguration[]\t=\tL\"Reload-Configuration\";\nconst\twchar_t\tService::Main::CommandNames::kPause[]\t\t\t\t=\tL\"Pause\";\nconst\twchar_t\tService::Main::CommandNames::kContinue[]\t\t\t=\tL\"Continue\";\n\nMemory::SharedPtr\tMain::_sRep;\n\nMain::Main (Memory::SharedPtr rep)\n{\n\tEnsure (_sRep.IsNull ());\n\t_sRep = rep;\n\t#if\t\tqPlatform_POSIX\n\t\tSetupSignalHanlders_ ();\n\t#endif\n}\n\n#if\t\tqPlatform_POSIX\nvoid\tMain::SetupSignalHanlders_ ()\n{\n\tsignal (SIGTERM, SignalHandler);\n\tsignal (kSIG_ReReadConfiguration, SignalHandler);\n}\n#endif\n\nMain::State\tMain::GetState () const\n{\n\t#if\t\tqPlatform_POSIX\n\tif (GetServicePID () != 0) {\n\t\treturn eRunning;\n\t}\n\t#endif\n\treturn eStopped;\t\/\/ otherwise (esp on other platforms where not implemtned) must be stopped\n}\n\n#if\t\tqPlatform_POSIX\npid_t\tMain::GetServicePID () const\n{\n\tifstream\tin (_sRep->GetPIDFileName ().AsTString ().c_str ());\n\tif (in) {\n\t\tpid_t\tn = 0;\n\t\tin >> n;\n\t\treturn n;\n\t}\n\treturn 0;\n}\n#endif\n\nString\t\tMain::GetServiceStatusMessage () const\n{\n\tconst\twchar_t\tkTAB[]\t=\tL\" \";\t\/\/ use spaces instead of tab so formatting independent of tabstop settings\n\tServiceDescription\tsvd\t=\tGetServiceDescription ();\n\twstringstream\ttmp;\n\ttmp << L\"Service '\" << svd.fName.As () << \"'\" << endl;\n\tswitch (this->GetState ()) {\n\t\tcase\teStopped:\t\n\t\t\ttmp << kTAB << L\"State: \" << kTAB << kTAB << kTAB << \"STOPPED\" << endl;\n\t\t\tbreak;\n\t\tcase\teRunning:\t\n\t\t\ttmp << kTAB << L\"State: \" << kTAB << kTAB << kTAB << \"Running\" << endl; \n\t\t\t#if\t\tqPlatform_POSIX\n\t\t\t\ttmp << kTAB << L\"PID: \" << kTAB << kTAB << kTAB << GetServicePID () << endl;\n\t\t\t#endif\n\t\t\tbreak;\n\t\tcase\tePaused:\t\n\t\t\ttmp << kTAB << L\"State: \" << kTAB << kTAB << kTAB << \"PAUSED\" << endl; \n\t\t\t#if\t\tqPlatform_POSIX\n\t\t\t\ttmp << kTAB << L\"PID: \" << kTAB<< kTAB << kTAB << GetServicePID () << endl;\n\t\t\t#endif\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tAssertNotReached ();\n\t}\n\ttmp << _sRep->GetServiceStatusMessage ().As ();\n\treturn tmp.str ();\n}\n\nvoid\tMain::RunAsService ()\n{\n\t\/\/ VERY PRIMITIVE IMPL - WE NEED LOCKING on tmpfile stuff - add good tempfile supprot to fileuitls or use existing...\n\n\ttry {\n#if\t\tqPlatform_POSIX\n\t\tofstream\tout (_sRep->GetPIDFileName ().AsTString ().c_str ());\n\t\tout << getpid () << endl;\n#endif\n\t\t_sRep->OnStartRequest ();\n\t}\n\tcatch (const Execution::ThreadAbortException& \/*threadAbort*\/) {\n#if\t\tqPlatform_POSIX\n\t\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n\t\t\/\/ ignore this - just means service ended normally\n\t}\n\tcatch (...) {\n\t\tDbgTrace (TSTR (\"Unexpected exception ended running service\"));\n#if\t\tqPlatform_POSIX\n\t\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n\t\tthrow;\n\t}\n}\n\nvoid\tMain::Start ()\n{\n\t\/\/ Check not already runnig, (someday) and then for and exec the \n\n#if\t\tqPlatform_POSIX\n\t\/\/ REALLY should use GETSTATE - and return state based on if PID file exsits...\n\tif (GetServicePID () != 0) {\n\t\tExecution::DoThrow (Execution::StringException (L\"Cannot Start service because its already running\"));\n\t}\n#endif\n\tCharacters::TString\tthisEXEPath\t=\tExecution::GetEXEPath ();\n#if\t\tqPlatform_POSIX\n\tpid_t\tpid\t=\tfork ();\n\tif (pid == 0) {\n\t\t\/\/ Child - exec -\n\t\t\/\/\t\tTODO:\t\tSHOULD BE CAREFUL ABOUT CLOSING FILE DESCRIPTORS BEFORE THIS ACTION - WE DONT WANT HTEM INHERITED!!!\n\t\t\/\/\t\t\t\t\tBUT DONT DO WILLYNILLY - THINK THROUGH - I CANNNOT RECALL THE EXACT RIGHT ANSWER\n\t\tint\tr\t=\texecl (thisEXEPath.c_str (), thisEXEPath.c_str (), (String (L\"--\") + String (CommandNames::kRunAsService)).AsTString ().c_str (), nullptr);\n\t\texit (-1);\n\t}\n\telse if (pid < 0) {\n\t\t\/\/ failed to fork - serious error\n\t\tExecution::errno_ErrorException::DoThrow (errno);\n\t}\n\telse {\n\t\t\/\/ parent - in this case - no reason to wait - our work is done... Future versions might wait to\n\t\t\/\/ see if the 'pidfile' got created....\n\t\t\/\/\t\t--LGP 2011-09-23\n\t}\n#endif\n}\n\nvoid\tMain::Stop ()\n{\n\t\/\/ Send signal to server to stop\n#if\t\tqPlatform_POSIX\n\tkill (GetServicePID (), SIGTERM);\n#endif\n}\n\nvoid\tMain::Kill ()\n{\n\tStop ();\n\t\/\/ Send signal to server to stop\n#if\t\tqPlatform_POSIX\n\tkill (GetServicePID (), SIGKILL);\n\t\/\/ REALY should WAIT for server to stop and only do this it fails - \n\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n}\n\nvoid\tMain::Restart ()\n{\n\tIgnoreExceptionsForCall (Stop ());\n#if\t\tqPlatform_POSIX\n\t\/\/ REALY should WAIT for server to stop and only do this it fails - \n\tunlink (_sRep->GetPIDFileName ().AsTString ().c_str ());\n#endif\n\tStart ();\n}\n\nvoid\tMain::ReReadConfiguration ()\n{\n\t\/\/ SEND APPROPRIATE SIGNAL\n#if\t\tqPlatform_POSIX\n\tpid_t\tpid\t=\tGetServicePID ();\n\tAssert (pid != 0);\t\/\/ maybe throw if non-zero???\n\tkill (GetServicePID (), kSIG_ReReadConfiguration);\n#endif\n}\n\nvoid\tMain::Pause ()\n{\n\tAssertNotImplemented ();\n}\n\nvoid\tMain::Continue ()\n{\n\tAssertNotImplemented ();\n}\n\nMain::ServiceDescription\tMain::GetServiceDescription () const\n{\n\treturn _sRep->GetServiceDescription ();\n}\n\n#if\t\tqPlatform_POSIX\nvoid\tMain::SignalHandler (int signum)\n{\n\t_sRep->SignalHandler (signum);\n}\n#endif\n\nbool\tMain::_HandleStandardCommandLineArgument (const String& arg)\n{\n\tif (Execution::MatchesCommandLineArgument (arg, CommandNames::kRunAsService)) {\n\t\tRunAsService ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStart)) {\n\t\tStart ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStop)) {\n\t\tStop ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kKill)) {\n\t\tKill ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRestart)) {\n\t\tRestart ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kReloadConfiguration)) {\n\t\tReReadConfiguration ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kPause)) {\n\t\tPause ();\n\t\treturn true;\n\t}\n\telse if (Execution::MatchesCommandLineArgument (arg, CommandNames::kContinue)) {\n\t\tContinue ();\n\t\treturn true;\n\t}\n\t\/\/\/ MANY more neeeded, and fix to use named constants...\n\treturn false;\n}\n\n<|endoftext|>"} {"text":"\n#include \n#include \n\nint main(int argc, char **argv)\n{\n QApplication app( argc, argv );\n QPushButton bb( \"Insight + Qt\", 0 );\n bb.resize( 100, 30 );\n app.setMainWidget( &bb );\n bb.show();\n return app.exec();\n}\nENH: ITK and Qt declarations combined.\n#include \n#include \n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n\nint main(int argc, char **argv)\n{\n\n typedef itk::Image< float, 2 > ImageType;\n\n typedef itk::DiscreteGaussianImageFilter< \n ImageType,\n ImageType > FilterType;\n\n typedef itk::ImageFileReader< ImageType > ReaderType;\n\n ReaderType::Pointer reader = ReaderType::New();\n \n FilterType::Pointer filter = FilterType::New();\n\n filter->SetInput( reader->GetOutput() );\n\n \/\/ Create Qt Application to let Qt get its \n \/\/ parameters from the command line\n QApplication app( argc, argv );\n\n reader->SetFileName( argv[1] );\n\n QPushButton bb( \"Start\", 0 );\n bb.resize( 100, 30 );\n\n\/\/ QObject::connect( &bb, SIGNAL(clicked()), &a, SLOT(quit()) );\n\n app.setMainWidget( &bb );\n bb.show();\n\n return app.exec();\n\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n * Copyright (c) 2011 Giulio Camuffo \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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"uimanagercomponent.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"uiasset.h\"\n#include \"engineaccess.h\"\n\nREGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )\n\nusing namespace GluonEngine;\nusing namespace GluonGraphics;\n\ntemplate \nQScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)\n{\n return engine->newQObject( qobject );\n}\n\ntemplate \nvoid scriptValueToQObject(const QScriptValue &value, Tp &qobject)\n{\n qobject = qobject_cast( value.toQObject() );\n}\n\ntemplate \nint qScriptRegisterQObjectMetaType( QScriptEngine *engine )\n{\n return qScriptRegisterMetaType( engine, scriptValueFromQObject, scriptValueToQObject );\n}\n\nclass UiManagerComponent::UiManagerComponentPrivate\n{\n public:\n UiManagerComponentPrivate( UiManagerComponent *component )\n : q(component)\n , scene(0)\n , ui(0)\n , target(0)\n , updateFunction(0)\n {\n }\n\n void setupBindings( QScriptEngine* engine )\n {\n \/\/FIXME: this code is duplicated with the scripting conponent.\n \/\/It should be moved to a common place.\n\n engine->importExtension( \"jsmoke.qtcore\" );\n engine->importExtension( \"jsmoke.qtgui\" );\n engine->importExtension( \"jsmoke.qtopengl\" );\n\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n\n QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;\n QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;\n QScriptValue object = engine->globalObject();\n\n QScriptValue component = engine->newQObject( q, ownership, wrapOptions );\n object.setProperty( \"Component\", component );\n\n QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions );\n object.setProperty( \"GameObject\", gameObj );\n\n QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions );\n object.setProperty( \"Scene\", sceneObj );\n\n QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions );\n object.setProperty( \"GameProject\", gameProjectObj );\n\n QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions );\n object.setProperty( \"Game\", game );\n }\n\n UiManagerComponent* q;\n QPixmap pixmap;\n QGraphicsView* view;\n QGraphicsScene* scene;\n UiAsset *ui;\n QSizeF size;\n Item *item;\n EngineAccess* engineAccess;\n RenderTarget* target;\n\n QDeclarativeExpression *updateFunction;\n};\n\nUiManagerComponent::UiManagerComponent( QObject* parent )\n : Component( parent )\n , d( new UiManagerComponentPrivate( this ) )\n{\n\n}\n\nUiManagerComponent::UiManagerComponent( const UiManagerComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nUiManagerComponent::~UiManagerComponent()\n{\n delete d;\n}\n\nQString UiManagerComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid UiManagerComponent::initialize()\n{\n\/\/ d->fbo = GluonGraphics::Engine::instance()->fbo();\n\/\/ d->pixmap = QPixmap( widget->size() );\n\/\/ d->pixmap.fill( Qt::transparent );\n\/\/ d->view->setParent(widget->parentWidget());\n\/\/ d->view->setAttribute(Qt::WA_TranslucentBackground);\n\/\/ d->view->setAttribute(Qt::WA_NoSystemBackground);\n\/\/ d->view->viewport()->setAttribute(Qt::WA_TranslucentBackground);\n\/\/ d->view->viewport()->setAttribute(Qt::WA_NoSystemBackground);\n\/\/ d->view->setStyleSheet(\"border: none\");\n\/\/ QPalette p = d->view->viewport()->palette();\n\/\/ p.setColor(QPalette::Base, Qt::transparent);\n\/\/ d->view->viewport()->setPalette(p);\n\/\/ d->view->setScene(d->scene);\n\/\/ d->view->setSceneRect(QRectF(0,0,1000,1000));\n\n\/\/ d->view->resize(widget->size());\n\/\/ d->view->show();\n\/\/ d->scene->setBackgroundBrush(Qt::blue);\n\n\/\/ d->texture = widget->bindTexture(d->pixmap);\n\/\/ widget->update();\n\/\/ widget->updateGL();\n\/\/ widget->makeCurrent();\n\n if( !d->scene )\n {\n d->scene = new QGraphicsScene( this );\n d->scene->setSceneRect(QRectF(QPointF(0,0), QSize(1024,768)));\n\n d->target = new RenderTarget(1024,768,this);\n d->target->setMaterialInstance(Engine::instance()->material(\"default\")->createInstance(\"qmlTarget\"));\n Engine::instance()->addRenderTarget(d->target, 1);\n }\n\n if( d->ui && !d->ui->isLoaded() )\n {\n qmlRegisterType(\"org.kde.gluon\", 1, 0, \"GameObject\" );\n qmlRegisterInterface(\"gameObject\");\n\n d->ui->load();\n\n QDeclarativeEngine* engine = d->ui->engine();\n\n d->engineAccess = new EngineAccess(this);\n engine->rootContext()->setContextProperty( \"__engineAccess\", d->engineAccess );\n\n \/\/Glorious hack:steal the engine\n QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(),\n \"__engineAccess.setEngine( this )\" );\n expr->evaluate();\n delete expr;\n }\n\n if( d->ui && d->ui->isLoaded() )\n {\n d->ui->execute();\n\n QGraphicsWidget* gWidget = d->ui->widget();\n if( gWidget )\n {\n d->scene->addItem( gWidget );\n\n d->updateFunction = new QDeclarativeExpression( d->ui->engine()->rootContext(),\n d->ui->widget(), \"update()\" );\n }\n }\n}\n\nvoid UiManagerComponent::setScriptEngine( QScriptValue &value )\n{\n QScriptEngine* engine = value.engine();\n\n QScriptValue originalGlobalObject = engine->globalObject();\n QScriptValue newGlobalObject = engine->newObject();\n\n QString eval = QLatin1String( \"eval\" );\n QString version = QLatin1String( \"version\" );\n\n QScriptValueIterator iter( originalGlobalObject );\n QVector names;\n QVector values;\n QVector flags;\n while ( iter.hasNext() )\n {\n iter.next();\n\n QString name = iter.name();\n\n if ( name == version )\n {\n continue;\n }\n\n if ( name != eval )\n {\n names.append( name );\n values.append( iter.value() );\n flags.append( iter.flags() | QScriptValue::Undeletable );\n }\n newGlobalObject.setProperty( iter.scriptName(), iter.value() );\n }\n\n engine->setGlobalObject( newGlobalObject );\n\n d->setupBindings( engine );\n\n delete d->engineAccess;\n d->ui->engine()->rootContext()->setContextProperty( \"__engineAccess\", 0 );\n}\n\nvoid UiManagerComponent::start()\n{\n\n}\n\nvoid UiManagerComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( !d->scene || !d->ui || !d->ui->widget() )\n {\n return;\n }\n\n QPainter p( d->target->framebufferObject() );\n d->scene->render( &p );\n}\n\nvoid UiManagerComponent::update( int elapsedMilliseconds )\n{\n if( d->updateFunction )\n {\n d->updateFunction->evaluate();\n\n if( d->updateFunction->hasError() )\n {\n debug( d->updateFunction->error().toString() );\n }\n }\n}\n\nvoid UiManagerComponent::cleanup()\n{\n if( !d->ui )\n {\n return;\n }\n\n QGraphicsWidget* widget = d->ui->widget();\n if( d->scene && widget && widget->scene() == d->scene )\n {\n d->scene->removeItem( widget );\n }\n\n delete d->scene;\n d->scene = 0;\n\n delete d->updateFunction;\n d->updateFunction = 0;\n\n delete d->target;\n d->target = 0;\n}\n\nvoid UiManagerComponent::setUi(UiAsset* ui)\n{\n d->ui = ui;\n}\n\nUiAsset* UiManagerComponent::ui() const\n{\n return d->ui;\n}\n\nvoid UiManagerComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF UiManagerComponent::size() const\n{\n return d->size;\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );\n\n#include \"uimanagercomponent.moc\"\nCreate a custom fbo and bind it before drawing.\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n * Copyright (c) 2011 Giulio Camuffo \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 as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"uimanagercomponent.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"uiasset.h\"\n#include \"engineaccess.h\"\n\nREGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )\n\nusing namespace GluonEngine;\nusing namespace GluonGraphics;\n\ntemplate \nQScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)\n{\n return engine->newQObject( qobject );\n}\n\ntemplate \nvoid scriptValueToQObject(const QScriptValue &value, Tp &qobject)\n{\n qobject = qobject_cast( value.toQObject() );\n}\n\ntemplate \nint qScriptRegisterQObjectMetaType( QScriptEngine *engine )\n{\n return qScriptRegisterMetaType( engine, scriptValueFromQObject, scriptValueToQObject );\n}\n\nclass UiManagerComponent::UiManagerComponentPrivate\n{\n public:\n UiManagerComponentPrivate( UiManagerComponent *component )\n : q(component)\n , scene(0)\n , ui(0)\n , target(0)\n , updateFunction(0)\n {\n }\n\n void setupBindings( QScriptEngine* engine )\n {\n \/\/FIXME: this code is duplicated with the scripting conponent.\n \/\/It should be moved to a common place.\n\n engine->importExtension( \"jsmoke.qtcore\" );\n engine->importExtension( \"jsmoke.qtgui\" );\n engine->importExtension( \"jsmoke.qtopengl\" );\n\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n\n QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;\n QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;\n QScriptValue object = engine->globalObject();\n\n QScriptValue component = engine->newQObject( q, ownership, wrapOptions );\n object.setProperty( \"Component\", component );\n\n QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions );\n object.setProperty( \"GameObject\", gameObj );\n\n QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions );\n object.setProperty( \"Scene\", sceneObj );\n\n QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions );\n object.setProperty( \"GameProject\", gameProjectObj );\n\n QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions );\n object.setProperty( \"Game\", game );\n }\n\n UiManagerComponent* q;\n QPixmap pixmap;\n QGraphicsView* view;\n QGraphicsScene* scene;\n UiAsset *ui;\n QSizeF size;\n Item *item;\n EngineAccess* engineAccess;\n RenderTarget* target;\n\n QDeclarativeExpression *updateFunction;\n};\n\nUiManagerComponent::UiManagerComponent( QObject* parent )\n : Component( parent )\n , d( new UiManagerComponentPrivate( this ) )\n{\n\n}\n\nUiManagerComponent::UiManagerComponent( const UiManagerComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nUiManagerComponent::~UiManagerComponent()\n{\n delete d;\n}\n\nQString UiManagerComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid UiManagerComponent::initialize()\n{\n\/\/ d->fbo = GluonGraphics::Engine::instance()->fbo();\n\/\/ d->pixmap = QPixmap( widget->size() );\n\/\/ d->pixmap.fill( Qt::transparent );\n\/\/ d->view->setParent(widget->parentWidget());\n\/\/ d->view->setAttribute(Qt::WA_TranslucentBackground);\n\/\/ d->view->setAttribute(Qt::WA_NoSystemBackground);\n\/\/ d->view->viewport()->setAttribute(Qt::WA_TranslucentBackground);\n\/\/ d->view->viewport()->setAttribute(Qt::WA_NoSystemBackground);\n\/\/ d->view->setStyleSheet(\"border: none\");\n\/\/ QPalette p = d->view->viewport()->palette();\n\/\/ p.setColor(QPalette::Base, Qt::transparent);\n\/\/ d->view->viewport()->setPalette(p);\n\/\/ d->view->setScene(d->scene);\n\/\/ d->view->setSceneRect(QRectF(0,0,1000,1000));\n\n\/\/ d->view->resize(widget->size());\n\/\/ d->view->show();\n\/\/ d->scene->setBackgroundBrush(Qt::blue);\n\n\/\/ d->texture = widget->bindTexture(d->pixmap);\n\/\/ widget->update();\n\/\/ widget->updateGL();\n\/\/ widget->makeCurrent();\n\n if( !d->scene )\n {\n d->scene = new QGraphicsScene( this );\n d->scene->setSceneRect(QRectF(QPointF(0,0), QSize(1024,768)));\n\n d->target = new RenderTarget(this);\n d->target->setFramebufferObject(new QGLFramebufferObject(1024, 512, QGLFramebufferObject::CombinedDepthStencil));\n d->target->setMaterialInstance(Engine::instance()->material(\"default\")->createInstance(\"qmlTarget\"));\n Engine::instance()->addRenderTarget(d->target, 1);\n }\n\n if( d->ui && !d->ui->isLoaded() )\n {\n qmlRegisterType(\"org.kde.gluon\", 1, 0, \"GameObject\" );\n qmlRegisterInterface(\"gameObject\");\n\n d->ui->load();\n\n QDeclarativeEngine* engine = d->ui->engine();\n\n d->engineAccess = new EngineAccess(this);\n engine->rootContext()->setContextProperty( \"__engineAccess\", d->engineAccess );\n\n \/\/Glorious hack:steal the engine\n QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(),\n \"__engineAccess.setEngine( this )\" );\n expr->evaluate();\n delete expr;\n }\n\n if( d->ui && d->ui->isLoaded() )\n {\n d->ui->execute();\n\n QGraphicsWidget* gWidget = d->ui->widget();\n if( gWidget )\n {\n d->scene->addItem( gWidget );\n\n d->updateFunction = new QDeclarativeExpression( d->ui->engine()->rootContext(),\n d->ui->widget(), \"update()\" );\n }\n }\n}\n\nvoid UiManagerComponent::setScriptEngine( QScriptValue &value )\n{\n QScriptEngine* engine = value.engine();\n\n QScriptValue originalGlobalObject = engine->globalObject();\n QScriptValue newGlobalObject = engine->newObject();\n\n QString eval = QLatin1String( \"eval\" );\n QString version = QLatin1String( \"version\" );\n\n QScriptValueIterator iter( originalGlobalObject );\n QVector names;\n QVector values;\n QVector flags;\n while ( iter.hasNext() )\n {\n iter.next();\n\n QString name = iter.name();\n\n if ( name == version )\n {\n continue;\n }\n\n if ( name != eval )\n {\n names.append( name );\n values.append( iter.value() );\n flags.append( iter.flags() | QScriptValue::Undeletable );\n }\n newGlobalObject.setProperty( iter.scriptName(), iter.value() );\n }\n\n engine->setGlobalObject( newGlobalObject );\n\n d->setupBindings( engine );\n\n delete d->engineAccess;\n d->ui->engine()->rootContext()->setContextProperty( \"__engineAccess\", 0 );\n}\n\nvoid UiManagerComponent::start()\n{\n\n}\n\nvoid UiManagerComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( !d->scene || !d->ui || !d->ui->widget() )\n {\n return;\n }\n\n d->target->bind();\n\n QPainter p( d->target->framebufferObject() );\n d->scene->render( &p );\n p.end();\n\n d->target->release();\n}\n\nvoid UiManagerComponent::update( int elapsedMilliseconds )\n{\n if( d->updateFunction )\n {\n d->updateFunction->evaluate();\n\n if( d->updateFunction->hasError() )\n {\n debug( d->updateFunction->error().toString() );\n }\n }\n}\n\nvoid UiManagerComponent::cleanup()\n{\n if( !d->ui )\n {\n return;\n }\n\n QGraphicsWidget* widget = d->ui->widget();\n if( d->scene && widget && widget->scene() == d->scene )\n {\n d->scene->removeItem( widget );\n }\n\n delete d->scene;\n d->scene = 0;\n\n delete d->updateFunction;\n d->updateFunction = 0;\n\n delete d->target;\n d->target = 0;\n}\n\nvoid UiManagerComponent::setUi(UiAsset* ui)\n{\n d->ui = ui;\n}\n\nUiAsset* UiManagerComponent::ui() const\n{\n return d->ui;\n}\n\nvoid UiManagerComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF UiManagerComponent::size() const\n{\n return d->size;\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );\n\n#include \"uimanagercomponent.moc\"\n<|endoftext|>"} {"text":"#include \"compress_keyword_encoding.h\"\n#include \"bytebuffer.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nstd::string initializeSymbols()\n{\n std::string s;\n for(int i = 1; i < 255; ++i)\n s += i;\n\n return s;\n}\n\nbool CompressKeywordEncoding::CompressImpl(const ByteBuffer& input, ByteBuffer& output)\n{\n std::string symbols = initializeSymbols();\n\n const char * inChars = (const char *)input.Data();\n\n size_t symIndex;\n char c;\n for (size_t i=0; i < input.Size(); ++i)\n {\n c = inChars[i];\n\n if ((symIndex = symbols.find(c)) != std::string::npos)\n symbols.erase(symbols.begin() + symIndex);\n }\n\n std::map::iterator it;\n std::map stringFrequencies;\n\n std::istringstream in((char *)input.Data());\n std::string temp;\n while (in.good())\n {\n in >> temp;\n it = stringFrequencies.find(temp);\n\n if (it != stringFrequencies.end())\n ++it->second;\n else\n stringFrequencies.insert(it, std::make_pair(temp, 1));\n }\n\n std::map> reverseStringFrequencies;\n std::map>::iterator it1;\n\n for (const auto& elem: stringFrequencies)\n {\n it1 = reverseStringFrequencies.find(elem.second);\n if (it1 == reverseStringFrequencies.end())\n it1 = reverseStringFrequencies.insert(it1, std::make_pair(elem.second, std::vector()));\n\n it1->second.push_back(elem.first);\n }\n\n std::unordered_map encodedStrings;\n std::unordered_map::iterator encodedStringsIt;\n\n std::map>::reverse_iterator it2 = reverseStringFrequencies.rbegin();\n for (size_t i = 0; i < symbols.size() && it2 != reverseStringFrequencies.rend(); ++it2)\n {\n for (size_t j = 0; j < it2->second.size() && i < symbols.size(); ++j)\n {\n if ((it2->second[j].size() > 2 \/* min word size *\/ && it2->first > 1 \/* min freq *\/) ||\n (it2->second[j].size() > 1 \/* min word size *\/ && it2->first > 2 \/* min freq *\/))\n {\n encodedStrings.insert(std::make_pair(it2->second[j], symbols[i++]));\n std::cout << it2->second[j] << std::endl;\n }\n }\n }\n\n output.WriteDynInt(encodedStrings.size());\n for(encodedStringsIt = encodedStrings.begin(); encodedStringsIt != encodedStrings.end(); ++encodedStringsIt)\n {\n output.WriteUInt8(encodedStringsIt->second);\n output.WriteString(encodedStringsIt->first);\n }\n\n in = std::istringstream(std::string((const char *)input.Data(), input.Size()));\n\n std::string str = in.str();\n\n std::ostringstream out;\n\n while (in.good())\n {\n std::streamoff prev = in.tellg();\n in >> temp;\n std::streamoff after = in.tellg();\n\n if ((encodedStringsIt = encodedStrings.find(temp)) != encodedStrings.end())\n output.WriteString(std::string(1, encodedStringsIt->second));\n else\n output.WriteString(temp);\n\n std::string str2;\n if (after != -1)\n output.WriteString((str2 = str.substr(prev, after - prev - temp.size())));\n else\n output.WriteString(str.substr(prev, input.Size() - prev - str2.size()));\n }\n\n return true;\n}\n\nbool CompressKeywordEncoding::DecompressImpl(const ByteBuffer& input, ByteBuffer& output)\n{\n ByteBuffer* hack = const_cast(&input);\n\n std::unordered_map encodedSymbols;\n std::unordered_map::iterator encodedSymbolsIt;\n\n size_t numTableEntries = hack->ReadDynInt();\n for(; numTableEntries > 0; --numTableEntries)\n encodedSymbols.insert(std::make_pair((char)hack->ReadUInt8(), hack->ReadString()));\n\n std::stringstream ss;\n\n std::string temp, spaces;\n while (hack->CanRead())\n {\n temp = hack->ReadString();\n spaces = hack->ReadString();\n\n if (hack->CanRead())\n {\n ss << spaces;\n\n if (temp.size() > 0 && (encodedSymbolsIt = encodedSymbols.find(temp[0])) != encodedSymbols.end())\n ss << encodedSymbolsIt->second;\n else\n ss << temp;\n }\n\n if (!hack->CanRead()) \/\/ last iter\n ss << spaces;\n };\n\n std::string r = ss.str();\n output.WriteBuffer(r.c_str(), r.size());\n \/\/output.WriteUInt8(0);\n\n return true;\n}\nKeyword encoding is now properly compressing however it's slow as shit.#include \"compress_keyword_encoding.h\"\n#include \"bytebuffer.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"utils.h\"\n\nstd::vector InitializeSymbols()\n{\n std::vector vec;\n for (uint8 i = 0; i < 255; ++i)\n if (std::isprint(i) && i != '$') \/\/ $ is used by regex replace\n vec.push_back(i);\n\n return vec;\n}\n\nbool CompressKeywordEncoding::CompressImpl(const ByteBuffer& input, ByteBuffer& output)\n{\n\n \/\/ regex is used to match words and build frequency map\n\n std::cmatch sm;\n std::regex e(\"\\\\b\\\\S+\\\\b\"); \/\/ word\n\n dict::type_unordered_map stringFrequencies;\n dict::init(stringFrequencies, \"\");\n\n {\n std::string str((const char*)input.Data(), input.Size());\n while (std::regex_search(str.c_str(), sm, e))\n {\n for (auto x : sm)\n stringFrequencies[x.str()]++;\n str = sm.suffix().str();\n }\n }\n\n \/\/ remove used symbols\n\n std::vector symbols = InitializeSymbols();\n for (size_t i = 0; i < input.Size(); ++i)\n std::remove(symbols.begin(), symbols.end(), input.Data()[i]);\n\n if (symbols.empty())\n std::cerr << \"Empty symbols!!\" << std::endl;\n\n \/\/ invert frequency map, key by frequency\n\n std::map> reverseStringFrequencies;\n std::map>::iterator it1;\n\n for (const auto& elem: stringFrequencies)\n {\n it1 = reverseStringFrequencies.find(elem.second);\n if (it1 == reverseStringFrequencies.end())\n it1 = reverseStringFrequencies.insert(it1, std::make_pair(elem.second, std::vector()));\n\n it1->second.push_back(elem.first);\n }\n\n \/\/ pick symbols for common words\n\n std::unordered_map encodedStrings;\n std::unordered_map::iterator encodedStringsIt;\n std::map>::reverse_iterator it2 = reverseStringFrequencies.rbegin();\n for (size_t i = 0; i < symbols.size() && it2 != reverseStringFrequencies.rend(); ++it2)\n {\n for (size_t j = 0; j < it2->second.size() && i < symbols.size(); ++j)\n {\n \/\/if ((it2->second[j].size() > 2 \/* min word size *\/ && it2->first > 1 \/* min freq *\/) ||\n \/\/ (it2->second[j].size() > 1 \/* min word size *\/ && it2->first > 2 \/* min freq *\/))\n {\n encodedStrings.insert(std::make_pair(it2->second[j], symbols[i++]));\n }\n }\n }\n\n \/\/ write symbol - word map\n\n output.WriteDynInt(encodedStrings.size());\n for (encodedStringsIt = encodedStrings.begin(); encodedStringsIt != encodedStrings.end(); ++encodedStringsIt)\n {\n output.WriteUInt8(encodedStringsIt->second);\n output.WriteString(encodedStringsIt->first);\n }\n\n \/\/ modify and write text\n\n {\n std::string str((const char*)input.Data(), input.Size());\n\n for (std::unordered_map::value_type p : encodedStrings)\n {\n std::regex rx(\"\\\\b\" + p.first + \"\\\\b\");\n str = std::regex_replace(str, rx, std::string(1, p.second));\n }\n\n output.WriteBuffer(str.data(), str.size());\n }\n\n return true;\n}\n\nbool CompressKeywordEncoding::DecompressImpl(const ByteBuffer& input, ByteBuffer& output)\n{\n ByteBuffer* hack = const_cast(&input);\n\n std::unordered_map encodedSymbols; \/\/ symbol -> word\n\n size_t numTableEntries = hack->ReadDynInt();\n for(; numTableEntries > 0; --numTableEntries)\n {\n uint8 c = hack->ReadUInt8();\n std::string str = hack->ReadString();\n encodedSymbols[c] = str;\n }\n\n std::string str(&(*((const char *)input.Data() + hack->GetReadPos())), input.Size() - hack->GetReadPos());\n\n std::unordered_map::const_iterator itr;\n while (hack->CanRead())\n {\n uint8 c = hack->ReadUInt8();\n\n itr = encodedSymbols.find(c);\n if (itr != encodedSymbols.end())\n output.WriteBuffer(itr->second.data(), itr->second.size());\n else\n output.WriteUInt8(c);\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"#include \/\/ cout\n#include \/\/ ifstream\n#include \/\/ istringstream\n#include \/\/ log;exp\n#include \/\/ vector\n#include \/\/ for_each\nusing namespace std;\n\nint main(int argc, char* argv[]){\n string str, a,b,c; \/\/ define variables and constants.\n int i=0, loc;\n double val1=1.0, val2=1.0, val, logval1=0, logval2=0;\n const double valMax = 1e64;\n vector vectorSeqNo1,vectorSeqNo2,vectorLoc1,vectorLoc2;\n vector vectorVal1, vectorVal2;\n \n ifstream file(argv[1]); \/\/ open file. Filename as argument of main.\n \n \/\/ loop over lines in file until end-of-file.\n while (getline(file,str)){\n if (str[0]=='#'||str.empty()){;}else{ \/\/ check if line should be ignored, if first char is '#' or empty line.\n\tistringstream ss(str); \/\/ get columns.\n\tss >> a >> b >> c; \/\/ split columns at spaces. Does not handle cases with spaces in SeqNo.\n\tval = stod(c); \n\tif ((any_of(b.begin(),b.end(),::isdigit)) && (!isnan(val))){ \/\/ error handling. loc must be digit, and nan values are not allowed.\n\t loc = stoi(b);\n\t if(loc==1){ \/\/ create data array corresponding to loc=1.\n\t vectorSeqNo1.push_back(stoi(a)); \/\/ storing SeqNo to have data structure of file... Not sure if necessary.\n\t vectorLoc1.push_back(loc); \/\/ store Loc for loc count. \n\t vectorVal1.push_back(val); \/\/ store Values for GeoMean calculations.\n\t }\n\t else if (loc==2){ \/\/ create data array corresponding to loc=2. Same as in loc=1.\n\t vectorSeqNo2.push_back(stoi(a));\n\t vectorLoc2.push_back(loc);\n\t vectorVal2.push_back(val);\n\t }\n\t \/\/else{if(!isnan(val)){cout<<\"str: \"< valMax){logval1+=log(val1);val1=1.0;} \/\/ then log it and add onto logval.\n });\n \n \/\/ same as in for loc=1.\n for_each(vectorVal2.begin(), vectorVal2.end(), [&] (double val){ \n val2 *= val;\n if (val2 > valMax){logval2+=log(val2);val2=1.0;}\n });\n \n \/\/ output results.\n cout << \"File: \" << argv[1] << \" with \" << i << \" lines\" << endl;\n cout << \"Valid values Loc1: \" << vectorLoc1.size() << \" with GeoMean: \" << exp((logval1+log(val1))\/vectorLoc1.size()) << endl;\n cout << \"Valid values Loc2: \" << vectorLoc2.size() << \" with GeoMean: \" << exp((logval2+log(val2))\/vectorLoc2.size()) << endl;\n return 0;\n}no newline at end of file?#include \/\/ cout\n#include \/\/ ifstream\n#include \/\/ istringstream\n#include \/\/ log;exp\n#include \/\/ vector\n#include \/\/ for_each\nusing namespace std;\n\nint main(int argc, char* argv[]){\n string str, a,b,c; \/\/ define variables and constants.\n int i=0, loc;\n double val1=1.0, val2=1.0, val, logval1=0, logval2=0;\n const double valMax = 1e64;\n vector vectorSeqNo1,vectorSeqNo2,vectorLoc1,vectorLoc2;\n vector vectorVal1, vectorVal2;\n \n ifstream file(argv[1]); \/\/ open file. Filename as argument of main.\n \n \/\/ loop over lines in file until end-of-file.\n while (getline(file,str)){\n if (str[0]=='#'||str.empty()){;}else{ \/\/ check if line should be ignored, if first char is '#' or empty line.\n\tistringstream ss(str); \/\/ get columns.\n\tss >> a >> b >> c; \/\/ split columns at spaces. Does not handle cases with spaces in SeqNo.\n\tval = stod(c); \n\tif ((any_of(b.begin(),b.end(),::isdigit)) && (!isnan(val))){ \/\/ error handling. loc must be digit, and nan values are not allowed.\n\t loc = stoi(b);\n\t if(loc==1){ \/\/ create data array corresponding to loc=1.\n\t vectorSeqNo1.push_back(stoi(a)); \/\/ storing SeqNo to have data structure of file... Not sure if necessary.\n\t vectorLoc1.push_back(loc); \/\/ store Loc for loc count. \n\t vectorVal1.push_back(val); \/\/ store Values for GeoMean calculations.\n\t }\n\t else if (loc==2){ \/\/ create data array corresponding to loc=2. Same as in loc=1.\n\t vectorSeqNo2.push_back(stoi(a));\n\t vectorLoc2.push_back(loc);\n\t vectorVal2.push_back(val);\n\t }\n\t \/\/else{if(!isnan(val)){cout<<\"str: \"< valMax){logval1+=log(val1);val1=1.0;} \/\/ then log it and add onto logval.\n });\n \n \/\/ same as in for loc=1.\n for_each(vectorVal2.begin(), vectorVal2.end(), [&] (double val){ \n val2 *= val;\n if (val2 > valMax){logval2+=log(val2);val2=1.0;}\n });\n \n \/\/ output results.\n cout << \"File: \" << argv[1] << \" with \" << i << \" lines\" << endl;\n cout << \"Valid values Loc1: \" << vectorLoc1.size() << \" with GeoMean: \" << exp((logval1+log(val1))\/vectorLoc1.size()) << endl;\n cout << \"Valid values Loc2: \" << vectorLoc2.size() << \" with GeoMean: \" << exp((logval2+log(val2))\/vectorLoc2.size()) << endl;\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreGLHardwareBufferManager.h\"\n#include \"OgreGLHardwareVertexBuffer.h\"\n#include \"OgreException.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreGLStateCacheManager.h\"\n\nnamespace Ogre {\n\n\t\/\/---------------------------------------------------------------------\n GLHardwareVertexBuffer::GLHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, \n size_t numVertices, HardwareBuffer::Usage usage, bool useShadowBuffer)\n : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, false, useShadowBuffer)\n {\n glGenBuffersARB( 1, &mBufferId );\n\n if (!mBufferId)\n {\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n \"Cannot create GL vertex buffer\", \n \"GLHardwareVertexBuffer::GLHardwareVertexBuffer\");\n }\n\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n \/\/ Initialise mapped buffer and set usage\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, \n GLHardwareBufferManager::getGLUsage(usage));\n\n \/\/std::cerr << \"creating vertex buffer = \" << mBufferId << std::endl;\n }\n\t\/\/---------------------------------------------------------------------\n GLHardwareVertexBuffer::~GLHardwareVertexBuffer()\n {\n static_cast(mMgr)->getStateCacheManager()->deleteGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n }\n\t\/\/---------------------------------------------------------------------\n void* GLHardwareVertexBuffer::lockImpl(size_t offset, \n size_t length, LockOptions options)\n {\n if(mIsLocked)\n {\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,\n \"Invalid attempt to lock an vertex buffer that has already been locked\",\n \"GLHardwareVertexBuffer::lock\");\n }\n\n\n\t\tvoid* retPtr = 0;\n\n\t\tGLHardwareBufferManager* glBufManager = static_cast(HardwareBufferManager::getSingletonPtr());\n\n\t\t\/\/ Try to use scratch buffers for smaller buffers\n\t\tif( length < glBufManager->getGLMapBufferThreshold() )\n\t\t{\n\t\t\t\/\/ if this fails, we fall back on mapping\n\t\t\tretPtr = glBufManager->allocateScratch((uint32)length);\n\n\t\t\tif (retPtr)\n\t\t\t{\n\t\t\t\tmLockedToScratch = true;\n\t\t\t\tmScratchOffset = offset;\n\t\t\t\tmScratchSize = length;\n\t\t\t\tmScratchPtr = retPtr;\n\t\t\t\tmScratchUploadOnUnlock = (options != HBL_READ_ONLY);\n\n\t\t\t\tif (options != HBL_DISCARD && options != HBL_NO_OVERWRITE)\n\t\t\t\t{\n\t\t\t\t\t\/\/ have to read back the data before returning the pointer\n\t\t\t\t\treadData(offset, length, retPtr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!retPtr)\n\t\t{\n GLenum access = 0;\n\t\t\t\/\/ Use glMapBuffer\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\t\t\t\/\/ Use glMapBuffer\n\t\t\tif(options == HBL_DISCARD || options == HBL_NO_OVERWRITE) \/\/ TODO: check possibility to use GL_MAP_UNSYNCHRONIZED_BIT for HBL_NO_OVERWRITE locking promise\n\t\t\t{\n\t\t\t\t\/\/ Discard the buffer\n\t\t\t\tglBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, \n\t\t\t\t\tGLHardwareBufferManager::getGLUsage(mUsage));\n\t\t\t}\n\t\t\tif (mUsage & HBU_WRITE_ONLY)\n\t\t\t\taccess = GL_WRITE_ONLY_ARB;\n\t\t\telse if (options == HBL_READ_ONLY)\n\t\t\t\taccess = GL_READ_ONLY_ARB;\n\t\t\telse\n\t\t\t\taccess = GL_READ_WRITE_ARB;\n\n\t\t\tvoid* pBuffer = glMapBufferARB( GL_ARRAY_BUFFER_ARB, access);\n if(pBuffer == 0)\n\t\t\t{\n\t\t\t\tOGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n\t\t\t\t\t\"Vertex Buffer: Out of memory\", \"GLHardwareVertexBuffer::lock\");\n\t\t\t}\n\n\t\t\t\/\/ return offsetted\n\t\t\tretPtr = static_cast(\n\t\t\t\tstatic_cast(pBuffer) + offset);\n\n\t\t\tmLockedToScratch = false;\n\t\t}\n\t\tmIsLocked = true;\n\t\treturn retPtr;\n }\n\t\/\/---------------------------------------------------------------------\n\tvoid GLHardwareVertexBuffer::unlockImpl(void)\n {\n\t\tif (mLockedToScratch)\n\t\t{\n\t\t\tif (mScratchUploadOnUnlock)\n\t\t\t{\n\t\t\t\t\/\/ have to write the data back to vertex buffer\n\t\t\t\twriteData(mScratchOffset, mScratchSize, mScratchPtr, \n\t\t\t\t\tmScratchOffset == 0 && mScratchSize == getSizeInBytes());\n\t\t\t}\n\n\t\t\t\/\/ deallocate from scratch buffer\n\t\t\tstatic_cast(\n\t\t\t\tHardwareBufferManager::getSingletonPtr())->deallocateScratch(mScratchPtr);\n\n\t\t\tmLockedToScratch = false;\n\t\t}\n\t\telse\n\t\t{\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n\t\t\tif(!glUnmapBufferARB( GL_ARRAY_BUFFER_ARB ))\n\t\t\t{\n\t\t\t\tOGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n\t\t\t\t\t\"Buffer data corrupted, please reload\", \n\t\t\t\t\t\"GLHardwareVertexBuffer::unlock\");\n\t\t\t}\n\t\t}\n\n mIsLocked = false;\n }\n\t\/\/---------------------------------------------------------------------\n void GLHardwareVertexBuffer::readData(size_t offset, size_t length, \n void* pDest)\n {\n if(mUseShadowBuffer)\n {\n \/\/ get data from the shadow buffer\n void* srcData = mShadowBuffer->lock(offset, length, HBL_READ_ONLY);\n memcpy(pDest, srcData, length);\n mShadowBuffer->unlock();\n }\n else\n {\n \/\/ get data from the real buffer\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n glGetBufferSubDataARB(GL_ARRAY_BUFFER_ARB, offset, length, pDest);\n }\n }\n\t\/\/---------------------------------------------------------------------\n void GLHardwareVertexBuffer::writeData(size_t offset, size_t length, \n const void* pSource, bool discardWholeBuffer)\n {\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n \/\/ Update the shadow buffer\n if(mUseShadowBuffer)\n {\n void* destData = mShadowBuffer->lock(offset, length, \n discardWholeBuffer ? HBL_DISCARD : HBL_NORMAL);\n memcpy(destData, pSource, length);\n mShadowBuffer->unlock();\n }\n\n if (offset == 0 && length == mSizeInBytes)\n {\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, pSource, \n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n else\n {\n if(discardWholeBuffer)\n {\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, \n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n\n \/\/ Now update the real buffer\n glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, offset, length, pSource); \n }\n }\n\t\/\/---------------------------------------------------------------------\n void GLHardwareVertexBuffer::_updateFromShadow(void)\n {\n if (mUseShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate)\n {\n const void *srcData = mShadowBuffer->lock(\n mLockStart, mLockSize, HBL_READ_ONLY);\n\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n \/\/ Update whole buffer if possible, otherwise normal\n if (mLockStart == 0 && mLockSize == mSizeInBytes)\n {\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, srcData,\n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n else\n {\n glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, mLockStart, mLockSize, srcData);\n }\n\n mShadowBuffer->unlock();\n mShadowUpdated = false;\n }\n }\n}\nRecover GLHardwareVertexBuffer if glBufferDataARB fails (happens on OSX Mavericks)\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreGLHardwareBufferManager.h\"\n#include \"OgreGLHardwareVertexBuffer.h\"\n#include \"OgreException.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreGLStateCacheManager.h\"\n\nnamespace Ogre {\n\n\t\/\/---------------------------------------------------------------------\n GLHardwareVertexBuffer::GLHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, \n size_t numVertices, HardwareBuffer::Usage usage, bool useShadowBuffer)\n : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, false, useShadowBuffer)\n {\n glGenBuffersARB( 1, &mBufferId );\n\n if (!mBufferId)\n {\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n \"Cannot create GL vertex buffer\", \n \"GLHardwareVertexBuffer::GLHardwareVertexBuffer\");\n }\n\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n \/\/ Initialise mapped buffer and set usage\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, \n GLHardwareBufferManager::getGLUsage(usage));\n\n \/\/std::cerr << \"creating vertex buffer = \" << mBufferId << std::endl;\n }\n\t\/\/---------------------------------------------------------------------\n GLHardwareVertexBuffer::~GLHardwareVertexBuffer()\n {\n static_cast(mMgr)->getStateCacheManager()->deleteGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n }\n\t\/\/---------------------------------------------------------------------\n void* GLHardwareVertexBuffer::lockImpl(size_t offset, \n size_t length, LockOptions options)\n {\n if(mIsLocked)\n {\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,\n \"Invalid attempt to lock an vertex buffer that has already been locked\",\n \"GLHardwareVertexBuffer::lock\");\n }\n\n\n\t\tvoid* retPtr = 0;\n\n\t\tGLHardwareBufferManager* glBufManager = static_cast(HardwareBufferManager::getSingletonPtr());\n\n\t\t\/\/ Try to use scratch buffers for smaller buffers\n\t\tif( length < glBufManager->getGLMapBufferThreshold() )\n\t\t{\n\t\t\t\/\/ if this fails, we fall back on mapping\n\t\t\tretPtr = glBufManager->allocateScratch((uint32)length);\n\n\t\t\tif (retPtr)\n\t\t\t{\n\t\t\t\tmLockedToScratch = true;\n\t\t\t\tmScratchOffset = offset;\n\t\t\t\tmScratchSize = length;\n\t\t\t\tmScratchPtr = retPtr;\n\t\t\t\tmScratchUploadOnUnlock = (options != HBL_READ_ONLY);\n\n\t\t\t\tif (options != HBL_DISCARD && options != HBL_NO_OVERWRITE)\n\t\t\t\t{\n\t\t\t\t\t\/\/ have to read back the data before returning the pointer\n\t\t\t\t\treadData(offset, length, retPtr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!retPtr)\n\t\t{\n GLenum access = 0;\n\t\t\t\/\/ Use glMapBuffer\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\t\t\t\/\/ Use glMapBuffer\n\t\t\tif(options == HBL_DISCARD || options == HBL_NO_OVERWRITE) \/\/ TODO: check possibility to use GL_MAP_UNSYNCHRONIZED_BIT for HBL_NO_OVERWRITE locking promise\n\t\t\t{\n\t\t\t\t\/\/ Discard the buffer\n\t\t\t\tglBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, \n\t\t\t\t\tGLHardwareBufferManager::getGLUsage(mUsage));\n \n GLenum error = glGetError();\n if(error != 0)\n {\n String glErrDesc;\n const char* glerrStr = (const char*)gluErrorString(error);\n if (glerrStr)\n glErrDesc = glerrStr;\n \n LogManager::getSingleton().logMessage(\"GLHardwareVertexBuffer::lock - Error: failed to Discard the buffer. Try to recreate the buffer\", LML_CRITICAL);\n \n static_cast(mMgr)->getStateCacheManager()->deleteGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n mBufferId = 0;\n \n glGenBuffersARB( 1, &mBufferId );\n \n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n \n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL,\n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n\t\t\t}\n \n\t\t\tif (mUsage & HBU_WRITE_ONLY)\n\t\t\t\taccess = GL_WRITE_ONLY_ARB;\n\t\t\telse if (options == HBL_READ_ONLY)\n\t\t\t\taccess = GL_READ_ONLY_ARB;\n\t\t\telse\n\t\t\t\taccess = GL_READ_WRITE_ARB;\n\n\t\t\tvoid* pBuffer = glMapBufferARB( GL_ARRAY_BUFFER_ARB, access);\n if(pBuffer == 0)\n\t\t\t{\n\t\t\t\tOGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n\t\t\t\t\t\"Vertex Buffer: Out of memory\", \"GLHardwareVertexBuffer::lock\");\n\t\t\t}\n\n\t\t\t\/\/ return offsetted\n\t\t\tretPtr = static_cast(\n\t\t\t\tstatic_cast(pBuffer) + offset);\n\n\t\t\tmLockedToScratch = false;\n\t\t}\n\t\tmIsLocked = true;\n\t\treturn retPtr;\n }\n\t\/\/---------------------------------------------------------------------\n\tvoid GLHardwareVertexBuffer::unlockImpl(void)\n {\n\t\tif (mLockedToScratch)\n\t\t{\n\t\t\tif (mScratchUploadOnUnlock)\n\t\t\t{\n\t\t\t\t\/\/ have to write the data back to vertex buffer\n\t\t\t\twriteData(mScratchOffset, mScratchSize, mScratchPtr, \n\t\t\t\t\tmScratchOffset == 0 && mScratchSize == getSizeInBytes());\n\t\t\t}\n\n\t\t\t\/\/ deallocate from scratch buffer\n\t\t\tstatic_cast(\n\t\t\t\tHardwareBufferManager::getSingletonPtr())->deallocateScratch(mScratchPtr);\n\n\t\t\tmLockedToScratch = false;\n\t\t}\n\t\telse\n\t\t{\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n\t\t\tif(!glUnmapBufferARB( GL_ARRAY_BUFFER_ARB ))\n\t\t\t{\n\t\t\t\tOGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n\t\t\t\t\t\"Buffer data corrupted, please reload\", \n\t\t\t\t\t\"GLHardwareVertexBuffer::unlock\");\n\t\t\t}\n\t\t}\n\n mIsLocked = false;\n }\n\t\/\/---------------------------------------------------------------------\n void GLHardwareVertexBuffer::readData(size_t offset, size_t length, \n void* pDest)\n {\n if(mUseShadowBuffer)\n {\n \/\/ get data from the shadow buffer\n void* srcData = mShadowBuffer->lock(offset, length, HBL_READ_ONLY);\n memcpy(pDest, srcData, length);\n mShadowBuffer->unlock();\n }\n else\n {\n \/\/ get data from the real buffer\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n glGetBufferSubDataARB(GL_ARRAY_BUFFER_ARB, offset, length, pDest);\n }\n }\n\t\/\/---------------------------------------------------------------------\n void GLHardwareVertexBuffer::writeData(size_t offset, size_t length, \n const void* pSource, bool discardWholeBuffer)\n {\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n \/\/ Update the shadow buffer\n if(mUseShadowBuffer)\n {\n void* destData = mShadowBuffer->lock(offset, length, \n discardWholeBuffer ? HBL_DISCARD : HBL_NORMAL);\n memcpy(destData, pSource, length);\n mShadowBuffer->unlock();\n }\n\n if (offset == 0 && length == mSizeInBytes)\n {\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, pSource, \n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n else\n {\n if(discardWholeBuffer)\n {\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, \n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n\n \/\/ Now update the real buffer\n glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, offset, length, pSource); \n }\n }\n\t\/\/---------------------------------------------------------------------\n void GLHardwareVertexBuffer::_updateFromShadow(void)\n {\n if (mUseShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate)\n {\n const void *srcData = mShadowBuffer->lock(\n mLockStart, mLockSize, HBL_READ_ONLY);\n\n static_cast(mMgr)->getStateCacheManager()->bindGLBuffer(GL_ARRAY_BUFFER_ARB, mBufferId);\n\n \/\/ Update whole buffer if possible, otherwise normal\n if (mLockStart == 0 && mLockSize == mSizeInBytes)\n {\n glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, srcData,\n GLHardwareBufferManager::getGLUsage(mUsage));\n }\n else\n {\n glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, mLockStart, mLockSize, srcData);\n }\n\n mShadowBuffer->unlock();\n mShadowUpdated = false;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"..\/Simulator\/Simulator.h\"\n#include \"..\/Models\/FourLayerVisionSpikingModel.h\"\n\n#include \"..\/SpikeAnalyser\/SpikeAnalyser.h\"\n#include \"..\/Helpers\/TimerWithMessages.h\"\n#include \"..\/Helpers\/TerminalHelpers.h\"\n\n\n\/\/ Use the following line to compile the binary\n\/\/ make FILE='JITest' EXPERIMENT_DIRECTORY='Experiments' model -j8\n\n\n\/\/ The function which will autorun when the executable is created\nint main (int argc, char *argv[]){\n\n\tTimerWithMessages * experiment_timer = new TimerWithMessages();\n\n\t\n\t\/\/ Simulator Parameters\n\t\/\/ float timestep = 0.00002;\n\tfloat timestep = 0.00002;\n\tbool high_fidelity_spike_storage = true;\n\n\t\/\/ bool simulate_network_to_test_untrained = true;\n\t\/\/ bool simulate_network_to_train_network = true;\n\t\/\/ bool simulate_network_to_test_trained = true;\n\t\n\t\/\/ \/\/ Parameters for OPTIMISATION + Information Analysis\n\t\/\/ const float optimal_max_firing_rate = 100.0f;\/\/set if optimizing based on maxfr \/\/Maximum rate (spikes\/sec) 87 +- 46 (*1)\n\t\/\/ \/\/*1 Bair, W., & Movshon, J. A. (2004). Adaptive Temporal Integration of Motion in Direction-Selective Neurons in Macaque Visual Cortex. The Journal of Neuroscience, 24(33), 7305遯カ�ソス7323.\n\t\/\/ int number_of_bins = 5;\n\t\/\/ bool useThresholdForMaxFR = true;\n\t\/\/ const float presentation_time_per_stimulus_per_epoch_test = 0.5f;\n\t\/\/ float max_firing_rate = optimal_max_firing_rate*presentation_time_per_stimulus_per_epoch_test;\n\n\n\tfloat presentation_time_per_stimulus_per_epoch = 0.2;\n\n\n\t\/\/ SIMULATOR OPTIONS\n\tSimulator_Options * simulator_options = new Simulator_Options();\n\n\tsimulator_options->run_simulation_general_options->presentation_time_per_stimulus_per_epoch = presentation_time_per_stimulus_per_epoch;\n\tsimulator_options->run_simulation_general_options->number_of_epochs = 1;\n\tsimulator_options->run_simulation_general_options->apply_stdp_to_relevant_synapses = false;\n\tsimulator_options->run_simulation_general_options->stimulus_presentation_order_seed = 1;\n\n\tsimulator_options->recording_electrodes_options->count_neuron_spikes_recording_electrodes_bool = true;\n\n\tsimulator_options->stimuli_presentation_options->presentation_format = PRESENTATION_FORMAT_OBJECT_BY_OBJECT_RESET_BETWEEN_OBJECTS;\n\tsimulator_options->stimuli_presentation_options->object_order = OBJECT_ORDER_ORIGINAL;\n\tsimulator_options->stimuli_presentation_options->transform_order = TRANSFORM_ORDER_ORIGINAL;\n\n\n\t\/\/ OPTIMISATION\n\tint number_of_optimisation_stages = 5;\n\tint* indices_of_neuron_group_of_interest_for_each_optimisation_stage = (int*)malloc(number_of_optimisation_stages*sizeof(int));\n\tfloat* ideal_output_scores_for_each_optimisation_stage = (float*)malloc(number_of_optimisation_stages*sizeof(float));\n\tfloat* final_optimal_parameter_for_each_optimisation_stage = (float*)malloc(number_of_optimisation_stages*sizeof(float));\n\n\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[0] = 0;\n\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[1] = 0;\n\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[2] = 1;\n\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[3] = 0;\n\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[4] = 2;\n\n\n\tideal_output_scores_for_each_optimisation_stage[0] = 100.0;\n\tideal_output_scores_for_each_optimisation_stage[1] = 150.0;\n\tideal_output_scores_for_each_optimisation_stage[2] = 150.0;\n\tideal_output_scores_for_each_optimisation_stage[3] = 100.0;\n\tideal_output_scores_for_each_optimisation_stage[4] = 100.0;\n\n\n\tfloat initial_optimisation_parameter_min = 1.0f*pow(10, -12);;\n\tfloat initial_optimisation_parameter_max = 1.0*pow(10, 1);\n\t\n\n\tfloat optimisation_ideal_output_score = 100.0;\n\tfloat optimisation_threshold = 5.0;\n\t\n\tfor (int optimisation_stage = 0; optimisation_stage < number_of_optimisation_stages; optimisation_stage++) {\n\n\t\tfloat optimisation_parameter_min = initial_optimisation_parameter_min;\n\t\tfloat optimisation_parameter_max = initial_optimisation_parameter_max;\n\n\t\tfloat final_optimal_parameter = 0.0; \/\/ Eventually have an array of these to use on subsequent optimisation_stage iterations :)\n\t\tint number_of_iterations_for_optimisation_stage = 0;\n\n\t\tfloat previous_optimisation_output_score = -1.0;\n\n\t\twhile (true) {\n\n\t\t\tnumber_of_iterations_for_optimisation_stage++;\n\t\t\t\n\n\t\t\t\/\/ MODEL\n\t\t\tFourLayerVisionSpikingModel * four_layer_vision_spiking_model = new FourLayerVisionSpikingModel();\n\t\t\tfour_layer_vision_spiking_model->SetTimestep(timestep);\n\n\t\t\t\n\n\n\t\t\tfloat test_optimisation_parameter_value = (optimisation_parameter_max + optimisation_parameter_min) \/ 2.0;\n\t\t\t\n\t\t\tif (optimisation_stage >= 0) {\n\t\t\t\tfour_layer_vision_spiking_model->number_of_non_input_layers = 1;\n\t\t\t\tfour_layer_vision_spiking_model->INHIBITORY_NEURONS_ON = false;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 1) {\n\t\t\t\tfour_layer_vision_spiking_model->E2E_L_SYNAPSES_ON = true;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[0] = final_optimal_parameter_for_each_optimisation_stage[0];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 2) {\n\t\t\t\tfour_layer_vision_spiking_model->INHIBITORY_NEURONS_ON = true;\n\t\t\t\tfour_layer_vision_spiking_model->E2I_L_SYNAPSES_ON = true;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0] = final_optimal_parameter_for_each_optimisation_stage[1];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 3) {\n\t\t\t\tfour_layer_vision_spiking_model->I2E_L_SYNAPSES_ON = true;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0] = final_optimal_parameter_for_each_optimisation_stage[2];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 4) {\n\t\t\t\tfour_layer_vision_spiking_model->number_of_non_input_layers = 2;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0] = final_optimal_parameter_for_each_optimisation_stage[3];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[1] = test_optimisation_parameter_value;\n\t\t\t}\n\n\n\n\t\t\tfour_layer_vision_spiking_model->finalise_model();\n\t\t\tfour_layer_vision_spiking_model->copy_model_to_device(high_fidelity_spike_storage);\n\n\t\t\t\/\/ CREATE SIMULATOR\n\t\t\tSimulator * simulator = new Simulator(four_layer_vision_spiking_model, simulator_options);\n\n\t\t\t\/\/ RUN SIMULATION\n\t\t\tSpikeAnalyser * spike_analyser = new SpikeAnalyser(four_layer_vision_spiking_model->spiking_neurons, four_layer_vision_spiking_model->input_spiking_neurons);\n\t\t\tsimulator->RunSimulation(spike_analyser);\n\t\t\tspike_analyser->calculate_various_neuron_spike_totals_and_averages(presentation_time_per_stimulus_per_epoch);\n\n\n\t\t\tfloat optimisation_output_score = spike_analyser->max_number_of_spikes_per_neuron_group_per_second[indices_of_neuron_group_of_interest_for_each_optimisation_stage[optimisation_stage]];\n\n\t\t\t\/\/ printf(\"previous_optimisation_output_score: %f\\n\", previous_optimisation_output_score);\n\t\t\t\/\/ printf(\"number_of_iterations_for_optimisation_stage: %d\\n\", number_of_iterations_for_optimisation_stage);\n\t\t\t\/\/ printf(\"optimisation_parameter_max: %.12f\\n\", optimisation_parameter_max);\n\t\t\t\/\/ printf(\"optimisation_parameter_min: %.12f\\n\", optimisation_parameter_min);\n\t\t\t\/\/ printf(\"test_optimisation_parameter_value: %.12f\\n\", test_optimisation_parameter_value);\n\t\t\t\/\/ printf(\"optimisation_output_score: %f\\n\", optimisation_output_score);\t\t\t\n\n\t\t\tif (optimisation_output_score <= optimisation_ideal_output_score) {\n\n\t\t\t\tif (optimisation_ideal_output_score - optimisation_output_score < optimisation_threshold) {\n\t\t\t\t\tfinal_optimal_parameter_for_each_optimisation_stage[optimisation_stage] = optimisation_output_score;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\toptimisation_parameter_min = test_optimisation_parameter_value;\n\t\t\t\t}\n\n\t\t\t} else if (optimisation_output_score >= optimisation_ideal_output_score) {\n\n\t\t\t\tif (optimisation_output_score - optimisation_ideal_output_score < optimisation_threshold) {\n\t\t\t\t\tfinal_optimal_parameter_for_each_optimisation_stage[optimisation_stage] = optimisation_output_score;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\toptimisation_parameter_max = test_optimisation_parameter_value;\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\t\/\/ printf(\"NEW optimisation_parameter_max: %.12f\\n\", optimisation_parameter_max);\n\t\t\t\/\/ printf(\"NEW optimisation_parameter_min: %.12f\\n\", optimisation_parameter_min);\n\n\n\t\t\tprint_line_of_dashes_with_blank_lines_either_side();\n\n\t\t\tfree(four_layer_vision_spiking_model);\n\t\t\tfree(simulator);\n\n\t\t\tprevious_optimisation_output_score = optimisation_output_score;\n\t\t\t\n\t\t}\t\n\n\t\tprintf(\"final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]: %f\\n\", final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]);\n\t\tprintf(\"number_of_iterations_for_optimisation_stage: %d\\n\", number_of_iterations_for_optimisation_stage);\n\n\t}\n\n\n\tprint_line_of_dashes_with_blank_lines_either_side();\n\n\tfor (int optimisation_stage = 0; optimisation_stage < number_of_optimisation_stages; optimisation_stage++) {\n\n\t\tprintf(\"final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]: %f\\n\", final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]);\n\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/ END OF EXPERIMENT \/\/\/\/\/\/\/\/\/\/\/\n\texperiment_timer->stop_timer_and_log_time_and_message(\"Experiment Completed.\", true);\n\n\treturn 0;\n}Further JITest optimisation work + GPU usage reporting#include \"..\/Simulator\/Simulator.h\"\n#include \"..\/Models\/FourLayerVisionSpikingModel.h\"\n\n#include \"..\/SpikeAnalyser\/SpikeAnalyser.h\"\n#include \"..\/Helpers\/TimerWithMessages.h\"\n#include \"..\/Helpers\/TerminalHelpers.h\"\n\n#include \"cuda_profiler_api.h\"\n\n\n\/\/ Use the following line to compile the binary\n\/\/ make FILE='JITest' EXPERIMENT_DIRECTORY='Experiments' model -j8\n\n\n\/\/ The function which will autorun when the executable is created\nint main (int argc, char *argv[]){\n\n\tTimerWithMessages * experiment_timer = new TimerWithMessages();\n\n\t\n\t\/\/ Simulator Parameters\n\t\/\/ float timestep = 0.00002;\n\tfloat timestep = 0.00002;\n\tbool high_fidelity_spike_storage = true;\n\n\t\/\/ bool simulate_network_to_test_untrained = true;\n\t\/\/ bool simulate_network_to_train_network = true;\n\t\/\/ bool simulate_network_to_test_trained = true;\n\t\n\t\/\/ \/\/ Parameters for OPTIMISATION + Information Analysis\n\t\/\/ const float optimal_max_firing_rate = 100.0f;\/\/set if optimizing based on maxfr \/\/Maximum rate (spikes\/sec) 87 +- 46 (*1)\n\t\/\/ \/\/*1 Bair, W., & Movshon, J. A. (2004). Adaptive Temporal Integration of Motion in Direction-Selective Neurons in Macaque Visual Cortex. The Journal of Neuroscience, 24(33), 7305遯カ�ソス7323.\n\t\/\/ int number_of_bins = 5;\n\t\/\/ bool useThresholdForMaxFR = true;\n\t\/\/ const float presentation_time_per_stimulus_per_epoch_test = 0.5f;\n\t\/\/ float max_firing_rate = optimal_max_firing_rate*presentation_time_per_stimulus_per_epoch_test;\n\n\n\tfloat presentation_time_per_stimulus_per_epoch = 0.2;\n\n\n\t\/\/ SIMULATOR OPTIONS\n\tSimulator_Options * simulator_options = new Simulator_Options();\n\n\tsimulator_options->run_simulation_general_options->presentation_time_per_stimulus_per_epoch = presentation_time_per_stimulus_per_epoch;\n\tsimulator_options->run_simulation_general_options->number_of_epochs = 1;\n\tsimulator_options->run_simulation_general_options->apply_stdp_to_relevant_synapses = false;\n\tsimulator_options->run_simulation_general_options->stimulus_presentation_order_seed = 1;\n\n\tsimulator_options->recording_electrodes_options->count_neuron_spikes_recording_electrodes_bool = true;\n\n\tsimulator_options->stimuli_presentation_options->presentation_format = PRESENTATION_FORMAT_OBJECT_BY_OBJECT_RESET_BETWEEN_OBJECTS;\n\tsimulator_options->stimuli_presentation_options->object_order = OBJECT_ORDER_ORIGINAL;\n\tsimulator_options->stimuli_presentation_options->transform_order = TRANSFORM_ORDER_ORIGINAL;\n\n\n\t\/\/ OPTIMISATION\n\tint number_of_optimisation_stages = 1;\n\tint* indices_of_neuron_group_of_interest_for_each_optimisation_stage = (int*)malloc(number_of_optimisation_stages*sizeof(int));\n\tfloat* ideal_output_scores_for_each_optimisation_stage = (float*)malloc(number_of_optimisation_stages*sizeof(float));\n\tfloat* final_optimal_parameter_for_each_optimisation_stage = (float*)malloc(number_of_optimisation_stages*sizeof(float));\n\n\t\n\n\tif (number_of_optimisation_stages >= 1) {\n\t\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[0] = 0;\n\t\tideal_output_scores_for_each_optimisation_stage[0] = 100.0;\n\t}\n\tif (number_of_optimisation_stages >= 2) {\n\t\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[1] = 0;\n\t\tideal_output_scores_for_each_optimisation_stage[1] = 150.0;\n\t}\n\tif (number_of_optimisation_stages >= 3) {\n\t\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[2] = 1;\n\t\tideal_output_scores_for_each_optimisation_stage[2] = 150.0;\n\t}\n\tif (number_of_optimisation_stages >= 4) {\n\t\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[3] = 0;\n\t\tideal_output_scores_for_each_optimisation_stage[3] = 100.0;\n\t}\n\tif (number_of_optimisation_stages >= 5) {\n\t\tindices_of_neuron_group_of_interest_for_each_optimisation_stage[4] = 2;\n\t\tideal_output_scores_for_each_optimisation_stage[4] = 100.0;\n\t}\n\t\n\n\tfloat initial_optimisation_parameter_min = 1.0f*pow(10, -12);;\n\tfloat initial_optimisation_parameter_max = 1.0*pow(10, -3);\n\t\n\n\tfloat optimisation_ideal_output_score = 100.0;\n\tfloat optimisation_threshold = 5.0;\n\t\n\tfor (int optimisation_stage = 0; optimisation_stage < number_of_optimisation_stages; optimisation_stage++) {\n\n\t\tfloat optimisation_parameter_min = initial_optimisation_parameter_min;\n\t\tfloat optimisation_parameter_max = initial_optimisation_parameter_max;\n\n\t\tfloat final_optimal_parameter = 0.0; \/\/ Eventually have an array of these to use on subsequent optimisation_stage iterations :)\n\t\tint number_of_iterations_for_optimisation_stage = 0;\n\n\t\tfloat previous_optimisation_output_score = -1.0;\n\n\t\t\/\/ while (true) {\n\t\tfor (int temp_i = 0; temp_i < 3; temp_i++) {\n\n\t\t\tnumber_of_iterations_for_optimisation_stage++;\n\t\t\t\n\n\t\t\t\/\/ MODEL\n\t\t\tFourLayerVisionSpikingModel * four_layer_vision_spiking_model = new FourLayerVisionSpikingModel();\n\t\t\tfour_layer_vision_spiking_model->SetTimestep(timestep);\n\n\t\t\t\n\n\n\t\t\tfloat test_optimisation_parameter_value = (optimisation_parameter_max + optimisation_parameter_min) \/ 2.0;\n\t\t\t\n\t\t\tif (optimisation_stage >= 0) {\n\t\t\t\tfour_layer_vision_spiking_model->number_of_non_input_layers = 1;\n\t\t\t\tfour_layer_vision_spiking_model->INHIBITORY_NEURONS_ON = false;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 1) {\n\t\t\t\tfour_layer_vision_spiking_model->E2E_L_SYNAPSES_ON = true;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[0] = final_optimal_parameter_for_each_optimisation_stage[0];\n\t\t\tfour_layer_vision_spiking_model->finalise_model();\n\t\t\tfour_layer_vision_spiking_model->copy_model_to_device(high_fidelity_spike_storage);\n\n\t\t\t\/\/ CREATE SIMULATOR\n\t\t\tSimulator * simulator = new Simulator(four_layer_vision_spiking_model, simulator_options);\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 2) {\n\t\t\t\tfour_layer_vision_spiking_model->INHIBITORY_NEURONS_ON = true;\n\t\t\t\tfour_layer_vision_spiking_model->E2I_L_SYNAPSES_ON = true;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_L[0] = final_optimal_parameter_for_each_optimisation_stage[1];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 3) {\n\t\t\t\tfour_layer_vision_spiking_model->I2E_L_SYNAPSES_ON = true;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2I_L[0] = final_optimal_parameter_for_each_optimisation_stage[2];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0] = test_optimisation_parameter_value;\n\t\t\t}\n\n\t\t\tif (optimisation_stage >= 4) {\n\t\t\t\tfour_layer_vision_spiking_model->number_of_non_input_layers = 2;\n\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_I2E_L[0] = final_optimal_parameter_for_each_optimisation_stage[3];\n\t\t\t\tfour_layer_vision_spiking_model->LBL_biological_conductance_scaling_constant_lambda_E2E_FF[1] = test_optimisation_parameter_value;\n\t\t\t}\n\n\n\n\t\t\tfour_layer_vision_spiking_model->finalise_model();\n\t\t\tfour_layer_vision_spiking_model->copy_model_to_device(high_fidelity_spike_storage);\n\n\t\t\t\/\/ CREATE SIMULATOR\n\t\t\tSimulator * simulator = new Simulator(four_layer_vision_spiking_model, simulator_options);\n\n\t\t\t\/\/ RUN SIMULATION\n\t\t\tSpikeAnalyser * spike_analyser = new SpikeAnalyser(four_layer_vision_spiking_model->spiking_neurons, four_layer_vision_spiking_model->input_spiking_neurons);\n\t\t\tsimulator->RunSimulation(spike_analyser);\n\t\t\tspike_analyser->calculate_various_neuron_spike_totals_and_averages(presentation_time_per_stimulus_per_epoch);\n\n\n\t\t\tfloat optimisation_output_score = spike_analyser->max_number_of_spikes_per_neuron_group_per_second[indices_of_neuron_group_of_interest_for_each_optimisation_stage[optimisation_stage]];\n\n\t\t\tprintf(\"previous_optimisation_output_score: %f\\n\", previous_optimisation_output_score);\n\t\t\tprintf(\"number_of_iterations_for_optimisation_stage: %d\\n\", number_of_iterations_for_optimisation_stage);\n\t\t\tprintf(\"optimisation_parameter_max: %.12f\\n\", optimisation_parameter_max);\n\t\t\tprintf(\"optimisation_parameter_min: %.12f\\n\", optimisation_parameter_min);\n\t\t\tprintf(\"test_optimisation_parameter_value: %.12f\\n\", test_optimisation_parameter_value);\n\t\t\tprintf(\"optimisation_output_score: %f\\n\", optimisation_output_score);\t\t\t\n\n\t\t\tif (optimisation_output_score <= optimisation_ideal_output_score) {\n\n\t\t\t\tif (optimisation_ideal_output_score - optimisation_output_score < optimisation_threshold) {\n\t\t\t\t\tfinal_optimal_parameter_for_each_optimisation_stage[optimisation_stage] = optimisation_output_score;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\toptimisation_parameter_min = test_optimisation_parameter_value;\n\t\t\t\t}\n\n\t\t\t} else if (optimisation_output_score >= optimisation_ideal_output_score) {\n\n\t\t\t\tif (optimisation_output_score - optimisation_ideal_output_score < optimisation_threshold) {\n\t\t\t\t\tfinal_optimal_parameter_for_each_optimisation_stage[optimisation_stage] = optimisation_output_score;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\toptimisation_parameter_max = test_optimisation_parameter_value;\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\tprintf(\"NEW optimisation_parameter_max: %.12f\\n\", optimisation_parameter_max);\n\t\t\tprintf(\"NEW optimisation_parameter_min: %.12f\\n\", optimisation_parameter_min);\n\n\n\t\t\tprint_line_of_dashes_with_blank_lines_either_side();\n\n\t\t\tfree(four_layer_vision_spiking_model);\n\t\t\tfree(simulator);\n\n\t\t\tprevious_optimisation_output_score = optimisation_output_score;\n\n\n\t\t\t\/\/ show memory usage of GPU\n\n\t size_t free_byte ;\n\n\t size_t total_byte ;\n\n\t \tcudaError_t cuda_status = cudaMemGetInfo( &free_byte, &total_byte ) ;\n\n\t if ( cudaSuccess != cuda_status ){\n\n\t printf(\"Error: cudaMemGetInfo fails, %s \\n\", cudaGetErrorString(cuda_status) );\n\n\t exit(1);\n\n\t }\n\n\n\t double free_db = (double)free_byte ;\n\n\t double total_db = (double)total_byte ;\n\n\t double used_db = total_db - free_db ;\n\n\t printf(\"GPU memory usage: used = %f, free = %f MB, total = %f MB\\n\",\n\n\t used_db\/1024.0\/1024.0, free_db\/1024.0\/1024.0, total_db\/1024.0\/1024.0);\n\t\t\t\n\t\t}\t\n\n\t\tprintf(\"final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]: %f\\n\", final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]);\n\t\tprintf(\"number_of_iterations_for_optimisation_stage: %d\\n\", number_of_iterations_for_optimisation_stage);\n\n\t}\n\n\n\tprint_line_of_dashes_with_blank_lines_either_side();\n\n\tfor (int optimisation_stage = 0; optimisation_stage < number_of_optimisation_stages; optimisation_stage++) {\n\n\t\tprintf(\"final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]: %f\\n\", final_optimal_parameter_for_each_optimisation_stage[optimisation_stage]);\n\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/ END OF EXPERIMENT \/\/\/\/\/\/\/\/\/\/\/\n\texperiment_timer->stop_timer_and_log_time_and_message(\"Experiment Completed.\", true);\n\n\tcudaProfilerStop();\n\n\treturn 0;\n}<|endoftext|>"} {"text":"#include \"CameraForm.h\"\n#include \"Object.h\"\n#include \"Director.h\"\n#include \"TransformPipelineParam.h\"\n\nusing namespace Math;\nusing namespace std;\nusing namespace Rendering::Light;\nusing namespace Device;\nusing namespace Core;\nusing namespace Rendering::Camera;\nusing namespace Rendering::Manager;\n\nCameraForm::CameraForm() \n\t: Component(), _frustum(nullptr), _renderTarget(nullptr)\n{\n}\n\nCameraForm::~CameraForm(void)\n{\n\n}\n\nvoid CameraForm::OnInitialize()\n{\n\t_fieldOfViewDegree\t= 60.0f;\n\t_clippingNear\t\t= 0.1f;\n\t_clippingFar\t\t= 1000.0f;\n\n\tconst Size& backBufferSize = Director::GetInstance()->GetBackBufferSize();\n\t_aspect = (float)backBufferSize.w \/ (float)backBufferSize.h;\n\n\t_projectionType = ProjectionType::Perspective;\n\t_clearColor = Color(0.5f, 0.5f, 1.0f, 1.0f);\n\n\t_frustum = new Frustum(0.0f);\t\t\n\n\t_renderTarget = new Texture::RenderTexture;\n\t_renderTarget->Initialize(backBufferSize, DXGI_FORMAT_R8G8B8A8_UNORM);\n\n\t_camConstBuffer = new Buffer::ConstBuffer;\n\tif(_camConstBuffer->Initialize(sizeof(ConstBufferParam)) == false)\n\t\tASSERT_MSG(\"Error, cam->constbuffer->Initialize\");\n\n\t\/\/_clearFlag = ClearFlag::FlagSolidColor;\n}\n\nvoid CameraForm::OnDestroy()\n{\n\tSAFE_DELETE(_frustum);\n\tSAFE_DELETE(_renderTarget);\n}\n\nvoid CameraForm::CalcAspect()\n{\n\tconst Size& backBufferSize = Device::Director::GetInstance()->GetBackBufferSize();\n\t_aspect = (float)backBufferSize.w \/ (float)backBufferSize.h;\n}\n\nvoid CameraForm::GetProjectionMatrix(Math::Matrix& outMatrix) const\n{\n\tif(_projectionType == ProjectionType::Perspective)\n\t{\n\t\tfloat fovRadian = Math::Common::Deg2Rad(_fieldOfViewDegree);\n\t\tMatrix::PerspectiveFovLH(outMatrix, _aspect, fovRadian, _clippingFar, _clippingNear);\n\t}\n\telse if(_projectionType == ProjectionType::Orthographic)\n\t{\n\t\tconst Size& backBufferSize = Device::Director::GetInstance()->GetBackBufferSize();\n\t\tMatrix::OrthoLH(outMatrix, (float)(backBufferSize.w), (float)(backBufferSize.h), _clippingNear, _clippingFar);\n\t}\n}\n\nvoid CameraForm::GetViewMatrix(Math::Matrix &outMatrix, const Math::Matrix &worldMatrix)\n{\n\toutMatrix = worldMatrix;\n\n\tVector3 worldPos;\n\tworldPos.x = worldMatrix._41;\n\tworldPos.y = worldMatrix._42;\n\tworldPos.z = worldMatrix._43;\n\n\tMath::Vector3 right\t\t= Math::Vector3(worldMatrix._11, worldMatrix._21, worldMatrix._31);\n\tMath::Vector3 up\t\t= Math::Vector3(worldMatrix._12, worldMatrix._22, worldMatrix._32);\n\tMath::Vector3 forward\t= Math::Vector3(worldMatrix._13, worldMatrix._23, worldMatrix._33);\n\n\tVector3 p;\n\tp.x = -Vector3::Dot(right,\t\tworldPos);\n\tp.y = -Vector3::Dot(up,\t\t\tworldPos);\n\tp.z = -Vector3::Dot(forward,\tworldPos);\n\n\toutMatrix._41 = p.x;\n\toutMatrix._42 = p.y;\n\toutMatrix._43 = p.z;\n\toutMatrix._44 = 1.0f;\n}\n\nvoid CameraForm::GetViewMatrix(Math::Matrix& outMatrix) const\n{\n\tMatrix worldMat;\n\t_owner->GetTransform()->FetchWorldMatrix(worldMat);\n\n\tGetViewMatrix(outMatrix, worldMat);\n}\n\nvoid CameraForm::UpdateTransformCB(const std::vector& objects)\n{\n\tTransformPipelineParam tfParam;\n\tGetProjectionMatrix(tfParam.projMat);\n\tGetViewMatrix(tfParam.viewMat);\n\n\t_viewProjMatrixInPrevRenderState = tfParam.viewMat * tfParam.projMat;\n\t_frustum->Make(_viewProjMatrixInPrevRenderState);\n\n\tConstBufferParam camCB;\n\t{\n\t\tMatrix worldMat;\n\t\t_owner->GetTransform()->FetchWorldMatrix(worldMat);\n\n\t\tcamCB.worldPos\t\t= Vector4(worldMat._41, worldMat._42, worldMat._43, 1.0f);\n\t\tcamCB.clippingNear\t= _clippingNear;\n\t\tcamCB.clippingFar\t= _clippingFar;\n\t\tcamCB.screenSize\t= Device::Director::GetInstance()->GetBackBufferSize().Cast();\n\t}\n\t\n\tif( memcmp(&_prevConstBufferData, &camCB, sizeof(ConstBufferParam)) != 0 )\n\t{\n\t\tID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();\n\t\t_camConstBuffer->UpdateSubResource(context, &camCB);\n\n\t\t_prevConstBufferData = camCB;\n\t}\n\n\tfor(auto iter = objects.begin(); iter != objects.end(); ++iter)\n\t{\n\t\t(*iter)->Culling(_frustum);\n\t\t(*iter)->UpdateTransformCB(tfParam);\n\t}\n}\n\nvoid CameraForm::SortTransparentMeshRenderQueue(const RenderManager* renderMgr)\n{\n\tconst RenderManager::MeshList transparentList = renderMgr->GetTransparentMeshes();\n\tif( transparentList.updateCounter > _transparentMeshQueue.updateCounter )\n\t{\n\t\tconst auto& renderMgrMeshes = transparentList.meshes.GetVector();\n\t\tauto& thisCamMeshes = _transparentMeshQueue.meshes;\n\n\t\tthisCamMeshes.clear();\n\t\tthisCamMeshes.insert( thisCamMeshes.end(), renderMgrMeshes.begin(), renderMgrMeshes.end());\n\n\t\t_transparentMeshQueue.updateCounter = transparentList.updateCounter;\n\t}\n\n\tconst Transform* transform = _owner->GetTransform();\n\n\tMath::Vector3 camPos;\n\ttransform->FetchWorldPosition(camPos);\n\n\tauto SortingByDistance = [&](const Mesh::Mesh*& left, const Mesh::Mesh*& right) -> bool\n\t{\n\t\tfloat leftDistance = D3D11_FLOAT32_MAX;\n\t\t{\n\t\t\tMath::Vector3 leftPos;\n\t\t\tleft->GetOwner()->GetTransform()->FetchWorldPosition(leftPos);\n\t\t\tleftDistance = Math::Vector3::Distance(leftPos, camPos);\n\t\t}\n\n\t\tfloat rightDistance = D3D11_FLOAT32_MAX;\n\t\t{\n\t\t\tMath::Vector3 rightPos;\n\t\t\tright->GetOwner()->GetTransform()->FetchWorldPosition(rightPos);\n\t\t\trightDistance = Math::Vector3::Distance(rightPos, camPos);\n\t\t}\n\n\t\treturn leftDistance < rightDistance;\n\t};\n\n\tstd::sort(_transparentMeshQueue.meshes.begin(), _transparentMeshQueue.meshes.end(), SortingByDistance);\n}\n\nvoid CameraForm::_Clone(CameraForm* newCam) const\n{\n\t(*newCam) = (*this);\n\tnewCam->_frustum\t\t= new Frustum(0.0f);\n\tnewCam->_renderTarget\t= new Texture::RenderTexture;\n\t{\n\t\tconst Size& size = Director::GetInstance()->GetBackBufferSize();\n\t\tnewCam->_renderTarget->Initialize(size, DXGI_FORMAT_R8G8B8A8_UNORM);\n\t}\n\n\tnewCam->_camConstBuffer\t= new Buffer::ConstBuffer;\n\tif(_camConstBuffer->Initialize(sizeof(ConstBufferParam)) == false)\n\t\tASSERT_MSG(\"Error, cant create const buffer in _Clone\");\n}CameraForm - RenderTexture의 포맷을 r16g16b16a16으로 변경함(원래는 r8g8b8a8) #64#include \"CameraForm.h\"\n#include \"Object.h\"\n#include \"Director.h\"\n#include \"TransformPipelineParam.h\"\n\nusing namespace Math;\nusing namespace std;\nusing namespace Rendering::Light;\nusing namespace Device;\nusing namespace Core;\nusing namespace Rendering::Camera;\nusing namespace Rendering::Manager;\n\nCameraForm::CameraForm() \n\t: Component(), _frustum(nullptr), _renderTarget(nullptr)\n{\n}\n\nCameraForm::~CameraForm(void)\n{\n\n}\n\nvoid CameraForm::OnInitialize()\n{\n\t_fieldOfViewDegree\t= 60.0f;\n\t_clippingNear\t\t= 0.1f;\n\t_clippingFar\t\t= 1000.0f;\n\n\tconst Size& backBufferSize = Director::GetInstance()->GetBackBufferSize();\n\t_aspect = (float)backBufferSize.w \/ (float)backBufferSize.h;\n\n\t_projectionType = ProjectionType::Perspective;\n\t_clearColor = Color(0.5f, 0.5f, 1.0f, 1.0f);\n\n\t_frustum = new Frustum(0.0f);\t\t\n\n\t_renderTarget = new Texture::RenderTexture;\n\t_renderTarget->Initialize(backBufferSize, DXGI_FORMAT_R16G16B16A16_FLOAT);\n\n\t_camConstBuffer = new Buffer::ConstBuffer;\n\tif(_camConstBuffer->Initialize(sizeof(ConstBufferParam)) == false)\n\t\tASSERT_MSG(\"Error, cam->constbuffer->Initialize\");\n\n\t\/\/_clearFlag = ClearFlag::FlagSolidColor;\n}\n\nvoid CameraForm::OnDestroy()\n{\n\tSAFE_DELETE(_frustum);\n\tSAFE_DELETE(_renderTarget);\n}\n\nvoid CameraForm::CalcAspect()\n{\n\tconst Size& backBufferSize = Device::Director::GetInstance()->GetBackBufferSize();\n\t_aspect = (float)backBufferSize.w \/ (float)backBufferSize.h;\n}\n\nvoid CameraForm::GetProjectionMatrix(Math::Matrix& outMatrix) const\n{\n\tif(_projectionType == ProjectionType::Perspective)\n\t{\n\t\tfloat fovRadian = Math::Common::Deg2Rad(_fieldOfViewDegree);\n\t\tMatrix::PerspectiveFovLH(outMatrix, _aspect, fovRadian, _clippingFar, _clippingNear);\n\t}\n\telse if(_projectionType == ProjectionType::Orthographic)\n\t{\n\t\tconst Size& backBufferSize = Device::Director::GetInstance()->GetBackBufferSize();\n\t\tMatrix::OrthoLH(outMatrix, (float)(backBufferSize.w), (float)(backBufferSize.h), _clippingNear, _clippingFar);\n\t}\n}\n\nvoid CameraForm::GetViewMatrix(Math::Matrix &outMatrix, const Math::Matrix &worldMatrix)\n{\n\toutMatrix = worldMatrix;\n\n\tVector3 worldPos;\n\tworldPos.x = worldMatrix._41;\n\tworldPos.y = worldMatrix._42;\n\tworldPos.z = worldMatrix._43;\n\n\tMath::Vector3 right\t\t= Math::Vector3(worldMatrix._11, worldMatrix._21, worldMatrix._31);\n\tMath::Vector3 up\t\t= Math::Vector3(worldMatrix._12, worldMatrix._22, worldMatrix._32);\n\tMath::Vector3 forward\t= Math::Vector3(worldMatrix._13, worldMatrix._23, worldMatrix._33);\n\n\tVector3 p;\n\tp.x = -Vector3::Dot(right,\t\tworldPos);\n\tp.y = -Vector3::Dot(up,\t\t\tworldPos);\n\tp.z = -Vector3::Dot(forward,\tworldPos);\n\n\toutMatrix._41 = p.x;\n\toutMatrix._42 = p.y;\n\toutMatrix._43 = p.z;\n\toutMatrix._44 = 1.0f;\n}\n\nvoid CameraForm::GetViewMatrix(Math::Matrix& outMatrix) const\n{\n\tMatrix worldMat;\n\t_owner->GetTransform()->FetchWorldMatrix(worldMat);\n\n\tGetViewMatrix(outMatrix, worldMat);\n}\n\nvoid CameraForm::UpdateTransformCB(const std::vector& objects)\n{\n\tTransformPipelineParam tfParam;\n\tGetProjectionMatrix(tfParam.projMat);\n\tGetViewMatrix(tfParam.viewMat);\n\n\t_viewProjMatrixInPrevRenderState = tfParam.viewMat * tfParam.projMat;\n\t_frustum->Make(_viewProjMatrixInPrevRenderState);\n\n\tConstBufferParam camCB;\n\t{\n\t\tMatrix worldMat;\n\t\t_owner->GetTransform()->FetchWorldMatrix(worldMat);\n\n\t\tcamCB.worldPos\t\t= Vector4(worldMat._41, worldMat._42, worldMat._43, 1.0f);\n\t\tcamCB.clippingNear\t= _clippingNear;\n\t\tcamCB.clippingFar\t= _clippingFar;\n\t\tcamCB.screenSize\t= Device::Director::GetInstance()->GetBackBufferSize().Cast();\n\t}\n\t\n\tif( memcmp(&_prevConstBufferData, &camCB, sizeof(ConstBufferParam)) != 0 )\n\t{\n\t\tID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();\n\t\t_camConstBuffer->UpdateSubResource(context, &camCB);\n\n\t\t_prevConstBufferData = camCB;\n\t}\n\n\tfor(auto iter = objects.begin(); iter != objects.end(); ++iter)\n\t{\n\t\t(*iter)->Culling(_frustum);\n\t\t(*iter)->UpdateTransformCB(tfParam);\n\t}\n}\n\nvoid CameraForm::SortTransparentMeshRenderQueue(const RenderManager* renderMgr)\n{\n\tconst RenderManager::MeshList transparentList = renderMgr->GetTransparentMeshes();\n\tif( transparentList.updateCounter > _transparentMeshQueue.updateCounter )\n\t{\n\t\tconst auto& renderMgrMeshes = transparentList.meshes.GetVector();\n\t\tauto& thisCamMeshes = _transparentMeshQueue.meshes;\n\n\t\tthisCamMeshes.clear();\n\t\tthisCamMeshes.insert( thisCamMeshes.end(), renderMgrMeshes.begin(), renderMgrMeshes.end());\n\n\t\t_transparentMeshQueue.updateCounter = transparentList.updateCounter;\n\t}\n\n\tconst Transform* transform = _owner->GetTransform();\n\n\tMath::Vector3 camPos;\n\ttransform->FetchWorldPosition(camPos);\n\n\tauto SortingByDistance = [&](const Mesh::Mesh*& left, const Mesh::Mesh*& right) -> bool\n\t{\n\t\tfloat leftDistance = D3D11_FLOAT32_MAX;\n\t\t{\n\t\t\tMath::Vector3 leftPos;\n\t\t\tleft->GetOwner()->GetTransform()->FetchWorldPosition(leftPos);\n\t\t\tleftDistance = Math::Vector3::Distance(leftPos, camPos);\n\t\t}\n\n\t\tfloat rightDistance = D3D11_FLOAT32_MAX;\n\t\t{\n\t\t\tMath::Vector3 rightPos;\n\t\t\tright->GetOwner()->GetTransform()->FetchWorldPosition(rightPos);\n\t\t\trightDistance = Math::Vector3::Distance(rightPos, camPos);\n\t\t}\n\n\t\treturn leftDistance < rightDistance;\n\t};\n\n\tstd::sort(_transparentMeshQueue.meshes.begin(), _transparentMeshQueue.meshes.end(), SortingByDistance);\n}\n\nvoid CameraForm::_Clone(CameraForm* newCam) const\n{\n\t(*newCam) = (*this);\n\tnewCam->_frustum\t\t= new Frustum(0.0f);\n\tnewCam->_renderTarget\t= new Texture::RenderTexture;\n\t{\n\t\tconst Size& size = Director::GetInstance()->GetBackBufferSize();\n\t\tnewCam->_renderTarget->Initialize(size, DXGI_FORMAT_R8G8B8A8_UNORM);\n\t}\n\n\tnewCam->_camConstBuffer\t= new Buffer::ConstBuffer;\n\tif(_camConstBuffer->Initialize(sizeof(ConstBufferParam)) == false)\n\t\tASSERT_MSG(\"Error, cant create const buffer in _Clone\");\n}<|endoftext|>"} {"text":"\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.com *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* other materials provided with the distribution. *\/\r\n\/* *\/\r\n\/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\/\r\n\/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\/\r\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\/\r\n\/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR *\/\r\n\/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\/\r\n\/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\/\r\n\/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON *\/\r\n\/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\/\r\n\/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\/\r\n\/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\r\n\/* *\/\r\n\/**************************************************************************************\/\r\n\r\n#ifndef Applet_INCLUDE_ONCE\r\n#define Applet_INCLUDE_ONCE\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nnamespace vl\r\n{\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Applet\r\n\/\/-----------------------------------------------------------------------------\r\n \/** The Applet class is an utilitly UIEventListener that features a ghost manipulator, \r\n trackball manipulator, an FPS counter and a simple rendering pipeline. \r\n\r\n Default key bindings:\r\n - Key_Escape: calls openglContext()->quitApplication()\r\n - Key_T: enables the TrackballManipulator.\r\n - Key_F: enables the GhostCameraManipulator (fly mode).\r\n - Key_F1: toggles fullscreen mode if supported.\r\n - Key_F5: saves a screenshot of the current OpenGL window. \r\n - Key_C: toggles the continuous update fo the OpenGL window (see also OpenGLContext::setContinuousUpdate()).\r\n - Key_U: updates the OpenGL window content by calling openglContext()->update(). *\/\r\n class Applet: public UIEventListener\r\n {\r\n public:\r\n virtual const char* className() { return \"Applet\"; }\r\n\r\n \/** Constructor *\/\r\n Applet();\r\n\r\n \/** Initializes the default rendering (with Rendering), the default scene manager (with SceneManagerActorTree) and camera manipulators (GhostCameraManipulator and TrackballManipulator). *\/\r\n void initialize();\r\n\r\n \/\/ --- UIEventListener ---\r\n\r\n virtual void addedListenerEvent(OpenGLContext* openglContext);\r\n\r\n virtual void removedListenerEvent(OpenGLContext*);\r\n\r\n virtual void keyReleaseEvent(unsigned short, EKey key);\r\n\r\n virtual void destroyEvent();\r\n\r\n virtual void updateEvent();\r\n\r\n virtual void resizeEvent(int, int);\r\n\r\n virtual void initEvent() {}\r\n \r\n virtual void enableEvent(bool) {}\r\n\r\n virtual void mouseMoveEvent(int, int) {}\r\n\r\n virtual void mouseUpEvent(EMouseButton, int, int) {}\r\n\r\n virtual void mouseDownEvent(EMouseButton, int, int) {}\r\n\r\n virtual void mouseWheelEvent(int) {}\r\n\r\n virtual void keyPressEvent(unsigned short, EKey) {}\r\n\r\n virtual void fileDroppedEvent(const std::vector&) {}\r\n\r\n virtual void visibilityEvent(bool) {}\r\n\r\n \/\/ --- --- ---\r\n\r\n \/** The rendering used by the Applet, by default a Rendering. *\/\r\n RenderingAbstract* rendering() { return mRendering.get(); }\r\n \r\n \/** The rendering used by the Applet, by default a Rendering. *\/\r\n const RenderingAbstract* rendering() const { return mRendering.get(); }\r\n \r\n \/** Sets the rendering used by the Applet, by default a Rendering. *\/\r\n void setRendering(RenderingAbstract* rendering) { mRendering = rendering; }\r\n\r\n \/** The scene manager used by the default rendering. *\/\r\n SceneManagerActorTree* sceneManager() { return mSceneManagerActorTree.get(); }\r\n\r\n \/** The scene manager used by the default rendering. *\/\r\n const SceneManagerActorTree* sceneManager() const { return mSceneManagerActorTree.get(); }\r\n\r\n \/** GhostCameraManipulator used by the applet, activated by the \"F\" key. *\/\r\n GhostCameraManipulator* ghostCamera() { return mFly.get(); }\r\n\r\n \/** TrackballManipulator used by the applet, activated by the \"T\" key. *\/\r\n TrackballManipulator* trackball() { return mTrackball.get(); }\r\n\r\n \/** Current average frames per second (updated every 500ms). *\/\r\n double fps() const { return mFPS; }\r\n\r\n \/** Override this to update the content of your scene. \r\n Called by updateEvent() right before rendering()->render() and swapping opengl front\/back buffers. \r\n \\note Since updateScene() is called by updateEvent() this function is called only if somebody\r\n requests a OpenGLContext::update() or if OpenGLContext::continuousUpdate() is set to \\p true. *\/\r\n\t virtual void updateScene() {}\r\n\r\n \/** Sets the applet name, used for the window title and for naming screenshots. *\/\r\n void setAppletName(const String& app_name) { mAppletName = app_name; } \r\n\r\n \/** The applet name, used for the window title and for naming screenshots. *\/\r\n const String& appletName() const { return mAppletName; }\r\n\r\n protected:\r\n void bindManipulators(Camera* camera);\r\n\r\n private:\r\n ref mRendering;\r\n ref mFly;\r\n ref mTrackball;\r\n ref mSceneManagerActorTree;\r\n ref mReadPixels;\r\n String mAppletName;\r\n double mStartTime;\r\n double mFPS;\r\n int mFrameCount;\r\n };\r\n}\r\n\r\n#endif\r\nupdated comments.\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.com *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* other materials provided with the distribution. *\/\r\n\/* *\/\r\n\/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\/\r\n\/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\/\r\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\/\r\n\/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR *\/\r\n\/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\/\r\n\/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\/\r\n\/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON *\/\r\n\/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\/\r\n\/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\/\r\n\/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\r\n\/* *\/\r\n\/**************************************************************************************\/\r\n\r\n#ifndef Applet_INCLUDE_ONCE\r\n#define Applet_INCLUDE_ONCE\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nnamespace vl\r\n{\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Applet\r\n\/\/-----------------------------------------------------------------------------\r\n \/** \r\n * The Applet class is an utilitly UIEventListener that features a ghost manipulator, \r\n * trackball manipulator, an FPS counter and a simple rendering pipeline. \r\n * \r\n * Default key bindings:\r\n * - Key_Escape: calls openglContext()->quitApplication()\r\n * - Key_T: enables the TrackballManipulator.\r\n * - Key_F: enables the GhostCameraManipulator (fly mode).\r\n * - Key_F1: toggles fullscreen mode if supported.\r\n * - Key_F5: saves a screenshot of the current OpenGL window. \r\n * - Key_C: toggles the continuous update fo the OpenGL window (see also OpenGLContext::setContinuousUpdate()).\r\n * - Key_U: updates the OpenGL window content by calling openglContext()->update(). \r\n *\/\r\n class Applet: public UIEventListener\r\n {\r\n public:\r\n virtual const char* className() { return \"Applet\"; }\r\n\r\n \/** Constructor *\/\r\n Applet();\r\n\r\n \/** \r\n * Initializes the default rendering (with Rendering), the default scene manager (with SceneManagerActorTree) \r\n * and camera manipulators (GhostCameraManipulator and TrackballManipulator). \r\n *\/\r\n void initialize();\r\n\r\n \/\/ --- UIEventListener ---\r\n\r\n virtual void addedListenerEvent(OpenGLContext* openglContext);\r\n\r\n virtual void removedListenerEvent(OpenGLContext*);\r\n\r\n virtual void keyReleaseEvent(unsigned short, EKey key);\r\n\r\n virtual void destroyEvent();\r\n\r\n virtual void updateEvent();\r\n\r\n virtual void resizeEvent(int, int);\r\n\r\n virtual void initEvent() {}\r\n \r\n virtual void enableEvent(bool) {}\r\n\r\n virtual void mouseMoveEvent(int, int) {}\r\n\r\n virtual void mouseUpEvent(EMouseButton, int, int) {}\r\n\r\n virtual void mouseDownEvent(EMouseButton, int, int) {}\r\n\r\n virtual void mouseWheelEvent(int) {}\r\n\r\n virtual void keyPressEvent(unsigned short, EKey) {}\r\n\r\n virtual void fileDroppedEvent(const std::vector&) {}\r\n\r\n virtual void visibilityEvent(bool) {}\r\n\r\n \/\/ --- --- ---\r\n\r\n \/** The rendering used by the Applet, by default a Rendering. *\/\r\n RenderingAbstract* rendering() { return mRendering.get(); }\r\n \r\n \/** The rendering used by the Applet, by default a Rendering. *\/\r\n const RenderingAbstract* rendering() const { return mRendering.get(); }\r\n \r\n \/** Sets the rendering used by the Applet, by default a Rendering. *\/\r\n void setRendering(RenderingAbstract* rendering) { mRendering = rendering; }\r\n\r\n \/** The scene manager used by the default rendering. *\/\r\n SceneManagerActorTree* sceneManager() { return mSceneManagerActorTree.get(); }\r\n\r\n \/** The scene manager used by the default rendering. *\/\r\n const SceneManagerActorTree* sceneManager() const { return mSceneManagerActorTree.get(); }\r\n\r\n \/** GhostCameraManipulator used by the applet, activated by the \"F\" key. *\/\r\n GhostCameraManipulator* ghostCamera() { return mFly.get(); }\r\n\r\n \/** TrackballManipulator used by the applet, activated by the \"T\" key. *\/\r\n TrackballManipulator* trackball() { return mTrackball.get(); }\r\n\r\n \/** Current average frames per second (updated every 500ms). *\/\r\n double fps() const { return mFPS; }\r\n\r\n \/** \r\n * Override this to update the content of your scene. \r\n * Called by updateEvent() right before rendering()->render() and swapping opengl front\/back buffers. \r\n * \\note Since updateScene() is called by updateEvent() this function is called only if somebody\r\n * requests a OpenGLContext::update() or if OpenGLContext::continuousUpdate() is set to \\p true. \r\n *\/\r\n\t virtual void updateScene() {}\r\n\r\n \/** Sets the applet name, used for the window title and for naming screenshots. *\/\r\n void setAppletName(const String& app_name) { mAppletName = app_name; } \r\n\r\n \/** The applet name, used for the window title and for naming screenshots. *\/\r\n const String& appletName() const { return mAppletName; }\r\n\r\n protected:\r\n void bindManipulators(Camera* camera);\r\n\r\n private:\r\n ref mRendering;\r\n ref mFly;\r\n ref mTrackball;\r\n ref mSceneManagerActorTree;\r\n ref mReadPixels;\r\n String mAppletName;\r\n double mStartTime;\r\n double mFPS;\r\n int mFrameCount;\r\n };\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"..\\Quantities\\Dimensionless.hpp\"\n#include \"..\\Quantities\\Quantities.hpp\"\n#include \"R3Element.hpp\"\n\nnamespace Principia {\nnamespace Geometry {\ntemplate\nstruct Multivector;\n\ntemplate\nstruct Multivector {\n Multivector(R3Element coordinates) : coordinates(coordinates) {};\n R3Element coordinates;\n};\n\ntemplate\nstruct Multivector {\n Multivector(R3Element coordinates) : coordinates(coordinates) {};\n R3Element Coordinates;\n};\n\ntemplate\nstruct Multivector {\n Multivector(Scalar coordinates) : coordinates(coordinates) {};\n Scalar Coordinates;\n};\n\ntemplate\nusing Vector = Multivector;\n\ntemplate\nusing Bivector = Multivector;\n\ntemplate\nusing Trivector = Multivector;\n\ntemplate\nScalar InnerProduct(Vector const& left,\n Vector const& right);\n\ntemplate\nScalar InnerProduct(Bivector const& left,\n Bivector const& right);\n\ntemplate\nScalar InnerProduct(Trivector const& left,\n Trivector const& right);\n\ntemplate\nBivector Wedge(Vector const& Left,\n Vector const& right);\n\ntemplate\nTrivector Wedge(Bivector const& Left,\n Vector const& right);\n\ntemplate\nTrivector Wedge(Vector const& Left,\n Bivector const& right);\n\ntemplate\nMultivector operator+ (Multivector const& right);\ntemplate\nMultivector operator- (Multivector const& right);\ntemplate\n\nMultivector operator+ (Multivector const& left,\n Multivector const& right);\ntemplate\nMultivector operator- (Multivector const& left,\n Multivector const& right);\n\ntemplate\nMultivector operator* (Quantities::Dimensionless const& left,\n Multivector const& right);\ntemplate\nMultivector operator* (Multivector const& left,\n Quantities::Dimensionless const& right);\ntemplate\nMultivector operator\/ (Multivector const& left,\n Quantities::Dimensionless const& right);\n\ntemplate\nMultivector , Frame,\n Rank> operator* (U const& left,\n Multivector const& right);\ntemplate\nMultivector, Frame,\n Rank> operator* (Multivector const& left,\n Quantities::Dimensionless const& right);\ntemplate\nMultivector, Frame,\n Rank> operator\/ (Multivector const& left,\n Quantities::Dimensionless const& right);\n\n}\n}\n\n#include \"Grassmann-body.hpp\"\nStyleguide compliance.#pragma once\n\n#include \"..\\Quantities\\Dimensionless.hpp\"\n#include \"..\\Quantities\\Quantities.hpp\"\n#include \"R3Element.hpp\"\n\nnamespace Principia {\nnamespace Geometry {\ntemplate\nstruct Multivector;\n\ntemplate\nstruct Multivector {\n Multivector(R3Element coordinates) : coordinates(coordinates) {};\n R3Element coordinates;\n};\n\ntemplate\nstruct Multivector {\n Multivector(R3Element coordinates) : coordinates(coordinates) {};\n R3Element coordinates;\n};\n\ntemplate\nstruct Multivector {\n Multivector(Scalar coordinates) : coordinates(coordinates) {};\n Scalar coordinates;\n};\n\ntemplate\nusing Vector = Multivector;\n\ntemplate\nusing Bivector = Multivector;\n\ntemplate\nusing Trivector = Multivector;\n\ntemplate\nScalar InnerProduct(Vector const& left,\n Vector const& right);\n\ntemplate\nScalar InnerProduct(Bivector const& left,\n Bivector const& right);\n\ntemplate\nScalar InnerProduct(Trivector const& left,\n Trivector const& right);\n\ntemplate\nBivector Wedge(Vector const& Left,\n Vector const& right);\n\ntemplate\nTrivector Wedge(Bivector const& Left,\n Vector const& right);\n\ntemplate\nTrivector Wedge(Vector const& Left,\n Bivector const& right);\n\ntemplate\nMultivector operator+ (Multivector const& right);\ntemplate\nMultivector operator- (Multivector const& right);\ntemplate\n\nMultivector operator+ (Multivector const& left,\n Multivector const& right);\ntemplate\nMultivector operator- (Multivector const& left,\n Multivector const& right);\n\ntemplate\nMultivector operator* (Quantities::Dimensionless const& left,\n Multivector const& right);\ntemplate\nMultivector operator* (Multivector const& left,\n Quantities::Dimensionless const& right);\ntemplate\nMultivector operator\/ (Multivector const& left,\n Quantities::Dimensionless const& right);\n\ntemplate\nMultivector , Frame,\n Rank> operator* (U const& left,\n Multivector const& right);\ntemplate\nMultivector, Frame,\n Rank> operator* (Multivector const& left,\n Quantities::Dimensionless const& right);\ntemplate\nMultivector, Frame,\n Rank> operator\/ (Multivector const& left,\n Quantities::Dimensionless const& right);\n\n}\n}\n\n#include \"Grassmann-body.hpp\"\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/socket\/client_socket.h\"\n\n#include \"base\/histogram.h\"\n\nnamespace net {\n\nClientSocket::ClientSocket()\n : omnibox_speculation_(false),\n subresource_speculation_(false),\n was_used_to_transmit_data_(false) {}\n\nClientSocket::~ClientSocket() {\n EmitPreconnectionHistograms();\n}\n\nvoid ClientSocket::EmitPreconnectionHistograms() const {\n DCHECK(!subresource_speculation_ || !omnibox_speculation_);\n \/\/ 0 ==> non-speculative, never connected.\n \/\/ 1 ==> non-speculative never used (but connected).\n \/\/ 2 ==> non-spculative and used.\n \/\/ 3 ==> omnibox_speculative never connected.\n \/\/ 4 ==> omnibox_speculative never used (but connected).\n \/\/ 5 ==> omnibox_speculative and used.\n \/\/ 6 ==> subresource_speculative never connected.\n \/\/ 7 ==> subresource_speculative never used (but connected).\n \/\/ 8 ==> subresource_speculative and used.\n int result;\n if (was_used_to_transmit_data_)\n result = 2;\n else if (was_ever_connected_)\n result = 1;\n else\n result = 0; \/\/ Never used, and not really connected.\n\n if (omnibox_speculation_)\n result += 3;\n else if (subresource_speculation_)\n result += 6;\n UMA_HISTOGRAM_ENUMERATION(\"Net.PreconnectUtilization\", result, 9);\n}\n\nvoid ClientSocket::SetSubresourceSpeculation() {\n if (was_used_to_transmit_data_)\n return;\n subresource_speculation_ = true;\n}\n\nvoid ClientSocket::SetOmniboxSpeculation() {\n if (was_used_to_transmit_data_)\n return;\n omnibox_speculation_ = true;\n}\n\nvoid ClientSocket::UpdateConnectivityState(bool is_reused) {\n \/\/ Record if this connection has every actually connected successfully.\n \/\/ Note that IsConnected() won't be defined at destruction time, so we need\n \/\/ to record this data now, while the derived class is present.\n was_ever_connected_ |= IsConnected();\n \/\/ A socket is_reused only after it has transmitted some data.\n was_used_to_transmit_data_ |= is_reused;\n}\n\n} \/\/ namespace net\n\nInitialize was_ever_connected_ in ClientSocket.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/socket\/client_socket.h\"\n\n#include \"base\/histogram.h\"\n\nnamespace net {\n\nClientSocket::ClientSocket()\n : was_ever_connected_(false),\n omnibox_speculation_(false),\n subresource_speculation_(false),\n was_used_to_transmit_data_(false) {}\n\nClientSocket::~ClientSocket() {\n EmitPreconnectionHistograms();\n}\n\nvoid ClientSocket::EmitPreconnectionHistograms() const {\n DCHECK(!subresource_speculation_ || !omnibox_speculation_);\n \/\/ 0 ==> non-speculative, never connected.\n \/\/ 1 ==> non-speculative never used (but connected).\n \/\/ 2 ==> non-spculative and used.\n \/\/ 3 ==> omnibox_speculative never connected.\n \/\/ 4 ==> omnibox_speculative never used (but connected).\n \/\/ 5 ==> omnibox_speculative and used.\n \/\/ 6 ==> subresource_speculative never connected.\n \/\/ 7 ==> subresource_speculative never used (but connected).\n \/\/ 8 ==> subresource_speculative and used.\n int result;\n if (was_used_to_transmit_data_)\n result = 2;\n else if (was_ever_connected_)\n result = 1;\n else\n result = 0; \/\/ Never used, and not really connected.\n\n if (omnibox_speculation_)\n result += 3;\n else if (subresource_speculation_)\n result += 6;\n UMA_HISTOGRAM_ENUMERATION(\"Net.PreconnectUtilization\", result, 9);\n}\n\nvoid ClientSocket::SetSubresourceSpeculation() {\n if (was_used_to_transmit_data_)\n return;\n subresource_speculation_ = true;\n}\n\nvoid ClientSocket::SetOmniboxSpeculation() {\n if (was_used_to_transmit_data_)\n return;\n omnibox_speculation_ = true;\n}\n\nvoid ClientSocket::UpdateConnectivityState(bool is_reused) {\n \/\/ Record if this connection has every actually connected successfully.\n \/\/ Note that IsConnected() won't be defined at destruction time, so we need\n \/\/ to record this data now, while the derived class is present.\n was_ever_connected_ |= IsConnected();\n \/\/ A socket is_reused only after it has transmitted some data.\n was_used_to_transmit_data_ |= is_reused;\n}\n\n} \/\/ namespace net\n\n<|endoftext|>"} {"text":"\/\/ VisualBlock.cpp\r\n\r\n#include \"VisualBlock.h\"\r\n#include \"VisualPainter.h\"\r\n#include \"Assert.h\"\r\n#include \r\n\r\n#undef min\r\n#undef max\r\n\r\nVisualBlock::VisualBlock( size_t length )\r\n\t: m_length( length )\r\n{\r\n\tm_lines.push_back( VisualLine() );\r\n}\r\n\r\nVisualBlock::VisualBlock( size_t length, LayoutAllocator& allocator, ArrayOf items )\r\n\t: m_length( length )\r\n{\r\n\tm_layout.Copy( allocator, items );\r\n\r\n\tArrayOf lines = allocator.lines.Allocated();\r\n\tm_lines.reserve( lines.size() );\r\n\r\n\tTextRun* runs = m_layout.runs;\r\n\tsize_t lastEnd = 0;\r\n\tsize_t textStart = 0;\r\n\r\n\tfor ( size_t* it = lines.begin(); it != lines.end(); ++it )\r\n\t{\r\n\t\tTextRun* runStart = runs + lastEnd;\r\n\t\tTextRun* runEnd = runs + *it;\r\n\r\n\t\tm_lines.push_back( VisualLine( textStart, runStart, runEnd ) );\r\n\r\n\t\ttextStart = m_lines.back().TextEnd();\r\n\t\tlastEnd = *it;\r\n\t}\r\n}\r\n\r\nvoid VisualBlock::Draw( VisualPainter& painter, RECT rect ) const\r\n{\r\n\tsize_t i = rect.top \/ painter.style.lineHeight;\r\n\trect.top = i * painter.style.lineHeight;\r\n\r\n\tif ( 0 < i && i < m_lines.size() )\r\n\t\tpainter.prevSelection.Swap( m_lines[i-1].MakeVisualSelection( painter.selection, m_layout ) );\r\n\r\n\tfor ( ; i < m_lines.size() && !IsRectEmpty( &rect ); ++i )\r\n\t{\r\n\t\tDrawSelection( m_lines[i], painter, rect );\r\n\t\tm_lines[i].Draw( painter, rect, m_layout );\r\n\r\n\t\trect.top += painter.style.lineHeight;\r\n\t}\r\n}\r\n\r\nvoid VisualBlock::DrawSelection( const VisualLine& line, VisualPainter& painter, RECT rect ) const\r\n{\r\n\tVisualSelection selection;\r\n\r\n\tif ( painter.selection.Intersects( line.TextStart(), line.TextEnd() ) )\r\n\t\tselection = line.MakeVisualSelection( painter.selection, m_layout );\r\n\r\n\tif ( &line == &m_lines.back() && painter.selection.Intersects( line.TextEnd(), m_length ) )\r\n\t\tselection.Add( line.Width(), line.Width() + painter.style.avgCharWidth );\r\n\r\n\tselection.Draw( painter, rect );\r\n\tselection.Swap( painter.prevSelection );\r\n}\r\n\r\nPOINT VisualBlock::PointFromChar( size_t pos, bool advancing, TextStyle& style ) const\r\n{\r\n\tPOINT result;\r\n\tbool trailingEdge = advancing;\r\n\r\n\tif ( pos == 0 )\r\n\t\ttrailingEdge = false;\r\n\telse if ( pos >= m_lines.back().TextEnd() )\r\n\t\ttrailingEdge = true;\r\n\r\n\tif ( trailingEdge )\r\n\t\t--pos;\r\n\r\n\tsize_t line = LineContaining( pos );\r\n\r\n \tif ( line < m_lines.size() )\r\n\t{\r\n\t\tresult.x = m_lines[line].CPtoX( pos, trailingEdge, m_layout );\r\n\t\tresult.y = line * style.lineHeight;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tresult.x = 0;\r\n\t\tresult.y = 0;\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nsize_t VisualBlock::CharFromPoint( POINT* point, TextStyle& style ) const\r\n{\r\n\tint line = point->y \/ style.lineHeight;\r\n\r\n\tif ( line < 0 || size_t( line ) >= m_lines.size() )\r\n\t\tline = m_lines.size() - 1;\r\n\r\n\tpoint->y = line * style.lineHeight;\r\n\treturn m_lines[line].XtoCP( &point->x, m_layout );\r\n}\r\n\r\nsize_t VisualBlock::LineStart( LONG y, TextStyle& style ) const\r\n{\r\n\tint line = y \/ style.lineHeight;\r\n\tAssert( line >= 0 && size_t( line ) < m_lines.size() );\r\n\treturn m_lines[line].TextStart();\r\n}\r\n\r\nsize_t VisualBlock::LineEnd( LONG y, TextStyle& style ) const\r\n{\r\n\tint line = y \/ style.lineHeight;\r\n\tAssert( line >= 0 && size_t( line ) < m_lines.size() );\r\n\treturn m_lines[line].TextEnd();\r\n}\r\n\r\nsize_t VisualBlock::LineCount() const\r\n{\r\n\treturn m_lines.size();\r\n}\r\n\r\nstruct CompareLines\r\n{\r\n\tbool operator()( const VisualLine& line, size_t pos ) const\r\n\t{\r\n\t\treturn line.TextEnd() <= pos;\r\n\t}\r\n\r\n\tbool operator()( size_t pos, const VisualLine& line ) const\r\n\t{\r\n\t\treturn pos < line.TextStart();\r\n\t}\r\n\r\n\tbool operator()( const VisualLine& a, const VisualLine& b ) const\r\n\t{\r\n\t\treturn a.TextStart() < b.TextStart();\r\n\t}\r\n};\r\n\r\nsize_t VisualBlock::LineContaining( size_t pos ) const\r\n{\r\n\treturn std::lower_bound( m_lines.begin(), m_lines.end(), pos, CompareLines() ) - m_lines.begin();\r\n}\r\n\r\nsize_t VisualBlock::Length() const\r\n{\r\n\treturn m_length;\r\n}\r\n\r\nLONG VisualBlock::Height( TextStyle& style ) const\r\n{\r\n\treturn m_lines.size() * style.lineHeight;\r\n}\r\n\r\nbool VisualBlock::EndsWithNewline() const\r\n{\r\n\treturn m_lines.back().TextEnd() < m_length;\r\n}\r\nOnly draw the newline selection if the block ends with a newline.\/\/ VisualBlock.cpp\r\n\r\n#include \"VisualBlock.h\"\r\n#include \"VisualPainter.h\"\r\n#include \"Assert.h\"\r\n#include \r\n\r\n#undef min\r\n#undef max\r\n\r\nVisualBlock::VisualBlock( size_t length )\r\n\t: m_length( length )\r\n{\r\n\tm_lines.push_back( VisualLine() );\r\n}\r\n\r\nVisualBlock::VisualBlock( size_t length, LayoutAllocator& allocator, ArrayOf items )\r\n\t: m_length( length )\r\n{\r\n\tm_layout.Copy( allocator, items );\r\n\r\n\tArrayOf lines = allocator.lines.Allocated();\r\n\tm_lines.reserve( lines.size() );\r\n\r\n\tTextRun* runs = m_layout.runs;\r\n\tsize_t lastEnd = 0;\r\n\tsize_t textStart = 0;\r\n\r\n\tfor ( size_t* it = lines.begin(); it != lines.end(); ++it )\r\n\t{\r\n\t\tTextRun* runStart = runs + lastEnd;\r\n\t\tTextRun* runEnd = runs + *it;\r\n\r\n\t\tm_lines.push_back( VisualLine( textStart, runStart, runEnd ) );\r\n\r\n\t\ttextStart = m_lines.back().TextEnd();\r\n\t\tlastEnd = *it;\r\n\t}\r\n}\r\n\r\nvoid VisualBlock::Draw( VisualPainter& painter, RECT rect ) const\r\n{\r\n\tsize_t i = rect.top \/ painter.style.lineHeight;\r\n\trect.top = i * painter.style.lineHeight;\r\n\r\n\tif ( 0 < i && i < m_lines.size() )\r\n\t\tpainter.prevSelection.Swap( m_lines[i-1].MakeVisualSelection( painter.selection, m_layout ) );\r\n\r\n\tfor ( ; i < m_lines.size() && !IsRectEmpty( &rect ); ++i )\r\n\t{\r\n\t\tDrawSelection( m_lines[i], painter, rect );\r\n\t\tm_lines[i].Draw( painter, rect, m_layout );\r\n\r\n\t\trect.top += painter.style.lineHeight;\r\n\t}\r\n}\r\n\r\nvoid VisualBlock::DrawSelection( const VisualLine& line, VisualPainter& painter, RECT rect ) const\r\n{\r\n\tVisualSelection selection;\r\n\r\n\tif ( painter.selection.Intersects( line.TextStart(), line.TextEnd() ) )\r\n\t\tselection = line.MakeVisualSelection( painter.selection, m_layout );\r\n\r\n\tif ( &line == &m_lines.back() && painter.selection.Intersects( line.TextEnd(), m_length ) && EndsWithNewline() )\r\n\t\tselection.Add( line.Width(), line.Width() + painter.style.avgCharWidth );\r\n\r\n\tselection.Draw( painter, rect );\r\n\tselection.Swap( painter.prevSelection );\r\n}\r\n\r\nPOINT VisualBlock::PointFromChar( size_t pos, bool advancing, TextStyle& style ) const\r\n{\r\n\tPOINT result;\r\n\tbool trailingEdge = advancing;\r\n\r\n\tif ( pos == 0 )\r\n\t\ttrailingEdge = false;\r\n\telse if ( pos >= m_lines.back().TextEnd() )\r\n\t\ttrailingEdge = true;\r\n\r\n\tif ( trailingEdge )\r\n\t\t--pos;\r\n\r\n\tsize_t line = LineContaining( pos );\r\n\r\n \tif ( line < m_lines.size() )\r\n\t{\r\n\t\tresult.x = m_lines[line].CPtoX( pos, trailingEdge, m_layout );\r\n\t\tresult.y = line * style.lineHeight;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tresult.x = 0;\r\n\t\tresult.y = 0;\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nsize_t VisualBlock::CharFromPoint( POINT* point, TextStyle& style ) const\r\n{\r\n\tint line = point->y \/ style.lineHeight;\r\n\r\n\tif ( line < 0 || size_t( line ) >= m_lines.size() )\r\n\t\tline = m_lines.size() - 1;\r\n\r\n\tpoint->y = line * style.lineHeight;\r\n\treturn m_lines[line].XtoCP( &point->x, m_layout );\r\n}\r\n\r\nsize_t VisualBlock::LineStart( LONG y, TextStyle& style ) const\r\n{\r\n\tint line = y \/ style.lineHeight;\r\n\tAssert( line >= 0 && size_t( line ) < m_lines.size() );\r\n\treturn m_lines[line].TextStart();\r\n}\r\n\r\nsize_t VisualBlock::LineEnd( LONG y, TextStyle& style ) const\r\n{\r\n\tint line = y \/ style.lineHeight;\r\n\tAssert( line >= 0 && size_t( line ) < m_lines.size() );\r\n\treturn m_lines[line].TextEnd();\r\n}\r\n\r\nsize_t VisualBlock::LineCount() const\r\n{\r\n\treturn m_lines.size();\r\n}\r\n\r\nstruct CompareLines\r\n{\r\n\tbool operator()( const VisualLine& line, size_t pos ) const\r\n\t{\r\n\t\treturn line.TextEnd() <= pos;\r\n\t}\r\n\r\n\tbool operator()( size_t pos, const VisualLine& line ) const\r\n\t{\r\n\t\treturn pos < line.TextStart();\r\n\t}\r\n\r\n\tbool operator()( const VisualLine& a, const VisualLine& b ) const\r\n\t{\r\n\t\treturn a.TextStart() < b.TextStart();\r\n\t}\r\n};\r\n\r\nsize_t VisualBlock::LineContaining( size_t pos ) const\r\n{\r\n\treturn std::lower_bound( m_lines.begin(), m_lines.end(), pos, CompareLines() ) - m_lines.begin();\r\n}\r\n\r\nsize_t VisualBlock::Length() const\r\n{\r\n\treturn m_length;\r\n}\r\n\r\nLONG VisualBlock::Height( TextStyle& style ) const\r\n{\r\n\treturn m_lines.size() * style.lineHeight;\r\n}\r\n\r\nbool VisualBlock::EndsWithNewline() const\r\n{\r\n\treturn m_lines.back().TextEnd() < m_length;\r\n}\r\n<|endoftext|>"} {"text":"#include \"Judge.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace WinnerPoker;\n\nstd::vector test(const std::vector &t)\n{\n std::stringstream ss;\n ss << \"{ \";\n for (auto &&item : t)\n {\n ss << item << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n std::cout << ss.str();\n\n std::vector vector;\n auto zip = Judge::getInstance().zip(t);\n for (auto &&x : zip)\n {\n for (int i = 1; i <= x.second; ++i)\n {\n vector.push_back((x.first << 8) | i);\n }\n }\n\n ss.str(\"\");\n ss << \"{ \";\n for (auto &&item : vector)\n {\n ss << item << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n \/\/ std::cout << ss.str();\n std::cout << std::endl;\n return vector;\n}\n\nint main()\n{\n \/\/ std::vector hands = { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7 };\n \/\/ std::vector hands = { 3, 3, 4, 6, 6, 7, 8, 10, 10, 11, 12, 13, 13, 14, 15 };\n \/\/ std::vector hands = { 3, 3, 4, 4, 5, 5, 7, 7 };\n \/\/ std::vector hands = { 3, 4, 5, 5, 5, 5, 7, 7, 8, 9, 10 };\n\n \/\/ std::vector hands = { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n \/\/ 8, 8, 9, 9, 10, 10, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15 };\n\n \/\/ std::vector tv = {3, 3, 3, 4, 4, 4, 4, 5, 5, 6};\n \/\/ std::vector tv = {3, 3, 3, 4, 4, 4};\n \/\/ Judge::getInstance().setCurrentHandsCategory(test(tv));\n\n std::vector hands;\n hands = { 3, 3, 3, 4, 5, 5, 5, 6, 6, 7 };\n hands = { 3, 3, 3, 4, 4, 5, 5, 7 };\n hands = { 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7 };\n hands = { 3, 3, 5, 6, 6, 7, 7, 8 };\n hands = { 3, 4, 4, 5, 5, 6, 6, 7 };\n hands = { 3, 4, 5, 5, 6, 6, 7 };\n hands = { 3, 4, 4, 5, 5, 5, 6, 6, 7 };\n hands = { 3, 4, 5, 5, 5, 6, 6 };\n hands = { 3, 3, 3, 4, 4, 5, 5, 5, 6, 6 };\n hands = { 3, 3, 4, 4, 5, 5, 5, 6 };\n hands = { 3, 3, 3, 5, 14, 14, 14 };\n hands = { 3, 3, 3, 14, 14, 14 };\n hands = { 3, 3, 4, 4, 4, 5, 5, 5, 5, 6 };\n hands = { 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 8 };\n hands = { 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 7 };\n hands = { 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 8 };\n hands = { 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 7 };\n hands = { 3, 4, 4, 5, 5, 5, 5, 6 };\n hands = { 3, 4, 4, 5, 5, 5, 5, 6, 6 };\n hands = { 4, 5, 6, 6, 7, 8, 8, 8, 9, 9, 9, 12, 12, 12, 12 };\n\n Judge::getInstance().setCurrentHandsCategory(std::vector{});\n\n auto ret = Judge::getInstance().cardIntentions(test(hands));\n std::stringstream ss;\n\n for (auto &&item : ret)\n {\n ss.str(\"\");\n\n ss << \"{ \";\n for (auto &&element : item)\n {\n ss << element << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n \/\/ std::cout << ss.str();\n }\n\n for (auto &&item : ret)\n {\n ss.str(\"\");\n\n ss << \"{ \";\n for (auto &&element : item)\n {\n ss << (element >> 8) << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n std::cout << ss.str();\n }\n\n \/*\n for (int i = 0; i < 1024; ++i)\n {\n const auto &ret = Judge::getInstance().intentions(test(hands));\n\n std::stringstream ss;\n\n ss.str(\"\");\n ss << \"{ \";\n for (auto &&item : ret)\n {\n ss << (item >> 8) << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n std::cout << ss.str();\n }\n *\/\n return 0;\n}\nmarks#include \"Judge.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace WinnerPoker;\n\nstd::vector test(const std::vector &t)\n{\n std::stringstream ss;\n ss << \"{ \";\n for (auto &&item : t)\n {\n ss << item << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n \/\/ std::cout << ss.str();\n\n std::vector vector;\n auto zip = Judge::getInstance().zip(t);\n for (auto &&x : zip)\n {\n for (int i = 1; i <= x.second; ++i)\n {\n vector.push_back((x.first << 8) | i);\n }\n }\n\n ss.str(\"\");\n ss << \"{ \";\n for (auto &&item : vector)\n {\n ss << item << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n \/\/ std::cout << ss.str();\n \/\/ std::cout << std::endl;\n return vector;\n}\n\nint main()\n{\n \/\/ std::vector hands = { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7 };\n \/\/ std::vector hands = { 3, 3, 4, 6, 6, 7, 8, 10, 10, 11, 12, 13, 13, 14, 15 };\n \/\/ std::vector hands = { 3, 3, 4, 4, 5, 5, 7, 7 };\n \/\/ std::vector hands = { 3, 4, 5, 5, 5, 5, 7, 7, 8, 9, 10 };\n\n std::vector hands = { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 9, 9, 10, 10, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15 };\n\n std::vector tv = {3, 3, 3, 4, 4, 4, 4, 5};\n \/\/ std::vector tv = { 3, 3, 3, 4, 4, 4 };\n Judge::getInstance().setCurrentHandsCategory(test(tv));\n\n \/\/ std::vector hands;\n \/\/ hands = { 3, 3, 3, 4, 5, 5, 5, 6, 6, 7 };\n \/\/ hands = { 3, 3, 3, 4, 4, 5, 5, 7 };\n \/\/ hands = { 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7 };\n \/\/ hands = { 3, 3, 5, 6, 6, 7, 7, 8 };\n \/\/ hands = { 3, 4, 4, 5, 5, 6, 6, 7 };\n \/\/ hands = { 3, 4, 5, 5, 6, 6, 7 };\n \/\/ hands = { 3, 4, 4, 5, 5, 5, 6, 6, 7 };\n \/\/ hands = { 3, 4, 5, 5, 5, 6, 6 };\n \/\/ hands = { 3, 3, 3, 4, 4, 5, 5, 5, 6, 6 };\n \/\/ hands = { 3, 3, 4, 4, 5, 5, 5, 6 };\n \/\/ hands = { 3, 3, 3, 5, 14, 14, 14 };\n \/\/ hands = { 3, 3, 3, 14, 14, 14 };\n \/\/ hands = { 3, 3, 4, 4, 4, 5, 5, 5, 5, 6 };\n \/\/ hands = { 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 8 };\n \/\/ hands = { 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 7 };\n \/\/ hands = { 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 8 };\n \/\/ hands = { 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 7 };\n \/\/ hands = { 3, 4, 4, 5, 5, 5, 5, 6 };\n \/\/ hands = { 3, 4, 4, 5, 5, 5, 5, 6, 6 };\n \/\/ hands = { 4, 5, 6, 6, 7, 8, 8, 8, 9, 9, 9, 12, 12, 12, 12 };\n\n \/*\n Judge::getInstance().setCurrentHandsCategory(std::vector{});\n\n auto ret = Judge::getInstance().cardIntentions(test(hands));\n std::stringstream ss;\n\n for (auto &&item : ret)\n {\n ss.str(\"\");\n\n ss << \"{ \";\n for (auto &&element : item)\n {\n ss << element << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n \/\/ std::cout << ss.str();\n }\n\n for (auto &&item : ret)\n {\n ss.str(\"\");\n\n ss << \"{ \";\n for (auto &&element : item)\n {\n ss << (element >> 8) << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n std::cout << ss.str();\n }\n*\/\n\n for (int i = 0; i < 1024; ++i)\n {\n const auto &ret = Judge::getInstance().intentions(test(hands));\n\n std::stringstream ss;\n\n ss.str(\"\");\n ss << \"{ \";\n for (auto &&item : ret)\n {\n ss << (item >> 8) << \", \";\n }\n ss.seekp(-2, ss.end);\n ss << \" }\" << std::endl;\n\n std::cout << ss.str();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/courseID:CIS165-001\n\/\/name: David Ribeiro\n\/\/Prof. Wang\n\/\/Assignment#2\n\/\/Due by 9\/22\/2015\n\n\/*\n steps\n 1.Input:\n a. sales numbers for each of the divisions\n \n \n 2.Processing:\n a. Rewrites the sales figures for each division to the input number.\n \n \n 3.Output:\n a. Computes the highest number and the corresponding Sales division name \n *\/\n \n#include \n#include \nusing namespace std;\n\n\ndouble getSales(string, double);\nvoid findHighest();\n\n \/*Global Variables*\/\n\n\n \/\/ Establishing Integer values for Sales figures in Each Sales Division as a Global Variable\ndouble salesNe,\nsalesNw,\nsalesSe,\nsalesSw;\n\n\n \/*Main*\/\n\nint main()\n{\n \n \/\/ Establish the String Values for Each Sales Division\n string northE = \" NorthEast sales division\",\n northW = \" NorthWest sales division\",\n southE = \" SouthEast sales division\",\n southW = \" SouthWest sales division\";\n \n \n \/\/ Input the Sales for each division\n \/\/ Call getSale function for each Division and pass name of Division\n salesNe = getSales(northE, salesNe);\n salesNw = getSales(northW, salesNw);\n salesSe = getSales(southE, salesSe);\n salesSw = getSales(southW, salesSw);\n \/\/ Call the findHighest function\n findHighest();\n \n \n return 0;\n \n}\n\n \/\/ Proccessing\n \/*getSales*\/\n\ndouble getSales(string name, double sales){\n\n \n cout << \"What are the quarterly earnings for the \" << name << \"?\" << endl;\n \n cin >> sales;\n \n while (sales < 0)\n {\n cout << \"That was an invalid sales number, please enter a number over 0.\" << endl;\n \n cin >> sales;\n }\n\n return sales;\n}\n\n\n\n\n \/*findHighest*\/\nvoid findHighest(){\n \n double array[5] = {salesNe, salesNw, salesSe, salesSw};\n int temp = 0;\n \n for(int i=0;i<4;i++)\n {\n if(array[i]>temp)\n temp=array[i];\n }\n \n \/\/ Output\n if (temp == salesNe)\n {\n cout << \"The highest grossing division is the Northeast sales division and it's sales figure was $\"\n << salesNe << \".\" << endl;\n }\n else if (temp == salesNw)\n {\n cout << \"The highest grossing division is the NorthWest sales division and it's sales figure was $\"\n << salesNw << \".\" << endl;\n \n }\n else if (temp == salesSe)\n {\n cout << \"The highest grossing division is the Southeast sales division and it's sales figure was $\"\n << salesSe << \".\" << endl;\n\n }\n else if (temp == salesSw)\n {\n cout << \"The highest grossing division is the Southwest sales division and it's sales figure was $\"\n << salesSw << \".\" << endl;\n\n }\n \n \n }\n\n\n\n\n\n\n\n\n\n\n\n\n\nFixing detached Head<|endoftext|>"} {"text":"\/\/ Module: Log4CPLUS\n\/\/ File: loglevel.cxx\n\/\/ Created: 6\/2001\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2009 Tad E. Smith\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 \n#include \n#include \n#include \n#include \n\n\nnamespace log4cplus\n{\n\n\nnamespace\n{\n\nstatic tstring const ALL_STRING (LOG4CPLUS_TEXT(\"ALL\"));\nstatic tstring const TRACE_STRING (LOG4CPLUS_TEXT(\"TRACE\"));\nstatic tstring const DEBUG_STRING (LOG4CPLUS_TEXT(\"DEBUG\"));\nstatic tstring const INFO_STRING (LOG4CPLUS_TEXT(\"INFO\"));\nstatic tstring const WARN_STRING (LOG4CPLUS_TEXT(\"WARN\"));\nstatic tstring const ERROR_STRING (LOG4CPLUS_TEXT(\"ERROR\"));\nstatic tstring const FATAL_STRING (LOG4CPLUS_TEXT(\"FATAL\"));\nstatic tstring const OFF_STRING (LOG4CPLUS_TEXT(\"OFF\"));\nstatic tstring const NOTSET_STRING (LOG4CPLUS_TEXT(\"NOTSET\"));\nstatic tstring const UNKNOWN_STRING (LOG4CPLUS_TEXT(\"UNKNOWN\"));\n\n\nstruct log_levels_table_rec\n{\n LogLevel const ll;\n tstring const * const str;\n};\n\n\n#define DEF_LLTAB_REC(x) { x ## _LOG_LEVEL, &(x ## _STRING) }\n\nstatic log_levels_table_rec const log_levels_table[8] = {\n DEF_LLTAB_REC (OFF),\n DEF_LLTAB_REC (FATAL),\n DEF_LLTAB_REC (ERROR),\n DEF_LLTAB_REC (WARN),\n DEF_LLTAB_REC (INFO),\n DEF_LLTAB_REC (DEBUG),\n DEF_LLTAB_REC (TRACE),\n DEF_LLTAB_REC (ALL),\n};\n\n#undef DEF_LLTAB_REC\n\n\nstatic\ntstring const &\ndefaultLogLevelToStringMethod(LogLevel ll)\n{\n switch(ll) {\n case OFF_LOG_LEVEL: return OFF_STRING;\n case FATAL_LOG_LEVEL: return FATAL_STRING;\n case ERROR_LOG_LEVEL: return ERROR_STRING;\n case WARN_LOG_LEVEL: return WARN_STRING;\n case INFO_LOG_LEVEL: return INFO_STRING;\n case DEBUG_LOG_LEVEL: return DEBUG_STRING;\n case TRACE_LOG_LEVEL: return TRACE_STRING;\n \/\/case ALL_LOG_LEVEL: return ALL_STRING;\n case NOT_SET_LOG_LEVEL: return NOTSET_STRING;\n };\n \n return internal::empty_str;\n}\n\n\nstatic\nLogLevel\ndefaultStringToLogLevelMethod(const tstring& arg)\n{\n tstring s = helpers::toUpper(arg);\n\n size_t const tbl_size\n = sizeof (log_levels_table) \/ sizeof (log_levels_table[0]);\n\n for (log_levels_table_rec const * it = log_levels_table;\n it != log_levels_table + tbl_size; ++it)\n {\n if (*it->str == arg)\n return it->ll;\n }\n \n return NOT_SET_LOG_LEVEL;\n}\n\n} \/\/ namespace\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public static methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelManager&\ngetLogLevelManager() \n{\n static LogLevelManager singleton;\n return singleton;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelManager ctors and dtor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelManager::LogLevelManager() \n{\n toStringMethods.push_back (defaultLogLevelToStringMethod);\n fromStringMethods.push_back (defaultStringToLogLevelMethod);\n}\n\n\nLogLevelManager::~LogLevelManager() \n{ }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelManager public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntstring const &\nLogLevelManager::toString(LogLevel ll) const\n{\n for (LogLevelToStringMethodList::const_iterator it\n = toStringMethods.begin (); it != toStringMethods.end (); ++it)\n {\n tstring const & ret = (*it) (ll);\n if (! ret.empty ())\n return ret;\n }\n\n return UNKNOWN_STRING;\n}\n\n\nLogLevel \nLogLevelManager::fromString(const tstring& s) const\n{\n for (StringToLogLevelMethodList::const_iterator it\n = fromStringMethods.begin (); it != fromStringMethods.end (); ++it)\n {\n LogLevel ret = (*it) (s);\n if (ret != NOT_SET_LOG_LEVEL)\n return ret;\n }\n \n return NOT_SET_LOG_LEVEL;\n}\n\n\nvoid \nLogLevelManager::pushToStringMethod(LogLevelToStringMethod newToString)\n{\n toStringMethods.push_back (newToString);\n}\n\n\nvoid \nLogLevelManager::pushFromStringMethod(StringToLogLevelMethod newFromString)\n{\n fromStringMethods.push_back (newFromString);\n}\n\n \n} \/\/ namespace log4cplus\nloglevel.cxx: Move toUpper() call from defaultStringToLogLevelMethod() to fromString().\/\/ Module: Log4CPLUS\n\/\/ File: loglevel.cxx\n\/\/ Created: 6\/2001\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2009 Tad E. Smith\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 \n#include \n#include \n#include \n#include \n\n\nnamespace log4cplus\n{\n\n\nnamespace\n{\n\nstatic tstring const ALL_STRING (LOG4CPLUS_TEXT(\"ALL\"));\nstatic tstring const TRACE_STRING (LOG4CPLUS_TEXT(\"TRACE\"));\nstatic tstring const DEBUG_STRING (LOG4CPLUS_TEXT(\"DEBUG\"));\nstatic tstring const INFO_STRING (LOG4CPLUS_TEXT(\"INFO\"));\nstatic tstring const WARN_STRING (LOG4CPLUS_TEXT(\"WARN\"));\nstatic tstring const ERROR_STRING (LOG4CPLUS_TEXT(\"ERROR\"));\nstatic tstring const FATAL_STRING (LOG4CPLUS_TEXT(\"FATAL\"));\nstatic tstring const OFF_STRING (LOG4CPLUS_TEXT(\"OFF\"));\nstatic tstring const NOTSET_STRING (LOG4CPLUS_TEXT(\"NOTSET\"));\nstatic tstring const UNKNOWN_STRING (LOG4CPLUS_TEXT(\"UNKNOWN\"));\n\n\nstruct log_levels_table_rec\n{\n LogLevel const ll;\n tstring const * const str;\n};\n\n\n#define DEF_LLTAB_REC(x) { x ## _LOG_LEVEL, &(x ## _STRING) }\n\nstatic log_levels_table_rec const log_levels_table[8] = {\n DEF_LLTAB_REC (OFF),\n DEF_LLTAB_REC (FATAL),\n DEF_LLTAB_REC (ERROR),\n DEF_LLTAB_REC (WARN),\n DEF_LLTAB_REC (INFO),\n DEF_LLTAB_REC (DEBUG),\n DEF_LLTAB_REC (TRACE),\n DEF_LLTAB_REC (ALL),\n};\n\n#undef DEF_LLTAB_REC\n\n\nstatic\ntstring const &\ndefaultLogLevelToStringMethod(LogLevel ll)\n{\n switch(ll) {\n case OFF_LOG_LEVEL: return OFF_STRING;\n case FATAL_LOG_LEVEL: return FATAL_STRING;\n case ERROR_LOG_LEVEL: return ERROR_STRING;\n case WARN_LOG_LEVEL: return WARN_STRING;\n case INFO_LOG_LEVEL: return INFO_STRING;\n case DEBUG_LOG_LEVEL: return DEBUG_STRING;\n case TRACE_LOG_LEVEL: return TRACE_STRING;\n \/\/case ALL_LOG_LEVEL: return ALL_STRING;\n case NOT_SET_LOG_LEVEL: return NOTSET_STRING;\n };\n \n return internal::empty_str;\n}\n\n\nstatic\nLogLevel\ndefaultStringToLogLevelMethod(const tstring& s)\n{\n size_t const tbl_size\n = sizeof (log_levels_table) \/ sizeof (log_levels_table[0]);\n\n for (log_levels_table_rec const * it = log_levels_table;\n it != log_levels_table + tbl_size; ++it)\n {\n if (*it->str == s)\n return it->ll;\n }\n \n return NOT_SET_LOG_LEVEL;\n}\n\n} \/\/ namespace\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public static methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelManager&\ngetLogLevelManager() \n{\n static LogLevelManager singleton;\n return singleton;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelManager ctors and dtor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelManager::LogLevelManager() \n{\n toStringMethods.push_back (defaultLogLevelToStringMethod);\n fromStringMethods.push_back (defaultStringToLogLevelMethod);\n}\n\n\nLogLevelManager::~LogLevelManager() \n{ }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelManager public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntstring const &\nLogLevelManager::toString(LogLevel ll) const\n{\n for (LogLevelToStringMethodList::const_iterator it\n = toStringMethods.begin (); it != toStringMethods.end (); ++it)\n {\n tstring const & ret = (*it) (ll);\n if (! ret.empty ())\n return ret;\n }\n\n return UNKNOWN_STRING;\n}\n\n\nLogLevel \nLogLevelManager::fromString(const tstring& arg) const\n{\n tstring s = helpers::toUpper(arg);\n\n for (StringToLogLevelMethodList::const_iterator it\n = fromStringMethods.begin (); it != fromStringMethods.end (); ++it)\n {\n LogLevel ret = (*it) (s);\n if (ret != NOT_SET_LOG_LEVEL)\n return ret;\n }\n \n return NOT_SET_LOG_LEVEL;\n}\n\n\nvoid \nLogLevelManager::pushToStringMethod(LogLevelToStringMethod newToString)\n{\n toStringMethods.push_back (newToString);\n}\n\n\nvoid \nLogLevelManager::pushFromStringMethod(StringToLogLevelMethod newFromString)\n{\n fromStringMethods.push_back (newFromString);\n}\n\n \n} \/\/ namespace log4cplus\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n#include \n\n#include \"mangling.hpp\"\n#include \"assert.hpp\"\n#include \"Utils.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"Type.hpp\"\n\n#include \"ast\/GetTypeVisitor.hpp\"\n\nusing namespace eddic;\n\nstd::string eddic::mangle(std::shared_ptr type){\n if(type->is_array()){\n return \"A\" + mangle(type->data_type());\n }\n\n if(type->is_pointer()){\n return \"P\" + mangle(type->data_type());\n }\n\n if(type->is_standard_type()){\n if(type == INT){\n return \"I\";\n } else if(type == CHAR){\n return \"C\";\n } else if(type == STRING){\n return \"S\";\n } else if(type == BOOL){\n return \"B\";\n } else if(type == FLOAT){\n return \"F\";\n } else if(type == VOID){\n return \"V\";\n }\n\n ASSERT_PATH_NOT_TAKEN(\"Not a standard type\");\n } else {\n std::ostringstream ss;\n\n ss << \"C\";\n ss << type->type().length();\n ss << type->type();\n \n return ss.str();\n }\n}\n\nstd::string eddic::mangle(std::shared_ptr function){\n std::ostringstream ss;\n\n ss << \"_F\";\n\n if(!function->struct_.empty()){\n ss << function->struct_.length();\n ss << function->struct_;\n }\n\n ss << function->name.length();\n ss << function->name;\n\n for(auto type : function->parameters){\n if(type.name != \"this\"){\n ss << mangle(type.paramType);\n }\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_ctor(const std::shared_ptr function){\n std::ostringstream ss;\n\n ss << \"_C\";\n\n ss << function->struct_.length();\n ss << function->struct_;\n\n for(auto type : function->parameters){\n if(type.name != \"this\"){\n ss << mangle(type.paramType);\n }\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_dtor(const std::shared_ptr function){\n std::ostringstream ss;\n\n ss << \"_D\";\n\n ss << function->struct_.length();\n ss << function->struct_;\n\n return ss.str();\n}\n\nstd::string eddic::mangle(const std::string& functionName, const std::vector& values, const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_F\";\n\n if(!struct_.empty()){\n ss << struct_.length();\n ss << struct_;\n }\n\n ss << functionName.length();\n ss << functionName;\n\n ast::GetTypeVisitor visitor;\n for(auto& value : values){\n auto type = visit(visitor, value);\n ss << mangle(type);\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_ctor(const std::vector& values, const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_C\";\n\n ss << struct_.length();\n ss << struct_;\n\n ast::GetTypeVisitor visitor;\n for(auto& value : values){\n auto type = visit(visitor, value);\n ss << mangle(type);\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_dtor(const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_D\";\n\n ss << struct_.length();\n ss << struct_;\n\n return ss.str();\n}\n\nstd::string eddic::mangle(const std::string& functionName, const std::vector>& types, const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_F\";\n\n if(!struct_.empty()){\n ss << struct_.length();\n ss << struct_;\n }\n\n ss << functionName.length();\n ss << functionName;\n\n for(auto type : types){\n ss << mangle(type);\n }\n\n return ss.str();\n}\n\nstd::string get_name_from_length(const std::string& mangled, unsigned int& i){\n std::ostringstream length;\n int digits = 0;\n\n for(; i < mangled.length(); ++i){\n if(isdigit(mangled[i])){\n length << mangled[i];\n ++digits;\n } else {\n break;\n }\n }\n\n int l = toNumber(length.str());\n\n std::ostringstream name;\n \n auto start = i;\n for(; i < start + l; ++i){\n name << mangled[i];\n }\n\n return name.str();\n}\n\nstd::string eddic::unmangle(std::string mangled){\n unsigned int o = 2;\n\n std::ostringstream function;\n\n function << get_name_from_length(mangled, o);\n\n \/\/Test if inside a struct\n if(isdigit(mangled[o])){\n function << \"::\";\n \n function << get_name_from_length(mangled, o);\n }\n\n function << '(';\n\n for(; o < mangled.length(); ++o){\n char current = mangled[o];\n\n bool array = false;\n if(current == 'A'){\n array = true;\n current = mangled[++o];\n }\n \n bool pointer = false;\n if(current == 'P'){\n pointer = true;\n current = mangled[++o];\n } \n\n if(current == 'I'){\n function << \"int\";\n } else if(current == 'C'){\n function << \"char\";\n } else if(current == 'S'){\n function << \"string\";\n } else if(current == 'B'){\n function << \"bool\";\n } else if(current == 'F'){\n function << \"float\";\n } \n\n if(array){\n function << \"[]\";\n }\n\n if(pointer){\n function << \"&\";\n }\n\n if(o < mangled.length() - 1){\n function << \", \";\n }\n }\n\n function << ')';\n\n return function.str();\n}\nHandle template types in mangling\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n#include \n\n#include \"mangling.hpp\"\n#include \"assert.hpp\"\n#include \"Utils.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"Type.hpp\"\n\n#include \"ast\/GetTypeVisitor.hpp\"\n\nusing namespace eddic;\n\nstd::string eddic::mangle(std::shared_ptr type){\n if(type->is_array()){\n return \"A\" + mangle(type->data_type());\n }\n\n if(type->is_pointer()){\n return \"P\" + mangle(type->data_type());\n }\n\n if(type->is_standard_type()){\n if(type == INT){\n return \"I\";\n } else if(type == CHAR){\n return \"C\";\n } else if(type == STRING){\n return \"S\";\n } else if(type == BOOL){\n return \"B\";\n } else if(type == FLOAT){\n return \"F\";\n } else if(type == VOID){\n return \"V\";\n }\n } \n \n if(type->is_custom_type()){\n std::ostringstream ss;\n\n ss << \"C\";\n ss << type->type().length();\n ss << type->type();\n \n return ss.str();\n }\n \n if(type->is_template()){\n std::ostringstream ss;\n\n ss << \"CT\";\n ss << type->type().length();\n ss << type->type();\n\n auto types = type->template_types();\n\n ss << types.size();\n\n for(auto& sub_type : types){\n ss << mangle(sub_type);\n }\n \n return ss.str();\n }\n\n ASSERT_PATH_NOT_TAKEN(\"Invalid type\");\n}\n\nstd::string eddic::mangle(std::shared_ptr function){\n std::ostringstream ss;\n\n ss << \"_F\";\n\n if(!function->struct_.empty()){\n ss << function->struct_.length();\n ss << function->struct_;\n }\n\n ss << function->name.length();\n ss << function->name;\n\n for(auto type : function->parameters){\n if(type.name != \"this\"){\n ss << mangle(type.paramType);\n }\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_ctor(const std::shared_ptr function){\n std::ostringstream ss;\n\n ss << \"_C\";\n\n ss << function->struct_.length();\n ss << function->struct_;\n\n for(auto type : function->parameters){\n if(type.name != \"this\"){\n ss << mangle(type.paramType);\n }\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_dtor(const std::shared_ptr function){\n std::ostringstream ss;\n\n ss << \"_D\";\n\n ss << function->struct_.length();\n ss << function->struct_;\n\n return ss.str();\n}\n\nstd::string eddic::mangle(const std::string& functionName, const std::vector& values, const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_F\";\n\n if(!struct_.empty()){\n ss << struct_.length();\n ss << struct_;\n }\n\n ss << functionName.length();\n ss << functionName;\n\n ast::GetTypeVisitor visitor;\n for(auto& value : values){\n auto type = visit(visitor, value);\n ss << mangle(type);\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_ctor(const std::vector& values, const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_C\";\n\n ss << struct_.length();\n ss << struct_;\n\n ast::GetTypeVisitor visitor;\n for(auto& value : values){\n auto type = visit(visitor, value);\n ss << mangle(type);\n }\n\n return ss.str();\n}\n\nstd::string eddic::mangle_dtor(const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_D\";\n\n ss << struct_.length();\n ss << struct_;\n\n return ss.str();\n}\n\nstd::string eddic::mangle(const std::string& functionName, const std::vector>& types, const std::string& struct_){\n std::ostringstream ss;\n\n ss << \"_F\";\n\n if(!struct_.empty()){\n ss << struct_.length();\n ss << struct_;\n }\n\n ss << functionName.length();\n ss << functionName;\n\n for(auto type : types){\n ss << mangle(type);\n }\n\n return ss.str();\n}\n\nstd::string get_name_from_length(const std::string& mangled, unsigned int& i){\n std::ostringstream length;\n int digits = 0;\n\n for(; i < mangled.length(); ++i){\n if(isdigit(mangled[i])){\n length << mangled[i];\n ++digits;\n } else {\n break;\n }\n }\n\n int l = toNumber(length.str());\n\n std::ostringstream name;\n \n auto start = i;\n for(; i < start + l; ++i){\n name << mangled[i];\n }\n\n return name.str();\n}\n\nstd::string eddic::unmangle(std::string mangled){\n unsigned int o = 2;\n\n std::ostringstream function;\n\n function << get_name_from_length(mangled, o);\n\n \/\/Test if inside a struct\n if(isdigit(mangled[o])){\n function << \"::\";\n \n function << get_name_from_length(mangled, o);\n }\n\n function << '(';\n\n for(; o < mangled.length(); ++o){\n char current = mangled[o];\n\n bool array = false;\n if(current == 'A'){\n array = true;\n current = mangled[++o];\n }\n \n bool pointer = false;\n if(current == 'P'){\n pointer = true;\n current = mangled[++o];\n } \n\n if(current == 'I'){\n function << \"int\";\n } else if(current == 'C'){\n function << \"char\";\n } else if(current == 'S'){\n function << \"string\";\n } else if(current == 'B'){\n function << \"bool\";\n } else if(current == 'F'){\n function << \"float\";\n } \n\n if(array){\n function << \"[]\";\n }\n\n if(pointer){\n function << \"&\";\n }\n\n if(o < mangled.length() - 1){\n function << \", \";\n }\n }\n\n function << ')';\n\n return function.str();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014-2017 Open Source Robotics Foundation, 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 \n#include \n#include \n\n#include \"rcutils\/allocator.h\"\n#include \"rcutils\/logging_macros.h\"\n#include \"rcutils\/strdup.h\"\n#include \"rmw\/error_handling.h\"\n#include \"rmw\/names_and_types.h\"\n#include \"rmw\/get_service_names_and_types.h\"\n#include \"rmw\/types.h\"\n#include \"rmw\/convert_rcutils_ret_to_rmw_ret.h\"\n#include \"rmw\/impl\/cpp\/macros.hpp\"\n\n#include \"identifier.hpp\"\n#include \"types.hpp\"\n#include \"demangle.hpp\"\n\n\/\/ The extern \"C\" here enforces that overloading is not used.\nextern \"C\"\n{\nrmw_ret_t\nrmw_get_service_names_and_types(\n const rmw_node_t * node,\n rcutils_allocator_t * allocator,\n rmw_names_and_types_t * service_names_and_types)\n{\n if (!allocator) {\n RMW_SET_ERROR_MSG(\"allocator is null\")\n return RMW_RET_INVALID_ARGUMENT;\n }\n if (!node) {\n RMW_SET_ERROR_MSG_ALLOC(\"null node handle\", *allocator)\n return RMW_RET_INVALID_ARGUMENT;\n }\n RMW_CHECK_TYPE_IDENTIFIERS_MATCH(\n node handle,\n node->implementation_identifier, opensplice_cpp_identifier,\n return RMW_RET_ERROR)\n\n rmw_ret_t ret = rmw_names_and_types_check_zero(service_names_and_types);\n if (ret != RMW_RET_OK) {\n return ret;\n }\n auto node_info = static_cast(node->data);\n if (!node_info) {\n RMW_SET_ERROR_MSG(\"node info handle is null\");\n }\n if (!node_info->publisher_listener) {\n RMW_SET_ERROR_MSG(\"publisher listener handle is null\");\n return RMW_RET_ERROR;\n }\n if (!node_info->publisher_listener) {\n RMW_SET_ERROR_MSG(\"publisher listener handle is null\");\n return RMW_RET_ERROR;\n }\n if (!node_info->subscriber_listener) {\n RMW_SET_ERROR_MSG(\"subscriber listener handle is null\");\n return RMW_RET_ERROR;\n }\n\n \/\/ combine publisher and subscriber information\n std::map> services;\n node_info->publisher_listener->fill_service_names_and_types(services);\n node_info->subscriber_listener->fill_service_names_and_types(services);\n\n \/\/ Fill out service_names_and_types\n if (services.size()) {\n \/\/ Setup string array to store names\n rmw_ret_t rmw_ret =\n rmw_names_and_types_init(service_names_and_types, services.size(), allocator);\n if (rmw_ret != RMW_RET_OK) {\n return rmw_ret;\n }\n \/\/ Setup cleanup function, in case of failure below\n auto fail_cleanup = [&service_names_and_types]() {\n rmw_ret_t rmw_ret = rmw_names_and_types_fini(service_names_and_types);\n if (rmw_ret != RMW_RET_OK) {\n RCUTILS_LOG_ERROR(\"error during report of error: %s\", rmw_get_error_string_safe())\n }\n };\n \/\/ For each service, store the name, initialize the string array for types, and store all types\n size_t index = 0;\n for (const auto & service_n_types : services) {\n \/\/ Duplicate and store the service_name\n char * service_name = rcutils_strdup(service_n_types.first.c_str(), *allocator);\n if (!service_name) {\n RMW_SET_ERROR_MSG_ALLOC(\"failed to allocate memory for service name\", *allocator);\n fail_cleanup();\n return RMW_RET_BAD_ALLOC;\n }\n service_names_and_types->names.data[index] = service_name;\n \/\/ Setup storage for types\n {\n rcutils_ret_t rcutils_ret = rcutils_string_array_init(\n &service_names_and_types->types[index],\n service_n_types.second.size(),\n allocator);\n if (rcutils_ret != RCUTILS_RET_OK) {\n RMW_SET_ERROR_MSG(rcutils_get_error_string_safe())\n fail_cleanup();\n return rmw_convert_rcutils_ret_to_rmw_ret(rcutils_ret);\n }\n }\n \/\/ Duplicate and store each type for the service\n size_t type_index = 0;\n for (const auto & type : service_n_types.second) {\n char * type_name = rcutils_strdup(type.c_str(), *allocator);\n if (!type_name) {\n RMW_SET_ERROR_MSG_ALLOC(\"failed to allocate memory for type name\", *allocator)\n fail_cleanup();\n return RMW_RET_BAD_ALLOC;\n }\n service_names_and_types->types[index].data[type_index] = type_name;\n ++type_index;\n } \/\/ for each type\n ++index;\n } \/\/ for each service\n }\n return RMW_RET_OK;\n}\n} \/\/ extern \"C\"\nstrip 'Sample_' from reported types (#234)\/\/ Copyright 2014-2017 Open Source Robotics Foundation, 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 \n#include \n#include \n\n#include \"rcutils\/allocator.h\"\n#include \"rcutils\/logging_macros.h\"\n#include \"rcutils\/strdup.h\"\n#include \"rmw\/error_handling.h\"\n#include \"rmw\/names_and_types.h\"\n#include \"rmw\/get_service_names_and_types.h\"\n#include \"rmw\/types.h\"\n#include \"rmw\/convert_rcutils_ret_to_rmw_ret.h\"\n#include \"rmw\/impl\/cpp\/macros.hpp\"\n\n#include \"identifier.hpp\"\n#include \"types.hpp\"\n#include \"demangle.hpp\"\n\n#define SAMPLE_PREFIX \"\/Sample_\"\n\/\/ The extern \"C\" here enforces that overloading is not used.\nextern \"C\"\n{\nrmw_ret_t\nrmw_get_service_names_and_types(\n const rmw_node_t * node,\n rcutils_allocator_t * allocator,\n rmw_names_and_types_t * service_names_and_types)\n{\n if (!allocator) {\n RMW_SET_ERROR_MSG(\"allocator is null\")\n return RMW_RET_INVALID_ARGUMENT;\n }\n if (!node) {\n RMW_SET_ERROR_MSG_ALLOC(\"null node handle\", *allocator)\n return RMW_RET_INVALID_ARGUMENT;\n }\n RMW_CHECK_TYPE_IDENTIFIERS_MATCH(\n node handle,\n node->implementation_identifier, opensplice_cpp_identifier,\n return RMW_RET_ERROR)\n\n rmw_ret_t ret = rmw_names_and_types_check_zero(service_names_and_types);\n if (ret != RMW_RET_OK) {\n return ret;\n }\n auto node_info = static_cast(node->data);\n if (!node_info) {\n RMW_SET_ERROR_MSG(\"node info handle is null\");\n }\n if (!node_info->publisher_listener) {\n RMW_SET_ERROR_MSG(\"publisher listener handle is null\");\n return RMW_RET_ERROR;\n }\n if (!node_info->publisher_listener) {\n RMW_SET_ERROR_MSG(\"publisher listener handle is null\");\n return RMW_RET_ERROR;\n }\n if (!node_info->subscriber_listener) {\n RMW_SET_ERROR_MSG(\"subscriber listener handle is null\");\n return RMW_RET_ERROR;\n }\n\n \/\/ combine publisher and subscriber information\n std::map> services;\n node_info->publisher_listener->fill_service_names_and_types(services);\n node_info->subscriber_listener->fill_service_names_and_types(services);\n\n \/\/ Fill out service_names_and_types\n if (services.size()) {\n \/\/ Setup string array to store names\n rmw_ret_t rmw_ret =\n rmw_names_and_types_init(service_names_and_types, services.size(), allocator);\n if (rmw_ret != RMW_RET_OK) {\n return rmw_ret;\n }\n \/\/ Setup cleanup function, in case of failure below\n auto fail_cleanup = [&service_names_and_types]() {\n rmw_ret_t rmw_ret = rmw_names_and_types_fini(service_names_and_types);\n if (rmw_ret != RMW_RET_OK) {\n RCUTILS_LOG_ERROR(\"error during report of error: %s\", rmw_get_error_string_safe())\n }\n };\n \/\/ For each service, store the name, initialize the string array for types, and store all types\n size_t index = 0;\n for (const auto & service_n_types : services) {\n \/\/ Duplicate and store the service_name\n char * service_name = rcutils_strdup(service_n_types.first.c_str(), *allocator);\n if (!service_name) {\n RMW_SET_ERROR_MSG_ALLOC(\"failed to allocate memory for service name\", *allocator);\n fail_cleanup();\n return RMW_RET_BAD_ALLOC;\n }\n service_names_and_types->names.data[index] = service_name;\n \/\/ Setup storage for types\n {\n rcutils_ret_t rcutils_ret = rcutils_string_array_init(\n &service_names_and_types->types[index],\n service_n_types.second.size(),\n allocator);\n if (rcutils_ret != RCUTILS_RET_OK) {\n RMW_SET_ERROR_MSG(rcutils_get_error_string_safe())\n fail_cleanup();\n return rmw_convert_rcutils_ret_to_rmw_ret(rcutils_ret);\n }\n }\n \/\/ Duplicate and store each type for the service\n size_t type_index = 0;\n for (const auto & type : service_n_types.second) {\n size_t n = type.find(SAMPLE_PREFIX);\n if (std::string::npos == n) {\n char * error_msg = rcutils_format_string(\n *allocator,\n \"failed to convert DDS type name to ROS service type name: '\" SAMPLE_PREFIX\n \"' not found in type: '%s'\", type.c_str());\n RMW_SET_ERROR_MSG(error_msg)\n allocator->deallocate(error_msg, allocator->state);\n fail_cleanup();\n return RMW_RET_ERROR;\n }\n std::string stripped_type = type.substr(0, n + 1) + type.substr(n + strlen(SAMPLE_PREFIX));\n char * type_name = rcutils_strdup(stripped_type.c_str(), *allocator);\n if (!type_name) {\n RMW_SET_ERROR_MSG_ALLOC(\"failed to allocate memory for type name\", *allocator)\n fail_cleanup();\n return RMW_RET_BAD_ALLOC;\n }\n service_names_and_types->types[index].data[type_index] = type_name;\n ++type_index;\n } \/\/ for each type\n ++index;\n } \/\/ for each service\n }\n return RMW_RET_OK;\n}\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"#include \"testing\/testing.hpp\"\n\n#include \"platform\/local_country_file.hpp\"\n\n#include \"geometry\/mercator.hpp\"\n#include \"geometry\/point2d.hpp\"\n\n#include \"indexer\/classificator_loader.hpp\"\n#include \"indexer\/data_source.hpp\"\n#include \"indexer\/feature_altitude.hpp\"\n#include \"indexer\/mwm_set.hpp\"\n\n#include \"routing_common\/car_model.hpp\"\n#include \"routing\/features_road_graph.hpp\"\n#include \"routing\/road_graph.hpp\"\n\n#include \"routing\/routing_integration_tests\/routing_test_tools.hpp\"\n\n#include \n\nusing namespace routing;\nusing namespace integration;\n\n\/\/ The test on combinatorial explosion of number of fake edges at FeaturesRoadGraph.\n\/\/ It might happen when a lot of roads intersect at one point. For example,\n\/\/ https:\/\/www.openstreetmap.org\/#map=19\/50.73197\/-1.21295\nUNIT_TEST(FakeEdgesCombinatorialExplosion)\n{\n classificator::Load();\n\n std::vector localFiles;\n GetAllLocalFiles(localFiles);\n TEST(!localFiles.empty(), ());\n\n FrozenDataSource dataSource;\n for (auto const & file : localFiles)\n {\n auto const result = dataSource.Register(file);\n TEST_EQUAL(result.second, MwmSet::RegResult::Success, ());\n }\n\n FeaturesRoadGraph graph(dataSource, IRoadGraph::Mode::ObeyOnewayTag,\n make_shared(CountryParentNameGetterFn()));\n Junction const j(m2::PointD(MercatorBounds::FromLatLon(50.73208, -1.21279)), feature::kDefaultAltitudeMeters);\n std::vector> sourceVicinity;\n graph.FindClosestEdges(MercatorBounds::RectByCenterXYAndSizeInMeters(\n j.GetPoint(), FeaturesRoadGraph::kClosestEdgesRadiusM),\n 20 \/* count *\/, sourceVicinity);\n \/\/ In case of the combinatorial explosion mentioned above all the memory was consumed for\n \/\/ FeaturesRoadGraph::m_fakeIngoingEdges and FeaturesRoadGraph::m_fakeOutgoingEdges fields.\n graph.AddFakeEdges(j, sourceVicinity);\n}\nFixing FakeEdgesCombinatorialExplosion test. Some memory for example (WorldCoasts_obsolete.mwm) may not be registered.#include \"testing\/testing.hpp\"\n\n#include \"platform\/local_country_file.hpp\"\n\n#include \"geometry\/mercator.hpp\"\n#include \"geometry\/point2d.hpp\"\n\n#include \"indexer\/classificator_loader.hpp\"\n#include \"indexer\/data_source.hpp\"\n#include \"indexer\/feature_altitude.hpp\"\n#include \"indexer\/mwm_set.hpp\"\n\n#include \"routing_common\/car_model.hpp\"\n#include \"routing\/features_road_graph.hpp\"\n#include \"routing\/road_graph.hpp\"\n\n#include \"routing\/routing_integration_tests\/routing_test_tools.hpp\"\n\n#include \n\nusing namespace routing;\nusing namespace integration;\n\n\/\/ The test on combinatorial explosion of number of fake edges at FeaturesRoadGraph.\n\/\/ It might happen when a lot of roads intersect at one point. For example,\n\/\/ https:\/\/www.openstreetmap.org\/#map=19\/50.73197\/-1.21295\nUNIT_TEST(FakeEdgesCombinatorialExplosion)\n{\n classificator::Load();\n\n std::vector localFiles;\n GetAllLocalFiles(localFiles);\n TEST(!localFiles.empty(), ());\n\n FrozenDataSource dataSource;\n for (auto const & file : localFiles)\n dataSource.Register(file);\n\n FeaturesRoadGraph graph(dataSource, IRoadGraph::Mode::ObeyOnewayTag,\n make_shared(CountryParentNameGetterFn()));\n Junction const j(m2::PointD(MercatorBounds::FromLatLon(50.73208, -1.21279)), feature::kDefaultAltitudeMeters);\n std::vector> sourceVicinity;\n graph.FindClosestEdges(MercatorBounds::RectByCenterXYAndSizeInMeters(\n j.GetPoint(), FeaturesRoadGraph::kClosestEdgesRadiusM),\n 20 \/* count *\/, sourceVicinity);\n \/\/ In case of the combinatorial explosion mentioned above all the memory was consumed for\n \/\/ FeaturesRoadGraph::m_fakeIngoingEdges and FeaturesRoadGraph::m_fakeOutgoingEdges fields.\n graph.AddFakeEdges(j, sourceVicinity);\n}\n<|endoftext|>"} {"text":"#include \"bignum_conversions.h\"\n\n#include \n#include \n#include \n#include \"bignum_types.h\"\n\n\/**\n * Returns an binary string representation of a uint32_t. The string returned is\n * of length BITS_PER_WORD.\n * @param number uint32_t to be converted.\n * @return String with the binary representation of number.\n *\/\nchar* uint32_t_to_string(uint32_t number)\n{\n char* str = (char*) calloc(BITS_PER_WORD + 1, sizeof(char));\n str[BITS_PER_WORD] = '\\0';\n\n for (uint32_t i = 0; i < BITS_PER_WORD; i++)\n {\n uint32_t masked_number = number & (1 << i);\n str[BITS_PER_WORD - 1 - i] = (masked_number != 0) ? '1' : '0';\n }\n\n return str;\n}\n\n\/**\n * Converts a bignum to a binary string. The returned string will have a length\n * of TOTAL_BIT_LENGTH.\n * @param number Number to be converted.\n * @return Binary string representation of the bignum.\n *\/\nchar* bignum_to_string(bignum number)\n{\n \/\/ make an array of strings which will each contain 1 of the\n \/\/ BIGNUM_NUMBER_OF_WORDS words in the bignum\n char** words = (char**) calloc(BIGNUM_NUMBER_OF_WORDS + 1, sizeof(char*));\n words[BIGNUM_NUMBER_OF_WORDS] = NULL;\n\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n words[i] = (char*) calloc(BITS_PER_WORD + 1, sizeof(char));\n words[i][BITS_PER_WORD] = '\\0';\n\n \/\/ convert each bignum element to a string\n words[i] = uint32_t_to_string(number[i]);\n }\n\n \/\/ concatenate the words together to form a TOTAL_BIT_LENGTH long string\n char* final_str = (char*) calloc(TOTAL_BIT_LENGTH + 1, sizeof(char));\n final_str[TOTAL_BIT_LENGTH] = '\\0';\n\n char* src;\n char* dest = final_str;\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n src = words[BIGNUM_NUMBER_OF_WORDS - i - 1];\n strncpy(dest, src, BITS_PER_WORD);\n\n dest += BITS_PER_WORD;\n }\n\n free_string_words(&words);\n\n \/\/ return concatenated string\n return final_str;\n}\n\n\/**\n * Pads the binary string with zeros until it is TOTAL_BIT_LENGTH long.\n * @param old_str string to be padded with zeros\n *\/\nvoid pad_string_with_zeros(char** old_str)\n{\n char* new_str = (char*) calloc(TOTAL_BIT_LENGTH + 1, sizeof(char));\n new_str[TOTAL_BIT_LENGTH] = '\\0';\n for (uint32_t i = 0; i < TOTAL_BIT_LENGTH; i++)\n {\n new_str[i] = '0';\n }\n\n uint32_t old_str_length = strlen(*old_str);\n\n for (uint32_t i = 0; i < old_str_length; i++)\n {\n new_str[(TOTAL_BIT_LENGTH - old_str_length) + i] = (*old_str)[i];\n }\n\n free(*old_str);\n *old_str = new_str;\n}\n\n\/**\n * Separates a TOTAL_BIT_LENGTH long binary string into an array of binary\n * strings of length BITS_PER_WORD. The returned array contains the most\n * significant bits at its last index, and its least significant bits at its\n * first position. Ex: str_words[0] contains bits (BITS_PER_WORD downto 0)\n * @param str String to be decomposed.\n * @return Decomposed string.\n *\/\nchar** cut_string_to_multiple_words(char* str)\n{\n \/\/ cut str into BIGNUM_NUMBER_OF_WORDS pieces, each of which is\n \/\/ BITS_PER_WORD long\n\n \/\/ array of BITS_PER_WORD length strings\n char** str_words = (char**) calloc(BIGNUM_NUMBER_OF_WORDS + 1,\n sizeof(char*));\n str_words[BIGNUM_NUMBER_OF_WORDS] = NULL;\n\n \/\/ allocate each one of the strings and fill them up\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n str_words[i] = (char*) calloc(BITS_PER_WORD + 1, sizeof(char));\n str_words[i][BITS_PER_WORD] = '\\0';\n\n for (uint32_t j = 0; j < BITS_PER_WORD; j++)\n {\n str_words[i][j] = str[i * BITS_PER_WORD + j];\n }\n }\n\n \/\/ until now, the strings have been cut in big-endian form, but we want\n \/\/ little endian for indexing, so we have to invert the array.\n char* tmp;\n uint32_t middle_of_array = ceil(BIGNUM_NUMBER_OF_WORDS \/ 2.0);\n for (uint32_t i = 0; i < middle_of_array; i++)\n {\n tmp = str_words[i];\n str_words[i] = str_words[BIGNUM_NUMBER_OF_WORDS - 1 - i];\n str_words[BIGNUM_NUMBER_OF_WORDS - 1 - i] = tmp;\n }\n\n return str_words;\n}\n\n\/**\n * Frees an array containing BIGNUM_NUMBER_OF_WORDS strings.\n * @param words Pointer to the array of strings to be freed.\n *\/\nvoid free_string_words(char*** words)\n{\n if (*words != NULL)\n {\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n if ((*words)[i] != NULL)\n {\n free((*words)[i]);\n (*words)[i] = NULL;\n }\n }\n\n \/\/ free the char** pointing to the words\n free(*words);\n *words = NULL;\n }\n}\n\n\/**\n * Returns a uint32_t representation of the binary string of length\n * BITS_PER_WORD passed as a parameter.\n * @param str String to be converted.\n * @return Converted value.\n *\/\nuint32_t string_to_uint32_t(char* str)\n{\n uint32_t number = 0;\n\n for (uint32_t i = 0; i < BITS_PER_WORD; i++)\n {\n uint32_t bit_value = str[BITS_PER_WORD - 1 - i] == '1' ? 1 : 0;\n number |= bit_value << i;\n }\n\n return number;\n}\n\n\/**\n * Converts the \"str\" binary string of length TOTAL_BITS_LENGTH into a bignum.\n * @param str String to be converted.\n * @param number Number which will be assigned the value of the binary string\n * str.\n *\/\nvoid string_to_bignum(char* str, bignum number)\n{\n char** words = cut_string_to_multiple_words(str);\n\n \/\/ set the number\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n number[i] = string_to_uint32_t(words[i]);\n }\n\n free_string_words(&words);\n}\n\n\/**\n * Transforms an array of bignums to an array of coalesced_bignums. ATTENTION:\n * this function frees the memory pointed to by the bignum, and returns the\n * coalesced_bignum array.\n * @param in bignum array to convert\n * @return converted coalesced_bignum array\n *\/\ncoalesced_bignum* bignum_to_coalesced_bignum(bignum** in)\n{\n coalesced_bignum* out = (coalesced_bignum*) calloc(BIGNUM_NUMBER_OF_WORDS,\n sizeof(coalesced_bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)\n {\n out[i][j] = (*in)[j][i];\n }\n }\n\n free(*in);\n *in = NULL;\n\n return out;\n}\n\n\/**\n * Transforms an array of coalesced_bignums to an array of bignums. ATTENTION:\n * this function frees the memory pointed to by the coalesced_bignum, and\n * returns the bignum array.\n * @param in coalesced_bignum array to convert\n * @return converted bignum array\n *\/\nbignum* coalesced_bignum_to_bignum(coalesced_bignum** in)\n{\n bignum* out = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)\n {\n out[i][j] = (*in)[j][i];\n }\n }\n\n free(*in);\n *in = NULL;\n\n return out;\n}\n\n\/**\n * Transforms 2 arrays of bignums to an interleaved_bignum array. ATTENTION:\n * this function frees the memory pointed to by the 2 bignum arrays, and returns\n * the interleaved_bignum array.\n * @param in_1 First array of data elements.\n * @param in_2 Second array of data elements.\n * @return converted interleaved_bignum array.\n *\/\ninterleaved_bignum* bignums_to_interleaved_bignum(bignum** in_1, bignum** in_2)\n{\n interleaved_bignum* out = (interleaved_bignum*) calloc(TOTAL_NUMBER_OF_THREADS,\n sizeof(interleaved_bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < 2 * BIGNUM_NUMBER_OF_WORDS; j++)\n {\n if (j % 2 == 0)\n {\n out[i][j] = (*in_1)[i][j \/ 2];\n }\n else\n {\n out[i][j] = (*in_2)[i][j \/ 2];\n }\n }\n }\n\n free(*in_1);\n free(*in_2);\n *in_1 = NULL;\n *in_2 = NULL;\n\n return out;\n}\n\n\/**\n * Transforms an interleaved_bignum array to 2 bignum arrays. ATTENTION: this\n * function frees the memory pointed to by the interleaved_bignum, and allocates\n * memory to hold the 2 resulting bignums.\n * @param out_1 Address of a pointer which will contain the first array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param out_2 Address of a pointer which will contain the second array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param in interleaved_bignum to convert.\n *\/\nvoid interleaved_bignum_to_bignums(bignum** out_1, bignum** out_2,\n interleaved_bignum** in)\n{\n bignum* out_1_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n bignum* out_2_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < 2 * BIGNUM_NUMBER_OF_WORDS; j++)\n {\n if (j % 2 == 0)\n {\n out_1_tmp[i][j \/ 2] = (*in)[i][j];\n }\n else\n {\n out_2_tmp[i][j \/ 2] = (*in)[i][j];\n }\n }\n }\n\n free(*in);\n *in = NULL;\n\n *out_1 = out_1_tmp;\n *out_2 = out_2_tmp;\n}\n\n\/**\n * Transforms 2 arrays of bignums to a coalesced_interleaved_bignum array.\n * ATTENTION: this function frees the memory pointed to by the 2 bignum arrays,\n * and returns the coalesced_interleaved_bignum array.\n * @param in_1 First array of data elements.\n * @param in_2 Second array of data elements.\n * @return converted coalesced_interleaved_bignum array.\n *\/\ncoalesced_interleaved_bignum* bignums_to_coalesced_interleaved_bignum(bignum** in_1,\n bignum** in_2)\n{\n coalesced_interleaved_bignum* out =\n (coalesced_interleaved_bignum*) calloc(BIGNUM_NUMBER_OF_WORDS,\n sizeof(coalesced_interleaved_bignum));\n\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n for (uint32_t j = 0; j < 2 * TOTAL_NUMBER_OF_THREADS; j += 2)\n {\n out[i][j] = (*in_1)[j \/ 2][i];\n out[i][j + 1] = (*in_2)[j \/ 2][i];\n }\n }\n\n free(*in_1);\n free(*in_2);\n *in_1 = NULL;\n *in_2 = NULL;\n\n return out;\n}\n\n\/**\n * Transforms a coalesced_interleaved_bignum array to 2 bignum arrays.\n * ATTENTION: this function frees the memory pointed to by the\n * coalesced_interleaved_bignum, and allocates memory to hold the 2 resulting\n * bignums.\n * @param out_1 Address of a pointer which will contain the first array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param out_2 Address of a pointer which will contain the second array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param in coalesced_interleaved_bignum to convert.\n *\/\nvoid coalesced_interleaved_bignum_to_bignums(bignum** out_1, bignum** out_2,\n coalesced_interleaved_bignum** in)\n{\n bignum* out_1_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n bignum* out_2_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n for (uint32_t j = 0; j < 2 * TOTAL_NUMBER_OF_THREADS; j += 2)\n {\n (*out_1)[j \/ 2][i] = in[i][j];\n (*out_2)[j \/ 2][i] = in[i][j + 1];\n }\n }\n\n free(*in);\n *in = NULL;\n\n *out_1 = out_1_tmp;\n *out_2 = out_2_tmp;\n}\nminor index fix#include \"bignum_conversions.h\"\n\n#include \n#include \n#include \n#include \"bignum_types.h\"\n\n\/**\n * Returns an binary string representation of a uint32_t. The string returned is\n * of length BITS_PER_WORD.\n * @param number uint32_t to be converted.\n * @return String with the binary representation of number.\n *\/\nchar* uint32_t_to_string(uint32_t number)\n{\n char* str = (char*) calloc(BITS_PER_WORD + 1, sizeof(char));\n str[BITS_PER_WORD] = '\\0';\n\n for (uint32_t i = 0; i < BITS_PER_WORD; i++)\n {\n uint32_t masked_number = number & (1 << i);\n str[BITS_PER_WORD - 1 - i] = (masked_number != 0) ? '1' : '0';\n }\n\n return str;\n}\n\n\/**\n * Converts a bignum to a binary string. The returned string will have a length\n * of TOTAL_BIT_LENGTH.\n * @param number Number to be converted.\n * @return Binary string representation of the bignum.\n *\/\nchar* bignum_to_string(bignum number)\n{\n \/\/ make an array of strings which will each contain 1 of the\n \/\/ BIGNUM_NUMBER_OF_WORDS words in the bignum\n char** words = (char**) calloc(BIGNUM_NUMBER_OF_WORDS + 1, sizeof(char*));\n words[BIGNUM_NUMBER_OF_WORDS] = NULL;\n\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n words[i] = (char*) calloc(BITS_PER_WORD + 1, sizeof(char));\n words[i][BITS_PER_WORD] = '\\0';\n\n \/\/ convert each bignum element to a string\n words[i] = uint32_t_to_string(number[i]);\n }\n\n \/\/ concatenate the words together to form a TOTAL_BIT_LENGTH long string\n char* final_str = (char*) calloc(TOTAL_BIT_LENGTH + 1, sizeof(char));\n final_str[TOTAL_BIT_LENGTH] = '\\0';\n\n char* src;\n char* dest = final_str;\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n src = words[BIGNUM_NUMBER_OF_WORDS - i - 1];\n strncpy(dest, src, BITS_PER_WORD);\n\n dest += BITS_PER_WORD;\n }\n\n free_string_words(&words);\n\n \/\/ return concatenated string\n return final_str;\n}\n\n\/**\n * Pads the binary string with zeros until it is TOTAL_BIT_LENGTH long.\n * @param old_str string to be padded with zeros\n *\/\nvoid pad_string_with_zeros(char** old_str)\n{\n char* new_str = (char*) calloc(TOTAL_BIT_LENGTH + 1, sizeof(char));\n new_str[TOTAL_BIT_LENGTH] = '\\0';\n for (uint32_t i = 0; i < TOTAL_BIT_LENGTH; i++)\n {\n new_str[i] = '0';\n }\n\n uint32_t old_str_length = strlen(*old_str);\n\n for (uint32_t i = 0; i < old_str_length; i++)\n {\n new_str[(TOTAL_BIT_LENGTH - old_str_length) + i] = (*old_str)[i];\n }\n\n free(*old_str);\n *old_str = new_str;\n}\n\n\/**\n * Separates a TOTAL_BIT_LENGTH long binary string into an array of binary\n * strings of length BITS_PER_WORD. The returned array contains the most\n * significant bits at its last index, and its least significant bits at its\n * first position. Ex: str_words[0] contains bits (BITS_PER_WORD downto 0)\n * @param str String to be decomposed.\n * @return Decomposed string.\n *\/\nchar** cut_string_to_multiple_words(char* str)\n{\n \/\/ cut str into BIGNUM_NUMBER_OF_WORDS pieces, each of which is\n \/\/ BITS_PER_WORD long\n\n \/\/ array of BITS_PER_WORD length strings\n char** str_words = (char**) calloc(BIGNUM_NUMBER_OF_WORDS + 1,\n sizeof(char*));\n str_words[BIGNUM_NUMBER_OF_WORDS] = NULL;\n\n \/\/ allocate each one of the strings and fill them up\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n str_words[i] = (char*) calloc(BITS_PER_WORD + 1, sizeof(char));\n str_words[i][BITS_PER_WORD] = '\\0';\n\n for (uint32_t j = 0; j < BITS_PER_WORD; j++)\n {\n str_words[i][j] = str[i * BITS_PER_WORD + j];\n }\n }\n\n \/\/ until now, the strings have been cut in big-endian form, but we want\n \/\/ little endian for indexing, so we have to invert the array.\n char* tmp;\n uint32_t middle_of_array = ceil(BIGNUM_NUMBER_OF_WORDS \/ 2.0);\n for (uint32_t i = 0; i < middle_of_array; i++)\n {\n tmp = str_words[i];\n str_words[i] = str_words[BIGNUM_NUMBER_OF_WORDS - 1 - i];\n str_words[BIGNUM_NUMBER_OF_WORDS - 1 - i] = tmp;\n }\n\n return str_words;\n}\n\n\/**\n * Frees an array containing BIGNUM_NUMBER_OF_WORDS strings.\n * @param words Pointer to the array of strings to be freed.\n *\/\nvoid free_string_words(char*** words)\n{\n if (*words != NULL)\n {\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n if ((*words)[i] != NULL)\n {\n free((*words)[i]);\n (*words)[i] = NULL;\n }\n }\n\n \/\/ free the char** pointing to the words\n free(*words);\n *words = NULL;\n }\n}\n\n\/**\n * Returns a uint32_t representation of the binary string of length\n * BITS_PER_WORD passed as a parameter.\n * @param str String to be converted.\n * @return Converted value.\n *\/\nuint32_t string_to_uint32_t(char* str)\n{\n uint32_t number = 0;\n\n for (uint32_t i = 0; i < BITS_PER_WORD; i++)\n {\n uint32_t bit_value = str[BITS_PER_WORD - 1 - i] == '1' ? 1 : 0;\n number |= bit_value << i;\n }\n\n return number;\n}\n\n\/**\n * Converts the \"str\" binary string of length TOTAL_BITS_LENGTH into a bignum.\n * @param str String to be converted.\n * @param number Number which will be assigned the value of the binary string\n * str.\n *\/\nvoid string_to_bignum(char* str, bignum number)\n{\n char** words = cut_string_to_multiple_words(str);\n\n \/\/ set the number\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n number[i] = string_to_uint32_t(words[i]);\n }\n\n free_string_words(&words);\n}\n\n\/**\n * Transforms an array of bignums to an array of coalesced_bignums. ATTENTION:\n * this function frees the memory pointed to by the bignum, and returns the\n * coalesced_bignum array.\n * @param in bignum array to convert\n * @return converted coalesced_bignum array\n *\/\ncoalesced_bignum* bignum_to_coalesced_bignum(bignum** in)\n{\n coalesced_bignum* out = (coalesced_bignum*) calloc(BIGNUM_NUMBER_OF_WORDS,\n sizeof(coalesced_bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)\n {\n out[j][i] = (*in)[i][j];\n }\n }\n\n free(*in);\n *in = NULL;\n\n return out;\n}\n\n\/**\n * Transforms an array of coalesced_bignums to an array of bignums. ATTENTION:\n * this function frees the memory pointed to by the coalesced_bignum, and\n * returns the bignum array.\n * @param in coalesced_bignum array to convert\n * @return converted bignum array\n *\/\nbignum* coalesced_bignum_to_bignum(coalesced_bignum** in)\n{\n bignum* out = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)\n {\n out[i][j] = (*in)[j][i];\n }\n }\n\n free(*in);\n *in = NULL;\n\n return out;\n}\n\n\/**\n * Transforms 2 arrays of bignums to an interleaved_bignum array. ATTENTION:\n * this function frees the memory pointed to by the 2 bignum arrays, and returns\n * the interleaved_bignum array.\n * @param in_1 First array of data elements.\n * @param in_2 Second array of data elements.\n * @return converted interleaved_bignum array.\n *\/\ninterleaved_bignum* bignums_to_interleaved_bignum(bignum** in_1, bignum** in_2)\n{\n interleaved_bignum* out = (interleaved_bignum*) calloc(TOTAL_NUMBER_OF_THREADS,\n sizeof(interleaved_bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < 2 * BIGNUM_NUMBER_OF_WORDS; j++)\n {\n if (j % 2 == 0)\n {\n out[i][j] = (*in_1)[i][j \/ 2];\n }\n else\n {\n out[i][j] = (*in_2)[i][j \/ 2];\n }\n }\n }\n\n free(*in_1);\n free(*in_2);\n *in_1 = NULL;\n *in_2 = NULL;\n\n return out;\n}\n\n\/**\n * Transforms an interleaved_bignum array to 2 bignum arrays. ATTENTION: this\n * function frees the memory pointed to by the interleaved_bignum, and allocates\n * memory to hold the 2 resulting bignums.\n * @param out_1 Address of a pointer which will contain the first array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param out_2 Address of a pointer which will contain the second array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param in interleaved_bignum to convert.\n *\/\nvoid interleaved_bignum_to_bignums(bignum** out_1, bignum** out_2,\n interleaved_bignum** in)\n{\n bignum* out_1_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n bignum* out_2_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n\n for (uint32_t i = 0; i < TOTAL_NUMBER_OF_THREADS; i++)\n {\n for (uint32_t j = 0; j < 2 * BIGNUM_NUMBER_OF_WORDS; j++)\n {\n if (j % 2 == 0)\n {\n out_1_tmp[i][j \/ 2] = (*in)[i][j];\n }\n else\n {\n out_2_tmp[i][j \/ 2] = (*in)[i][j];\n }\n }\n }\n\n free(*in);\n *in = NULL;\n\n *out_1 = out_1_tmp;\n *out_2 = out_2_tmp;\n}\n\n\/**\n * Transforms 2 arrays of bignums to a coalesced_interleaved_bignum array.\n * ATTENTION: this function frees the memory pointed to by the 2 bignum arrays,\n * and returns the coalesced_interleaved_bignum array.\n * @param in_1 First array of data elements.\n * @param in_2 Second array of data elements.\n * @return converted coalesced_interleaved_bignum array.\n *\/\ncoalesced_interleaved_bignum* bignums_to_coalesced_interleaved_bignum(bignum** in_1,\n bignum** in_2)\n{\n coalesced_interleaved_bignum* out =\n (coalesced_interleaved_bignum*) calloc(BIGNUM_NUMBER_OF_WORDS,\n sizeof(coalesced_interleaved_bignum));\n\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n for (uint32_t j = 0; j < 2 * TOTAL_NUMBER_OF_THREADS; j += 2)\n {\n out[i][j] = (*in_1)[j \/ 2][i];\n out[i][j + 1] = (*in_2)[j \/ 2][i];\n }\n }\n\n free(*in_1);\n free(*in_2);\n *in_1 = NULL;\n *in_2 = NULL;\n\n return out;\n}\n\n\/**\n * Transforms a coalesced_interleaved_bignum array to 2 bignum arrays.\n * ATTENTION: this function frees the memory pointed to by the\n * coalesced_interleaved_bignum, and allocates memory to hold the 2 resulting\n * bignums.\n * @param out_1 Address of a pointer which will contain the first array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param out_2 Address of a pointer which will contain the second array of data\n * elements. Memory is allocated by this function to hold the data.\n * @param in coalesced_interleaved_bignum to convert.\n *\/\nvoid coalesced_interleaved_bignum_to_bignums(bignum** out_1, bignum** out_2,\n coalesced_interleaved_bignum** in)\n{\n bignum* out_1_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n bignum* out_2_tmp = (bignum*) calloc(TOTAL_NUMBER_OF_THREADS, sizeof(bignum));\n\n for (uint32_t i = 0; i < BIGNUM_NUMBER_OF_WORDS; i++)\n {\n for (uint32_t j = 0; j < 2 * TOTAL_NUMBER_OF_THREADS; j += 2)\n {\n (*out_1)[j \/ 2][i] = in[i][j];\n (*out_2)[j \/ 2][i] = in[i][j + 1];\n }\n }\n\n free(*in);\n *in = NULL;\n\n *out_1 = out_1_tmp;\n *out_2 = out_2_tmp;\n}\n<|endoftext|>"} {"text":"#include \"xml.h\"\n\nnamespace ospray {\n namespace xml {\n\n std::string toString(const float f) \n { std::stringstream ss; ss << f; return ss.str(); }\n\n std::string toString(const vec3f &v) \n { std::stringstream ss; ss << v.x << \" \" << v.y << \" \" << v.z; return ss.str(); }\n\n Node::~Node()\n {\n for (int i=0;iname))\n throw std::runtime_error(\"XML error: could not parse node name\");\n \n skipWhites(s);\n \n Prop prop;\n while (parseProp(s,prop)) {\n node->prop.push_back(new Prop(prop));\n skipWhites(s);\n }\n\n if (*s == '\/') {\n consume(s,\"\/>\");\n return node;\n }\n\n consume(s,\">\");\n\n while (1) {\n skipWhites(s);\n if (*s == '<' && s[1] == '\/') {\n consume(s,\"<\/\");\n std::string name = \"\";\n parseIdentifier(s,name);\n if (name != node->name)\n throw std::runtime_error(\"invalid XML node - started with '<\"+node->name+\"...'>, but ended with '<\/\"+name+\">\");\n consume(s,\">\");\n break;\n \/\/ either end of current node\n } else if (*s == '<') {\n \/\/ child node\n Node *child = parseNode(s);\n node->child.push_back(child);\n } else {\n if (node->content != \"\")\n throw std::runtime_error(\"invalid XML node - two different contents!?\");\n \/\/ content\n char *begin = s;\n while (*s != '<' && *s != 0) ++s;\n char *end = s;\n while (isspace(end[-1])) --end;\n node->content = makeString(begin,end);\n }\n }\n return node;\n } catch (std::runtime_error e) {\n delete node;\n throw e;\n }\n }\n\n bool parseHeader(char *&s)\n {\n consume(s,\"') {\n consume(s,\"?>\");\n return true;\n }\n\n if (!isWhite(*s)) return false; ++s;\n\n skipWhites(s);\n \n Prop headerProp;\n while (parseProp(s,headerProp)) {\n \/\/ ignore header prop\n skipWhites(s);\n }\n \n consume(s,\"?>\");\n \n return true;\n }\n\n bool parseXML(XMLDoc *xml, char *s)\n {\n if (!parseHeader(s))\n throw std::runtime_error(\"could not parse XML header\");\n \n skipWhites(s);\n while (*s != 0) {\n Node *node = parseNode(s);\n if (node)xml->child.push_back(node);\n skipWhites(s);\n }\n\n if (*s != 0) throw std::runtime_error(\"un-parsed junk at end of file\"); ++s;\n return xml;\n }\n\n void Writer::spaces()\n {\n for (int i=0;ihasContent); \/\/ content may not be written before properties\n fprintf(xml,\" %s=\\\"%s\\\"\",name.c_str(),value.c_str());\n }\n\n void Writer::openNode(const std::string &type)\n {\n assert(xml);\n spaces(); fprintf(xml,\"<%s\",type.c_str());\n State *s = new State;\n s->type = type;\n state.push(s);\n }\n \n void Writer::closeNode()\n {\n assert(xml);\n assert(!state.empty());\n State *s = state.top();\n assert(s);\n if (s->hasContent)\n fprintf(xml,\"<\/%s>\",s->type.c_str());\n else \n fprintf(xml,\"\/>\\n\");\n delete s;\n state.pop();\n }\n\n XMLDoc *readXML(const std::string &fn)\n {\n FILE *file = fopen(fn.c_str(),\"r\");\n if (!file) {\n throw std::runtime_error(\"ospray::XML error: could not open file '\"+fn+\"'\");\n }\n\n fseek(file,0,SEEK_END);\n long numBytes = ftell(file);\n fseek(file,0,SEEK_SET);\n char *mem = new char[numBytes+1];\n mem[numBytes] = 0;\n fread(mem,1,numBytes,file);\n XMLDoc *xml = new XMLDoc;\n bool valid = false;\n try {\n valid = parseXML(xml,mem);\n } catch (std::runtime_error e) {\n delete[] mem;\n fclose(file);\n }\n delete[] mem;\n fclose(file);\n\n if (!valid) {\n delete xml;\n return NULL;\n }\n return xml;\n }\n\n Writer::Writer(FILE *xml, FILE *bin)\n : xml(xml), bin(bin)\n {}\n\n \/*! write document header, may only be called once *\/\n void Writer::writeHeader(const std::string &version)\n {\n assert(xml);\n fprintf(xml,\"\\n\",version.c_str());\n }\n\n \/*! write document footer. may only be called once, at end of write *\/\n void Writer::writeFooter()\n {\n assert(xml);\n }\n\n\n }\n}\n'fix' for xml parser. can now handle partially written xml files that do not properly close all nodes (as seems to happen in vtk files)#include \"xml.h\"\n\nnamespace ospray {\n namespace xml {\n\n std::string toString(const float f) \n { std::stringstream ss; ss << f; return ss.str(); }\n\n std::string toString(const vec3f &v) \n { std::stringstream ss; ss << v.x << \" \" << v.y << \" \" << v.z; return ss.str(); }\n\n Node::~Node()\n {\n for (int i=0;iname))\n throw std::runtime_error(\"XML error: could not parse node name\");\n\n skipWhites(s);\n \n Prop prop;\n while (parseProp(s,prop)) {\n node->prop.push_back(new Prop(prop));\n skipWhites(s);\n }\n\n if (*s == '\/') {\n consume(s,\"\/>\");\n return node;\n }\n\n consume(s,\">\");\n\n while (1) {\n skipWhites(s);\n if (*s == '<' && s[1] == '\/') {\n consume(s,\"<\/\");\n std::string name = \"\";\n parseIdentifier(s,name);\n if (name != node->name)\n throw std::runtime_error(\"invalid XML node - started with '<\"+node->name+\"...'>, but ended with '<\/\"+name+\">\");\n consume(s,\">\");\n break;\n \/\/ either end of current node\n } else if (*s == '<') {\n \/\/ child node\n Node *child = parseNode(s);\n node->child.push_back(child);\n } else if (*s == 0) {\n std::cout << \"#osp:xml: warning: xml file ended with still-open nodes (this typically indicates a partial xml file)\" << std::endl;\n return node;\n } else {\n if (node->content != \"\")\n throw std::runtime_error(\"invalid XML node - two different contents!?\");\n \/\/ content\n char *begin = s;\n while (*s != '<' && *s != 0) ++s;\n char *end = s;\n while (isspace(end[-1])) --end;\n node->content = makeString(begin,end);\n }\n }\n return node;\n } catch (std::runtime_error e) {\n delete node;\n throw e;\n }\n }\n\n bool parseHeader(char *&s)\n {\n consume(s,\"') {\n consume(s,\"?>\");\n return true;\n }\n\n if (!isWhite(*s)) return false; ++s;\n\n skipWhites(s);\n \n Prop headerProp;\n while (parseProp(s,headerProp)) {\n \/\/ ignore header prop\n skipWhites(s);\n }\n \n consume(s,\"?>\");\n \n return true;\n }\n\n bool parseXML(XMLDoc *xml, char *s)\n {\n if (!parseHeader(s))\n throw std::runtime_error(\"could not parse XML header\");\n \n skipWhites(s);\n while (*s != 0) {\n Node *node = parseNode(s);\n if (node)xml->child.push_back(node);\n skipWhites(s);\n }\n\n if (*s != 0) throw std::runtime_error(\"un-parsed junk at end of file\"); ++s;\n return xml;\n }\n\n void Writer::spaces()\n {\n for (int i=0;ihasContent); \/\/ content may not be written before properties\n fprintf(xml,\" %s=\\\"%s\\\"\",name.c_str(),value.c_str());\n }\n\n void Writer::openNode(const std::string &type)\n {\n assert(xml);\n spaces(); fprintf(xml,\"<%s\",type.c_str());\n State *s = new State;\n s->type = type;\n state.push(s);\n }\n \n void Writer::closeNode()\n {\n assert(xml);\n assert(!state.empty());\n State *s = state.top();\n assert(s);\n if (s->hasContent)\n fprintf(xml,\"<\/%s>\",s->type.c_str());\n else \n fprintf(xml,\"\/>\\n\");\n delete s;\n state.pop();\n }\n\n XMLDoc *readXML(const std::string &fn)\n {\n FILE *file = fopen(fn.c_str(),\"r\");\n if (!file) {\n throw std::runtime_error(\"ospray::XML error: could not open file '\"+fn+\"'\");\n }\n\n fseek(file,0,SEEK_END);\n long numBytes = ftell(file);\n fseek(file,0,SEEK_SET);\n char *mem = new char[numBytes+1];\n mem[numBytes] = 0;\n fread(mem,1,numBytes,file);\n XMLDoc *xml = new XMLDoc;\n bool valid = false;\n try {\n valid = parseXML(xml,mem);\n } catch (std::runtime_error e) {\n delete[] mem;\n fclose(file);\n throw e;\n }\n delete[] mem;\n fclose(file);\n\n if (!valid) {\n delete xml;\n return NULL;\n }\n return xml;\n }\n\n Writer::Writer(FILE *xml, FILE *bin)\n : xml(xml), bin(bin)\n {}\n\n \/*! write document header, may only be called once *\/\n void Writer::writeHeader(const std::string &version)\n {\n assert(xml);\n fprintf(xml,\"\\n\",version.c_str());\n }\n\n \/*! write document footer. may only be called once, at end of write *\/\n void Writer::writeFooter()\n {\n assert(xml);\n }\n\n\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: SlsBitmapCompressor.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 19:03:35 $\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_sd.hxx\"\n\n#include \"SlsBitmapCompressor.hxx\"\n\n#include \n#include \n#include \n#include \n\nnamespace sd { namespace slidesorter { namespace cache {\n\n\n\/\/===== NoBitmapCompression ===================================================\n\n\/** This dummy replacement simply stores a shared pointer to the original\n preview bitmap.\n*\/\nclass NoBitmapCompression::DummyReplacement\n : public BitmapReplacement\n{\npublic:\n ::boost::shared_ptr mpPreview;\n Size maOriginalSize;\n\n DummyReplacement (const ::boost::shared_ptr& rpPreview) : mpPreview(rpPreview)\n {\n }\n virtual sal_Int32 GetMemorySize (void) const\n {\n return mpPreview->GetSizeBytes();\n }\n};\n\n\n\n\n::boost::shared_ptr NoBitmapCompression::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n return ::boost::shared_ptr(new DummyReplacement(rpBitmap));\n}\n\n\n\n\n::boost::shared_ptr NoBitmapCompression::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n return dynamic_cast(rBitmapData).mpPreview;\n}\n\n\n\n\nbool NoBitmapCompression::IsLossless (void) const\n{\n return true;\n}\n\n\n\n\n\/\/===== CompressionByDeletion =================================================\n\n::boost::shared_ptr CompressionByDeletion::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n return ::boost::shared_ptr();\n}\n\n\n\n\n::boost::shared_ptr CompressionByDeletion::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n \/\/ Return a NULL pointer. This will eventually lead to a request for\n \/\/ the creation of a new one.\n return ::boost::shared_ptr();\n}\n\n\n\n\nbool CompressionByDeletion::IsLossless (void) const\n{\n return false;\n}\n\n\n\n\n\/\/===== ResolutionReduction ===================================================\n\n\/** Store a scaled down bitmap together with the original size.\n*\/\nclass ResolutionReduction::ResolutionReducedReplacement : public BitmapReplacement\n{\npublic:\n ::boost::shared_ptr mpPreview;\n Size maOriginalSize;\n\n virtual sal_Int32 GetMemorySize (void) const\n {\n if (mpPreview.get() != NULL)\n return mpPreview->GetSizeBytes();\n else\n return 0;\n }\n};\n\n\n\n\n::boost::shared_ptr ResolutionReduction::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n ResolutionReducedReplacement* pResult = new ResolutionReducedReplacement();\n pResult->mpPreview.reset(new BitmapEx(*rpBitmap));\n Size aSize (rpBitmap->GetSizePixel());\n pResult->maOriginalSize = aSize;\n if (aSize.Width()>0 && aSize.Width()mpPreview->Scale(Size(mnWidth,nHeight));\n }\n\n return ::boost::shared_ptr(pResult);\n}\n\n\n\n\n::boost::shared_ptr ResolutionReduction::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n ::boost::shared_ptr pResult;\n\n const ResolutionReducedReplacement* pData (\n dynamic_cast(&rBitmapData));\n\n if (pData->mpPreview.get() != NULL)\n {\n pResult.reset(new BitmapEx(*pData->mpPreview));\n if (pData->maOriginalSize.Width() > mnWidth)\n pResult->Scale(pData->maOriginalSize);\n }\n\n return pResult;\n}\n\n\n\n\nbool ResolutionReduction::IsLossless (void) const\n{\n return false;\n}\n\n\n\n\n\/\/===== PNGCompression ========================================================\n\n\nclass PngCompression::PngReplacement : public BitmapReplacement\n{\npublic:\n void* mpData;\n sal_Int32 mnDataSize;\n Size maImageSize;\n PngReplacement (void)\n : mpData(NULL),\n mnDataSize(0),\n maImageSize(0,0)\n {}\n virtual ~PngReplacement (void)\n {\n delete [] mpData;\n }\n virtual sal_Int32 GetMemorySize (void) const\n {\n return mnDataSize;\n }\n};\n\n\n\n\n::boost::shared_ptr PngCompression::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n ::vcl::PNGWriter aWriter (*rpBitmap);\n SvMemoryStream aStream (32768, 32768);\n aWriter.Write(aStream);\n\n PngReplacement* pResult = new PngReplacement();\n pResult->maImageSize = rpBitmap->GetSizePixel();\n pResult->mnDataSize = aStream.Tell();\n pResult->mpData = new char[pResult->mnDataSize];\n memcpy(pResult->mpData, aStream.GetData(), pResult->mnDataSize);\n\n return ::boost::shared_ptr(pResult);\n}\n\n\n\n\n::boost::shared_ptr PngCompression::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n BitmapEx* pResult = NULL;\n const PngReplacement* pData (dynamic_cast(&rBitmapData));\n if (pData != NULL)\n {\n SvMemoryStream aStream (pData->mpData, pData->mnDataSize, STREAM_READ);\n ::vcl::PNGReader aReader (aStream);\n pResult = new BitmapEx(aReader.Read());\n }\n\n sal_Int32 nRatio ((100L * (ULONG)pResult->GetSizeBytes()) \/ (ULONG)pData->mnDataSize);\n\n return ::boost::shared_ptr(pResult);\n}\n\n\n\n\nbool PngCompression::IsLossless (void) const\n{\n return true;\n}\n\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::cache\nINTEGRATION: CWS sdwarningsbegone (1.4.38); FILE MERGED 2006\/11\/27 16:30:59 cl 1.4.38.3: #i69285# warning free code changes for sd project 2006\/11\/27 15:15:02 cl 1.4.38.2: #i69285# warning free code changes for sd project 2006\/11\/22 12:42:10 cl 1.4.38.1: #i69285# warning free code changes for unxlngi6.pro\/*************************************************************************\n *\n * $RCSfile: SlsBitmapCompressor.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 18:12:59 $\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_sd.hxx\"\n\n#include \"SlsBitmapCompressor.hxx\"\n\n#include \n#include \n#include \n#include \n\nnamespace sd { namespace slidesorter { namespace cache {\n\n\n\/\/===== NoBitmapCompression ===================================================\n\n\/** This dummy replacement simply stores a shared pointer to the original\n preview bitmap.\n*\/\nclass NoBitmapCompression::DummyReplacement\n : public BitmapReplacement\n{\npublic:\n ::boost::shared_ptr mpPreview;\n Size maOriginalSize;\n\n DummyReplacement (const ::boost::shared_ptr& rpPreview) : mpPreview(rpPreview)\n {\n }\n\n virtual ~DummyReplacement();\n\n virtual sal_Int32 GetMemorySize (void) const;\n};\n\nNoBitmapCompression::DummyReplacement::~DummyReplacement()\n{\n}\n\nsal_Int32 NoBitmapCompression::DummyReplacement::GetMemorySize (void) const\n{\n return mpPreview->GetSizeBytes();\n}\n\n::boost::shared_ptr NoBitmapCompression::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n return ::boost::shared_ptr(new DummyReplacement(rpBitmap));\n}\n\n::boost::shared_ptr NoBitmapCompression::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n return dynamic_cast(rBitmapData).mpPreview;\n}\n\n\n\n\nbool NoBitmapCompression::IsLossless (void) const\n{\n return true;\n}\n\n\n\n\n\/\/===== CompressionByDeletion =================================================\n\n::boost::shared_ptr CompressionByDeletion::Compress (\n const ::boost::shared_ptr& ) const\n{\n return ::boost::shared_ptr();\n}\n\n\n\n\n::boost::shared_ptr CompressionByDeletion::Decompress (\n const BitmapReplacement& ) const\n{\n \/\/ Return a NULL pointer. This will eventually lead to a request for\n \/\/ the creation of a new one.\n return ::boost::shared_ptr();\n}\n\n\n\n\nbool CompressionByDeletion::IsLossless (void) const\n{\n return false;\n}\n\n\n\n\n\/\/===== ResolutionReduction ===================================================\n\n\/** Store a scaled down bitmap together with the original size.\n*\/\nclass ResolutionReduction::ResolutionReducedReplacement : public BitmapReplacement\n{\npublic:\n ::boost::shared_ptr mpPreview;\n Size maOriginalSize;\n\n virtual ~ResolutionReducedReplacement();\n\n virtual sal_Int32 GetMemorySize (void) const;\n};\n\nResolutionReduction::ResolutionReducedReplacement::~ResolutionReducedReplacement()\n{\n}\n\nsal_Int32 ResolutionReduction::ResolutionReducedReplacement::GetMemorySize (void) const\n{\n if (mpPreview.get() != NULL)\n return mpPreview->GetSizeBytes();\n else\n return 0;\n}\n\n::boost::shared_ptr ResolutionReduction::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n ResolutionReducedReplacement* pResult = new ResolutionReducedReplacement();\n pResult->mpPreview.reset(new BitmapEx(*rpBitmap));\n Size aSize (rpBitmap->GetSizePixel());\n pResult->maOriginalSize = aSize;\n if (aSize.Width()>0 && aSize.Width()mpPreview->Scale(Size(mnWidth,nHeight));\n }\n\n return ::boost::shared_ptr(pResult);\n}\n\n\n\n\n::boost::shared_ptr ResolutionReduction::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n ::boost::shared_ptr pResult;\n\n const ResolutionReducedReplacement* pData (\n dynamic_cast(&rBitmapData));\n\n if (pData->mpPreview.get() != NULL)\n {\n pResult.reset(new BitmapEx(*pData->mpPreview));\n if (pData->maOriginalSize.Width() > mnWidth)\n pResult->Scale(pData->maOriginalSize);\n }\n\n return pResult;\n}\n\n\n\n\nbool ResolutionReduction::IsLossless (void) const\n{\n return false;\n}\n\n\n\n\n\/\/===== PNGCompression ========================================================\n\n\nclass PngCompression::PngReplacement : public BitmapReplacement\n{\npublic:\n void* mpData;\n sal_Int32 mnDataSize;\n Size maImageSize;\n PngReplacement (void)\n : mpData(NULL),\n mnDataSize(0),\n maImageSize(0,0)\n {}\n virtual ~PngReplacement (void)\n {\n delete [] (char*)mpData;\n }\n virtual sal_Int32 GetMemorySize (void) const\n {\n return mnDataSize;\n }\n};\n\n\n\n\n::boost::shared_ptr PngCompression::Compress (\n const ::boost::shared_ptr& rpBitmap) const\n{\n ::vcl::PNGWriter aWriter (*rpBitmap);\n SvMemoryStream aStream (32768, 32768);\n aWriter.Write(aStream);\n\n PngReplacement* pResult = new PngReplacement();\n pResult->maImageSize = rpBitmap->GetSizePixel();\n pResult->mnDataSize = aStream.Tell();\n pResult->mpData = new char[pResult->mnDataSize];\n memcpy(pResult->mpData, aStream.GetData(), pResult->mnDataSize);\n\n return ::boost::shared_ptr(pResult);\n}\n\n\n\n\n::boost::shared_ptr PngCompression::Decompress (\n const BitmapReplacement& rBitmapData) const\n{\n BitmapEx* pResult = NULL;\n const PngReplacement* pData (dynamic_cast(&rBitmapData));\n if (pData != NULL)\n {\n SvMemoryStream aStream (pData->mpData, pData->mnDataSize, STREAM_READ);\n ::vcl::PNGReader aReader (aStream);\n pResult = new BitmapEx(aReader.Read());\n }\n\n\/\/ sal_Int32 nRatio ((100L * (ULONG)pResult->GetSizeBytes()) \/ (ULONG)pData->mnDataSize);\n\n return ::boost::shared_ptr(pResult);\n}\n\n\n\n\nbool PngCompression::IsLossless (void) const\n{\n return true;\n}\n\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::cache\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2018 The nanoFramework project contributors\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include \n#include \n#include \n#include \n\n\/\/ initialization of configuration manager\n\/\/ provided as weak so it can be replaced at target level, if required because of the target implementing the storage with a mechanism other then saving to flash\n__nfweak void ConfigurationManager_Initialize()\n{\n \/\/ enumerate the blocks\n ConfigurationManager_EnumerateConfigurationBlocks();\n};\n\n\/\/ Enumerates the configuration blocks from the configuration flash sector \n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak void ConfigurationManager_EnumerateConfigurationBlocks()\n{\n \/\/ find network configuration blocks\n HAL_CONFIGURATION_NETWORK* networkConfigs = ConfigurationManager_FindNetworkConfigurationBlocks((uint32_t)&__nanoConfig_start__, (uint32_t)&__nanoConfig_end__);\n\n \/\/ find wireless 80211 network configuration blocks\n HAL_CONFIGURATION_NETWORK_WIRELESS80211* networkWirelessConfigs = ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks((uint32_t)&__nanoConfig_start__, (uint32_t)&__nanoConfig_end__);\n\n \/\/ alloc memory for g_TargetConfiguration\n \/\/ because this is a struct of structs that use flexible members the memory has to be allocated from the heap\n \/\/ the malloc size for each struct is computed separately \n uint32_t sizeOfNetworkInterfaceConfigs = offsetof(HAL_CONFIGURATION_NETWORK, Configs) + networkConfigs->Count * sizeof(networkConfigs->Configs[0]);\n uint32_t sizeOfWireless80211Configs = offsetof(HAL_CONFIGURATION_NETWORK_WIRELESS80211, Configs) + networkWirelessConfigs->Count * sizeof(networkWirelessConfigs->Configs[0]);\n\n g_TargetConfiguration.NetworkInterfaceConfigs = (HAL_CONFIGURATION_NETWORK*)platform_malloc(sizeOfNetworkInterfaceConfigs);\n g_TargetConfiguration.Wireless80211Configs = (HAL_CONFIGURATION_NETWORK_WIRELESS80211*)platform_malloc(sizeOfWireless80211Configs);\n\n \/\/ copy structs to g_TargetConfiguration\n memcpy((HAL_CONFIGURATION_NETWORK*)g_TargetConfiguration.NetworkInterfaceConfigs, networkConfigs, sizeOfNetworkInterfaceConfigs);\n memcpy((HAL_CONFIGURATION_NETWORK_WIRELESS80211*)g_TargetConfiguration.Wireless80211Configs, networkWirelessConfigs, sizeOfWireless80211Configs);\n\n \/\/ \/\/ now free the memory of the original structs\n platform_free(networkConfigs);\n platform_free(networkWirelessConfigs);\n}\n\n\/\/ Gets the network configuration block from the configuration flash sector \n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak bool ConfigurationManager_GetConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex)\n{\n int sizeOfBlock = 0;\n uint8_t* blockAddress;\n\n \/\/ validate if the requested block exists\n \/\/ Count has to be non zero\n \/\/ requested Index has to exist (array index starts at zero, so need to add one)\n if(configuration == DeviceConfigurationOption_Network)\n {\n if(g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count)\n {\n return FALSE;\n }\n\n \/\/ set block size\n sizeOfBlock = sizeof(HAL_Configuration_NetworkInterface);\n\n \/\/ get block address\n blockAddress = (uint8_t*)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex];\n }\n else if(configuration == DeviceConfigurationOption_Wireless80211Network)\n {\n if(g_TargetConfiguration.Wireless80211Configs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.Wireless80211Configs->Count)\n {\n return FALSE;\n }\n\n \/\/ set block size\n sizeOfBlock = sizeof(HAL_Configuration_Wireless80211);\n\n \/\/ get block address\n blockAddress = (uint8_t*)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex];\n }\n\n \/\/ copy the config block content to the pointer in the argument\n memcpy(configurationBlock, blockAddress, sizeOfBlock);\n\n return TRUE;\n}\n\n\/\/ Stores the configuration block to the configuration flash sector \n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak bool ConfigurationManager_StoreConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex, uint32_t blockSize)\n{\n ByteAddress storageAddress;\n bool requiresEnumeration = FALSE;\n bool success = FALSE;\n\n if(configuration == DeviceConfigurationOption_Network)\n {\n if(g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count)\n {\n \/\/ this is a block that wasn't here before, so we need to enumerate the blocks again after storing it\n requiresEnumeration = TRUE;\n }\n\n \/\/ set storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_NetworkInterface);\n }\n else if(configuration == DeviceConfigurationOption_Wireless80211Network)\n {\n if(g_TargetConfiguration.Wireless80211Configs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.Wireless80211Configs->Count)\n {\n \/\/ this is a block that wasn't here before, so we need to enumerate the blocks again after storing it\n requiresEnumeration = TRUE;\n }\n\n \/\/ set storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_Wireless80211);\n }\n else if(configuration == DeviceConfigurationOption_All)\n {\n \/\/ particular situation where we are receiving the full configuration block\n\n \/\/ set storage address as the start of the flash configuration sector\n storageAddress = (ByteAddress)&__nanoConfig_start__;\n\n \/\/ always enumerate the blocks again after storing it\n requiresEnumeration = TRUE;\n\n \/\/ for save all the block size has to be provided, check it \n if(blockSize == 0)\n {\n return FALSE;\n }\n }\n\n \/\/ copy the config block content to the config block storage\n success = STM32FlashDriver_Write(NULL, storageAddress, blockSize, (unsigned char*)configurationBlock, true);\n\n if(success == TRUE && requiresEnumeration)\n {\n \/\/ free the current allocation(s)\n platform_free(g_TargetConfiguration.NetworkInterfaceConfigs);\n platform_free(g_TargetConfiguration.Wireless80211Configs);\n\n \/\/ perform enumeration of configuration blocks\n ConfigurationManager_EnumerateConfigurationBlocks();\n }\n\n return success;\n}\n\n\/\/ Updates a configuration block in the configuration flash sector\n\/\/ The flash sector has to be erased before writing the updated block\n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak bool ConfigurationManager_UpdateConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex)\n{\n ByteAddress storageAddress;\n uint32_t blockOffset;\n uint8_t* blockAddressInCopy;\n uint32_t blockSize;\n bool success = FALSE;\n\n \/\/ config sector size\n int sizeOfConfigSector = (uint32_t)&__nanoConfig_end__ - (uint32_t)&__nanoConfig_start__;\n\n \/\/ allocate memory from CRT heap\n uint8_t* configSectorCopy = (uint8_t*)platform_malloc(sizeOfConfigSector);\n\n if(configSectorCopy != NULL)\n {\n \/\/ copy config sector from flash to RAM\n memcpy(configSectorCopy, &__nanoConfig_start__, sizeOfConfigSector);\n\n \/\/ find out the address for the config block to update in the configSectorCopy\n \/\/ because we are copying back the config block to flash and just replacing the config block content\n \/\/ the addresses in g_TargetConfiguration will remain the same\n \/\/ plus we can calculate the offset of the config block from g_TargetConfiguration\n if(configuration == DeviceConfigurationOption_Network)\n {\n \/\/ get storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_NetworkInterface);\n }\n else if(configuration == DeviceConfigurationOption_Wireless80211Network)\n {\n \/\/ storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_Wireless80211);\n }\n else\n {\n \/\/ this not a valid configuration option to update, quit\n \/\/ free memory first\n platform_free(configSectorCopy);\n\n return FALSE;\n }\n \n \/\/ erase config sector\n if(STM32FlashDriver_EraseBlock(NULL, (uint32_t)&__nanoConfig_start__) == TRUE)\n {\n \/\/ flash block is erased\n\n \/\/ subtract the start address of config sector to get the offset\n blockOffset = storageAddress - (uint32_t)&__nanoConfig_start__;\n\n \/\/ set pointer to block to udpate\n blockAddressInCopy = configSectorCopy + blockOffset;\n \n \/\/ replace config block with new content by replacing memory\n memcpy(blockAddressInCopy, configSectorCopy, blockSize);\n\n \/\/ copy the config block copy back to the config block storage\n success = STM32FlashDriver_Write(NULL, (uint32_t)&__nanoConfig_start__, sizeOfConfigSector, (unsigned char*)configSectorCopy, true);\n }\n\n \/\/ free memory\n platform_free(configSectorCopy);\n }\n\n return success;\n}\nUpdate STM32 StoreConfigurationBlock\/\/\n\/\/ Copyright (c) 2018 The nanoFramework project contributors\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include \n#include \n#include \n#include \n\n\/\/ initialization of configuration manager\n\/\/ provided as weak so it can be replaced at target level, if required because of the target implementing the storage with a mechanism other then saving to flash\n__nfweak void ConfigurationManager_Initialize()\n{\n \/\/ enumerate the blocks\n ConfigurationManager_EnumerateConfigurationBlocks();\n};\n\n\/\/ Enumerates the configuration blocks from the configuration flash sector \n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak void ConfigurationManager_EnumerateConfigurationBlocks()\n{\n \/\/ find network configuration blocks\n HAL_CONFIGURATION_NETWORK* networkConfigs = ConfigurationManager_FindNetworkConfigurationBlocks((uint32_t)&__nanoConfig_start__, (uint32_t)&__nanoConfig_end__);\n\n \/\/ find wireless 80211 network configuration blocks\n HAL_CONFIGURATION_NETWORK_WIRELESS80211* networkWirelessConfigs = ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks((uint32_t)&__nanoConfig_start__, (uint32_t)&__nanoConfig_end__);\n\n \/\/ alloc memory for g_TargetConfiguration\n \/\/ because this is a struct of structs that use flexible members the memory has to be allocated from the heap\n \/\/ the malloc size for each struct is computed separately \n uint32_t sizeOfNetworkInterfaceConfigs = offsetof(HAL_CONFIGURATION_NETWORK, Configs) + networkConfigs->Count * sizeof(networkConfigs->Configs[0]);\n uint32_t sizeOfWireless80211Configs = offsetof(HAL_CONFIGURATION_NETWORK_WIRELESS80211, Configs) + networkWirelessConfigs->Count * sizeof(networkWirelessConfigs->Configs[0]);\n\n g_TargetConfiguration.NetworkInterfaceConfigs = (HAL_CONFIGURATION_NETWORK*)platform_malloc(sizeOfNetworkInterfaceConfigs);\n g_TargetConfiguration.Wireless80211Configs = (HAL_CONFIGURATION_NETWORK_WIRELESS80211*)platform_malloc(sizeOfWireless80211Configs);\n\n \/\/ copy structs to g_TargetConfiguration\n memcpy((HAL_CONFIGURATION_NETWORK*)g_TargetConfiguration.NetworkInterfaceConfigs, networkConfigs, sizeOfNetworkInterfaceConfigs);\n memcpy((HAL_CONFIGURATION_NETWORK_WIRELESS80211*)g_TargetConfiguration.Wireless80211Configs, networkWirelessConfigs, sizeOfWireless80211Configs);\n\n \/\/ \/\/ now free the memory of the original structs\n platform_free(networkConfigs);\n platform_free(networkWirelessConfigs);\n}\n\n\/\/ Gets the network configuration block from the configuration flash sector \n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak bool ConfigurationManager_GetConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex)\n{\n int sizeOfBlock = 0;\n uint8_t* blockAddress;\n\n \/\/ validate if the requested block exists\n \/\/ Count has to be non zero\n \/\/ requested Index has to exist (array index starts at zero, so need to add one)\n if(configuration == DeviceConfigurationOption_Network)\n {\n if(g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count)\n {\n return FALSE;\n }\n\n \/\/ set block size\n sizeOfBlock = sizeof(HAL_Configuration_NetworkInterface);\n\n \/\/ get block address\n blockAddress = (uint8_t*)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex];\n }\n else if(configuration == DeviceConfigurationOption_Wireless80211Network)\n {\n if(g_TargetConfiguration.Wireless80211Configs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.Wireless80211Configs->Count)\n {\n return FALSE;\n }\n\n \/\/ set block size\n sizeOfBlock = sizeof(HAL_Configuration_Wireless80211);\n\n \/\/ get block address\n blockAddress = (uint8_t*)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex];\n }\n\n \/\/ copy the config block content to the pointer in the argument\n memcpy(configurationBlock, blockAddress, sizeOfBlock);\n\n return TRUE;\n}\n\n\/\/ Stores the configuration block to the configuration flash sector\n\/\/ NOTE: because inserting or removing a configuration block it's very 'RAM expensive' we choose not to support those operations\n\/\/ the host debugger will have to be used to manage these operations on the device configuration collection \n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak bool ConfigurationManager_StoreConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex, uint32_t blockSize)\n{\n ByteAddress storageAddress;\n bool requiresEnumeration = FALSE;\n bool success = FALSE;\n\n if(configuration == DeviceConfigurationOption_Network)\n {\n if(g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count)\n {\n \/\/ there is no room for this block, fail the operation\n return FALSE;\n }\n\n \/\/ set storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_NetworkInterface);\n }\n else if(configuration == DeviceConfigurationOption_Wireless80211Network)\n {\n if(g_TargetConfiguration.Wireless80211Configs->Count == 0 ||\n (configurationIndex + 1) > g_TargetConfiguration.Wireless80211Configs->Count)\n {\n \/\/ there is no room for this block, fail the operation\n return FALSE;\n }\n\n \/\/ set storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_Wireless80211);\n }\n else if(configuration == DeviceConfigurationOption_All)\n {\n \/\/ particular situation where we are receiving the full configuration block\n\n \/\/ set storage address as the start of the flash configuration sector\n storageAddress = (ByteAddress)&__nanoConfig_start__;\n\n \/\/ always enumerate the blocks again after storing it\n requiresEnumeration = TRUE;\n\n \/\/ for save all the block size has to be provided, check that \n if(blockSize == 0)\n {\n return FALSE;\n }\n }\n\n \/\/ copy the config block content to the config block storage\n success = STM32FlashDriver_Write(NULL, storageAddress, blockSize, (unsigned char*)configurationBlock, true);\n\n if(success == TRUE && requiresEnumeration)\n {\n \/\/ free the current allocation(s)\n platform_free(g_TargetConfiguration.NetworkInterfaceConfigs);\n platform_free(g_TargetConfiguration.Wireless80211Configs);\n\n \/\/ perform enumeration of configuration blocks\n ConfigurationManager_EnumerateConfigurationBlocks();\n }\n\n return success;\n}\n\n\/\/ Updates a configuration block in the configuration flash sector\n\/\/ The flash sector has to be erased before writing the updated block\n\/\/ it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used\n__nfweak bool ConfigurationManager_UpdateConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex)\n{\n ByteAddress storageAddress;\n uint32_t blockOffset;\n uint8_t* blockAddressInCopy;\n uint32_t blockSize;\n bool success = FALSE;\n\n \/\/ config sector size\n int sizeOfConfigSector = (uint32_t)&__nanoConfig_end__ - (uint32_t)&__nanoConfig_start__;\n\n \/\/ allocate memory from CRT heap\n uint8_t* configSectorCopy = (uint8_t*)platform_malloc(sizeOfConfigSector);\n\n if(configSectorCopy != NULL)\n {\n \/\/ copy config sector from flash to RAM\n memcpy(configSectorCopy, &__nanoConfig_start__, sizeOfConfigSector);\n\n \/\/ find out the address for the config block to update in the configSectorCopy\n \/\/ because we are copying back the config block to flash and just replacing the config block content\n \/\/ the addresses in g_TargetConfiguration will remain the same\n \/\/ plus we can calculate the offset of the config block from g_TargetConfiguration\n if(configuration == DeviceConfigurationOption_Network)\n {\n \/\/ get storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_NetworkInterface);\n }\n else if(configuration == DeviceConfigurationOption_Wireless80211Network)\n {\n \/\/ storage address from block address\n storageAddress = (ByteAddress)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex];\n\n \/\/ set block size, in case it's not already set\n blockSize = sizeof(HAL_Configuration_Wireless80211);\n }\n else\n {\n \/\/ this not a valid configuration option to update, quit\n \/\/ free memory first\n platform_free(configSectorCopy);\n\n return FALSE;\n }\n \n \/\/ erase config sector\n if(STM32FlashDriver_EraseBlock(NULL, (uint32_t)&__nanoConfig_start__) == TRUE)\n {\n \/\/ flash block is erased\n\n \/\/ subtract the start address of config sector to get the offset\n blockOffset = storageAddress - (uint32_t)&__nanoConfig_start__;\n\n \/\/ set pointer to block to udpate\n blockAddressInCopy = configSectorCopy + blockOffset;\n \n \/\/ replace config block with new content by replacing memory\n memcpy(blockAddressInCopy, configSectorCopy, blockSize);\n\n \/\/ copy the config block copy back to the config block storage\n success = STM32FlashDriver_Write(NULL, (uint32_t)&__nanoConfig_start__, sizeOfConfigSector, (unsigned char*)configSectorCopy, true);\n }\n\n \/\/ free memory\n platform_free(configSectorCopy);\n }\n\n return success;\n}\n<|endoftext|>"} {"text":"\n *\n * This source file is subject to the MIT license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace hhpack\\typesafety;\n\nuse Exception;\n\nfinal class ApplicationResult\n{\n\n public function __construct(\n private ResultType $result = ResultType::Ok,\n private ?Exception $exception = null\n )\n {\n }\n\n public function isOk() : bool\n {\n return ResultType::Ok === $this->result;\n }\n\n public function isError() : bool\n {\n return ResultType::Error === $this->result;\n }\n\n public function displayError(Output $output) : void\n {\n if ($this->exception === null) {\n return;\n }\n $output->error($this->exception->getMessage());\n $output->error($this->exception->getTraceAsString());\n }\n\n public static function Ok() : this\n {\n return new static();\n }\n\n public static function Error(Exception $exception) : this\n {\n return new static(ResultType::Error, $exception);\n }\n\n}\nfix nullable member error\n *\n * This source file is subject to the MIT license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace hhpack\\typesafety;\n\nuse Exception;\n\nfinal class ApplicationResult\n{\n\n public function __construct(\n private ResultType $result = ResultType::Ok,\n private ?Exception $exception = null\n )\n {\n }\n\n public function isOk() : bool\n {\n return ResultType::Ok === $this->result;\n }\n\n public function isError() : bool\n {\n return ResultType::Error === $this->result;\n }\n\n public function displayError(Output $output) : void\n {\n if ($this->exception === null) {\n return;\n }\n $exception = $this->exception;\n $output->error($exception->getMessage());\n $output->error($exception->getTraceAsString());\n }\n\n public static function Ok() : this\n {\n return new static();\n }\n\n public static function Error(Exception $exception) : this\n {\n return new static(ResultType::Error, $exception);\n }\n\n}\n<|endoftext|>"} {"text":"\/\/===--- Pattern.cpp - Swift Language Pattern-Matching ASTs ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Pattern class and subclasses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/Pattern.h\"\n#include \"swift\/AST\/AST.h\"\n#include \"swift\/AST\/ASTWalker.h\"\n#include \"swift\/AST\/TypeLoc.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace swift;\n\n\/\/\/ Diagnostic printing of PatternKinds.\nllvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS, PatternKind kind) {\n switch (kind) {\n case PatternKind::Paren:\n return OS << \"parenthesized pattern\";\n case PatternKind::Tuple:\n return OS << \"tuple pattern\";\n case PatternKind::Named:\n return OS << \"pattern variable binding\";\n case PatternKind::Any:\n return OS << \"'_' pattern\";\n case PatternKind::Typed:\n return OS << \"pattern type annotation\";\n case PatternKind::Is:\n return OS << \"prefix 'is' pattern\";\n case PatternKind::Expr:\n return OS << \"expression pattern\";\n case PatternKind::Var:\n return OS << \"'var' binding pattern\";\n case PatternKind::EnumElement:\n return OS << \"enum case matching pattern\";\n case PatternKind::OptionalSome:\n return OS << \"optional .Some matching pattern\";\n case PatternKind::Bool:\n return OS << \"bool matching pattern\";\n }\n llvm_unreachable(\"bad PatternKind\");\n}\n\nStringRef Pattern::getKindName(PatternKind K) {\n switch (K) {\n#define PATTERN(Id, Parent) case PatternKind::Id: return #Id;\n#include \"swift\/AST\/PatternNodes.def\"\n }\n llvm_unreachable(\"bad PatternKind\");\n}\n\n\/\/ Metaprogram to verify that every concrete class implements\n\/\/ a 'static bool classof(const Pattern*)'.\ntemplate struct CheckClassOfPattern {\n static const bool IsImplemented = true;\n};\ntemplate <> struct CheckClassOfPattern {\n static const bool IsImplemented = false;\n};\n\n#define PATTERN(ID, PARENT) \\\nstatic_assert(CheckClassOfPattern::IsImplemented, \\\n #ID \"Pattern is missing classof(const Pattern*)\");\n#include \"swift\/AST\/PatternNodes.def\"\n\n\/\/ Metaprogram to verify that every concrete class implements\n\/\/ 'SourceRange getSourceRange()'.\ntypedef const char (&TwoChars)[2];\ntemplate \ninline char checkSourceRangeType(SourceRange (Class::*)() const);\ninline TwoChars checkSourceRangeType(SourceRange (Pattern::*)() const);\n\n\/\/\/ getSourceRange - Return the full source range of the pattern.\nSourceRange Pattern::getSourceRange() const {\n switch (getKind()) {\n#define PATTERN(ID, PARENT) \\\ncase PatternKind::ID: \\\nstatic_assert(sizeof(checkSourceRangeType(&ID##Pattern::getSourceRange)) == 1, \\\n #ID \"Pattern is missing getSourceRange()\"); \\\nreturn cast(this)->getSourceRange();\n#include \"swift\/AST\/PatternNodes.def\"\n }\n \n llvm_unreachable(\"pattern type not handled!\");\n}\n\n\/\/\/ getLoc - Return the caret location of the pattern.\nSourceLoc Pattern::getLoc() const {\n switch (getKind()) {\n#define PATTERN(ID, PARENT) \\\n case PatternKind::ID: \\\n if (&Pattern::getLoc != &ID##Pattern::getLoc) \\\n return cast(this)->getLoc(); \\\n break;\n#include \"swift\/AST\/PatternNodes.def\"\n }\n\n return getStartLoc();\n}\n\nvoid Pattern::collectVariables(SmallVectorImpl &variables) const {\n forEachVariable([&](VarDecl *VD) { variables.push_back(VD); });\n}\n\nVarDecl *Pattern::getSingleVar() const {\n auto pattern = getSemanticsProvidingPattern();\n if (auto named = dyn_cast(pattern))\n return named->getDecl();\n\n return nullptr;\n}\n\nnamespace {\n class WalkToVarDecls : public ASTWalker {\n const std::function &fn;\n public:\n \n WalkToVarDecls(const std::function &fn)\n : fn(fn) {}\n \n Pattern *walkToPatternPost(Pattern *P) override {\n \/\/ Handle vars.\n if (auto *Named = dyn_cast(P))\n fn(Named->getDecl());\n return P;\n }\n };\n}\n\n\n\/\/\/ \\brief apply the specified function to all variables referenced in this\n\/\/\/ pattern.\nvoid Pattern::forEachVariable(const std::function &fn) const {\n switch (getKind()) {\n case PatternKind::Any:\n case PatternKind::Bool:\n return;\n\n case PatternKind::Is:\n if (auto SP = cast(this)->getSubPattern())\n SP->forEachVariable(fn);\n return;\n\n case PatternKind::Named:\n fn(cast(this)->getDecl());\n return;\n\n case PatternKind::Paren:\n case PatternKind::Typed:\n case PatternKind::Var:\n return getSemanticsProvidingPattern()->forEachVariable(fn);\n\n case PatternKind::Tuple:\n for (auto elt : cast(this)->getElements())\n elt.getPattern()->forEachVariable(fn);\n return;\n\n case PatternKind::EnumElement:\n if (auto SP = cast(this)->getSubPattern())\n SP->forEachVariable(fn);\n return;\n\n case PatternKind::OptionalSome:\n cast(this)->getSubPattern()->forEachVariable(fn);\n return;\n\n case PatternKind::Expr:\n \/\/ An ExprPattern only exists before sema has resolved a refutable pattern\n \/\/ into a concrete pattern. We have to use an AST Walker to find the\n \/\/ VarDecls buried down inside of it.\n const_cast(this)->walk(WalkToVarDecls(fn));\n return;\n }\n}\n\n\/\/\/ \\brief apply the specified function to all pattern nodes recursively in\n\/\/\/ this pattern. This is a pre-order traversal.\nvoid Pattern::forEachNode(const std::function &f) {\n f(this);\n\n switch (getKind()) {\n \/\/ Leaf patterns have no recursion.\n case PatternKind::Any:\n case PatternKind::Named:\n case PatternKind::Expr:\/\/ FIXME: expr nodes are not modeled right in general.\n case PatternKind::Bool:\n return;\n\n case PatternKind::Is:\n if (auto SP = cast(this)->getSubPattern())\n SP->forEachNode(f);\n return;\n\n case PatternKind::Paren:\n return cast(this)->getSubPattern()->forEachNode(f);\n case PatternKind::Typed:\n return cast(this)->getSubPattern()->forEachNode(f);\n case PatternKind::Var:\n return cast(this)->getSubPattern()->forEachNode(f);\n\n case PatternKind::Tuple:\n for (auto elt : cast(this)->getElements())\n elt.getPattern()->forEachNode(f);\n return;\n\n case PatternKind::EnumElement: {\n auto *OP = cast(this);\n if (OP->hasSubPattern())\n OP->getSubPattern()->forEachNode(f);\n return;\n }\n case PatternKind::OptionalSome:\n cast(this)->getSubPattern()->forEachNode(f);\n return;\n }\n}\n\nbool Pattern::hasStorage() const {\n bool HasStorage = false;\n forEachVariable([&](VarDecl *VD) {\n if (VD->hasStorage())\n HasStorage = true;\n });\n\n return HasStorage;\n}\n\n\/\/\/ Return true if this is a non-resolved ExprPattern which is syntactically\n\/\/\/ irrefutable.\nstatic bool isIrrefutableExprPattern(const ExprPattern *EP) {\n \/\/ If the pattern has a registered match expression, it's\n \/\/ a type-checked ExprPattern.\n if (EP->getMatchExpr()) return false;\n\n auto expr = EP->getSubExpr();\n while (true) {\n \/\/ Drill into parens.\n if (auto parens = dyn_cast(expr)) {\n expr = parens->getSubExpr();\n continue;\n }\n\n \/\/ A '_' is an untranslated AnyPattern.\n if (isa(expr))\n return true;\n\n \/\/ Everything else is non-exhaustive.\n return false;\n }\n}\n\n\/\/\/ Return true if this pattern (or a subpattern) is refutable.\nbool Pattern::isRefutablePattern() const {\n bool foundRefutablePattern = false;\n const_cast(this)->forEachNode([&](Pattern *Node) {\n\n \/\/ If this is an always matching 'is' pattern, then it isn't refutable.\n if (auto *is = dyn_cast(Node))\n if (is->getCastKind() == CheckedCastKind::Coercion)\n return;\n\n \/\/ If this is an ExprPattern that isn't resolved yet, do some simple\n \/\/ syntactic checks.\n \/\/ FIXME: This is unsound, since type checking will turn other more\n \/\/ complicated patterns into non-refutable forms.\n if (auto *ep = dyn_cast(Node))\n if (isIrrefutableExprPattern(ep))\n return;\n\n switch (Node->getKind()) {\n#define PATTERN(ID, PARENT) case PatternKind::ID: break;\n#define REFUTABLE_PATTERN(ID, PARENT) \\\ncase PatternKind::ID: foundRefutablePattern = true; break;\n#include \"swift\/AST\/PatternNodes.def\"\n }\n });\n \n return foundRefutablePattern;\n}\n\n\/\/\/ Standard allocator for Patterns.\nvoid *Pattern::operator new(size_t numBytes, const ASTContext &C) {\n return C.Allocate(numBytes, alignof(Pattern));\n}\n\n\/\/\/ Find the name directly bound by this pattern. When used as a\n\/\/\/ tuple element in a function signature, such names become part of\n\/\/\/ the type.\nIdentifier Pattern::getBoundName() const {\n if (auto *NP = dyn_cast(getSemanticsProvidingPattern()))\n return NP->getBoundName();\n return Identifier();\n}\n\nIdentifier NamedPattern::getBoundName() const {\n return Var->getName();\n}\n\n\n\/\/\/ Allocate a new pattern that matches a tuple.\nTuplePattern *TuplePattern::create(ASTContext &C, SourceLoc lp,\n ArrayRef elts, SourceLoc rp,\n Optional implicit) {\n if (!implicit.hasValue())\n implicit = !lp.isValid();\n\n unsigned n = elts.size();\n void *buffer = C.Allocate(totalSizeToAlloc(n),\n alignof(TuplePattern));\n TuplePattern *pattern = ::new (buffer) TuplePattern(lp, n, rp, *implicit);\n std::uninitialized_copy(elts.begin(), elts.end(),\n pattern->getTrailingObjects());\n return pattern;\n}\n\nPattern *TuplePattern::createSimple(ASTContext &C, SourceLoc lp,\n ArrayRef elements,\n SourceLoc rp,\n Optional implicit) {\n assert(lp.isValid() == rp.isValid());\n\n if (elements.size() == 1 &&\n elements[0].getPattern()->getBoundName().empty()) {\n auto &first = const_cast(elements.front());\n return new (C) ParenPattern(lp, first.getPattern(), rp, implicit);\n }\n\n return create(C, lp, elements, rp, implicit);\n}\n\nSourceRange TuplePattern::getSourceRange() const {\n if (LPLoc.isValid())\n return { LPLoc, RPLoc };\n auto Fields = getElements();\n if (Fields.empty())\n return {};\n return { Fields.front().getPattern()->getStartLoc(),\n Fields.back().getPattern()->getEndLoc() };\n}\n\nSourceRange TypedPattern::getSourceRange() const {\n if (isImplicit()) {\n \/\/ If a TypedPattern is implicit, then its type is definitely implicit, so\n \/\/ we should ignore its location. On the other hand, the sub-pattern can\n \/\/ be explicit or implicit.\n return SubPattern->getSourceRange();\n }\n\n if (SubPattern->isImplicit())\n return PatType.getSourceRange();\n\n return { SubPattern->getSourceRange().Start, PatType.getSourceRange().End };\n}\n\n[AST] Don’t include propagated type locations in the source range of a type pattern.\/\/===--- Pattern.cpp - Swift Language Pattern-Matching ASTs ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Pattern class and subclasses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/Pattern.h\"\n#include \"swift\/AST\/AST.h\"\n#include \"swift\/AST\/ASTWalker.h\"\n#include \"swift\/AST\/TypeLoc.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace swift;\n\n\/\/\/ Diagnostic printing of PatternKinds.\nllvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS, PatternKind kind) {\n switch (kind) {\n case PatternKind::Paren:\n return OS << \"parenthesized pattern\";\n case PatternKind::Tuple:\n return OS << \"tuple pattern\";\n case PatternKind::Named:\n return OS << \"pattern variable binding\";\n case PatternKind::Any:\n return OS << \"'_' pattern\";\n case PatternKind::Typed:\n return OS << \"pattern type annotation\";\n case PatternKind::Is:\n return OS << \"prefix 'is' pattern\";\n case PatternKind::Expr:\n return OS << \"expression pattern\";\n case PatternKind::Var:\n return OS << \"'var' binding pattern\";\n case PatternKind::EnumElement:\n return OS << \"enum case matching pattern\";\n case PatternKind::OptionalSome:\n return OS << \"optional .Some matching pattern\";\n case PatternKind::Bool:\n return OS << \"bool matching pattern\";\n }\n llvm_unreachable(\"bad PatternKind\");\n}\n\nStringRef Pattern::getKindName(PatternKind K) {\n switch (K) {\n#define PATTERN(Id, Parent) case PatternKind::Id: return #Id;\n#include \"swift\/AST\/PatternNodes.def\"\n }\n llvm_unreachable(\"bad PatternKind\");\n}\n\n\/\/ Metaprogram to verify that every concrete class implements\n\/\/ a 'static bool classof(const Pattern*)'.\ntemplate struct CheckClassOfPattern {\n static const bool IsImplemented = true;\n};\ntemplate <> struct CheckClassOfPattern {\n static const bool IsImplemented = false;\n};\n\n#define PATTERN(ID, PARENT) \\\nstatic_assert(CheckClassOfPattern::IsImplemented, \\\n #ID \"Pattern is missing classof(const Pattern*)\");\n#include \"swift\/AST\/PatternNodes.def\"\n\n\/\/ Metaprogram to verify that every concrete class implements\n\/\/ 'SourceRange getSourceRange()'.\ntypedef const char (&TwoChars)[2];\ntemplate \ninline char checkSourceRangeType(SourceRange (Class::*)() const);\ninline TwoChars checkSourceRangeType(SourceRange (Pattern::*)() const);\n\n\/\/\/ getSourceRange - Return the full source range of the pattern.\nSourceRange Pattern::getSourceRange() const {\n switch (getKind()) {\n#define PATTERN(ID, PARENT) \\\ncase PatternKind::ID: \\\nstatic_assert(sizeof(checkSourceRangeType(&ID##Pattern::getSourceRange)) == 1, \\\n #ID \"Pattern is missing getSourceRange()\"); \\\nreturn cast(this)->getSourceRange();\n#include \"swift\/AST\/PatternNodes.def\"\n }\n \n llvm_unreachable(\"pattern type not handled!\");\n}\n\n\/\/\/ getLoc - Return the caret location of the pattern.\nSourceLoc Pattern::getLoc() const {\n switch (getKind()) {\n#define PATTERN(ID, PARENT) \\\n case PatternKind::ID: \\\n if (&Pattern::getLoc != &ID##Pattern::getLoc) \\\n return cast(this)->getLoc(); \\\n break;\n#include \"swift\/AST\/PatternNodes.def\"\n }\n\n return getStartLoc();\n}\n\nvoid Pattern::collectVariables(SmallVectorImpl &variables) const {\n forEachVariable([&](VarDecl *VD) { variables.push_back(VD); });\n}\n\nVarDecl *Pattern::getSingleVar() const {\n auto pattern = getSemanticsProvidingPattern();\n if (auto named = dyn_cast(pattern))\n return named->getDecl();\n\n return nullptr;\n}\n\nnamespace {\n class WalkToVarDecls : public ASTWalker {\n const std::function &fn;\n public:\n \n WalkToVarDecls(const std::function &fn)\n : fn(fn) {}\n \n Pattern *walkToPatternPost(Pattern *P) override {\n \/\/ Handle vars.\n if (auto *Named = dyn_cast(P))\n fn(Named->getDecl());\n return P;\n }\n };\n}\n\n\n\/\/\/ \\brief apply the specified function to all variables referenced in this\n\/\/\/ pattern.\nvoid Pattern::forEachVariable(const std::function &fn) const {\n switch (getKind()) {\n case PatternKind::Any:\n case PatternKind::Bool:\n return;\n\n case PatternKind::Is:\n if (auto SP = cast(this)->getSubPattern())\n SP->forEachVariable(fn);\n return;\n\n case PatternKind::Named:\n fn(cast(this)->getDecl());\n return;\n\n case PatternKind::Paren:\n case PatternKind::Typed:\n case PatternKind::Var:\n return getSemanticsProvidingPattern()->forEachVariable(fn);\n\n case PatternKind::Tuple:\n for (auto elt : cast(this)->getElements())\n elt.getPattern()->forEachVariable(fn);\n return;\n\n case PatternKind::EnumElement:\n if (auto SP = cast(this)->getSubPattern())\n SP->forEachVariable(fn);\n return;\n\n case PatternKind::OptionalSome:\n cast(this)->getSubPattern()->forEachVariable(fn);\n return;\n\n case PatternKind::Expr:\n \/\/ An ExprPattern only exists before sema has resolved a refutable pattern\n \/\/ into a concrete pattern. We have to use an AST Walker to find the\n \/\/ VarDecls buried down inside of it.\n const_cast(this)->walk(WalkToVarDecls(fn));\n return;\n }\n}\n\n\/\/\/ \\brief apply the specified function to all pattern nodes recursively in\n\/\/\/ this pattern. This is a pre-order traversal.\nvoid Pattern::forEachNode(const std::function &f) {\n f(this);\n\n switch (getKind()) {\n \/\/ Leaf patterns have no recursion.\n case PatternKind::Any:\n case PatternKind::Named:\n case PatternKind::Expr:\/\/ FIXME: expr nodes are not modeled right in general.\n case PatternKind::Bool:\n return;\n\n case PatternKind::Is:\n if (auto SP = cast(this)->getSubPattern())\n SP->forEachNode(f);\n return;\n\n case PatternKind::Paren:\n return cast(this)->getSubPattern()->forEachNode(f);\n case PatternKind::Typed:\n return cast(this)->getSubPattern()->forEachNode(f);\n case PatternKind::Var:\n return cast(this)->getSubPattern()->forEachNode(f);\n\n case PatternKind::Tuple:\n for (auto elt : cast(this)->getElements())\n elt.getPattern()->forEachNode(f);\n return;\n\n case PatternKind::EnumElement: {\n auto *OP = cast(this);\n if (OP->hasSubPattern())\n OP->getSubPattern()->forEachNode(f);\n return;\n }\n case PatternKind::OptionalSome:\n cast(this)->getSubPattern()->forEachNode(f);\n return;\n }\n}\n\nbool Pattern::hasStorage() const {\n bool HasStorage = false;\n forEachVariable([&](VarDecl *VD) {\n if (VD->hasStorage())\n HasStorage = true;\n });\n\n return HasStorage;\n}\n\n\/\/\/ Return true if this is a non-resolved ExprPattern which is syntactically\n\/\/\/ irrefutable.\nstatic bool isIrrefutableExprPattern(const ExprPattern *EP) {\n \/\/ If the pattern has a registered match expression, it's\n \/\/ a type-checked ExprPattern.\n if (EP->getMatchExpr()) return false;\n\n auto expr = EP->getSubExpr();\n while (true) {\n \/\/ Drill into parens.\n if (auto parens = dyn_cast(expr)) {\n expr = parens->getSubExpr();\n continue;\n }\n\n \/\/ A '_' is an untranslated AnyPattern.\n if (isa(expr))\n return true;\n\n \/\/ Everything else is non-exhaustive.\n return false;\n }\n}\n\n\/\/\/ Return true if this pattern (or a subpattern) is refutable.\nbool Pattern::isRefutablePattern() const {\n bool foundRefutablePattern = false;\n const_cast(this)->forEachNode([&](Pattern *Node) {\n\n \/\/ If this is an always matching 'is' pattern, then it isn't refutable.\n if (auto *is = dyn_cast(Node))\n if (is->getCastKind() == CheckedCastKind::Coercion)\n return;\n\n \/\/ If this is an ExprPattern that isn't resolved yet, do some simple\n \/\/ syntactic checks.\n \/\/ FIXME: This is unsound, since type checking will turn other more\n \/\/ complicated patterns into non-refutable forms.\n if (auto *ep = dyn_cast(Node))\n if (isIrrefutableExprPattern(ep))\n return;\n\n switch (Node->getKind()) {\n#define PATTERN(ID, PARENT) case PatternKind::ID: break;\n#define REFUTABLE_PATTERN(ID, PARENT) \\\ncase PatternKind::ID: foundRefutablePattern = true; break;\n#include \"swift\/AST\/PatternNodes.def\"\n }\n });\n \n return foundRefutablePattern;\n}\n\n\/\/\/ Standard allocator for Patterns.\nvoid *Pattern::operator new(size_t numBytes, const ASTContext &C) {\n return C.Allocate(numBytes, alignof(Pattern));\n}\n\n\/\/\/ Find the name directly bound by this pattern. When used as a\n\/\/\/ tuple element in a function signature, such names become part of\n\/\/\/ the type.\nIdentifier Pattern::getBoundName() const {\n if (auto *NP = dyn_cast(getSemanticsProvidingPattern()))\n return NP->getBoundName();\n return Identifier();\n}\n\nIdentifier NamedPattern::getBoundName() const {\n return Var->getName();\n}\n\n\n\/\/\/ Allocate a new pattern that matches a tuple.\nTuplePattern *TuplePattern::create(ASTContext &C, SourceLoc lp,\n ArrayRef elts, SourceLoc rp,\n Optional implicit) {\n if (!implicit.hasValue())\n implicit = !lp.isValid();\n\n unsigned n = elts.size();\n void *buffer = C.Allocate(totalSizeToAlloc(n),\n alignof(TuplePattern));\n TuplePattern *pattern = ::new (buffer) TuplePattern(lp, n, rp, *implicit);\n std::uninitialized_copy(elts.begin(), elts.end(),\n pattern->getTrailingObjects());\n return pattern;\n}\n\nPattern *TuplePattern::createSimple(ASTContext &C, SourceLoc lp,\n ArrayRef elements,\n SourceLoc rp,\n Optional implicit) {\n assert(lp.isValid() == rp.isValid());\n\n if (elements.size() == 1 &&\n elements[0].getPattern()->getBoundName().empty()) {\n auto &first = const_cast(elements.front());\n return new (C) ParenPattern(lp, first.getPattern(), rp, implicit);\n }\n\n return create(C, lp, elements, rp, implicit);\n}\n\nSourceRange TuplePattern::getSourceRange() const {\n if (LPLoc.isValid())\n return { LPLoc, RPLoc };\n auto Fields = getElements();\n if (Fields.empty())\n return {};\n return { Fields.front().getPattern()->getStartLoc(),\n Fields.back().getPattern()->getEndLoc() };\n}\n\nSourceRange TypedPattern::getSourceRange() const {\n if (isImplicit() || isPropagatedType()) {\n \/\/ If a TypedPattern is implicit, then its type is definitely implicit, so\n \/\/ we should ignore its location. On the other hand, the sub-pattern can\n \/\/ be explicit or implicit.\n return SubPattern->getSourceRange();\n }\n\n if (SubPattern->isImplicit())\n return PatType.getSourceRange();\n\n return { SubPattern->getSourceRange().Start, PatType.getSourceRange().End };\n}\n\n<|endoftext|>"} {"text":"\/\/ SciTE - Scintilla based Text Editor\n\/** @file Cookie.cxx\n ** Examine start of files for coding cookies and type information.\n **\/\n\/\/ Copyright 2011 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n\n#include \n#include \n\n#include \"Scintilla.h\"\n\n#include \"GUI.h\"\n\n#include \"StringHelpers.h\"\n#include \"Cookie.h\"\n\nstd::string ExtractLine(const char *buf, size_t length) {\n\tunsigned int endl = 0;\n\tif (length > 0) {\n\t\twhile ((endl < length) && (buf[endl] != '\\r') && (buf[endl] != '\\n')) {\n\t\t\tendl++;\n\t\t}\n\t\tif (((endl + 1) < length) && (buf[endl] == '\\r') && (buf[endl+1] == '\\n')) {\n\t\t\tendl++;\n\t\t}\n\t\tif (endl < length) {\n\t\t\tendl++;\n\t\t}\n\t}\n\treturn std::string(buf, 0, endl);\n}\n\nstatic const char codingCookie[] = \"coding\";\n\nstatic bool isEncodingChar(char ch) {\n\treturn (ch == '_') || (ch == '-') || (ch == '.') ||\n\t (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||\n\t (ch >= '0' && ch <= '9');\n}\n\nstatic bool isSpaceChar(char ch) {\n\treturn (ch == ' ') || (ch == '\\t');\n}\n\nstatic UniMode CookieValue(const std::string &s) {\n\tsize_t posCoding = s.find(codingCookie);\n\tif (posCoding != std::string::npos) {\n\t\tposCoding += strlen(codingCookie);\n\t\tif ((s[posCoding] == ':') || (s[posCoding] == '=')) {\n\t\t\tposCoding++;\n\t\t\tif ((s[posCoding] == '\\\"') || (s[posCoding] == '\\'')) {\n\t\t\t\tposCoding++;\n\t\t\t}\n\t\t\twhile ((posCoding < s.length()) &&\n\t\t\t (isSpaceChar(s[posCoding]))) {\n\t\t\t\tposCoding++;\n\t\t\t}\n\t\t\tsize_t endCoding = posCoding;\n\t\t\twhile ((endCoding < s.length()) &&\n\t\t\t (isEncodingChar(s[endCoding]))) {\n\t\t\t\tendCoding++;\n\t\t\t}\n\t\t\tstd::string code(s, posCoding, endCoding-posCoding);\n\t\t\tLowerCaseAZ(code);\n\t\t\tif (code == \"utf-8\") {\n\t\t\t\treturn uniCookie;\n\t\t\t}\n\t\t}\n\t}\n\treturn uni8Bit;\n}\n\nUniMode CodingCookieValue(const char *buf, size_t length) {\n\tstd::string l1 = ExtractLine(buf, length);\n\tUniMode unicodeMode = CookieValue(l1);\n\tif (unicodeMode == uni8Bit) {\n\t\tstd::string l2 = ExtractLine(buf + l1.length(), length - l1.length());\n\t\tunicodeMode = CookieValue(l2);\n\t}\n\treturn unicodeMode;\n}\n\nInvoke the correct constructor. The only 3 argument std::string constructor is (const string& str, size_t pos, size_t len = npos). This requires a std::string first arg, not a char* so the char* is converted to std::string with the single argument constructor which depends on a NUL terminator. When the file being opened is larger than the buffer size (128K) there is no NUL and the call fails.\/\/ SciTE - Scintilla based Text Editor\n\/** @file Cookie.cxx\n ** Examine start of files for coding cookies and type information.\n **\/\n\/\/ Copyright 2011 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n\n#include \n#include \n\n#include \"Scintilla.h\"\n\n#include \"GUI.h\"\n\n#include \"StringHelpers.h\"\n#include \"Cookie.h\"\n\nstd::string ExtractLine(const char *buf, size_t length) {\n\tunsigned int endl = 0;\n\tif (length > 0) {\n\t\twhile ((endl < length) && (buf[endl] != '\\r') && (buf[endl] != '\\n')) {\n\t\t\tendl++;\n\t\t}\n\t\tif (((endl + 1) < length) && (buf[endl] == '\\r') && (buf[endl+1] == '\\n')) {\n\t\t\tendl++;\n\t\t}\n\t\tif (endl < length) {\n\t\t\tendl++;\n\t\t}\n\t}\n\treturn std::string(buf, endl);\n}\n\nstatic const char codingCookie[] = \"coding\";\n\nstatic bool isEncodingChar(char ch) {\n\treturn (ch == '_') || (ch == '-') || (ch == '.') ||\n\t (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||\n\t (ch >= '0' && ch <= '9');\n}\n\nstatic bool isSpaceChar(char ch) {\n\treturn (ch == ' ') || (ch == '\\t');\n}\n\nstatic UniMode CookieValue(const std::string &s) {\n\tsize_t posCoding = s.find(codingCookie);\n\tif (posCoding != std::string::npos) {\n\t\tposCoding += strlen(codingCookie);\n\t\tif ((s[posCoding] == ':') || (s[posCoding] == '=')) {\n\t\t\tposCoding++;\n\t\t\tif ((s[posCoding] == '\\\"') || (s[posCoding] == '\\'')) {\n\t\t\t\tposCoding++;\n\t\t\t}\n\t\t\twhile ((posCoding < s.length()) &&\n\t\t\t (isSpaceChar(s[posCoding]))) {\n\t\t\t\tposCoding++;\n\t\t\t}\n\t\t\tsize_t endCoding = posCoding;\n\t\t\twhile ((endCoding < s.length()) &&\n\t\t\t (isEncodingChar(s[endCoding]))) {\n\t\t\t\tendCoding++;\n\t\t\t}\n\t\t\tstd::string code(s, posCoding, endCoding-posCoding);\n\t\t\tLowerCaseAZ(code);\n\t\t\tif (code == \"utf-8\") {\n\t\t\t\treturn uniCookie;\n\t\t\t}\n\t\t}\n\t}\n\treturn uni8Bit;\n}\n\nUniMode CodingCookieValue(const char *buf, size_t length) {\n\tstd::string l1 = ExtractLine(buf, length);\n\tUniMode unicodeMode = CookieValue(l1);\n\tif (unicodeMode == uni8Bit) {\n\t\tstd::string l2 = ExtractLine(buf + l1.length(), length - l1.length());\n\t\tunicodeMode = CookieValue(l2);\n\t}\n\treturn unicodeMode;\n}\n\n<|endoftext|>"} {"text":"#if (TARGET_OS_WATCH != 1)\n\n#include \"braincloud\/internal\/DefaultWebSocket.h\"\n\n#include \n#include \n#include \n\n#define MAX_PAYLOAD (64 * 1024)\n\nstatic std::mutex lwsContextMutex;\n\nnamespace BrainCloud\n{\n static struct lws_protocols protocols[] = {\n {\n \"brainCloud\",\n &DefaultWebSocket::libWebsocketsCallback,\n 0,\n MAX_PAYLOAD,\n 0, NULL, 0\n },\n { NULL, NULL, 0, 0 } \/* terminator *\/\n };\n\n static const struct lws_extension exts[] = {\n {\n \"permessage-deflate\",\n lws_extension_callback_pm_deflate,\n \"permessage-deflate; client_no_context_takeover\"\n },\n {\n \"deflate-frame\",\n lws_extension_callback_pm_deflate,\n \"deflate_frame\"\n },\n { NULL, NULL, NULL \/* terminator *\/ }\n };\n\n IWebSocket* IWebSocket::create(const std::string& address, int port, const std::map& headers)\n {\n return new DefaultWebSocket(address, port, headers);\n }\n\n \/\/struct lws_context* DefaultWebSocket::_pLwsContext = NULL;\n\n DefaultWebSocket::~DefaultWebSocket()\n {\n close();\n }\n\n DefaultWebSocket::DefaultWebSocket(const std::string& uri, int port, const std::map& headers)\n : _isValid(false)\n , _pLwsContext(NULL)\n , _pLws(NULL)\n , _isConnecting(true)\n , _authHeaders(headers)\n {\n std::string uriCopy = uri;\n \n \/\/ Split address into host\/addr\/origin\/protocol\n std::string protocol = uriCopy.substr(0, std::min(uriCopy.size(), uriCopy.find_first_of(':')));\n size_t protocolSize = protocol.size() + 3;\n size_t argsPos = std::min(uriCopy.size(), uriCopy.find_first_of('?', protocolSize));\n if (uriCopy[argsPos - 1] != '\/')\n {\n uriCopy.insert(uriCopy.begin() + argsPos, '\/');\n }\n size_t slashPos = std::min(uriCopy.size(), uriCopy.find_first_of('\/', protocolSize));\n std::string path = uriCopy.substr(slashPos);\n if (path.empty())\n {\n path = \"\/\";\n }\n std::string addr = uriCopy.substr(protocolSize, slashPos - protocolSize);\n std::string host = addr;\n std::string origin = host + \":\" + std::to_string(port);\n\n \/\/ Validate\n std::string protocolCaps = protocol;\n std::transform(protocol.begin(), protocol.end(), protocolCaps.begin(), [](unsigned char c){ return std::toupper(c); });\n if (protocolCaps != \"WS\" && protocolCaps != \"WSS\")\n {\n std::cout << \"Invalid websocket protocol: \" << protocol << std::endl;\n return;\n }\n bool useSSL = protocolCaps == \"WSS\";\n\n \/\/ Create context\n \/\/if (!_pLwsContext)\n {\n struct lws_context_creation_info info;\n memset(&info, 0, sizeof info);\n\n info.port = CONTEXT_PORT_NO_LISTEN;\n info.protocols = protocols;\n info.gid = -1;\n info.uid = -1;\n info.extensions = exts;\n info.options = LWS_SERVER_OPTION_VALIDATE_UTF8;\n info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;\n\n std::unique_lock lock(lwsContextMutex);\n _pLwsContext = lws_create_context(&info);\n if (!_pLwsContext)\n {\n std::cout << \"Failed to create websocket context\" << std::endl;\n return;\n }\n }\n\n \/\/ Start update thread\n _updateThread = std::thread([this]()\n {\n _mutex.lock();\n while (_isConnecting || _isValid)\n {\n _mutex.unlock();\n lws_callback_on_writable_all_protocol(_pLwsContext, &protocols[0]);\n lws_service(_pLwsContext, 100);\n _mutex.lock();\n }\n _mutex.unlock();\n });\n\n \/\/ Create connection\n {\n struct lws_client_connect_info connectInfo;\n memset(&connectInfo, 0, sizeof(connectInfo));\n\n connectInfo.context = _pLwsContext;\n connectInfo.address = addr.c_str();\n connectInfo.port = port;\n if (useSSL)\n {\n connectInfo.ssl_connection = \n LCCSCF_USE_SSL\n#if defined(BC_SSL_ALLOW_SELFSIGNED)\n | LCCSCF_ALLOW_SELFSIGNED\n#endif\n \/\/ | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK\n \/\/ | LCCSCF_ALLOW_EXPIRED\n ;\n }\n else\n {\n connectInfo.ssl_connection = 0;\n }\n connectInfo.path = path.c_str();\n connectInfo.host = host.c_str();\n connectInfo.origin = origin.c_str();\n connectInfo.protocol = protocols[0].name;\n connectInfo.ietf_version_or_minus_one = -1;\n connectInfo.userdata = this;\n\n _pLws = lws_client_connect_via_info(&connectInfo);\n if (!_pLws)\n {\n std::cout << \"Failed to create websocket context\" << std::endl;\n return;\n }\n }\n }\n\n int DefaultWebSocket::libWebsocketsCallback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len)\n {\n DefaultWebSocket *pWebSocket = (DefaultWebSocket *)lws_wsi_user(wsi);\n\n switch (reason)\n {\n case LWS_CALLBACK_WSI_DESTROY:\n case LWS_CALLBACK_CLOSED_CLIENT_HTTP:\n case LWS_CALLBACK_CLOSED:\n {\n if (!pWebSocket)\n {\n return -1;\n }\n pWebSocket->onClose();\n break;\n }\n case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:\n {\n if (!pWebSocket || !in)\n {\n return -1;\n }\n pWebSocket->onError((const char*)in);\n break;\n }\n case LWS_CALLBACK_CLIENT_ESTABLISHED:\n {\n if (!pWebSocket)\n {\n return -1;\n }\n pWebSocket->onConnect();\n break;\n }\n case LWS_CALLBACK_CLIENT_RECEIVE:\n {\n if (!pWebSocket || !in)\n {\n return -1;\n }\n pWebSocket->onRecv((const char*)in, (int)len);\n break;\n }\n case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:\n {\n if (!pWebSocket || !in)\n {\n return -1;\n }\n\n unsigned char **p = (unsigned char **)in;\n unsigned char *end = (*p) + len;\n if (!pWebSocket->onProcessHeaders(p, end))\n {\n return -1;\n }\n break;\n }\n case LWS_CALLBACK_CLIENT_WRITEABLE:\n {\n if (!pWebSocket)\n {\n return -1;\n }\n pWebSocket->processSendQueue();\n break;\n }\n default:\n break;\n }\n\n return 0;\n }\n\n bool DefaultWebSocket::isValid()\n {\n std::unique_lock lock(_mutex);\n\n if (_isConnecting)\n {\n _connectionCondition.wait(lock, [this]() { return !_isConnecting; });\n }\n\n return _isValid;\n }\n\n void DefaultWebSocket::send(const std::string& message)\n {\n std::unique_lock lock(_mutex);\n _sendQueue.push(message);\n }\n\n void DefaultWebSocket::processSendQueue()\n {\n std::unique_lock lock(_mutex);\n while (!_sendQueue.empty())\n {\n const std::string& message = _sendQueue.front();\n\n _sendBuffer.resize(LWS_PRE + message.size());\n memcpy(_sendBuffer.data() + LWS_PRE, message.c_str(), message.size());\n lws_write(_pLws, _sendBuffer.data() + LWS_PRE, message.size(), LWS_WRITE_TEXT);\n\n _sendQueue.pop();\n }\n }\n\n std::string DefaultWebSocket::recv()\n {\n std::unique_lock lock(_recvMutex);\n\n if (!_recvQueue.empty())\n {\n std::string message = _recvQueue.front();\n _recvQueue.pop();\n return message;\n }\n\n _recvCondition.wait(lock, [this]()\n {\n return !_isValid || !_recvQueue.empty();\n });\n\n if (_isValid && !_recvQueue.empty())\n {\n std::string message = _recvQueue.front();\n _recvQueue.pop();\n return message;\n }\n\n return \"\";\n }\n\n void DefaultWebSocket::close()\n {\n \/\/ Stop and clean send queue\n {\n std::unique_lock lock(_mutex);\n while (!_sendQueue.empty()) _sendQueue.pop();\n _isValid = false;\n _isConnecting = false;\n _connectionCondition.notify_all();\n }\n\n \/\/ Stop and clean recving\n {\n std::unique_lock lock(_recvMutex);\n while (!_recvQueue.empty()) _recvQueue.pop();\n _recvCondition.notify_all();\n }\n\n \/\/ Join update thread\n if (_updateThread.joinable())\n {\n _updateThread.join();\n }\n\n \/\/ Destroy libWebSockets\n if (_pLws)\n {\n lws_set_timeout(_pLws, NO_PENDING_TIMEOUT, LWS_TO_KILL_SYNC);\n _pLws = NULL;\n }\n\n \/\/ Destroy the context\n if (_pLwsContext)\n {\n std::unique_lock lock(lwsContextMutex);\n lws_context_destroy(_pLwsContext);\n _pLwsContext = NULL;\n }\n }\n\n void DefaultWebSocket::onClose()\n {\n std::cout << \"WebSocket closed\" << std::endl;\n\n std::unique_lock lock(_mutex);\n _isValid = false;\n _isConnecting = false;\n _connectionCondition.notify_all();\n _pLws = NULL; \/\/ This is now invalid\n }\n\n void DefaultWebSocket::onError(const char* msg)\n {\n std::cout << \"WebSocket error: \" << msg << std::endl;\n\n std::unique_lock lock(_mutex);\n _isValid = false;\n _isConnecting = false;\n _connectionCondition.notify_all();\n _pLws = NULL; \/\/ This is now invalid\n }\n\n void DefaultWebSocket::onConnect()\n {\n std::cout << \"WebSocket Connected!\" << std::endl;\n\n std::unique_lock lock(_mutex);\n _isValid = true;\n _isConnecting = false;\n _connectionCondition.notify_all();\n }\n\n void DefaultWebSocket::onRecv(const char* buffer, int len)\n {\n std::unique_lock lock(_recvMutex);\n std::string message(buffer, len);\n _recvQueue.push(message);\n _recvCondition.notify_all();\n }\n\n bool DefaultWebSocket::onProcessHeaders(unsigned char** ppBuffer, unsigned char* pEnd)\n {\n if (_authHeaders.empty())\n {\n return true;\n }\n\n std::string key;\n\n for (std::map::iterator it = _authHeaders.begin(); it != _authHeaders.end(); ++it)\n {\n key = it->first;\n key += \":\";\n const std::string& value = it->second;\n\n if (lws_add_http_header_by_name(_pLws, (const unsigned char *)key.c_str(), (const unsigned char *)value.c_str(), (int)value.size(), ppBuffer, pEnd))\n {\n return false;\n }\n }\n\n return true;\n }\n};\n\n#endif\nFixed log for WS to make it easier to debug#if (TARGET_OS_WATCH != 1)\n\n#include \"braincloud\/internal\/DefaultWebSocket.h\"\n\n#include \n#include \n#include \n\n#define MAX_PAYLOAD (64 * 1024)\n\nstatic std::mutex lwsContextMutex;\n\nnamespace BrainCloud\n{\n static struct lws_protocols protocols[] = {\n {\n \"brainCloud\",\n &DefaultWebSocket::libWebsocketsCallback,\n 0,\n MAX_PAYLOAD,\n 0, NULL, 0\n },\n { NULL, NULL, 0, 0 } \/* terminator *\/\n };\n\n static const struct lws_extension exts[] = {\n {\n \"permessage-deflate\",\n lws_extension_callback_pm_deflate,\n \"permessage-deflate; client_no_context_takeover\"\n },\n {\n \"deflate-frame\",\n lws_extension_callback_pm_deflate,\n \"deflate_frame\"\n },\n { NULL, NULL, NULL \/* terminator *\/ }\n };\n\n IWebSocket* IWebSocket::create(const std::string& address, int port, const std::map& headers)\n {\n return new DefaultWebSocket(address, port, headers);\n }\n\n \/\/struct lws_context* DefaultWebSocket::_pLwsContext = NULL;\n\n DefaultWebSocket::~DefaultWebSocket()\n {\n close();\n }\n\n DefaultWebSocket::DefaultWebSocket(const std::string& uri, int port, const std::map& headers)\n : _isValid(false)\n , _pLwsContext(NULL)\n , _pLws(NULL)\n , _isConnecting(true)\n , _authHeaders(headers)\n {\n std::string uriCopy = uri;\n \n \/\/ Split address into host\/addr\/origin\/protocol\n std::string protocol = uriCopy.substr(0, std::min(uriCopy.size(), uriCopy.find_first_of(':')));\n size_t protocolSize = protocol.size() + 3;\n size_t argsPos = std::min(uriCopy.size(), uriCopy.find_first_of('?', protocolSize));\n if (uriCopy[argsPos - 1] != '\/')\n {\n uriCopy.insert(uriCopy.begin() + argsPos, '\/');\n }\n size_t slashPos = std::min(uriCopy.size(), uriCopy.find_first_of('\/', protocolSize));\n std::string path = uriCopy.substr(slashPos);\n if (path.empty())\n {\n path = \"\/\";\n }\n std::string addr = uriCopy.substr(protocolSize, slashPos - protocolSize);\n std::string host = addr;\n std::string origin = host + \":\" + std::to_string(port);\n\n \/\/ Validate\n std::string protocolCaps = protocol;\n std::transform(protocol.begin(), protocol.end(), protocolCaps.begin(), [](unsigned char c){ return std::toupper(c); });\n if (protocolCaps != \"WS\" && protocolCaps != \"WSS\")\n {\n std::cout << \"Invalid websocket protocol: \" << protocol << std::endl;\n return;\n }\n bool useSSL = protocolCaps == \"WSS\";\n\n \/\/ Create context\n \/\/if (!_pLwsContext)\n {\n struct lws_context_creation_info info;\n memset(&info, 0, sizeof info);\n\n info.port = CONTEXT_PORT_NO_LISTEN;\n info.protocols = protocols;\n info.gid = -1;\n info.uid = -1;\n info.extensions = exts;\n info.options = LWS_SERVER_OPTION_VALIDATE_UTF8;\n info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;\n\n std::unique_lock lock(lwsContextMutex);\n _pLwsContext = lws_create_context(&info);\n if (!_pLwsContext)\n {\n std::cout << \"Failed to create websocket context\" << std::endl;\n return;\n }\n }\n\n \/\/ Start update thread\n _updateThread = std::thread([this]()\n {\n _mutex.lock();\n while (_isConnecting || _isValid)\n {\n _mutex.unlock();\n lws_callback_on_writable_all_protocol(_pLwsContext, &protocols[0]);\n lws_service(_pLwsContext, 100);\n _mutex.lock();\n }\n _mutex.unlock();\n });\n\n \/\/ Create connection\n {\n struct lws_client_connect_info connectInfo;\n memset(&connectInfo, 0, sizeof(connectInfo));\n\n connectInfo.context = _pLwsContext;\n connectInfo.address = addr.c_str();\n connectInfo.port = port;\n if (useSSL)\n {\n connectInfo.ssl_connection = \n LCCSCF_USE_SSL\n#if defined(BC_SSL_ALLOW_SELFSIGNED)\n | LCCSCF_ALLOW_SELFSIGNED\n#endif\n \/\/ | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK\n \/\/ | LCCSCF_ALLOW_EXPIRED\n ;\n }\n else\n {\n connectInfo.ssl_connection = 0;\n }\n connectInfo.path = path.c_str();\n connectInfo.host = host.c_str();\n connectInfo.origin = origin.c_str();\n connectInfo.protocol = protocols[0].name;\n connectInfo.ietf_version_or_minus_one = -1;\n connectInfo.userdata = this;\n\n _pLws = lws_client_connect_via_info(&connectInfo);\n if (!_pLws)\n {\n std::cout << \"Failed to create websocket client\" << std::endl;\n return;\n }\n }\n }\n\n int DefaultWebSocket::libWebsocketsCallback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len)\n {\n DefaultWebSocket *pWebSocket = (DefaultWebSocket *)lws_wsi_user(wsi);\n\n switch (reason)\n {\n case LWS_CALLBACK_WSI_DESTROY:\n case LWS_CALLBACK_CLOSED_CLIENT_HTTP:\n case LWS_CALLBACK_CLOSED:\n {\n if (!pWebSocket)\n {\n return -1;\n }\n pWebSocket->onClose();\n break;\n }\n case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:\n {\n if (!pWebSocket || !in)\n {\n return -1;\n }\n pWebSocket->onError((const char*)in);\n break;\n }\n case LWS_CALLBACK_CLIENT_ESTABLISHED:\n {\n if (!pWebSocket)\n {\n return -1;\n }\n pWebSocket->onConnect();\n break;\n }\n case LWS_CALLBACK_CLIENT_RECEIVE:\n {\n if (!pWebSocket || !in)\n {\n return -1;\n }\n pWebSocket->onRecv((const char*)in, (int)len);\n break;\n }\n case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:\n {\n if (!pWebSocket || !in)\n {\n return -1;\n }\n\n unsigned char **p = (unsigned char **)in;\n unsigned char *end = (*p) + len;\n if (!pWebSocket->onProcessHeaders(p, end))\n {\n return -1;\n }\n break;\n }\n case LWS_CALLBACK_CLIENT_WRITEABLE:\n {\n if (!pWebSocket)\n {\n return -1;\n }\n pWebSocket->processSendQueue();\n break;\n }\n default:\n break;\n }\n\n return 0;\n }\n\n bool DefaultWebSocket::isValid()\n {\n std::unique_lock lock(_mutex);\n\n if (_isConnecting)\n {\n _connectionCondition.wait(lock, [this]() { return !_isConnecting; });\n }\n\n return _isValid;\n }\n\n void DefaultWebSocket::send(const std::string& message)\n {\n std::unique_lock lock(_mutex);\n _sendQueue.push(message);\n }\n\n void DefaultWebSocket::processSendQueue()\n {\n std::unique_lock lock(_mutex);\n while (!_sendQueue.empty())\n {\n const std::string& message = _sendQueue.front();\n\n _sendBuffer.resize(LWS_PRE + message.size());\n memcpy(_sendBuffer.data() + LWS_PRE, message.c_str(), message.size());\n lws_write(_pLws, _sendBuffer.data() + LWS_PRE, message.size(), LWS_WRITE_TEXT);\n\n _sendQueue.pop();\n }\n }\n\n std::string DefaultWebSocket::recv()\n {\n std::unique_lock lock(_recvMutex);\n\n if (!_recvQueue.empty())\n {\n std::string message = _recvQueue.front();\n _recvQueue.pop();\n return message;\n }\n\n _recvCondition.wait(lock, [this]()\n {\n return !_isValid || !_recvQueue.empty();\n });\n\n if (_isValid && !_recvQueue.empty())\n {\n std::string message = _recvQueue.front();\n _recvQueue.pop();\n return message;\n }\n\n return \"\";\n }\n\n void DefaultWebSocket::close()\n {\n \/\/ Stop and clean send queue\n {\n std::unique_lock lock(_mutex);\n while (!_sendQueue.empty()) _sendQueue.pop();\n _isValid = false;\n _isConnecting = false;\n _connectionCondition.notify_all();\n }\n\n \/\/ Stop and clean recving\n {\n std::unique_lock lock(_recvMutex);\n while (!_recvQueue.empty()) _recvQueue.pop();\n _recvCondition.notify_all();\n }\n\n \/\/ Join update thread\n if (_updateThread.joinable())\n {\n _updateThread.join();\n }\n\n \/\/ Destroy libWebSockets\n if (_pLws)\n {\n lws_set_timeout(_pLws, NO_PENDING_TIMEOUT, LWS_TO_KILL_SYNC);\n _pLws = NULL;\n }\n\n \/\/ Destroy the context\n if (_pLwsContext)\n {\n std::unique_lock lock(lwsContextMutex);\n lws_context_destroy(_pLwsContext);\n _pLwsContext = NULL;\n }\n }\n\n void DefaultWebSocket::onClose()\n {\n std::cout << \"WebSocket closed\" << std::endl;\n\n std::unique_lock lock(_mutex);\n _isValid = false;\n _isConnecting = false;\n _connectionCondition.notify_all();\n _pLws = NULL; \/\/ This is now invalid\n }\n\n void DefaultWebSocket::onError(const char* msg)\n {\n std::cout << \"WebSocket error: \" << msg << std::endl;\n\n std::unique_lock lock(_mutex);\n _isValid = false;\n _isConnecting = false;\n _connectionCondition.notify_all();\n _pLws = NULL; \/\/ This is now invalid\n }\n\n void DefaultWebSocket::onConnect()\n {\n std::cout << \"WebSocket Connected!\" << std::endl;\n\n std::unique_lock lock(_mutex);\n _isValid = true;\n _isConnecting = false;\n _connectionCondition.notify_all();\n }\n\n void DefaultWebSocket::onRecv(const char* buffer, int len)\n {\n std::unique_lock lock(_recvMutex);\n std::string message(buffer, len);\n _recvQueue.push(message);\n _recvCondition.notify_all();\n }\n\n bool DefaultWebSocket::onProcessHeaders(unsigned char** ppBuffer, unsigned char* pEnd)\n {\n if (_authHeaders.empty())\n {\n return true;\n }\n\n std::string key;\n\n for (std::map::iterator it = _authHeaders.begin(); it != _authHeaders.end(); ++it)\n {\n key = it->first;\n key += \":\";\n const std::string& value = it->second;\n\n if (lws_add_http_header_by_name(_pLws, (const unsigned char *)key.c_str(), (const unsigned char *)value.c_str(), (int)value.size(), ppBuffer, pEnd))\n {\n return false;\n }\n }\n\n return true;\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Cuboid.cpp\n\/\/ Copyright (c) 2009, Dan Heeks\n\/\/ This program is released under the BSD license. See the file COPYING for details.\r\n\n#include \"stdafx.h\"\n#include \"Cuboid.h\"\n#include \"..\/interface\/PropertyVertex.h\"\n#include \"..\/interface\/PropertyDouble.h\"\n#include \"..\/interface\/PropertyLength.h\"\n#include \"Gripper.h\"\n#include \"MarkedList.h\"\n\nCCuboid::CCuboid(const gp_Ax2& pos, double x, double y, double z, const wxChar* title, const HeeksColor& col):CSolid(BRepPrimAPI_MakeBox(pos, x, y, z), title, col), m_pos(pos), m_x(x), m_y(y), m_z(z)\n{\n}\n\nCCuboid::CCuboid(const TopoDS_Solid &solid, const wxChar* title, const HeeksColor& col):CSolid(solid, title, col), m_pos(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0)), m_x(0.0), m_y(0.0), m_z(0.0)\n{\n}\n\nconst wxBitmap &CCuboid::GetIcon()\n{\n\tstatic wxBitmap* icon = NULL;\n\tif(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T(\"\/icons\/cube.png\")));\n\treturn *icon;\n}\n\nHeeksObj *CCuboid::MakeACopy(void)const\n{\n\treturn new CCuboid(*this);\n}\n\nCCuboid::CCuboid( const CCuboid & rhs ) : CSolid(rhs)\n{\n *this = rhs; \/\/ Call the assignment operator.\n}\n\nCCuboid & CCuboid::operator= ( const CCuboid & rhs )\n{\n if (this != &rhs)\n {\n m_pos = rhs.m_pos;\n m_x = rhs.m_x;\n m_y = rhs.m_y;\n m_z = rhs.m_z;\n\n CSolid::operator=( rhs );\n }\n\n return(*this);\n}\n\nbool CCuboid::IsDifferent(HeeksObj* other)\n{\n\tCCuboid* cube = (CCuboid*)other;\n\tif(cube->m_x != m_x || cube->m_y != m_y || cube->m_z != m_z)\n\t\treturn true;\n\n\tif(!IsEqual(cube->m_pos,m_pos))\n\t\treturn true;\n\n\treturn CShape::IsDifferent(other);\n}\n\nstatic void on_set_centre(const double *vt, HeeksObj* object){\n\tgp_Trsf mat;\n\tmat.SetTranslation ( gp_Vec ( ((CCuboid*)object)->m_pos.Location(), make_point(vt) ) );\n\t((CCuboid*)object)->m_pos.Transform(mat);\n}\n\nstatic void on_set_x(double value, HeeksObj* object){\n\t((CCuboid*)object)->m_x = value;\n}\n\nstatic void on_set_y(double value, HeeksObj* object){\n\t((CCuboid*)object)->m_y = value;\n}\n\nstatic void on_set_z(double value, HeeksObj* object){\n\t((CCuboid*)object)->m_z = value;\n}\n\nvoid CCuboid::MakeTransformedShape(const gp_Trsf &mat)\r\n{\r\n\tm_pos.Transform(mat);\n\tdouble scale = gp_Vec(1, 0, 0).Transformed(mat).Magnitude();\n\tm_x = fabs(m_x * scale);\n\tm_y = fabs(m_y * scale);\n\tm_z = fabs(m_z * scale);\n\tm_shape = BRepPrimAPI_MakeBox(m_pos, m_x, m_y, m_z).Shape();\n}\n\nwxString CCuboid::StretchedName(){ return _(\"Stretched Cuboid\");}\n\nvoid CCuboid::GetProperties(std::list *list)\n{\n\tdouble pos[3];\n\textract(m_pos.Location(), pos);\n\tlist->push_back(new PropertyVertex(_(\"datum corner\"), pos, this, on_set_centre));\n\tlist->push_back(new PropertyLength(_(\"width ( x )\"), m_x, this, on_set_x));\n\tlist->push_back(new PropertyLength(_(\"height( y )\"), m_y, this, on_set_y));\n\tlist->push_back(new PropertyLength(_(\"depth ( z )\"), m_z, this, on_set_z));\n\n\tCSolid::GetProperties(list);\n}\n\nclass CCuboidCanvas: public ObjectCanvas\r\n{\r\npublic:\r\n\tCCuboidCanvas::CCuboidCanvas(wxWindow* parent) : ObjectCanvas(parent)\r\n\t{\r\n\t\t\/\/ just draw a picture of a cube with some text\r\n\t\tPictureFrame* picture = new PictureFrame(this, wxImage(wxGetApp().GetResFolder() + _T(\"\/bitmaps\/dlgcuboid.png\")));\r\n\t\twxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);\r\n\t\tsizer->Add(picture, 1, wxGROW);\r\n\t\tSetSizer(sizer);\r\n\t}\r\n};\r\n\r\nstatic CCuboidCanvas* object_canvas = NULL;\n\nObjectCanvas* CCuboid::GetDialog(wxWindow* parent)\n{\n\tif(object_canvas == NULL)object_canvas = new CCuboidCanvas(parent);\n\treturn object_canvas;\n}\n\nvoid CCuboid::GetGripperPositions(std::list *list, bool just_for_endof)\n{\n\tgp_Pnt o = m_pos.Location();\n\tgp_Pnt px(o.XYZ() + m_pos.XDirection().XYZ() * m_x);\n\tgp_Pnt py(o.XYZ() + m_pos.YDirection().XYZ() * m_y);\n\tgp_Dir z_dir = m_pos.XDirection() ^ m_pos.YDirection();\n\tgp_Pnt pz(o.XYZ() + z_dir.XYZ() * m_z);\n\tgp_Pnt m2(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y\/2);\n\tgp_Pnt m3(o.XYZ() + m_pos.XDirection().XYZ() * m_x\/2 + m_pos.YDirection().XYZ() * m_y);\n\tgp_Pnt m8(o.XYZ() + m_pos.YDirection().XYZ() * m_y\/2 + z_dir.XYZ() * m_z);\n\tgp_Pnt pxy(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y);\n\tgp_Pnt pxz(o.XYZ() + m_pos.XDirection().XYZ() * m_x + z_dir.XYZ() * m_z);\n\tgp_Pnt pyz(o.XYZ() + m_pos.YDirection().XYZ() * m_y + z_dir.XYZ() * m_z);\n\tgp_Pnt pxyz(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y + z_dir.XYZ() * m_z);\n\tlist->push_back(GripData(GripperTypeTranslate,o.X(),o.Y(),o.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotateObject,px.X(),px.Y(),px.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotateObject,py.X(),py.Y(),py.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotateObject,pz.X(),pz.Y(),pz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeScale,pxyz.X(),pxyz.Y(),pxyz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotate,pxy.X(),pxy.Y(),pxy.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotate,pxz.X(),pxz.Y(),pxz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotate,pyz.X(),pyz.Y(),pyz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeObjectScaleX,m2.X(),m2.Y(),m2.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeObjectScaleY,m3.X(),m3.Y(),m3.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeObjectScaleZ,m8.X(),m8.Y(),m8.Z(),NULL));\n}\n\nvoid CCuboid::OnApplyProperties()\n{\n\tCCuboid* new_object = new CCuboid(m_pos, m_x, m_y, m_z, m_title.c_str(), m_color);\n\tnew_object->CopyIDsFrom(this);\n\tOwner()->Add(new_object, NULL);\n\tOwner()->Remove(this);\n\tif(wxGetApp().m_marked_list->ObjectMarked(this))\n\t{\n\t\twxGetApp().m_marked_list->Remove(this, false);\n\t\twxGetApp().m_marked_list->Add(new_object, true);\n\t}\n\twxGetApp().Repaint();\n}\n\n\nbool CCuboid::GetScaleAboutMatrix(double *m)\n{\n\tgp_Trsf mat = make_matrix(m_pos.Location(), m_pos.XDirection(), m_pos.YDirection());\n\textract(mat, m);\n\treturn true;\n}\n\nbool CCuboid::Stretch(const double *p, const double* shift, void* data)\n{\n\tgp_Pnt vp = make_point(p);\n\tgp_Vec vshift = make_vector(shift);\n\n\tgp_Pnt o = m_pos.Location();\n\tgp_Dir z_dir = m_pos.XDirection() ^ m_pos.YDirection();\n\tgp_Pnt m2(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y\/2);\n\tgp_Pnt m3(o.XYZ() + m_pos.XDirection().XYZ() * m_x\/2 + m_pos.YDirection().XYZ() * m_y);\n\tgp_Pnt m8(o.XYZ() + m_pos.YDirection().XYZ() * m_y\/2 + z_dir.XYZ() * m_z);\n\n\tbool make_a_new_cuboid = false;\n\n\tif(m2.IsEqual(vp, wxGetApp().m_geom_tol)){\n\t\tm2 = m2.XYZ() + vshift.XYZ();\n\t\tdouble new_x = gp_Vec(m2.XYZ()) * gp_Vec(m_pos.XDirection()) - gp_Vec(o.XYZ()) * gp_Vec(m_pos.XDirection());\n\t\tif(new_x > 0){\n\t\t\tmake_a_new_cuboid = true;\n\t\t\tm_x = new_x;\n\t\t}\n\t}\n\telse if(m3.IsEqual(vp, wxGetApp().m_geom_tol)){\n\t\tm3 = m3.XYZ() + vshift.XYZ();\n\t\tdouble new_y = gp_Vec(m3.XYZ()) * gp_Vec(m_pos.YDirection()) - gp_Vec(o.XYZ()) * gp_Vec(m_pos.YDirection());\n\t\tif(new_y > 0){\n\t\t\tmake_a_new_cuboid = true;\n\t\t\tm_y = new_y;\n\t\t}\n\t}\n\telse if(m8.IsEqual(vp, wxGetApp().m_geom_tol)){\n\t\tm8 = m8.XYZ() + vshift.XYZ();\n\t\tdouble new_z = gp_Vec(m8.XYZ()) * gp_Vec(z_dir) - gp_Vec(o.XYZ()) * gp_Vec(z_dir);\n\t\tif(new_z > 0){\n\t\t\tmake_a_new_cuboid = true;\n\t\t\tm_z = new_z;\n\t\t}\n\t}\n\n\tif(make_a_new_cuboid)\n\t{\n\t\tCCuboid* new_object = new CCuboid(m_pos, m_x, m_y, m_z, m_title.c_str(), m_color);\n\t\tnew_object->CopyIDsFrom(this);\n\t\tOwner()->Add(new_object, NULL);\n\t\tOwner()->Remove(this);\n\t\twxGetApp().m_marked_list->Clear(false);\n\t\twxGetApp().m_marked_list->Add(new_object, true);\n\t}\n\n\treturn true;\n}\n\nvoid CCuboid::SetXMLElement(TiXmlElement* element)\n{\n\tconst gp_Pnt& l = m_pos.Location();\n\telement->SetDoubleAttribute(\"lx\", l.X());\n\telement->SetDoubleAttribute(\"ly\", l.Y());\n\telement->SetDoubleAttribute(\"lz\", l.Z());\n\n\tconst gp_Dir& d = m_pos.Direction();\n\telement->SetDoubleAttribute(\"dx\", d.X());\n\telement->SetDoubleAttribute(\"dy\", d.Y());\n\telement->SetDoubleAttribute(\"dz\", d.Z());\n\n\tconst gp_Dir& x = m_pos.XDirection();\n\telement->SetDoubleAttribute(\"xx\", x.X());\n\telement->SetDoubleAttribute(\"xy\", x.Y());\n\telement->SetDoubleAttribute(\"xz\", x.Z());\n\n\telement->SetDoubleAttribute(\"wx\", m_x);\n\telement->SetDoubleAttribute(\"wy\", m_y);\n\telement->SetDoubleAttribute(\"wz\", m_z);\n\n\tCSolid::SetXMLElement(element);\n}\n\nvoid CCuboid::SetFromXMLElement(TiXmlElement* pElem)\n{\n\tdouble l[3] = {0, 0, 0};\n\tdouble d[3] = {0, 0, 1};\n\tdouble x[3] = {1, 0, 0};\n\n\tfor(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())\n\t{\n\t\tstd::string name(a->Name());\n\t\tif(name == \"lx\")\t {l[0] = a->DoubleValue();}\n\t\telse if(name == \"ly\"){l[1] = a->DoubleValue();}\n\t\telse if(name == \"lz\"){l[2] = a->DoubleValue();}\n\n\t\telse if(name == \"dx\"){d[0] = a->DoubleValue();}\n\t\telse if(name == \"dy\"){d[1] = a->DoubleValue();}\n\t\telse if(name == \"dz\"){d[2] = a->DoubleValue();}\n\n\t\telse if(name == \"xx\"){x[0] = a->DoubleValue();}\n\t\telse if(name == \"xy\"){x[1] = a->DoubleValue();}\n\t\telse if(name == \"xz\"){x[2] = a->DoubleValue();}\n\n\t\telse if(name == \"wx\"){m_x = a->DoubleValue();}\n\t\telse if(name == \"wy\"){m_y = a->DoubleValue();}\n\t\telse if(name == \"wz\"){m_z = a->DoubleValue();}\n\t}\n\n\tm_pos = gp_Ax2(make_point(l), make_vector(d), make_vector(x));\n\n\tCSolid::SetFromXMLElement(pElem);\n}\nfixed extra qualification ‘CCuboidCanvas::’ in Ubuntu build\/\/ Cuboid.cpp\n\/\/ Copyright (c) 2009, Dan Heeks\n\/\/ This program is released under the BSD license. See the file COPYING for details.\r\n\n#include \"stdafx.h\"\n#include \"Cuboid.h\"\n#include \"..\/interface\/PropertyVertex.h\"\n#include \"..\/interface\/PropertyDouble.h\"\n#include \"..\/interface\/PropertyLength.h\"\n#include \"Gripper.h\"\n#include \"MarkedList.h\"\n\nCCuboid::CCuboid(const gp_Ax2& pos, double x, double y, double z, const wxChar* title, const HeeksColor& col):CSolid(BRepPrimAPI_MakeBox(pos, x, y, z), title, col), m_pos(pos), m_x(x), m_y(y), m_z(z)\n{\n}\n\nCCuboid::CCuboid(const TopoDS_Solid &solid, const wxChar* title, const HeeksColor& col):CSolid(solid, title, col), m_pos(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0)), m_x(0.0), m_y(0.0), m_z(0.0)\n{\n}\n\nconst wxBitmap &CCuboid::GetIcon()\n{\n\tstatic wxBitmap* icon = NULL;\n\tif(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T(\"\/icons\/cube.png\")));\n\treturn *icon;\n}\n\nHeeksObj *CCuboid::MakeACopy(void)const\n{\n\treturn new CCuboid(*this);\n}\n\nCCuboid::CCuboid( const CCuboid & rhs ) : CSolid(rhs)\n{\n *this = rhs; \/\/ Call the assignment operator.\n}\n\nCCuboid & CCuboid::operator= ( const CCuboid & rhs )\n{\n if (this != &rhs)\n {\n m_pos = rhs.m_pos;\n m_x = rhs.m_x;\n m_y = rhs.m_y;\n m_z = rhs.m_z;\n\n CSolid::operator=( rhs );\n }\n\n return(*this);\n}\n\nbool CCuboid::IsDifferent(HeeksObj* other)\n{\n\tCCuboid* cube = (CCuboid*)other;\n\tif(cube->m_x != m_x || cube->m_y != m_y || cube->m_z != m_z)\n\t\treturn true;\n\n\tif(!IsEqual(cube->m_pos,m_pos))\n\t\treturn true;\n\n\treturn CShape::IsDifferent(other);\n}\n\nstatic void on_set_centre(const double *vt, HeeksObj* object){\n\tgp_Trsf mat;\n\tmat.SetTranslation ( gp_Vec ( ((CCuboid*)object)->m_pos.Location(), make_point(vt) ) );\n\t((CCuboid*)object)->m_pos.Transform(mat);\n}\n\nstatic void on_set_x(double value, HeeksObj* object){\n\t((CCuboid*)object)->m_x = value;\n}\n\nstatic void on_set_y(double value, HeeksObj* object){\n\t((CCuboid*)object)->m_y = value;\n}\n\nstatic void on_set_z(double value, HeeksObj* object){\n\t((CCuboid*)object)->m_z = value;\n}\n\nvoid CCuboid::MakeTransformedShape(const gp_Trsf &mat)\r\n{\r\n\tm_pos.Transform(mat);\n\tdouble scale = gp_Vec(1, 0, 0).Transformed(mat).Magnitude();\n\tm_x = fabs(m_x * scale);\n\tm_y = fabs(m_y * scale);\n\tm_z = fabs(m_z * scale);\n\tm_shape = BRepPrimAPI_MakeBox(m_pos, m_x, m_y, m_z).Shape();\n}\n\nwxString CCuboid::StretchedName(){ return _(\"Stretched Cuboid\");}\n\nvoid CCuboid::GetProperties(std::list *list)\n{\n\tdouble pos[3];\n\textract(m_pos.Location(), pos);\n\tlist->push_back(new PropertyVertex(_(\"datum corner\"), pos, this, on_set_centre));\n\tlist->push_back(new PropertyLength(_(\"width ( x )\"), m_x, this, on_set_x));\n\tlist->push_back(new PropertyLength(_(\"height( y )\"), m_y, this, on_set_y));\n\tlist->push_back(new PropertyLength(_(\"depth ( z )\"), m_z, this, on_set_z));\n\n\tCSolid::GetProperties(list);\n}\n\nclass CCuboidCanvas: public ObjectCanvas\r\n{\r\npublic:\r\n\tCCuboidCanvas(wxWindow* parent) : ObjectCanvas(parent)\r\n\t{\r\n\t\t\/\/ just draw a picture of a cube with some text\r\n\t\tPictureFrame* picture = new PictureFrame(this, wxImage(wxGetApp().GetResFolder() + _T(\"\/bitmaps\/dlgcuboid.png\")));\r\n\t\twxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);\r\n\t\tsizer->Add(picture, 1, wxGROW);\r\n\t\tSetSizer(sizer);\r\n\t}\r\n};\r\n\r\nstatic CCuboidCanvas* object_canvas = NULL;\n\nObjectCanvas* CCuboid::GetDialog(wxWindow* parent)\n{\n\tif(object_canvas == NULL)object_canvas = new CCuboidCanvas(parent);\n\treturn object_canvas;\n}\n\nvoid CCuboid::GetGripperPositions(std::list *list, bool just_for_endof)\n{\n\tgp_Pnt o = m_pos.Location();\n\tgp_Pnt px(o.XYZ() + m_pos.XDirection().XYZ() * m_x);\n\tgp_Pnt py(o.XYZ() + m_pos.YDirection().XYZ() * m_y);\n\tgp_Dir z_dir = m_pos.XDirection() ^ m_pos.YDirection();\n\tgp_Pnt pz(o.XYZ() + z_dir.XYZ() * m_z);\n\tgp_Pnt m2(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y\/2);\n\tgp_Pnt m3(o.XYZ() + m_pos.XDirection().XYZ() * m_x\/2 + m_pos.YDirection().XYZ() * m_y);\n\tgp_Pnt m8(o.XYZ() + m_pos.YDirection().XYZ() * m_y\/2 + z_dir.XYZ() * m_z);\n\tgp_Pnt pxy(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y);\n\tgp_Pnt pxz(o.XYZ() + m_pos.XDirection().XYZ() * m_x + z_dir.XYZ() * m_z);\n\tgp_Pnt pyz(o.XYZ() + m_pos.YDirection().XYZ() * m_y + z_dir.XYZ() * m_z);\n\tgp_Pnt pxyz(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y + z_dir.XYZ() * m_z);\n\tlist->push_back(GripData(GripperTypeTranslate,o.X(),o.Y(),o.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotateObject,px.X(),px.Y(),px.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotateObject,py.X(),py.Y(),py.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotateObject,pz.X(),pz.Y(),pz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeScale,pxyz.X(),pxyz.Y(),pxyz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotate,pxy.X(),pxy.Y(),pxy.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotate,pxz.X(),pxz.Y(),pxz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeRotate,pyz.X(),pyz.Y(),pyz.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeObjectScaleX,m2.X(),m2.Y(),m2.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeObjectScaleY,m3.X(),m3.Y(),m3.Z(),NULL));\n\tlist->push_back(GripData(GripperTypeObjectScaleZ,m8.X(),m8.Y(),m8.Z(),NULL));\n}\n\nvoid CCuboid::OnApplyProperties()\n{\n\tCCuboid* new_object = new CCuboid(m_pos, m_x, m_y, m_z, m_title.c_str(), m_color);\n\tnew_object->CopyIDsFrom(this);\n\tOwner()->Add(new_object, NULL);\n\tOwner()->Remove(this);\n\tif(wxGetApp().m_marked_list->ObjectMarked(this))\n\t{\n\t\twxGetApp().m_marked_list->Remove(this, false);\n\t\twxGetApp().m_marked_list->Add(new_object, true);\n\t}\n\twxGetApp().Repaint();\n}\n\n\nbool CCuboid::GetScaleAboutMatrix(double *m)\n{\n\tgp_Trsf mat = make_matrix(m_pos.Location(), m_pos.XDirection(), m_pos.YDirection());\n\textract(mat, m);\n\treturn true;\n}\n\nbool CCuboid::Stretch(const double *p, const double* shift, void* data)\n{\n\tgp_Pnt vp = make_point(p);\n\tgp_Vec vshift = make_vector(shift);\n\n\tgp_Pnt o = m_pos.Location();\n\tgp_Dir z_dir = m_pos.XDirection() ^ m_pos.YDirection();\n\tgp_Pnt m2(o.XYZ() + m_pos.XDirection().XYZ() * m_x + m_pos.YDirection().XYZ() * m_y\/2);\n\tgp_Pnt m3(o.XYZ() + m_pos.XDirection().XYZ() * m_x\/2 + m_pos.YDirection().XYZ() * m_y);\n\tgp_Pnt m8(o.XYZ() + m_pos.YDirection().XYZ() * m_y\/2 + z_dir.XYZ() * m_z);\n\n\tbool make_a_new_cuboid = false;\n\n\tif(m2.IsEqual(vp, wxGetApp().m_geom_tol)){\n\t\tm2 = m2.XYZ() + vshift.XYZ();\n\t\tdouble new_x = gp_Vec(m2.XYZ()) * gp_Vec(m_pos.XDirection()) - gp_Vec(o.XYZ()) * gp_Vec(m_pos.XDirection());\n\t\tif(new_x > 0){\n\t\t\tmake_a_new_cuboid = true;\n\t\t\tm_x = new_x;\n\t\t}\n\t}\n\telse if(m3.IsEqual(vp, wxGetApp().m_geom_tol)){\n\t\tm3 = m3.XYZ() + vshift.XYZ();\n\t\tdouble new_y = gp_Vec(m3.XYZ()) * gp_Vec(m_pos.YDirection()) - gp_Vec(o.XYZ()) * gp_Vec(m_pos.YDirection());\n\t\tif(new_y > 0){\n\t\t\tmake_a_new_cuboid = true;\n\t\t\tm_y = new_y;\n\t\t}\n\t}\n\telse if(m8.IsEqual(vp, wxGetApp().m_geom_tol)){\n\t\tm8 = m8.XYZ() + vshift.XYZ();\n\t\tdouble new_z = gp_Vec(m8.XYZ()) * gp_Vec(z_dir) - gp_Vec(o.XYZ()) * gp_Vec(z_dir);\n\t\tif(new_z > 0){\n\t\t\tmake_a_new_cuboid = true;\n\t\t\tm_z = new_z;\n\t\t}\n\t}\n\n\tif(make_a_new_cuboid)\n\t{\n\t\tCCuboid* new_object = new CCuboid(m_pos, m_x, m_y, m_z, m_title.c_str(), m_color);\n\t\tnew_object->CopyIDsFrom(this);\n\t\tOwner()->Add(new_object, NULL);\n\t\tOwner()->Remove(this);\n\t\twxGetApp().m_marked_list->Clear(false);\n\t\twxGetApp().m_marked_list->Add(new_object, true);\n\t}\n\n\treturn true;\n}\n\nvoid CCuboid::SetXMLElement(TiXmlElement* element)\n{\n\tconst gp_Pnt& l = m_pos.Location();\n\telement->SetDoubleAttribute(\"lx\", l.X());\n\telement->SetDoubleAttribute(\"ly\", l.Y());\n\telement->SetDoubleAttribute(\"lz\", l.Z());\n\n\tconst gp_Dir& d = m_pos.Direction();\n\telement->SetDoubleAttribute(\"dx\", d.X());\n\telement->SetDoubleAttribute(\"dy\", d.Y());\n\telement->SetDoubleAttribute(\"dz\", d.Z());\n\n\tconst gp_Dir& x = m_pos.XDirection();\n\telement->SetDoubleAttribute(\"xx\", x.X());\n\telement->SetDoubleAttribute(\"xy\", x.Y());\n\telement->SetDoubleAttribute(\"xz\", x.Z());\n\n\telement->SetDoubleAttribute(\"wx\", m_x);\n\telement->SetDoubleAttribute(\"wy\", m_y);\n\telement->SetDoubleAttribute(\"wz\", m_z);\n\n\tCSolid::SetXMLElement(element);\n}\n\nvoid CCuboid::SetFromXMLElement(TiXmlElement* pElem)\n{\n\tdouble l[3] = {0, 0, 0};\n\tdouble d[3] = {0, 0, 1};\n\tdouble x[3] = {1, 0, 0};\n\n\tfor(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())\n\t{\n\t\tstd::string name(a->Name());\n\t\tif(name == \"lx\")\t {l[0] = a->DoubleValue();}\n\t\telse if(name == \"ly\"){l[1] = a->DoubleValue();}\n\t\telse if(name == \"lz\"){l[2] = a->DoubleValue();}\n\n\t\telse if(name == \"dx\"){d[0] = a->DoubleValue();}\n\t\telse if(name == \"dy\"){d[1] = a->DoubleValue();}\n\t\telse if(name == \"dz\"){d[2] = a->DoubleValue();}\n\n\t\telse if(name == \"xx\"){x[0] = a->DoubleValue();}\n\t\telse if(name == \"xy\"){x[1] = a->DoubleValue();}\n\t\telse if(name == \"xz\"){x[2] = a->DoubleValue();}\n\n\t\telse if(name == \"wx\"){m_x = a->DoubleValue();}\n\t\telse if(name == \"wy\"){m_y = a->DoubleValue();}\n\t\telse if(name == \"wz\"){m_z = a->DoubleValue();}\n\t}\n\n\tm_pos = gp_Ax2(make_point(l), make_vector(d), make_vector(x));\n\n\tCSolid::SetFromXMLElement(pElem);\n}\n<|endoftext|>"} {"text":"#include \/\/ strrchr, strncpy\n#include \/\/ stdout\n#include \n\n#include \n\n#include \"TestTools.h\"\n\n\nvoid ChangeDirectoryToExecutableOrigin( const char* executablePath );\n\nvoid TestLogHandler( LogLevel level, const char* line )\n{\n switch(level)\n {\n case LOG_INFO:\n dummyLog(\"%s\", line);\n break;\n\n case LOG_ERROR:\n case LOG_FATAL_ERROR:\n dummyLog(\"%s\", line);\n break;\n\n default:\n assert(!\"Unknown log level\");\n }\n}\n\nvoid InitTests( int argc, char const * const * argv )\n{\n ChangeDirectoryToExecutableOrigin(argv[0]);\n SetLogHandler(TestLogHandler);\n dummyInit(dummyGetTAPReporter(stdout));\n dummyAddInlineTests();\n}\n\nint RunTests()\n{\n const int failedTests = dummyRunTests();\n SetLogHandler(DefaultLogHandler);\n \/\/return failedTests; \/\/ TODO: prove marks failed tests as doubious, with this line\n return 0;\n}\n\n#if defined(WIN32)\n\n#include \nvoid ChangeDirectory( const char* directory )\n{\n _chdir(directory);\n}\n\n#else\n\n#include \nvoid ChangeDirectory( const char* directory )\n{\n chdir(directory);\n}\n\n#endif\n\nvoid ChangeDirectoryToExecutableOrigin( const char* executablePath )\n{\n#if defined(WIN32)\n const char seperator = '\\\\';\n#else\n const char seperator = '\/';\n#endif\n const char* lastSeperator = strrchr(executablePath, seperator);\n if(lastSeperator)\n {\n char buffer[256];\n const int length = lastSeperator - executablePath;\n strncpy(buffer, executablePath, length);\n ChangeDirectory(buffer);\n }\n else\n {\n \/\/ Already in the directory of the executable.\n }\n}\nFixed test tools#include \/\/ strrchr, strncpy\n#include \/\/ stdout\n#include \n\n#include \n\n#include \"TestTools.h\"\n\n\nvoid ChangeDirectoryToExecutableOrigin( const char* executablePath );\n\nvoid TestLogHandler( LogLevel level, const char* line )\n{\n switch(level)\n {\n case LOG_INFO:\n dummyLog(\"%s\", line);\n break;\n\n case LOG_ERROR:\n case LOG_FATAL_ERROR:\n dummyLog(\"%s\", line);\n break;\n\n default:\n assert(!\"Unknown log level\");\n }\n}\n\nvoid InitTests( int argc, char const * const * argv )\n{\n ChangeDirectoryToExecutableOrigin(argv[0]);\n SetLogHandler(TestLogHandler);\n dummyInit(dummyGetTAPReporter(stdout));\n dummyAddInlineTests();\n}\n\nint RunTests()\n{\n const int failedTests = dummyRunTests();\n SetLogHandler(DefaultLogHandler);\n \/\/return failedTests; \/\/ TODO: prove marks failed tests as doubious, with this line\n return 0;\n}\n\n#if defined(WIN32)\n\n#include \nvoid ChangeDirectory( const char* directory )\n{\n _chdir(directory);\n}\n\n#else\n\n#include \nvoid ChangeDirectory( const char* directory )\n{\n chdir(directory);\n}\n\n#endif\n\nvoid ChangeDirectoryToExecutableOrigin( const char* executablePath )\n{\n#if defined(WIN32)\n const char seperator = '\\\\';\n#else\n const char seperator = '\/';\n#endif\n const char* lastSeperator = strrchr(executablePath, seperator);\n if(lastSeperator)\n {\n char buffer[256];\n const int length = lastSeperator - executablePath;\n strncpy(buffer, executablePath, length);\n buffer[length] = '\\0';\n ChangeDirectory(buffer);\n }\n else\n {\n \/\/ Already in the directory of the executable.\n }\n}\n<|endoftext|>"} {"text":"#define DEBUG_TYPE \"enerc\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/IRBuilder.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ECQ_PRECISE 0\n#define ECQ_APPROX 1\n\n#define FUNC_TRACE \"enerc_trace\"\n\n\/\/ I'm not sure why, but I can't seem to enable debug output in the usual way\n\/\/ (with command line flags). Here's a hack.\n#undef DEBUG\n#define DEBUG(s) s\n\nusing namespace llvm;\nnamespace {\n\n\/\/ Command-line flags.\ncl::opt optInstrument (\"accept-inst\",\n cl::desc(\"ACCEPT: enable profiling instrumentation\"));\ncl::opt optRelax (\"accept-relax\",\n cl::desc(\"ACCEPT: enable relaxations\"));\n\n\n\/**** HELPERS ****\/\n\n\/\/ Look at the qualifier metadata on the instruction and determine whether it\n\/\/ has approximate semantics.\nbool isApprox(Instruction *instr) {\n MDNode *md = instr->getMetadata(\"quals\");\n if (!md)\n return false;\n\n Value *val = md->getOperand(0);\n ConstantInt *ci = cast(val);\n if (ci) {\n APInt intval = ci->getValue();\n return intval == ECQ_APPROX;\n } else {\n llvm::errs() << \"INVALID METADATA\";\n return false;\n }\n}\n\n\/\/ Is it legal to elide this instruction?\nbool elidable_helper(Instruction *instr,\n std::set &seen) {\n \/\/ Check for cycles.\n if (seen.count(instr)) {\n llvm::errs() << \"CYCLE DETECTED\\n\";\n return false;\n }\n seen.insert(instr);\n\n if (isApprox(instr)) {\n return true;\n } else if (isa(instr) ||\n isa(instr) ||\n isa(instr)) {\n \/\/ Precise stores, returns, branches: never elidable.\n return false;\n } else {\n \/\/ Recursive case: all consumers are elidable.\n for (Value::use_iterator ui = instr->use_begin();\n ui != instr->use_end(); ++ui) {\n Instruction *user = dyn_cast(*ui);\n if (user && !elidable_helper(user, seen)) {\n return false;\n }\n }\n return true; \/\/ No non-elidable consumers.\n }\n}\n\/\/ Start with an empty \"seen\" (cycle-detection) set.\nbool elidable(Instruction *instr) {\n std::set seen;\n return elidable_helper(instr, seen);\n}\n\n\/\/ Format a source position.\nstd::string srcPosDesc(const Module &mod, const DebugLoc &dl) {\n std::stringstream ss;\n ss << mod.getModuleIdentifier() << \":\";\n ss << dl.getLine();\n if (dl.getCol())\n ss << \",\" << dl.getCol();\n return ss.str();\n}\n\n\n\/**** THE MAIN LLVM PASS ****\/\n\nstruct ACCEPTPass : public FunctionPass {\n static char ID;\n\n Constant *blockCountFunction;\n unsigned long gApproxInsts;\n unsigned long gElidableInsts;\n unsigned long gTotalInsts;\n Module *module;\n std::map, int> relaxConfig; \/\/ kind, num -> param\n\n ACCEPTPass() : FunctionPass(ID) {\n gApproxInsts = 0;\n gElidableInsts = 0;\n gTotalInsts = 0;\n module = 0;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &Info) const {\n Info.addRequired();\n }\n\n virtual bool runOnFunction(Function &F) {\n countAndInstrument(F);\n return perforateLoopsMain(F);\n }\n\n virtual bool doInitialization(Module &M) {\n module = &M;\n\n if (optInstrument)\n setUpInstrumentation();\n\n if (optRelax)\n loadRelaxConfig();\n\n return false;\n }\n\n virtual bool doFinalization(Module &M) {\n dumpStaticStats();\n if (!optRelax)\n dumpRelaxConfig();\n return false;\n }\n\n\n\n \/**** TRACING AND STATISTICS ****\/\n\n void countAndInstrument(Function &F) {\n for (Function::iterator bbi = F.begin(); bbi != F.end(); ++bbi) {\n unsigned int approxInsts = 0;\n unsigned int elidableInsts = 0;\n unsigned int totalInsts = 0;\n\n for (BasicBlock::iterator ii = bbi->begin(); ii != bbi->end();\n ++ii) {\n if ((Instruction*)ii == bbi->getTerminator()) {\n \/\/ Terminator instruction is not checked.\n continue;\n }\n\n \/\/ Record information about this instruction.\n bool iApprox = isApprox(ii);\n bool iElidable = elidable(ii);\n ++gTotalInsts;\n ++totalInsts;\n if (iApprox) {\n ++gApproxInsts;\n ++approxInsts;\n }\n if (iElidable) {\n ++gElidableInsts;\n ++elidableInsts;\n }\n }\n\n \/\/ Call the runtime profiling library for this block.\n if (optInstrument)\n insertTraceCall(F, bbi, approxInsts, elidableInsts, totalInsts);\n }\n }\n\n void setUpInstrumentation() {\n blockCountFunction = module->getOrInsertFunction(\n FUNC_TRACE,\n Type::getVoidTy(module->getContext()), \/\/ return type\n Type::getInt32Ty(module->getContext()), \/\/ approx\n Type::getInt32Ty(module->getContext()), \/\/ elidable\n Type::getInt32Ty(module->getContext()), \/\/ total\n NULL\n );\n }\n\n void insertTraceCall(Function &F, BasicBlock* bb,\n unsigned int approx,\n unsigned int elidable,\n unsigned int total) {\n std::vector args;\n args.push_back(\n ConstantInt::get(Type::getInt32Ty(F.getContext()), approx)\n );\n args.push_back(\n ConstantInt::get(Type::getInt32Ty(F.getContext()), elidable)\n );\n args.push_back(\n ConstantInt::get(Type::getInt32Ty(F.getContext()), total)\n );\n\n \/\/ For now, we're inserting calls at the end of basic blocks.\n CallInst::Create(\n blockCountFunction,\n args,\n \"\",\n bb->getTerminator()\n );\n }\n\n void dumpStaticStats() {\n FILE *results_file = fopen(\"enerc_static.txt\", \"w+\");\n fprintf(results_file,\n \"%lu %lu %lu\\n\", gApproxInsts, gElidableInsts, gTotalInsts);\n fclose(results_file);\n }\n\n\n \/**** RELAXATION CONFIGURATION ***\/\n\n typedef enum {\n rkPerforate\n } relaxKind;\n\n void dumpRelaxConfig() {\n std::ofstream configFile(\"accept_config.txt\");;\n for (std::map, int>::iterator i = relaxConfig.begin();\n i != relaxConfig.end(); ++i) {\n configFile << i->first.first << \" \"\n << i->first.second << \" \"\n << i->second << \"\\n\";\n }\n configFile.close();\n }\n\n void loadRelaxConfig() {\n std::ifstream configFile(\"accept_config.txt\");;\n if (!configFile.good()) {\n errs() << \"no config file; no optimizations will occur\\n\";\n return;\n }\n\n while (configFile.good()) {\n int kind;\n int ident;\n int param;\n configFile >> kind >> ident >> param;\n relaxConfig[std::pair(kind, ident)] = param;\n }\n\n configFile.close();\n }\n\n\n \/**** EXPERIMENT ****\/\n void perforateLoopsTop(Loop *loop, int &loopId, int &perforatedLoops) {\n std::vector subLoops = loop->getSubLoops();\n for (int i = 0; i < subLoops.size(); ++i)\n perforateLoopsTop(subLoops[i], loopId, perforatedLoops);\n if (perforateLoops(loop, loopId))\n ++perforatedLoops;\n ++loopId;\n }\n\n bool perforateLoopsMain(Function &F) {\n int perforatedLoops = 0;\n int loopId = 0;\n LoopInfo &loopInfo = getAnalysis();\n\n for (LoopInfo::iterator li = loopInfo.begin();\n li != loopInfo.end(); ++li, ++loopId) {\n Loop *loop = *li;\n perforateLoopsTop(loop, loopId, perforatedLoops);\n }\n return perforatedLoops > 0;\n }\n\n bool perforateLoops(Loop *loop, int &loopId) {\n int perforatedLoops = 0;\n\n \/\/ We only consider loops for which there is a header (condition), a\n \/\/ latch (increment, in \"for\"), and a preheader (initialization).\n if (!loop->getHeader() || !loop->getLoopLatch()\n || !loop->getLoopPreheader())\n return false;\n \/\/ Count elidable instructions in the loop.\n int cTotal = 0;\n int cElidable = 0;\n for (Loop::block_iterator bi = loop->block_begin();\n bi != loop->block_end(); ++bi) {\n BasicBlock *block = *bi;\n\n \/\/ Don't count the loop control.\n if (block == loop->getHeader() || block == loop->getLoopLatch())\n continue;\n\n for (BasicBlock::iterator ii = block->begin();\n ii != block->end(); ++ii) {\n if ((Instruction*)ii == block->getTerminator())\n continue;\n if (elidable(ii))\n ++cElidable;\n ++cTotal;\n }\n }\n\n \/\/ How elidable is the loop body as a whole?\n errs() << \"loop at \"\n << srcPosDesc(*module, loop->getHeader()->begin()->getDebugLoc())\n << \" - \" << cElidable << \"\/\" << cTotal << \"\\n\";\n\n \/*\n #define DUMPNN(e) if (e) (e)->dump(); else errs() << \"null\\n\";\n errs() << \"header: \";\n DUMPNN(loop->getHeader())\n errs() << \"preheader: \";\n DUMPNN(loop->getLoopPreheader())\n errs() << \"predecessor: \";\n DUMPNN(loop->getLoopPredecessor())\n errs() << \"latch: \";\n DUMPNN(loop->getLoopLatch())\n errs() << \"exit: \";\n DUMPNN(loop->getExitBlock())\n errs() << \"exiting: \";\n DUMPNN(loop->getExitingBlock())\n errs() << \"all contained blocks: \";\n for (Loop::block_iterator bi = loop->block_begin();\n bi != loop->block_end(); ++bi) {\n BasicBlock *block = *bi;\n block->dump();\n }\n *\/\n\n if (cElidable == cTotal) {\n errs() << \"can perforate.\\n\";\n if (optRelax) {\n int param = relaxConfig[std::pair(rkPerforate, loopId)];\n if (param) {\n errs() << \"perforating with factor 2^\" << param << \"\\n\";\n perforateLoop(loop, param);\n ++perforatedLoops;\n }\n } else {\n relaxConfig[std::pair(rkPerforate, loopId)] = 0;\n }\n }\n\n return perforatedLoops > 0;\n }\n\n void perforateLoop(Loop *loop, int logfactor=1) {\n \/\/ Check whether this loop is perforatable.\n \/\/ First, check for required blocks.\n if (!loop->getHeader() || !loop->getLoopLatch()\n || !loop->getLoopPreheader() || !loop->getExitBlock()) {\n llvm::errs() << \"malformed loop\\n\";\n return;\n }\n \/\/ Next, make sure the header (condition block) ends with a body\/exit\n \/\/ conditional branch.\n BranchInst *condBranch = dyn_cast(\n loop->getHeader()->getTerminator()\n );\n if (!condBranch || condBranch->getNumSuccessors() != 2) {\n llvm::errs() << \"malformed loop condition\\n\";\n return;\n }\n BasicBlock *bodyBlock;\n if (condBranch->getSuccessor(0) == loop->getExitBlock()) {\n bodyBlock = condBranch->getSuccessor(1);\n } else if (condBranch->getSuccessor(1) == loop->getExitBlock()) {\n bodyBlock = condBranch->getSuccessor(0);\n } else {\n llvm::errs() << \"loop condition does not exit\\n\";\n return;\n }\n\n IRBuilder<> builder(module->getContext());\n Value *result;\n\n \/\/ Add our own counter to the preheader.\n builder.SetInsertPoint(loop->getLoopPreheader()->getTerminator());\n AllocaInst *counterAlloca = builder.CreateAlloca(\n builder.getInt32Ty(),\n 0,\n \"accept_counter\"\n );\n builder.CreateStore(\n builder.getInt32(0),\n counterAlloca\n );\n\n \/\/ Increment the counter in the latch.\n builder.SetInsertPoint(loop->getLoopLatch()->getTerminator());\n result = builder.CreateLoad(\n counterAlloca,\n \"accept_tmp\"\n );\n result = builder.CreateAdd(\n result,\n builder.getInt32(1),\n \"accept_inc\"\n );\n builder.CreateStore(\n result,\n counterAlloca\n );\n\n \/\/ Get the first body block.\n\n \/\/ Check the counter before the loop's body.\n BasicBlock *checkBlock = BasicBlock::Create(\n module->getContext(),\n \"accept_cond\",\n bodyBlock->getParent(),\n bodyBlock\n );\n builder.SetInsertPoint(checkBlock);\n result = builder.CreateLoad(\n counterAlloca,\n \"accept_tmp\"\n );\n \/\/ Check whether the low n bits of the counter are zero.\n result = builder.CreateTrunc(\n result,\n Type::getIntNTy(module->getContext(), logfactor),\n \"accept_trunc\"\n );\n result = builder.CreateIsNull(\n result,\n \"accept_cmp\"\n );\n result = builder.CreateCondBr(\n result,\n bodyBlock,\n loop->getLoopLatch()\n );\n\n \/\/ Change the latch (condition block) to point to our new condition\n \/\/ instead of the body.\n condBranch->setSuccessor(0, checkBlock);\n }\n\n};\nchar ACCEPTPass::ID = 0;\n\n\n\/**** PASS REGISTRATION FOOTNOTE ***\/\n\n\/\/ Register ACCEPT as a \"standard pass\". This allows the pass to run without\n\/\/ running opt explicitly (e.g., as part of running `clang`).\nstatic void registerACCEPTPass(const PassManagerBuilder &,\n PassManagerBase &PM) {\n PM.add(new LoopInfo());\n PM.add(new ACCEPTPass());\n}\nstatic RegisterStandardPasses\n RegisterACCEPT(PassManagerBuilder::EP_EarlyAsPossible,\n registerACCEPTPass);\n\n}\ncorrect filename in source location strings#define DEBUG_TYPE \"enerc\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/IRBuilder.h\"\n#include \"llvm\/DebugInfo.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ECQ_PRECISE 0\n#define ECQ_APPROX 1\n\n#define FUNC_TRACE \"enerc_trace\"\n\n\/\/ I'm not sure why, but I can't seem to enable debug output in the usual way\n\/\/ (with command line flags). Here's a hack.\n#undef DEBUG\n#define DEBUG(s) s\n\nusing namespace llvm;\nnamespace {\n\n\/\/ Command-line flags.\ncl::opt optInstrument (\"accept-inst\",\n cl::desc(\"ACCEPT: enable profiling instrumentation\"));\ncl::opt optRelax (\"accept-relax\",\n cl::desc(\"ACCEPT: enable relaxations\"));\n\n\n\/**** HELPERS ****\/\n\n\/\/ Look at the qualifier metadata on the instruction and determine whether it\n\/\/ has approximate semantics.\nbool isApprox(Instruction *instr) {\n MDNode *md = instr->getMetadata(\"quals\");\n if (!md)\n return false;\n\n Value *val = md->getOperand(0);\n ConstantInt *ci = cast(val);\n if (ci) {\n APInt intval = ci->getValue();\n return intval == ECQ_APPROX;\n } else {\n llvm::errs() << \"INVALID METADATA\";\n return false;\n }\n}\n\n\/\/ Is it legal to elide this instruction?\nbool elidable_helper(Instruction *instr,\n std::set &seen) {\n \/\/ Check for cycles.\n if (seen.count(instr)) {\n llvm::errs() << \"CYCLE DETECTED\\n\";\n return false;\n }\n seen.insert(instr);\n\n if (isApprox(instr)) {\n return true;\n } else if (isa(instr) ||\n isa(instr) ||\n isa(instr)) {\n \/\/ Precise stores, returns, branches: never elidable.\n return false;\n } else {\n \/\/ Recursive case: all consumers are elidable.\n for (Value::use_iterator ui = instr->use_begin();\n ui != instr->use_end(); ++ui) {\n Instruction *user = dyn_cast(*ui);\n if (user && !elidable_helper(user, seen)) {\n return false;\n }\n }\n return true; \/\/ No non-elidable consumers.\n }\n}\n\/\/ Start with an empty \"seen\" (cycle-detection) set.\nbool elidable(Instruction *instr) {\n std::set seen;\n return elidable_helper(instr, seen);\n}\n\n\/\/ Format a source position.\nstd::string srcPosDesc(const Module &mod, const DebugLoc &dl) {\n LLVMContext &ctx = mod.getContext();\n std::stringstream ss;\n\n \/\/ Try to get filename from debug location.\n DIScope scope(dl.getScope(ctx));\n if (scope.Verify()) {\n ss << scope.getFilename().data();\n } else {\n \/\/ Fall back to the compilation unit name.\n ss << \"(\" << mod.getModuleIdentifier() << \")\";\n }\n ss << \":\";\n\n ss << dl.getLine();\n if (dl.getCol())\n ss << \",\" << dl.getCol();\n return ss.str();\n}\n\n\n\/**** THE MAIN LLVM PASS ****\/\n\nstruct ACCEPTPass : public FunctionPass {\n static char ID;\n\n Constant *blockCountFunction;\n unsigned long gApproxInsts;\n unsigned long gElidableInsts;\n unsigned long gTotalInsts;\n Module *module;\n std::map, int> relaxConfig; \/\/ kind, num -> param\n\n ACCEPTPass() : FunctionPass(ID) {\n gApproxInsts = 0;\n gElidableInsts = 0;\n gTotalInsts = 0;\n module = 0;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &Info) const {\n Info.addRequired();\n }\n\n virtual bool runOnFunction(Function &F) {\n countAndInstrument(F);\n return perforateLoopsMain(F);\n }\n\n virtual bool doInitialization(Module &M) {\n module = &M;\n\n if (optInstrument)\n setUpInstrumentation();\n\n if (optRelax)\n loadRelaxConfig();\n\n return false;\n }\n\n virtual bool doFinalization(Module &M) {\n dumpStaticStats();\n if (!optRelax)\n dumpRelaxConfig();\n return false;\n }\n\n\n\n \/**** TRACING AND STATISTICS ****\/\n\n void countAndInstrument(Function &F) {\n for (Function::iterator bbi = F.begin(); bbi != F.end(); ++bbi) {\n unsigned int approxInsts = 0;\n unsigned int elidableInsts = 0;\n unsigned int totalInsts = 0;\n\n for (BasicBlock::iterator ii = bbi->begin(); ii != bbi->end();\n ++ii) {\n if ((Instruction*)ii == bbi->getTerminator()) {\n \/\/ Terminator instruction is not checked.\n continue;\n }\n\n \/\/ Record information about this instruction.\n bool iApprox = isApprox(ii);\n bool iElidable = elidable(ii);\n ++gTotalInsts;\n ++totalInsts;\n if (iApprox) {\n ++gApproxInsts;\n ++approxInsts;\n }\n if (iElidable) {\n ++gElidableInsts;\n ++elidableInsts;\n }\n }\n\n \/\/ Call the runtime profiling library for this block.\n if (optInstrument)\n insertTraceCall(F, bbi, approxInsts, elidableInsts, totalInsts);\n }\n }\n\n void setUpInstrumentation() {\n blockCountFunction = module->getOrInsertFunction(\n FUNC_TRACE,\n Type::getVoidTy(module->getContext()), \/\/ return type\n Type::getInt32Ty(module->getContext()), \/\/ approx\n Type::getInt32Ty(module->getContext()), \/\/ elidable\n Type::getInt32Ty(module->getContext()), \/\/ total\n NULL\n );\n }\n\n void insertTraceCall(Function &F, BasicBlock* bb,\n unsigned int approx,\n unsigned int elidable,\n unsigned int total) {\n std::vector args;\n args.push_back(\n ConstantInt::get(Type::getInt32Ty(F.getContext()), approx)\n );\n args.push_back(\n ConstantInt::get(Type::getInt32Ty(F.getContext()), elidable)\n );\n args.push_back(\n ConstantInt::get(Type::getInt32Ty(F.getContext()), total)\n );\n\n \/\/ For now, we're inserting calls at the end of basic blocks.\n CallInst::Create(\n blockCountFunction,\n args,\n \"\",\n bb->getTerminator()\n );\n }\n\n void dumpStaticStats() {\n FILE *results_file = fopen(\"enerc_static.txt\", \"w+\");\n fprintf(results_file,\n \"%lu %lu %lu\\n\", gApproxInsts, gElidableInsts, gTotalInsts);\n fclose(results_file);\n }\n\n\n \/**** RELAXATION CONFIGURATION ***\/\n\n typedef enum {\n rkPerforate\n } relaxKind;\n\n void dumpRelaxConfig() {\n std::ofstream configFile(\"accept_config.txt\");;\n for (std::map, int>::iterator i = relaxConfig.begin();\n i != relaxConfig.end(); ++i) {\n configFile << i->first.first << \" \"\n << i->first.second << \" \"\n << i->second << \"\\n\";\n }\n configFile.close();\n }\n\n void loadRelaxConfig() {\n std::ifstream configFile(\"accept_config.txt\");;\n if (!configFile.good()) {\n errs() << \"no config file; no optimizations will occur\\n\";\n return;\n }\n\n while (configFile.good()) {\n int kind;\n int ident;\n int param;\n configFile >> kind >> ident >> param;\n relaxConfig[std::pair(kind, ident)] = param;\n }\n\n configFile.close();\n }\n\n\n \/**** EXPERIMENT ****\/\n void perforateLoopsTop(Loop *loop, int &loopId, int &perforatedLoops) {\n std::vector subLoops = loop->getSubLoops();\n for (int i = 0; i < subLoops.size(); ++i)\n perforateLoopsTop(subLoops[i], loopId, perforatedLoops);\n if (perforateLoops(loop, loopId))\n ++perforatedLoops;\n ++loopId;\n }\n\n bool perforateLoopsMain(Function &F) {\n int perforatedLoops = 0;\n int loopId = 0;\n LoopInfo &loopInfo = getAnalysis();\n\n for (LoopInfo::iterator li = loopInfo.begin();\n li != loopInfo.end(); ++li, ++loopId) {\n Loop *loop = *li;\n perforateLoopsTop(loop, loopId, perforatedLoops);\n }\n return perforatedLoops > 0;\n }\n\n bool perforateLoops(Loop *loop, int &loopId) {\n int perforatedLoops = 0;\n\n \/\/ We only consider loops for which there is a header (condition), a\n \/\/ latch (increment, in \"for\"), and a preheader (initialization).\n if (!loop->getHeader() || !loop->getLoopLatch()\n || !loop->getLoopPreheader())\n return false;\n \/\/ Count elidable instructions in the loop.\n int cTotal = 0;\n int cElidable = 0;\n for (Loop::block_iterator bi = loop->block_begin();\n bi != loop->block_end(); ++bi) {\n BasicBlock *block = *bi;\n\n \/\/ Don't count the loop control.\n if (block == loop->getHeader() || block == loop->getLoopLatch())\n continue;\n\n for (BasicBlock::iterator ii = block->begin();\n ii != block->end(); ++ii) {\n if ((Instruction*)ii == block->getTerminator())\n continue;\n if (elidable(ii))\n ++cElidable;\n ++cTotal;\n }\n }\n\n \/\/ How elidable is the loop body as a whole?\n errs() << \"loop at \"\n << srcPosDesc(*module, loop->getHeader()->begin()->getDebugLoc())\n << \" - \" << cElidable << \"\/\" << cTotal << \"\\n\";\n\n \/*\n #define DUMPNN(e) if (e) (e)->dump(); else errs() << \"null\\n\";\n errs() << \"header: \";\n DUMPNN(loop->getHeader())\n errs() << \"preheader: \";\n DUMPNN(loop->getLoopPreheader())\n errs() << \"predecessor: \";\n DUMPNN(loop->getLoopPredecessor())\n errs() << \"latch: \";\n DUMPNN(loop->getLoopLatch())\n errs() << \"exit: \";\n DUMPNN(loop->getExitBlock())\n errs() << \"exiting: \";\n DUMPNN(loop->getExitingBlock())\n errs() << \"all contained blocks: \";\n for (Loop::block_iterator bi = loop->block_begin();\n bi != loop->block_end(); ++bi) {\n BasicBlock *block = *bi;\n block->dump();\n }\n *\/\n\n if (cElidable == cTotal) {\n errs() << \"can perforate.\\n\";\n if (optRelax) {\n int param = relaxConfig[std::pair(rkPerforate, loopId)];\n if (param) {\n errs() << \"perforating with factor 2^\" << param << \"\\n\";\n perforateLoop(loop, param);\n ++perforatedLoops;\n }\n } else {\n relaxConfig[std::pair(rkPerforate, loopId)] = 0;\n }\n }\n\n return perforatedLoops > 0;\n }\n\n void perforateLoop(Loop *loop, int logfactor=1) {\n \/\/ Check whether this loop is perforatable.\n \/\/ First, check for required blocks.\n if (!loop->getHeader() || !loop->getLoopLatch()\n || !loop->getLoopPreheader() || !loop->getExitBlock()) {\n llvm::errs() << \"malformed loop\\n\";\n return;\n }\n \/\/ Next, make sure the header (condition block) ends with a body\/exit\n \/\/ conditional branch.\n BranchInst *condBranch = dyn_cast(\n loop->getHeader()->getTerminator()\n );\n if (!condBranch || condBranch->getNumSuccessors() != 2) {\n llvm::errs() << \"malformed loop condition\\n\";\n return;\n }\n BasicBlock *bodyBlock;\n if (condBranch->getSuccessor(0) == loop->getExitBlock()) {\n bodyBlock = condBranch->getSuccessor(1);\n } else if (condBranch->getSuccessor(1) == loop->getExitBlock()) {\n bodyBlock = condBranch->getSuccessor(0);\n } else {\n llvm::errs() << \"loop condition does not exit\\n\";\n return;\n }\n\n IRBuilder<> builder(module->getContext());\n Value *result;\n\n \/\/ Add our own counter to the preheader.\n builder.SetInsertPoint(loop->getLoopPreheader()->getTerminator());\n AllocaInst *counterAlloca = builder.CreateAlloca(\n builder.getInt32Ty(),\n 0,\n \"accept_counter\"\n );\n builder.CreateStore(\n builder.getInt32(0),\n counterAlloca\n );\n\n \/\/ Increment the counter in the latch.\n builder.SetInsertPoint(loop->getLoopLatch()->getTerminator());\n result = builder.CreateLoad(\n counterAlloca,\n \"accept_tmp\"\n );\n result = builder.CreateAdd(\n result,\n builder.getInt32(1),\n \"accept_inc\"\n );\n builder.CreateStore(\n result,\n counterAlloca\n );\n\n \/\/ Get the first body block.\n\n \/\/ Check the counter before the loop's body.\n BasicBlock *checkBlock = BasicBlock::Create(\n module->getContext(),\n \"accept_cond\",\n bodyBlock->getParent(),\n bodyBlock\n );\n builder.SetInsertPoint(checkBlock);\n result = builder.CreateLoad(\n counterAlloca,\n \"accept_tmp\"\n );\n \/\/ Check whether the low n bits of the counter are zero.\n result = builder.CreateTrunc(\n result,\n Type::getIntNTy(module->getContext(), logfactor),\n \"accept_trunc\"\n );\n result = builder.CreateIsNull(\n result,\n \"accept_cmp\"\n );\n result = builder.CreateCondBr(\n result,\n bodyBlock,\n loop->getLoopLatch()\n );\n\n \/\/ Change the latch (condition block) to point to our new condition\n \/\/ instead of the body.\n condBranch->setSuccessor(0, checkBlock);\n }\n\n};\nchar ACCEPTPass::ID = 0;\n\n\n\/**** PASS REGISTRATION FOOTNOTE ***\/\n\n\/\/ Register ACCEPT as a \"standard pass\". This allows the pass to run without\n\/\/ running opt explicitly (e.g., as part of running `clang`).\nstatic void registerACCEPTPass(const PassManagerBuilder &,\n PassManagerBase &PM) {\n PM.add(new LoopInfo());\n PM.add(new ACCEPTPass());\n}\nstatic RegisterStandardPasses\n RegisterACCEPT(PassManagerBuilder::EP_EarlyAsPossible,\n registerACCEPTPass);\n\n}\n<|endoftext|>"} {"text":"\/*\nDisplayController.h - Library for Controlling a 14x28 bits FlipDot display sign using two FP2800A.\nCreated by Antonio Carioca, March 3, 2014.\n*\/\n\n\/\/#include \"Arduino.h\"\n\n\/\/#include \n\/\/#include \"application.h\"\n#include \"mark-iv-flip-dot-display-sign-14x28-controller.h\"\n\n\/* CONSTANTS *\/\n\/\/const int DISPLAY_SIZE = 4;\nconst int DISPLAY_PIXEL_WIDTH = 28;\nconst int DISPLAY_PIXEL_HEIGHT = 14;\nconst int DISPLAY_SUBPANEL_QTY = 2;\n\n\/\/=== F O N T ===\n\/\/ Font courtesy of aspro648\n\/\/ coden taken from\n\/\/ http:\/\/www.instructables.com\/files\/orig\/FQC\/A1CY\/H5EW79JK\/FQCA1CYH5EW79JK.txt\n\/\/ The @ will display as space character.\n\/\/ NOTE: MOVING ALL THE ARRAY BELOW TO PROGMEM\n\n\n\/\/DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, prog_uchar fonteParam[][5]){\nDotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, byte fonteParam[][5]){\n\n\tpinMode(dataPin, OUTPUT);\n\tpinMode(clockPin, OUTPUT);\n\tpinMode(latchPin, OUTPUT);\n\tpinMode(enableSubPanel1Pin, OUTPUT);\n\tpinMode(enableSubPanel2Pin, OUTPUT);\n\t\/\/disable FP2800A's\n\tdigitalWrite(enableSubPanel1Pin, LOW);\n\tdigitalWrite(enableSubPanel2Pin, LOW);\n\n\t_dataPin = dataPin;\n\t_clockPin = clockPin;\n\t_latchPin = latchPin;\n\t_enableSubPanel1Pin = enableSubPanel1Pin;\n\t_enableSubPanel2Pin = enableSubPanel2Pin;\n\t_fontWidth = fontWidth;\n\t_fontHeight = fontHeight;\n\t_fonteParam = fonteParam; \n\t\n\t\/\/_maxNumRows = floor((DISPLAY_PIXEL_HEIGHT+1)\/(_fontHeight));\n\t_maxNumRows = (int)((DISPLAY_PIXEL_HEIGHT+1)\/(_fontHeight));\n\t\/\/_maxRowLength = floor((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) \/ (_fontWidth+1));\n\t_maxRowLength = (int)((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) \/ (_fontWidth+1));\n\t_maxMessageLength = _maxRowLength * _maxNumRows;\n\n}\n\/*\nvoid DotDisplay::setSerial(HardwareSerial* hwPrint){\n\tprinter = hwPrint; \/\/operate on the address of print\n\tif(printer) {\n\t\tprinter->begin(9600);\n\t}\n}\n*\/\n\n\nvoid DotDisplay::setDot(byte col, byte row, bool on){\n\n\t\n\t\/\/accidentally reversed two data pins, so reversing back on the code here\n\t\/\/on = !on;\n\n\t\/\/2 pins - Data\n\t\/\/5 pins - Column\n\t\/\/4 pins - Rows\n\n\t\/\/4 pins - Enable FP2800A (4 subpanels)\n\tbyte subPanel = 1; \n\t\/\/disable FP2800A's\n\tdigitalWrite(_enableSubPanel1Pin, LOW);\n\tdigitalWrite(_enableSubPanel2Pin, LOW);\n\n\t\/\/enables next sunpanel\n\tif(col>=DISPLAY_PIXEL_WIDTH){\n\t\t\/\/subPanel = floor(col \/ DISPLAY_PIXEL_WIDTH)+1;\n\t\tsubPanel = (int)(col \/ DISPLAY_PIXEL_WIDTH)+1;\n\t\tcol=col-DISPLAY_PIXEL_WIDTH;\n\t}\n\n\t\/*\n\tif(printer) {\n\tprinter->print(\"col: \");\n\tprinter->print(col);\n\tprinter->print(\", \");\n\tprinter->print(\"subPanel: \");\n\tprinter->println(subPanel);\n\t}\n\t*\/\n\n\t\/\/ IGNOREx4 + ROWx4 + IGNOREx1 + COLUMNx5 + DATAx2\n\tbyte dataPins = on?1:2;\n\tbyte colFirstThreeDigits = (col % 7)+1;\n\t\/\/byte colLastTwoDigits = floor(col\/7);\n\tbyte colLastTwoDigits = (int)(col\/7);\n\tbyte colByte = colFirstThreeDigits | (colLastTwoDigits << 3);\n\tbyte rowFirstThreeDigits = (row % 7)+1;\n\tbyte rowLastDigit = row<7;\n\tbyte rowByte = rowFirstThreeDigits | (rowLastDigit << 3);\n\tbyte firstbyte = (dataPins) | (colByte << 2);\n\tbyte secondbyte = rowByte;\n\t\n\tdigitalWrite(_latchPin, LOW); \n\tshiftOut(_dataPin, _clockPin, LSBFIRST, firstbyte); \n\tshiftOut(_dataPin, _clockPin, LSBFIRST, secondbyte); \n\tdigitalWrite(_latchPin, HIGH);\n\t\/\/delay(1);\n\t\n\t\/\/pulse the FP2800A's enable pins\n\tif(subPanel == 1){\n\t\tdigitalWrite(_enableSubPanel1Pin, HIGH); \n\t\tdelay(1);\n\t\tdigitalWrite(_enableSubPanel1Pin, LOW);\n\t} else if (subPanel == 2) {\n\t\tdigitalWrite(_enableSubPanel2Pin, HIGH); \n\t\tdelay(1);\n\t\tdigitalWrite(_enableSubPanel2Pin, LOW);\n\t}\n}\n\n\/\/void DotDisplay::updateDisplay(char *textMessage){\nvoid DotDisplay::updateDisplay(char textMessage[], char log[]){\n\tint currentColumn = 0; \n\tint currentRow = 0; \n\t\n\tchar temp[500];\n\tsprintf(log, \"_maxRowLength:%i, _maxNumRows:%i, MESSAGE:%s \", _maxRowLength, _maxNumRows,textMessage);\n\t\n\t\/\/goes through all characters\n\tfor (int ch = 0; ch < (_maxMessageLength);ch++){ \n\t\t\/\/get a character from the message\n\t\tint alphabetIndex = textMessage[ch] - ' '; \/\/Subtract '@' so we get a number\n\t\t\n\t\t\/\/Serial.println(alphabetIndex);\n\t\t\/\/strcat(log,\"Index: \");\n\t\t\/\/strcat(log,alphabetIndex);\n\t\tsprintf(temp, \"Character:%c \", textMessage[ch]);\n\t\t\n\t\tif ((alphabetIndex < 0) or (ch >=strlen(textMessage))) alphabetIndex=0; \n\t\t\n\t\t\/\/push it to the next row if necessary\n\t\tif((currentColumn + _fontWidth) > (DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY)){\n\t\t\tcurrentColumn=0;\n\t\t\tcurrentRow=currentRow+_fontHeight;\n\t\t}\n\n\n\t\t\/\/set all the bits in the next _fontWidth columns on the display\n\t\tfor(byte col = currentColumn; col<(currentColumn+_fontWidth); col++){\n\t\t\t\n\t\t\tbyte calculatedColumn = (col)%(_fontWidth+1);\n\t\t\t\/\/for(byte row = 0; row < _fontHeight; row++)\n\t\t\tint characterRow = 0;\n\t\t\tfor(byte row = currentRow; row < (currentRow + _fontHeight); row++){\n\t\t\t\t\/\/bool isOn = bitRead(pgm_read_byte(&(_fonteParam[alphabetIndex][calculatedColumn])),6-characterRow);\n\t\t\t\tbool isOn = bitRead((byte)_fonteParam[alphabetIndex][calculatedColumn],6-row);\/\/this index is needed as we are going from back to front\n\t\t\t\t\n\t\t\t\tsetDot(col, row, isOn);\n\t\t\t\t\/*\n\t\t\t\tif(printer) {\n\t\t\t\t\tprinter->print(isOn);\n\t\t\t\t}\n\t\t\t\t*\/\n\t\t\t\tchar dot[2];\n\t\t\t\tif (isOn) {\n\t\t\t\t\tstrcpy(dot,\"1\"); \n\t\t\t\t}else {\n\t\t\t\t\tstrcpy(dot,\"0\");\n\t\t\t\t} \n\t\t\t\tstrcat(temp,dot);\n\t\t\t\t\n\t\t\t\tcharacterRow++;\n\t\t\t}\n\t\t\t\/*\n\t\t\tif(printer) {\n\t\t\t\tprinter->println(\"\");\n\t\t\t}\n\t\t\t*\/\n\t\t\tstrcat(temp,\" \");\n\t\t}\n\t\t\/*\n\t\tif(printer) {\n\t\t\tprinter->println(\"\/\");\n\t\t}\n\t\t*\/\n\t\tstrcat(temp,\"\/\");\n\t\t\n\t\tcurrentColumn = currentColumn+(_fontWidth+1);\n\t}\n\tstrcat(log,temp);\n}\nFurther format changes\/*\nDisplayController.h - Library for Controlling a 14x28 bits FlipDot display sign using two FP2800A.\nCreated by Antonio Carioca, March 3, 2014.\n*\/\n\n\/\/#include \"Arduino.h\"\n\n\/\/#include \n\/\/#include \"application.h\"\n#include \"mark-iv-flip-dot-display-sign-14x28-controller.h\"\n\n\/* CONSTANTS *\/\n\/\/const int DISPLAY_SIZE = 4;\nconst int DISPLAY_PIXEL_WIDTH = 28;\nconst int DISPLAY_PIXEL_HEIGHT = 14;\nconst int DISPLAY_SUBPANEL_QTY = 2;\n\n\/\/=== F O N T ===\n\/\/ Font courtesy of aspro648\n\/\/ coden taken from\n\/\/ http:\/\/www.instructables.com\/files\/orig\/FQC\/A1CY\/H5EW79JK\/FQCA1CYH5EW79JK.txt\n\/\/ The @ will display as space character.\n\/\/ NOTE: MOVING ALL THE ARRAY BELOW TO PROGMEM\n\n\n\/\/DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, prog_uchar fonteParam[][5]){\nDotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, byte fonteParam[][5]){\n\n\tpinMode(dataPin, OUTPUT);\n\tpinMode(clockPin, OUTPUT);\n\tpinMode(latchPin, OUTPUT);\n\tpinMode(enableSubPanel1Pin, OUTPUT);\n\tpinMode(enableSubPanel2Pin, OUTPUT);\n\t\/\/disable FP2800A's\n\tdigitalWrite(enableSubPanel1Pin, LOW);\n\tdigitalWrite(enableSubPanel2Pin, LOW);\n\n\t_dataPin = dataPin;\n\t_clockPin = clockPin;\n\t_latchPin = latchPin;\n\t_enableSubPanel1Pin = enableSubPanel1Pin;\n\t_enableSubPanel2Pin = enableSubPanel2Pin;\n\t_fontWidth = fontWidth;\n\t_fontHeight = fontHeight;\n\t_fonteParam = fonteParam; \n\t\n\t\/\/_maxNumRows = floor((DISPLAY_PIXEL_HEIGHT+1)\/(_fontHeight));\n\t_maxNumRows = (int)((DISPLAY_PIXEL_HEIGHT+1)\/(_fontHeight));\n\t\/\/_maxRowLength = floor((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) \/ (_fontWidth+1));\n\t_maxRowLength = (int)((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) \/ (_fontWidth+1));\n\t_maxMessageLength = _maxRowLength * _maxNumRows;\n\n}\n\/*\nvoid DotDisplay::setSerial(HardwareSerial* hwPrint){\n\tprinter = hwPrint; \/\/operate on the address of print\n\tif(printer) {\n\t\tprinter->begin(9600);\n\t}\n}\n*\/\n\n\nvoid DotDisplay::setDot(byte col, byte row, bool on){\n\n\t\n\t\/\/accidentally reversed two data pins, so reversing back on the code here\n\t\/\/on = !on;\n\n\t\/\/2 pins - Data\n\t\/\/5 pins - Column\n\t\/\/4 pins - Rows\n\n\t\/\/4 pins - Enable FP2800A (4 subpanels)\n\tbyte subPanel = 1; \n\t\/\/disable FP2800A's\n\tdigitalWrite(_enableSubPanel1Pin, LOW);\n\tdigitalWrite(_enableSubPanel2Pin, LOW);\n\n\t\/\/enables next sunpanel\n\tif(col>=DISPLAY_PIXEL_WIDTH){\n\t\t\/\/subPanel = floor(col \/ DISPLAY_PIXEL_WIDTH)+1;\n\t\tsubPanel = (int)(col \/ DISPLAY_PIXEL_WIDTH)+1;\n\t\tcol=col-DISPLAY_PIXEL_WIDTH;\n\t}\n\n\t\/*\n\tif(printer) {\n\tprinter->print(\"col: \");\n\tprinter->print(col);\n\tprinter->print(\", \");\n\tprinter->print(\"subPanel: \");\n\tprinter->println(subPanel);\n\t}\n\t*\/\n\n\t\/\/ IGNOREx4 + ROWx4 + IGNOREx1 + COLUMNx5 + DATAx2\n\tbyte dataPins = on?1:2;\n\tbyte colFirstThreeDigits = (col % 7)+1;\n\t\/\/byte colLastTwoDigits = floor(col\/7);\n\tbyte colLastTwoDigits = (int)(col\/7);\n\tbyte colByte = colFirstThreeDigits | (colLastTwoDigits << 3);\n\tbyte rowFirstThreeDigits = (row % 7)+1;\n\tbyte rowLastDigit = row<7;\n\tbyte rowByte = rowFirstThreeDigits | (rowLastDigit << 3);\n\tbyte firstbyte = (dataPins) | (colByte << 2);\n\tbyte secondbyte = rowByte;\n\t\n\tdigitalWrite(_latchPin, LOW); \n\tshiftOut(_dataPin, _clockPin, LSBFIRST, firstbyte); \n\tshiftOut(_dataPin, _clockPin, LSBFIRST, secondbyte); \n\tdigitalWrite(_latchPin, HIGH);\n\t\/\/delay(1);\n\t\n\t\/\/pulse the FP2800A's enable pins\n\tif(subPanel == 1){\n\t\tdigitalWrite(_enableSubPanel1Pin, HIGH); \n\t\tdelay(1);\n\t\tdigitalWrite(_enableSubPanel1Pin, LOW);\n\t} else if (subPanel == 2) {\n\t\tdigitalWrite(_enableSubPanel2Pin, HIGH); \n\t\tdelay(1);\n\t\tdigitalWrite(_enableSubPanel2Pin, LOW);\n\t}\n}\n\n\/\/void DotDisplay::updateDisplay(char *textMessage){\nvoid DotDisplay::updateDisplay(char textMessage[], char log[]){\n\tint currentColumn = 0; \n\tint currentRow = 0; \n\t\n\tchar temp[500];\n\tsprintf(log, \"_maxRowLength:%i, _maxNumRows:%i, MESSAGE:%s\\n\", _maxRowLength, _maxNumRows,textMessage);\n\t\n\t\/\/goes through all characters\n\tfor (int ch = 0; ch < (_maxMessageLength);ch++){ \n\t\t\/\/get a character from the message\n\t\tint alphabetIndex = textMessage[ch] - ' '; \/\/Subtract '@' so we get a number\n\t\t\n\t\t\/\/Serial.println(alphabetIndex);\n\t\t\/\/strcat(log,\"Index: \");\n\t\t\/\/strcat(log,alphabetIndex);\n\t\tsprintf(temp, \"Character[%i]:%c \",ch, textMessage[ch]);\n\t\t\n\t\tif ((alphabetIndex < 0) or (ch >=strlen(textMessage))) alphabetIndex=0; \n\t\t\n\t\t\/\/push it to the next row if necessary\n\t\tif((currentColumn + _fontWidth) > (DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY)){\n\t\t\tcurrentColumn=0;\n\t\t\tcurrentRow=currentRow+_fontHeight;\n\t\t}\n\n\n\t\t\/\/set all the bits in the next _fontWidth columns on the display\n\t\tfor(byte col = currentColumn; col<(currentColumn+_fontWidth); col++){\n\t\t\t\n\t\t\tbyte calculatedColumn = (col)%(_fontWidth+1);\n\t\t\t\/\/for(byte row = 0; row < _fontHeight; row++)\n\t\t\tint characterRow = 0;\n\t\t\tfor(byte row = currentRow; row < (currentRow + _fontHeight); row++){\n\t\t\t\t\/\/bool isOn = bitRead(pgm_read_byte(&(_fonteParam[alphabetIndex][calculatedColumn])),6-characterRow);\n\t\t\t\tbool isOn = bitRead((byte)_fonteParam[alphabetIndex][calculatedColumn],6-row);\/\/this index is needed as we are going from back to front\n\t\t\t\t\n\t\t\t\tsetDot(col, row, isOn);\n\t\t\t\t\/*\n\t\t\t\tif(printer) {\n\t\t\t\t\tprinter->print(isOn);\n\t\t\t\t}\n\t\t\t\t*\/\n\t\t\t\tchar dot[2];\n\t\t\t\tif (isOn) {\n\t\t\t\t\tstrcpy(dot,\"1\"); \n\t\t\t\t}else {\n\t\t\t\t\tstrcpy(dot,\"0\");\n\t\t\t\t} \n\t\t\t\tstrcat(temp,dot);\n\t\t\t\t\n\t\t\t\tcharacterRow++;\n\t\t\t}\n\t\t\t\/*\n\t\t\tif(printer) {\n\t\t\t\tprinter->println(\"\");\n\t\t\t}\n\t\t\t*\/\n\t\t\tstrcat(temp,\" \");\n\t\t}\n\t\t\/*\n\t\tif(printer) {\n\t\t\tprinter->println(\"\/\");\n\t\t}\n\t\t*\/\n\t\tstrcat(temp,\"\/\");\n\t\t\n\t\tcurrentColumn = currentColumn+(_fontWidth+1);\n\t}\n\tstrcat(log,temp);\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\nusing namespace EasyCl;\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/DeviceManager\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSourceCode::SourceCode(string path)\n{\n\tload(path);\n}\n\nSourceCode::SourceCode()\n{\n}\n\nint SourceCode::load(string path)\n{\n\tisGood = false;\n\n\tifstream file(path);\n\tif(file.good() == false)\n\t{\n\t\tcout << \"Failed to load \" << path << \" .\" << endl;\n\t\treturn 0;\n\t}\n\n\tstring sourceCode(\n istreambuf_iterator(file),\n (istreambuf_iterator()));\n\n\tsource = cl::Program::Sources(1, make_pair(sourceCode.c_str(), sourceCode.length()+1));\n\tcode = sourceCode;\n\tisGood = true;\n\n\treturn 1;\n}\n\nbool SourceCode::good()\n{\n\treturn isGood;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ComputeDevice\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nComputeDevice::ComputeDevice(cl::Device dev,cl::Context con)\n{\n\tdevice = dev;\n\tcontext = con;\n\tcommandQueue = cl::CommandQueue(context, device);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ComputeDeviceList\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ComputeDevice::avliable()\n{\n\tint inQueueComunt = commandQueue.getInfo();\n\tif(inQueueComunt == 0)\n\t\treturn false;\n\treturn true;\n}\n\nComputeDevice* ComputeDeviceList::defaultDevice(cl_device_type deviceType)\n{\n\tif(deviceType == CL_DEVICE_TYPE_ALL)\n\t\treturn &devices[0];\n\n\tint deviceCount = devices.size();\n\tfor(int i=0;i();\n\t\t\/\/NOTE: I shouldn't need deviceType == CL_DEVICE_TYPE_ALL here. Just for completeness.\n\t\tif((type & deviceType) != 0 || deviceType == CL_DEVICE_TYPE_ALL)\n\t\t\treturn &devices[i];\n\t}\n\n\treturn NULL;\n}\n\nComputeDeviceList ComputeDeviceList::findDevice(string keyWord,cl_device_type deviceType)\n{\n\tint deviceCount = devices.size();\n\tComputeDeviceList list;\n\tfor(int i=0;i();\n\t\tif((type & deviceType) || deviceType == CL_DEVICE_TYPE_ALL)\n\t\t\tif(devices[i].device.getInfo().find(keyWord) != string::npos)\n\t\t\t\tlist.devices.push_back(devices[i]);\n\t}\n\n\treturn list;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ComputeDevice\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSoftware::Software(ComputeDevice* dev, SourceCode sou)\n{\n\t\/\/cl_int err = this->errorCode;\n\tdevice = dev;\n\tsourceCode = sou;\n\n\tprogram = cl::Program(device->context, sourceCode.source,&errorCode);\n\tif(errorCode != CL_SUCCESS)\n\t{\n\t\tcout << \"Error while creating Software\/cl::Program , code \" << errorCode << endl;\n\t\tisGood = false;\n\t}\n\telse\n\t\tisGood = true;\n}\n\nSoftware::Software()\n{\n}\n\nSoftware::~Software()\n{\n\tint size = buffers.size();\n\tfor(int i=0;i devs;\n\tdevs.push_back(device->device);\n\n\tcl_int result = program.build(devs,options.c_str());\n\tif(result != CL_SUCCESS)\n\t{\n\t\tcl_int err = 0;\n\t\t\/\/NOTE 2015\/5\/9 : nVidia OpenCL compiler SUCKS. the error message is mostly misleading.\n\t\t\/\/Go for AMD or Intel if possible. Really.\n\t\tcout << program.getBuildInfo(devs[0],&err) << endl;\n\n\t\tcout << \"Error occured while compiling OpenCL program\" << endl\n\t\t\t<< \"Error Code: \" << result << endl;\n\t\treturn result;\n\t}\n\treturn result;\n}\n\nbool Software::good()\n{\n\treturn isGood;\n}\n\ncl_int Software::getError()\n{\n\treturn errorCode;\n}\n\ncl_int Software::createBuffer(cl_mem_flags flags, size_t size, void* ptr,int& index)\n{\n\tint buffersListSize = buffers.size();\n\tint emptyIndex = -1;\n\tfor(int i=0;icontext,flags,size,ptr,&err);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error creating cl::Buffer , code \" << err << endl;\n\t\treturn err;\n\t}\n\tif(ptr != NULL)\n\t{\n\t\terr = device->commandQueue.enqueueWriteBuffer(*newBuffer,CL_TRUE,0,size, ptr);\n\t\tif(err != CL_SUCCESS)\n\t\t{\n\t\t\tcout << \"Error uploading data to device , code \" << err << endl;\n\t\t\tdelete newBuffer;\n\t\t\treturn err;\n\t\t}\n\t}\n\n\tif(emptyIndex >= 0)\n\t{\n\t\tbuffers[emptyIndex] = newBuffer;\n\t\tindex = emptyIndex;\n\t}\n\telse\n\t{\n\t\tindex = buffers.size();\n\t\tbuffers.push_back(newBuffer);\n\t}\n\treturn err;\n\n}\n\nvoid Software::releaseBuffer(int index)\n{\n\tdelete buffers[index];\n\tbuffers[index] = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/DeviceManager\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nKernel::Kernel(Software program, string funcName)\n{\n\tsoftware = program;\n\tcl_int err = 0;\n\n\tkernel = cl::Kernel(software.program, funcName.c_str(),&err);\n\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error creating kernel \" << funcName << \", code \" << err << endl;\n\t\treturn;\n\t}\n\n\tint argCount = kernel.getInfo();\n\tbuffers = new cl::Buffer* [argCount];\n\tdelProtect = new bool[argCount];\n\tfor(int i=0;i();\n\tfor(int i=0;i \" << &buffers[i] << \" : \" << i << endl;\n\t\t\tdelete buffers[i];\n\t\t}\n\tdelete [] buffers;\n\tdelete [] delProtect;\n}\n\ncl_int Kernel::setArgBuffer(int index, cl_mem_flags flags, size_t size, void* ptr)\n{\n\tif(buffers[index] != NULL && delProtect[index] == false)\n\t\tdelete buffers[index];\n\n\tcl_int err = 0;\n\tbuffers[index] = new cl::Buffer(software.device->context,flags,size,ptr,&err);\n\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error creating cl::Buffer , code \" << err << endl;\n\t\treturn err;\n\t}\n\n\tif(ptr != NULL)\n\t{\n\t\tcl::Event event;\n\t\terr = software.device->commandQueue.enqueueWriteBuffer(*buffers[index],CL_TRUE,0,size, ptr,NULL,&event);\n\t\tif(err != CL_SUCCESS)\n\t\t{\n\t\t\tcout << \"Error uploading data to device , code \" << err << endl;\n\t\t\t\/\/delete buffers[index];\n\t\t\treturn err;\n\t\t}\n\t\tevent.wait();\n\t}\n\n\n\terr = kernel.setArg(index, *buffers[index]);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error set argumant to kernel , code \" << err << endl;\n\t\tdelete buffers[index];\n\t\treturn err;\n\t}\n\tdelProtect[index] = false;\n\n\treturn err;\n}\n\ncl_int Kernel::setArg(int index, cl::Buffer& buf)\n{\n\tif(buffers[index] != NULL && delProtect[index] == false)\n\t\tdelete buffers[index];\n\tdelProtect[index] = true;\n\tbuffers[index] = &buf;\n\tcl_int err = kernel.setArg(index,buf);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error set argumant to kernel , code \" << err << endl;\n\t\treturn err;\n\t}\n\treturn err;\n}\n\ncl_int Kernel::enqueueNDRange(cl::NDRange offset, cl::NDRange global, cl::NDRange local)\n{\n\tcl_int err = 0;\n\tcl::Event event;\n\terr = software.device->commandQueue.enqueueNDRangeKernel(kernel,offset,global,local,NULL,&event);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error enqueuing NDRange Kernel, code \" << err << endl;\n\t\treturn err;\n\t}\n\tevent.wait();\n\treturn err;\n}\n\ncl_int Kernel::enqueueTask()\n{\n\tcl_int err = 0;\n\tcl::Event event;\n\terr = software.device->commandQueue.enqueueTask(kernel,NULL,&event);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error enqueuing Task, code \" << err << endl;\n\t\treturn err;\n\t}\n\tevent.wait();\n\treturn err;\n}\n\ncl_int Kernel::enqueueSPMD()\n{\n\tcl_int err = 0;\n\tint preferWorkSizeBase =\n\t\tkernel.getWorkGroupInfo\n\t\t(software.device->device);\n\tint maxComputeUnit = software.device->device.getInfo();\n\tint spmdSize = preferWorkSizeBase*maxComputeUnit;\n\tcl::NDRange global(spmdSize);\n\tcl::NDRange local(1);\n\tcl::Event event;\n\terr = software.device->commandQueue.enqueueNDRangeKernel(kernel,cl::NullRange,global,local,NULL,&event);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error enqueuing NDRange Kernel, code \" << err << endl;\n\t\treturn err;\n\t}\n\tevent.wait();\n\treturn err;\n\n}\n\ncl_int Kernel::readBuffer(int index, size_t size, void* ptr)\n{\n\tcl_int err = 0;\n\terr = software.device->commandQueue.enqueueReadBuffer(*buffers[index],CL_TRUE, 0, size, ptr);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error reading bufer \" << index << \", code \" << err << endl;\n\t\treturn err;\n\t}\n\treturn err;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/DeviceManager\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDeviceManager::DeviceManager()\n{\n\tvector platforms;\n\tcl::Platform::get(&platforms);\n\tint platformCount = platforms.size();\n\n\tfor(int i=0;i platformDevice = context.getInfo();\n\t\tComputeDeviceList deviceList;\n\t\tint deviceCount = platformDevice.size();\n\n\t\tfor(int j=0;jImprove SPMD#include \n\n#include \n#include \n#include \n\nusing namespace EasyCl;\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/DeviceManager\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSourceCode::SourceCode(string path)\n{\n\tload(path);\n}\n\nSourceCode::SourceCode()\n{\n}\n\nint SourceCode::load(string path)\n{\n\tisGood = false;\n\n\tifstream file(path);\n\tif(file.good() == false)\n\t{\n\t\tcout << \"Failed to load \" << path << \" .\" << endl;\n\t\treturn 0;\n\t}\n\n\tstring sourceCode(\n istreambuf_iterator(file),\n (istreambuf_iterator()));\n\n\tsource = cl::Program::Sources(1, make_pair(sourceCode.c_str(), sourceCode.length()+1));\n\tcode = sourceCode;\n\tisGood = true;\n\n\treturn 1;\n}\n\nbool SourceCode::good()\n{\n\treturn isGood;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ComputeDevice\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nComputeDevice::ComputeDevice(cl::Device dev,cl::Context con)\n{\n\tdevice = dev;\n\tcontext = con;\n\tcommandQueue = cl::CommandQueue(context, device);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ComputeDeviceList\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ComputeDevice::avliable()\n{\n\tint inQueueComunt = commandQueue.getInfo();\n\tif(inQueueComunt == 0)\n\t\treturn false;\n\treturn true;\n}\n\nComputeDevice* ComputeDeviceList::defaultDevice(cl_device_type deviceType)\n{\n\tif(deviceType == CL_DEVICE_TYPE_ALL)\n\t\treturn &devices[0];\n\n\tint deviceCount = devices.size();\n\tfor(int i=0;i();\n\t\t\/\/NOTE: I shouldn't need deviceType == CL_DEVICE_TYPE_ALL here. Just for completeness.\n\t\tif((type & deviceType) != 0 || deviceType == CL_DEVICE_TYPE_ALL)\n\t\t\treturn &devices[i];\n\t}\n\n\treturn NULL;\n}\n\nComputeDeviceList ComputeDeviceList::findDevice(string keyWord,cl_device_type deviceType)\n{\n\tint deviceCount = devices.size();\n\tComputeDeviceList list;\n\tfor(int i=0;i();\n\t\tif((type & deviceType) || deviceType == CL_DEVICE_TYPE_ALL)\n\t\t\tif(devices[i].device.getInfo().find(keyWord) != string::npos)\n\t\t\t\tlist.devices.push_back(devices[i]);\n\t}\n\n\treturn list;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ComputeDevice\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSoftware::Software(ComputeDevice* dev, SourceCode sou)\n{\n\t\/\/cl_int err = this->errorCode;\n\tdevice = dev;\n\tsourceCode = sou;\n\n\tprogram = cl::Program(device->context, sourceCode.source,&errorCode);\n\tif(errorCode != CL_SUCCESS)\n\t{\n\t\tcout << \"Error while creating Software\/cl::Program , code \" << errorCode << endl;\n\t\tisGood = false;\n\t}\n\telse\n\t\tisGood = true;\n}\n\nSoftware::Software()\n{\n}\n\nSoftware::~Software()\n{\n\tint size = buffers.size();\n\tfor(int i=0;i devs;\n\tdevs.push_back(device->device);\n\n\tcl_int result = program.build(devs,options.c_str());\n\tif(result != CL_SUCCESS)\n\t{\n\t\tcl_int err = 0;\n\t\t\/\/NOTE 2015\/5\/9 : nVidia OpenCL compiler SUCKS. the error message is mostly misleading.\n\t\t\/\/Go for AMD or Intel if possible. Really.\n\t\tcout << program.getBuildInfo(devs[0],&err) << endl;\n\n\t\tcout << \"Error occured while compiling OpenCL program\" << endl\n\t\t\t<< \"Error Code: \" << result << endl;\n\t\treturn result;\n\t}\n\treturn result;\n}\n\nbool Software::good()\n{\n\treturn isGood;\n}\n\ncl_int Software::getError()\n{\n\treturn errorCode;\n}\n\ncl_int Software::createBuffer(cl_mem_flags flags, size_t size, void* ptr,int& index)\n{\n\tint buffersListSize = buffers.size();\n\tint emptyIndex = -1;\n\tfor(int i=0;icontext,flags,size,ptr,&err);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error creating cl::Buffer , code \" << err << endl;\n\t\treturn err;\n\t}\n\tif(ptr != NULL)\n\t{\n\t\terr = device->commandQueue.enqueueWriteBuffer(*newBuffer,CL_TRUE,0,size, ptr);\n\t\tif(err != CL_SUCCESS)\n\t\t{\n\t\t\tcout << \"Error uploading data to device , code \" << err << endl;\n\t\t\tdelete newBuffer;\n\t\t\treturn err;\n\t\t}\n\t}\n\n\tif(emptyIndex >= 0)\n\t{\n\t\tbuffers[emptyIndex] = newBuffer;\n\t\tindex = emptyIndex;\n\t}\n\telse\n\t{\n\t\tindex = buffers.size();\n\t\tbuffers.push_back(newBuffer);\n\t}\n\treturn err;\n\n}\n\nvoid Software::releaseBuffer(int index)\n{\n\tdelete buffers[index];\n\tbuffers[index] = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/DeviceManager\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nKernel::Kernel(Software program, string funcName)\n{\n\tsoftware = program;\n\tcl_int err = 0;\n\n\tkernel = cl::Kernel(software.program, funcName.c_str(),&err);\n\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error creating kernel \" << funcName << \", code \" << err << endl;\n\t\treturn;\n\t}\n\n\tint argCount = kernel.getInfo();\n\tbuffers = new cl::Buffer* [argCount];\n\tdelProtect = new bool[argCount];\n\tfor(int i=0;i();\n\tfor(int i=0;i \" << &buffers[i] << \" : \" << i << endl;\n\t\t\tdelete buffers[i];\n\t\t}\n\tdelete [] buffers;\n\tdelete [] delProtect;\n}\n\ncl_int Kernel::setArgBuffer(int index, cl_mem_flags flags, size_t size, void* ptr)\n{\n\tif(buffers[index] != NULL && delProtect[index] == false)\n\t\tdelete buffers[index];\n\n\tcl_int err = 0;\n\tbuffers[index] = new cl::Buffer(software.device->context,flags,size,ptr,&err);\n\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error creating cl::Buffer , code \" << err << endl;\n\t\treturn err;\n\t}\n\n\tif(ptr != NULL)\n\t{\n\t\tcl::Event event;\n\t\terr = software.device->commandQueue.enqueueWriteBuffer(*buffers[index],CL_TRUE,0,size, ptr,NULL,&event);\n\t\tif(err != CL_SUCCESS)\n\t\t{\n\t\t\tcout << \"Error uploading data to device , code \" << err << endl;\n\t\t\t\/\/delete buffers[index];\n\t\t\treturn err;\n\t\t}\n\t\tevent.wait();\n\t}\n\n\n\terr = kernel.setArg(index, *buffers[index]);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error set argumant to kernel , code \" << err << endl;\n\t\tdelete buffers[index];\n\t\treturn err;\n\t}\n\tdelProtect[index] = false;\n\n\treturn err;\n}\n\ncl_int Kernel::setArg(int index, cl::Buffer& buf)\n{\n\tif(buffers[index] != NULL && delProtect[index] == false)\n\t\tdelete buffers[index];\n\tdelProtect[index] = true;\n\tbuffers[index] = &buf;\n\tcl_int err = kernel.setArg(index,buf);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error set argumant to kernel , code \" << err << endl;\n\t\treturn err;\n\t}\n\treturn err;\n}\n\ncl_int Kernel::enqueueNDRange(cl::NDRange offset, cl::NDRange global, cl::NDRange local)\n{\n\tcl_int err = 0;\n\tcl::Event event;\n\terr = software.device->commandQueue.enqueueNDRangeKernel(kernel,offset,global,local,NULL,&event);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error enqueuing NDRange Kernel, code \" << err << endl;\n\t\treturn err;\n\t}\n\tevent.wait();\n\treturn err;\n}\n\ncl_int Kernel::enqueueTask()\n{\n\tcl_int err = 0;\n\tcl::Event event;\n\terr = software.device->commandQueue.enqueueTask(kernel,NULL,&event);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error enqueuing Task, code \" << err << endl;\n\t\treturn err;\n\t}\n\tevent.wait();\n\treturn err;\n}\n\ncl_int Kernel::enqueueSPMD()\n{\n\tcl_int err = 0;\n\tint preferWorkSizeBase =\n\t\tkernel.getWorkGroupInfo\n\t\t(software.device->device);\n\tint maxComputeUnit = software.device->device.getInfo();\n\tint spmdSize = preferWorkSizeBase*maxComputeUnit;\n\tcl::NDRange global(spmdSize);\n\tcl::NDRange local(maxComputeUnit);\n\t\/\/cout << \"Base = \" << preferWorkSizeBase << \" CU = \" << maxComputeUnit << endl;\n\tcl::Event event;\n\terr = software.device->commandQueue.enqueueNDRangeKernel(kernel,cl::NullRange,global,local,NULL,&event);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error enqueuing NDRange Kernel, code \" << err << endl;\n\t\treturn err;\n\t}\n\tevent.wait();\n\treturn err;\n\n}\n\ncl_int Kernel::readBuffer(int index, size_t size, void* ptr)\n{\n\tcl_int err = 0;\n\terr = software.device->commandQueue.enqueueReadBuffer(*buffers[index],CL_TRUE, 0, size, ptr);\n\tif(err != CL_SUCCESS)\n\t{\n\t\tcout << \"Error reading bufer \" << index << \", code \" << err << endl;\n\t\treturn err;\n\t}\n\treturn err;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/DeviceManager\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDeviceManager::DeviceManager()\n{\n\tvector platforms;\n\tcl::Platform::get(&platforms);\n\tint platformCount = platforms.size();\n\n\tfor(int i=0;i platformDevice = context.getInfo();\n\t\tComputeDeviceList deviceList;\n\t\tint deviceCount = platformDevice.size();\n\n\t\tfor(int j=0;j"} {"text":"#ifndef REPEAT_HPP\n#define REPEAT_HPP\n\n#include \n#include \n#include \n\nnamespace iter {\n template \n struct repeat_iter {\n const Elem elem;\n size_t until;\n size_t start=0;\n repeat_iter(const Elem & elem,\n size_t until) : \n elem(elem),\n until(until) {}\n repeat_iter & operator++() {\n if (until != 0) ++start; \/\/no point in repeating 0 times\n \/\/so use that to repeat infinitely\n return *this;\n }\n bool operator!=(const repeat_iter &) {\n if (until == 0) return true;\n else if (start != until) return true;\n else return false;\n }\n Elem operator*()\n {\n return elem;\n }\n };\n template \n iterator_range> repeat(\n const Elem & elem,\n size_t until=0)\n \/\/-1 causes it to repeat infintely \n {\n return iterator_range>(\n repeat_iter(elem,until),\n repeat_iter(elem,until));\/\/just a dummy iter\n }\n \n}\n\n#endif \/\/REPEAT_HPP\nVarious touchups to repeat#ifndef REPEAT_HPP\n#define REPEAT_HPP\n\n#include \n\n#include \n\nnamespace iter {\n template \n class repeat_iter {\n private:\n const Elem elem;\n size_t until;\n size_t start=0;\n public:\n repeat_iter(const Elem & elem, size_t until) : \n elem(elem),\n until(until)\n { }\n\n repeat_iter & operator++() {\n if (this->until != 0) ++start; \/\/no point in repeating 0 times\n \/\/so use that to repeat infinitely\n return *this;\n }\n\n bool operator!=(const repeat_iter &) const {\n return this->until == 0 || this->start != this->until;\n }\n\n Elem operator*() const {\n return this->elem;\n }\n };\n\n \/\/-1 causes it to repeat infintely \n template \n iterator_range> repeat(\n const Elem & elem,\n size_t until=0)\n {\n return iterator_range>(\n repeat_iter(elem, until),\n repeat_iter(elem, until));\/\/just a dummy iter\n }\n \n}\n\n#endif \/\/REPEAT_HPP\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2011 Christian Van Brussel, Institute of Information\n and Communication Technologies, Electronics and Applied Mathematics\n at Universite catholique de Louvain, Belgium\n http:\/\/www.uclouvain.be\/en-icteam.html\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n#include \"cssysdef.h\"\n\n#include \"imap\/services.h\"\n#include \"imesh\/animesh.h\"\n#include \"iutil\/document.h\"\n#include \"iutil\/vfs.h\"\n#include \"cstool\/animeshtools.h\"\n#include \"csutil\/scf.h\"\n#include \"csutil\/stringquote.h\"\n\n#include \"splitmorph.h\"\n\nCS_PLUGIN_NAMESPACE_BEGIN (SplitMorph)\n{\n SCF_IMPLEMENT_FACTORY (SplitMorphLoader);\n\n SplitMorphLoader::SplitMorphLoader (iBase* parent)\n : scfImplementationType (this, parent)\n {}\n\n static const char* msgidFactory = \"crystalspace.mesh.loader.factory.animesh.splitmorph\";\n\n bool SplitMorphLoader::Initialize (iObjectRegistry* registry)\n {\n this->registry = registry;\n synldr = csQueryRegistry (registry);\n InitTokenTable (xmltokens);\n\n return true;\n }\n\n csPtr SplitMorphLoader::Parse (iDocumentNode* node,\n\t\t\t\t\tiStreamSource* ssource,\n\t\t\t\t\tiLoaderContext* ldr_context,\n\t\t\t\t\tiBase* context)\n {\n csString path, realPath, file, name, mask;\n\n csRef it = node->GetNodes ();\n while (it->HasNext ())\n {\n csRef child = it->Next ();\n if (child->GetType () != CS_NODE_ELEMENT) continue;\n const char* value = child->GetValue ();\n csStringID id = xmltokens.Request (value);\n switch (id)\n {\n case XMLTOKEN_VFSPATH:\n\tpath = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_REALPATH:\n\trealPath = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_BASEFILE:\n\tfile = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_MESHNAME:\n\tname = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_MASK:\n\tmask = child->GetContentsValue ();\n\tbreak;\n\n default:\n synldr->ReportBadToken (child);\n return csPtr (nullptr);\n }\n }\n\n \/\/ Check that the parameters are invalid\n if (file.IsEmpty ())\n {\n synldr->ReportError (msgidFactory, node, \"No base file provided!\");\n return csPtr (nullptr);\n }\n\n \/\/ If no name is provided then use the one from the mesh wrapper\n if (name.IsEmpty ())\n {\n if (node->GetParent ())\n\tname = node->GetParent ()->GetAttributeValue (\"name\");\n else name = \"splitmorph\";\n }\n\n \/\/ Check for a temporary path to be mounted\n if (!realPath.IsEmpty ())\n {\n csRef vfs = csQueryRegistry (registry);\n if (!vfs->Mount (\"\/tmp\/splitmorph\", realPath))\n {\n\tsynldr->ReportError (msgidFactory, node, \"Could not mount real path %s!\",\n\t\t\t CS::Quote::Single (realPath));\n\treturn csPtr (nullptr);\n }\n\n path = \"\/tmp\/splitmorph\/\";\n }\n\n \/\/ Import the animesh\n csRef meshFactory =\n CS::Mesh::AnimatedMeshTools::ImportSplitMorphMesh (registry, path, file, name, mask);\n if (!meshFactory)\n return csPtr (nullptr);\n\n \/\/ Unmount the temporary path\n if (!realPath.IsEmpty ())\n {\n csRef vfs = csQueryRegistry (registry);\n vfs->Unmount (\"\/tmp\/splitmorph\", nullptr);\n }\n\n return scfQueryInterface (meshFactory);\n }\n\n}\nCS_PLUGIN_NAMESPACE_END (SplitMorph)\nFixed memory leak\/*\n Copyright (C) 2011 Christian Van Brussel, Institute of Information\n and Communication Technologies, Electronics and Applied Mathematics\n at Universite catholique de Louvain, Belgium\n http:\/\/www.uclouvain.be\/en-icteam.html\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n#include \"cssysdef.h\"\n\n#include \"imap\/services.h\"\n#include \"imesh\/animesh.h\"\n#include \"iutil\/document.h\"\n#include \"iutil\/vfs.h\"\n#include \"cstool\/animeshtools.h\"\n#include \"csutil\/scf.h\"\n#include \"csutil\/stringquote.h\"\n\n#include \"splitmorph.h\"\n\nCS_PLUGIN_NAMESPACE_BEGIN (SplitMorph)\n{\n SCF_IMPLEMENT_FACTORY (SplitMorphLoader);\n\n SplitMorphLoader::SplitMorphLoader (iBase* parent)\n : scfImplementationType (this, parent)\n {}\n\n static const char* msgidFactory = \"crystalspace.mesh.loader.factory.animesh.splitmorph\";\n\n bool SplitMorphLoader::Initialize (iObjectRegistry* registry)\n {\n this->registry = registry;\n synldr = csQueryRegistry (registry);\n InitTokenTable (xmltokens);\n\n return true;\n }\n\n csPtr SplitMorphLoader::Parse (iDocumentNode* node,\n\t\t\t\t\tiStreamSource* ssource,\n\t\t\t\t\tiLoaderContext* ldr_context,\n\t\t\t\t\tiBase* context)\n {\n csString path, realPath, file, name, mask;\n\n csRef it = node->GetNodes ();\n while (it->HasNext ())\n {\n csRef child = it->Next ();\n if (child->GetType () != CS_NODE_ELEMENT) continue;\n const char* value = child->GetValue ();\n csStringID id = xmltokens.Request (value);\n switch (id)\n {\n case XMLTOKEN_VFSPATH:\n\tpath = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_REALPATH:\n\trealPath = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_BASEFILE:\n\tfile = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_MESHNAME:\n\tname = child->GetContentsValue ();\n\tbreak;\n\n case XMLTOKEN_MASK:\n\tmask = child->GetContentsValue ();\n\tbreak;\n\n default:\n synldr->ReportBadToken (child);\n return csPtr (nullptr);\n }\n }\n\n \/\/ Check that the parameters are invalid\n if (file.IsEmpty ())\n {\n synldr->ReportError (msgidFactory, node, \"No base file provided!\");\n return csPtr (nullptr);\n }\n\n \/\/ If no name is provided then use the one from the mesh wrapper\n if (name.IsEmpty ())\n {\n if (node->GetParent ())\n\tname = node->GetParent ()->GetAttributeValue (\"name\");\n else name = \"splitmorph\";\n }\n\n \/\/ Check for a temporary path to be mounted\n if (!realPath.IsEmpty ())\n {\n csRef vfs = csQueryRegistry (registry);\n if (!vfs->Mount (\"\/tmp\/splitmorph\", realPath))\n {\n\tsynldr->ReportError (msgidFactory, node, \"Could not mount real path %s!\",\n\t\t\t CS::Quote::Single (realPath));\n\treturn csPtr (nullptr);\n }\n\n path = \"\/tmp\/splitmorph\/\";\n }\n\n \/\/ Import the animesh\n csRef meshFactory =\n CS::Mesh::AnimatedMeshTools::ImportSplitMorphMesh (registry, path, file, name, mask);\n if (!meshFactory)\n return csPtr (nullptr);\n\n \/\/ Unmount the temporary path\n if (!realPath.IsEmpty ())\n {\n csRef vfs = csQueryRegistry (registry);\n vfs->Unmount (\"\/tmp\/splitmorph\", nullptr);\n }\n\n return csPtr (scfQueryInterface (meshFactory));\n }\n\n}\nCS_PLUGIN_NAMESPACE_END (SplitMorph)\n<|endoftext|>"} {"text":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef STREAM_HH_\n#define STREAM_HH_\n\n#include \"future.hh\"\n#include \n#include \n\n\/\/ A stream\/subscription pair is similar to a promise\/future pair,\n\/\/ but apply to a sequence of values instead of a single value.\n\/\/\n\/\/ A stream<> is the producer side. It may call produce() as long\n\/\/ as the future<> returned from the previous invocation is ready.\n\/\/ To signify no more data is available, call close().\n\/\/\n\/\/ A subscription<> is the consumer side. It is created by a call\n\/\/ to stream::listen(). Calling subscription::start(),\n\/\/ which registers the data processing callback, starts processing\n\/\/ events. It may register for end-of-stream notifications by\n\/\/ chaining the when_done() future, which also delivers error\n\/\/ events (as exceptions).\n\/\/\n\/\/ The consumer can pause generation of new data by returning\n\/\/ a non-ready future; when the future becomes ready, the producer\n\/\/ will resume processing.\n\ntemplate \nclass stream;\n\ntemplate \nclass subscription;\n\ntemplate \nclass stream {\n subscription* _sub = nullptr;\n promise<> _done;\n promise<> _ready;\npublic:\n using next_fn = std::function (T...)>;\n stream() = default;\n stream(const stream&) = delete;\n stream(stream&&) = delete;\n ~stream();\n void operator=(const stream&) = delete;\n void operator=(stream&&) = delete;\n\n \/\/ Returns a subscription that reads value from this\n \/\/ stream.\n subscription listen();\n\n \/\/ Returns a subscription that reads value from this\n \/\/ stream, and also sets up the listen function.\n subscription listen(next_fn next);\n\n \/\/ Becomes ready when the listener is ready to accept\n \/\/ values. Call only once, when beginning to produce\n \/\/ values.\n future<> started();\n\n \/\/ Produce a value. Call only after started(), and after\n \/\/ a previous produce() is ready.\n future<> produce(T... data);\n\n \/\/ End the stream. Call only after started(), and after\n \/\/ a previous produce() is ready. No functions may be called\n \/\/ after this.\n void close();\n\n \/\/ Signal an error. Call only after started(), and after\n \/\/ a previous produce() is ready. No functions may be called\n \/\/ after this.\n template \n void set_exception(E ex);\nprivate:\n void pause(future<> can_continue);\n void start();\n friend class subscription;\n};\n\ntemplate \nclass subscription {\npublic:\n using next_fn = typename stream::next_fn;\nprivate:\n stream* _stream;\n next_fn _next;\nprivate:\n explicit subscription(stream* s);\npublic:\n subscription(subscription&& x);\n ~subscription();\n\n \/\/\/ \\brief Start receiving events from the stream.\n \/\/\/\n \/\/\/ \\param next Callback to call for each event\n void start(std::function (T...)> next);\n\n \/\/ Becomes ready when the stream is empty, or when an error\n \/\/ happens (in that case, an exception is held).\n future<> done();\n\n friend class stream;\n};\n\n\ntemplate \ninline\nstream::~stream() {\n if (_sub) {\n _sub->_stream = nullptr;\n }\n}\n\ntemplate \ninline\nsubscription\nstream::listen() {\n return subscription(this);\n}\n\ntemplate \ninline\nsubscription\nstream::listen(next_fn next) {\n auto sub = subscription(this);\n sub.start(std::move(next));\n return sub;\n}\n\ntemplate \ninline\nfuture<>\nstream::started() {\n return _ready.get_future();\n}\n\ntemplate \ninline\nfuture<>\nstream::produce(T... data) {\n return _sub->_next(std::move(data)...).then_wrapped([this] (future<> f) {\n try {\n f.get();\n } catch (...) {\n _done.set_exception(std::current_exception());\n \/\/ FIXME: tell the producer to stop producing\n abort();\n }\n });\n}\n\ntemplate \ninline\nvoid\nstream::close() {\n _done.set_value();\n}\n\ntemplate \ntemplate \ninline\nvoid\nstream::set_exception(E ex) {\n _sub->_done.set_exception(ex);\n}\n\ntemplate \ninline\nsubscription::subscription(stream* s)\n : _stream(s) {\n assert(!_stream->_sub);\n _stream->_sub = this;\n}\n\ntemplate \ninline\nvoid\nsubscription::start(std::function (T...)> next) {\n _next = std::move(next);\n _stream->_ready.set_value();\n}\n\ntemplate \ninline\nsubscription::~subscription() {\n if (_stream) {\n _stream->_sub = nullptr;\n }\n}\n\ntemplate \ninline\nsubscription::subscription(subscription&& x)\n : _stream(x._stream), _next(std::move(x._next)) {\n x._stream = nullptr;\n if (_stream) {\n _stream->_sub = this;\n }\n}\n\ntemplate \ninline\nfuture<>\nsubscription::done() {\n return _stream->_done.get_future();\n}\n\n#endif \/* STREAM_HH_ *\/\nstream: use a smaller stick for failed producers\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef STREAM_HH_\n#define STREAM_HH_\n\n#include \"future.hh\"\n#include \n#include \n\n\/\/ A stream\/subscription pair is similar to a promise\/future pair,\n\/\/ but apply to a sequence of values instead of a single value.\n\/\/\n\/\/ A stream<> is the producer side. It may call produce() as long\n\/\/ as the future<> returned from the previous invocation is ready.\n\/\/ To signify no more data is available, call close().\n\/\/\n\/\/ A subscription<> is the consumer side. It is created by a call\n\/\/ to stream::listen(). Calling subscription::start(),\n\/\/ which registers the data processing callback, starts processing\n\/\/ events. It may register for end-of-stream notifications by\n\/\/ chaining the when_done() future, which also delivers error\n\/\/ events (as exceptions).\n\/\/\n\/\/ The consumer can pause generation of new data by returning\n\/\/ a non-ready future; when the future becomes ready, the producer\n\/\/ will resume processing.\n\ntemplate \nclass stream;\n\ntemplate \nclass subscription;\n\ntemplate \nclass stream {\n subscription* _sub = nullptr;\n promise<> _done;\n promise<> _ready;\npublic:\n using next_fn = std::function (T...)>;\n stream() = default;\n stream(const stream&) = delete;\n stream(stream&&) = delete;\n ~stream();\n void operator=(const stream&) = delete;\n void operator=(stream&&) = delete;\n\n \/\/ Returns a subscription that reads value from this\n \/\/ stream.\n subscription listen();\n\n \/\/ Returns a subscription that reads value from this\n \/\/ stream, and also sets up the listen function.\n subscription listen(next_fn next);\n\n \/\/ Becomes ready when the listener is ready to accept\n \/\/ values. Call only once, when beginning to produce\n \/\/ values.\n future<> started();\n\n \/\/ Produce a value. Call only after started(), and after\n \/\/ a previous produce() is ready.\n future<> produce(T... data);\n\n \/\/ End the stream. Call only after started(), and after\n \/\/ a previous produce() is ready. No functions may be called\n \/\/ after this.\n void close();\n\n \/\/ Signal an error. Call only after started(), and after\n \/\/ a previous produce() is ready. No functions may be called\n \/\/ after this.\n template \n void set_exception(E ex);\nprivate:\n void pause(future<> can_continue);\n void start();\n friend class subscription;\n};\n\ntemplate \nclass subscription {\npublic:\n using next_fn = typename stream::next_fn;\nprivate:\n stream* _stream;\n next_fn _next;\nprivate:\n explicit subscription(stream* s);\npublic:\n subscription(subscription&& x);\n ~subscription();\n\n \/\/\/ \\brief Start receiving events from the stream.\n \/\/\/\n \/\/\/ \\param next Callback to call for each event\n void start(std::function (T...)> next);\n\n \/\/ Becomes ready when the stream is empty, or when an error\n \/\/ happens (in that case, an exception is held).\n future<> done();\n\n friend class stream;\n};\n\n\ntemplate \ninline\nstream::~stream() {\n if (_sub) {\n _sub->_stream = nullptr;\n }\n}\n\ntemplate \ninline\nsubscription\nstream::listen() {\n return subscription(this);\n}\n\ntemplate \ninline\nsubscription\nstream::listen(next_fn next) {\n auto sub = subscription(this);\n sub.start(std::move(next));\n return sub;\n}\n\ntemplate \ninline\nfuture<>\nstream::started() {\n return _ready.get_future();\n}\n\ntemplate \ninline\nfuture<>\nstream::produce(T... data) {\n return _sub->_next(std::move(data)...).then_wrapped([this] (future<> f) {\n try {\n f.get();\n } catch (...) {\n _done.set_exception(std::current_exception());\n \/\/ FIXME: tell the producer to stop producing\n throw;\n }\n });\n}\n\ntemplate \ninline\nvoid\nstream::close() {\n _done.set_value();\n}\n\ntemplate \ntemplate \ninline\nvoid\nstream::set_exception(E ex) {\n _sub->_done.set_exception(ex);\n}\n\ntemplate \ninline\nsubscription::subscription(stream* s)\n : _stream(s) {\n assert(!_stream->_sub);\n _stream->_sub = this;\n}\n\ntemplate \ninline\nvoid\nsubscription::start(std::function (T...)> next) {\n _next = std::move(next);\n _stream->_ready.set_value();\n}\n\ntemplate \ninline\nsubscription::~subscription() {\n if (_stream) {\n _stream->_sub = nullptr;\n }\n}\n\ntemplate \ninline\nsubscription::subscription(subscription&& x)\n : _stream(x._stream), _next(std::move(x._next)) {\n x._stream = nullptr;\n if (_stream) {\n _stream->_sub = this;\n }\n}\n\ntemplate \ninline\nfuture<>\nsubscription::done() {\n return _stream->_done.get_future();\n}\n\n#endif \/* STREAM_HH_ *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ This file is a part of pomerol - a scientific ED code for obtaining\n\/\/ properties of a Hubbard model on a finite-size lattice\n\/\/\n\/\/ Copyright (C) 2010-2013 Andrey Antipov \n\/\/ Copyright (C) 2010-2013 Igor Krivenko \n\/\/\n\/\/ pomerol is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ pomerol 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 General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with pomerol. If not, see .\n\n\/** \\file examples\/example01.cpp\n** \\brief An example of how to use the pomerol library.\n**\n** \\author Andrey Antipov (Andrey.E.Antipov@gmail.com)\n*\/\n\n\/* In this file we provide a tutorial example of how to actually use the\n * pomerol library.\n *\/\n\n\/\/ Include the pomerol library\n#include \n\n\/\/ Use the namespace of Pomerol. Otherwise Pomerol::{name}\n\/\/ calling of the objects would be required\nusing namespace Pomerol;\n\nboost::mpi::communicator world;\n\/\/ Small routine to make fancy screen output for text.\nvoid print_section (const std::string& str);\n\n\/* Generic tips:\n * The calculation is done by computing a set of objects in the following order:\n * Lattice -> IndexClassification -> IndexHamiltonian -> Symmetrizer ->\n * -> StatesClassification -> Hamiltonian -> FieldOperator\n ;\n * (for thermal objects, such as GFs in Matsubara domain)\n * -> DensityMatrix -> Greens Function\n * -> TwoParticle GF -> Vertex4\n * The detailed explanation of each class is given below.\n *\/\n\nint main(int argc, char* argv[])\n{\n boost::mpi::environment MpiEnv(argc, argv);\n world = boost::mpi::communicator();\n\n \/* As pomerol is an ED code, it requires a finite-size lattice to be\n * provided. Here is an example of a lattice of 2 sites. *\/\n \/\/ First, we construct an empty lattice\n Lattice L;\n \/\/ Add a site with a name \"A\", that has 1 orbitals and 2 spins.\n L.addSite(new Lattice::Site(\"A\",1,2));\n \/\/ Add one more site with a name \"B\". It also has 1 orbitals and 2 spins.\n L.addSite(new Lattice::Site(\"B\",1,2));\n\n \/\/ Let us now connect two sites with a hopping term, with matrix element -1.\n RealType t=1.0;\n LatticePresets::addHopping(&L, \"A\",\"B\", -t);\n\n \/* Now add interaction. In order to provide some custom interaction, one can\n * give any custom term of 4,6 operators. This is done via\n * Lattice.addTerm(Lattice::Term) method.\n * We will use Hubbard-type n_{up}n_{down} interaction. For this and some\n * other typical interactions, such as SzSz or SS couplings a shortcut is\n * provided in the LatticePresets class.\n *\/\n RealType U = 2.0;\n RealType mu = 1.0;\n \/\/ LatticePresets::addCoulombS adds Un_{up}n_{down} for 1 orbital and 2 spins.\n LatticePresets::addCoulombS(&L, \"A\", U, -mu);\n LatticePresets::addCoulombS(&L, \"B\", U, -mu);\n\n \/\/ Let us now print which sites and terms are defined.\n if (!world.rank()) {\n INFO(\"Sites\"); \/\/ equivalent to std::cout << \"Sites\" << std::endl;\n L.printSites();\n INFO(\"Terms\");\n L.printTerms(2);\n INFO(\"Terms with 4 operators\");\n L.printTerms(4);\n\n print_section(\"Indices\");\n };\n \/* In order to go further, we need to introduce the index space. An index\n * is a number that uniquely identifies a combination of (site,orbital,spin).\n * The object that takes care of handling indices is called\n * IndexClassification.\n *\/\n\n \/\/ Construct IndexClassification\n IndexClassification IndexInfo(L.getSiteMap());\n\n \/* Important remark 1!\n * Most of the objects that are defined within Pomerol library have the\n * following semantics. They can be constructed, prepared and computed.\n * This means\n * - constructed: No operations are done except from initializing links to\n * other objects that current class depends on.\n * - prepared: Typically, this is when all memory allocation takes place.\n * - computed: The actual computation. This is the most costly operation.\n * When no heavy computation is done, it can be done during\n * preparation stage.\n *\/\n\n \/\/ IndexClassification does not require much computing time, so everything\n \/\/ is calculated during prepare() method.\n IndexInfo.prepare();\n\n \/\/ Print which indices we have\n IndexInfo.printIndices();\n \/\/ Save the total number of indices.\n ParticleIndex IndexSize = IndexInfo.getIndexSize();\n\n print_section(\"Matrix element storage\");\n \/* We now need to construct the actual Hamiltonian. First, we need to create\n * it in the index space, e.g. write down a formula with all terms. It is\n * useful for a subsequent symmetry analysis. The corresponding class is called\n * an IndexHamiltonian. It is inherited from Operator class, which is designed\n * to represent a generic second-quantized fermionic operator and fully model\n * the algebra of fermionic operators. This means one can multiply, add,\n * subtract it, and also calculate the commutator of two operators, etc.\n *\/\n\n \/\/ First construct the IndexHamiltonian object.\n IndexHamiltonian Storage(&L,IndexInfo);\n \/\/ Then prepare it. As previously no long computation required, so everything\n \/\/ is done in the prepare() method.\n Storage.prepare();\n \/\/ Print out the Hamiltonian.\n INFO(\"Terms\");\n INFO(Storage);\n\n \/\/ Let us make a test, that our Hamiltonian commutes with an operator, that\n \/\/ represents the total number of particles. The preset for such operator is\n \/\/ defined in OperatorPresets.h and .cpp files.\n OperatorPresets::N N(IndexSize);\n INFO(\"N terms\");\n N.printAllTerms();\n if ((Storage.commutes(N))) INFO(\"H commutes with N\");\n\n \/* The Hamiltonian that is set now, has a set of symmetries. One can identify\n * them by checking that the IndexHamiltonian commutes with the corresponding\n * symmetry operator. The class that does it is called Symmetrizer.\n *\/\n \/\/ Construct Symmetrizer\n Symmetrizer Symm(IndexInfo, Storage);\n \/* At this stage Symmetrizer checks symmetries with some predefined operators,\n * such as number-of-particles and sz operators.\n *\/\n Symm.compute();\n \/* A custom check for a symmetry can be done using\n * Symmetrizer.checkSymmetry(Operator).\n * After checking all the symmetry operations, Symmetrizer defines a set of\n * quantum numbers, which uniquely identifies the closed region in the\n * phase space.\n * Calling Symmetrizer::compute(true) will skip all symmetry operations and\n * result in a single Hamiltonian block in the end.\n *\/\n\n \/* We shall proceed now with obtaining the spectrum of the Hamiltonian.\n * First, introduce a basis of Fock states and classify them into blocks\n * that correspond to a set of quantum numbers. This is done in the\n * StatesClassification class. It provides all the information about Blocks\n * and FockStates.\n *\/\n StatesClassification S(IndexInfo,Symm);\n S.compute();\n\n \/* We now convert the IndexHamiltonian into the basis of Fock States. The\n * Hamiltonian class is the one, which does it.\n *\/\n Hamiltonian H(IndexInfo, Storage, S);\n \/\/ Enter all blocks of the Hamiltonian.\n H.prepare();\n \/\/ Diagonalize them.\n H.compute(world);\n \/\/ Get ground energy.\n INFO(\"The value of ground energy is \" << H.getGroundEnergy());\n\n \/* Important remark 2!\n * All the calculations done in the pomerol code are done with respect to the\n * block structure of the Hamiltonian. All objects that operate in Fock\n * space and all thermal objects, such as Green's functions are in fact a\n * set of pieces (called \"parts\") that operate on a certain block or set of\n * blocks. As such all actual computations are done within this parts and\n * grand objects like Green's functions or Hamiltonian basically just loops\n * over parts and tells them to run prepare() or compute() methods.\n *\/\n\n \/* At this stage the Hamiltonian, defined in Fock Space is\n * entered and diagonalized and it's spectrum and eigenfunctions can be\n * directly accessed to calculate some observables.\n *\n * We shall now proceed to the calculations of thermal quantities, e.g.\n * assume that our finite-size system was adiabatically connected to a thermal\n * reservoir, that sets certain temperature (in fact, inverse temperature\n * beta). This means, that the observables in the systems should be calculated\n * with a density-matrix exp(-\\beta H), rather than by averaging with the\n * ground state. In the eigenbasis of the Hamiltonian the calculation of\n * a density matrix is straightforward - it is just \\exp(-\\beta (E_i - E_0)),\n * where E_i is an energy of the excited state, and E_0 is the ground energy.\n * The procedure is done as following:\n *\/\n\n \/\/ Define inverse temperature\n RealType beta = 10.0;\n\n \/\/ Create the Density Matrix.\n DensityMatrix rho(S,H,beta);\n \/\/ Allocate all internal parts of density matrix.\n rho.prepare();\n \/\/ Actually compute the density matrix.\n rho.compute();\n \/\/ Truncate blocks that have only small contributions\n \/\/ rho.truncateBlocks(1e-15);\n\n \/* Lehmanns representation of the Green's function required creation and\n * annihilation operators, calculated in the basis of eigenstates of the\n * Hamiltonian. Creation\/AnnihilationOperator are the classes that do it.\n *\/\n\n \/\/ Let us create c^+_{\"A\",up} and c_{\"A\",up}\n ParticleIndex up_index = IndexInfo.getIndex(\"A\",0,up);\n CreationOperator CX(IndexInfo,S,H,up_index);\n CX.prepare();\n CX.compute();\n AnnihilationOperator C(IndexInfo,S,H,up_index);\n C.prepare();\n C.compute();\n\n \/\/ The local Greens function in the Matsubara domain G_{\"A\",up}(i\\omega_n)\n GreensFunction GF(S,H,C,CX, rho);\n GF.prepare();\n \/* Calculate the GF and cache values for 10 Matsubaras.\n * These values will be fast to retrieve. The other values are also\n * accessible, but will require a short calculation to be done.\n *\/\n GF.compute();\n\n for(int n = 0; n<10; ++n) {\n INFO(n << \" | \" << GF(n));\n }\n\n \/* The two particle GF is constructed in analogy to the single-particle GF,\n * it requires 4 operators to be provided though.\n *\/\n TwoParticleGF Chi(S,H,C,C,CX,CX,rho);\n \/* Some knobs to make calc faster - the larger the values of tolerances, the faster is calc, but rounding errors may show.\n Typically these errors are less then 10^{-3} of the value.\n Here are some knobs that give very high-precision. If you want to make things faster, and when many values on\n different frequencies required - change ReduceResonanceTolerance to something like 10^-4. *\/\n \/** A difference in energies with magnitude less than this value is treated as zero. *\/\n Chi.ReduceResonanceTolerance = 1e-8;\n \/** Minimal magnitude of the coefficient of a term to take it into account. *\/\n Chi.CoefficientTolerance = 1e-16;\n \/** Minimal magnitude of the coefficient of a term to take it into account with respect to amount of terms. *\/\n Chi.MultiTermCoefficientTolerance = 1e-6;\n\n Chi.prepare();\n std::vector > freqs_2pgf;\n Chi.compute(false, freqs_2pgf, world);\n\n if (world.rank()==0) {\n int nm = 2;\n for(int n1 = -nm; n1Update tutorial to add susceptibility and ensemble average\/\/\n\/\/ This file is a part of pomerol - a scientific ED code for obtaining\n\/\/ properties of a Hubbard model on a finite-size lattice\n\/\/\n\/\/ Copyright (C) 2010-2013 Andrey Antipov \n\/\/ Copyright (C) 2010-2013 Igor Krivenko \n\/\/\n\/\/ pomerol is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ pomerol 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 General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with pomerol. If not, see .\n\n\/** \\file examples\/example01.cpp\n** \\brief An example of how to use the pomerol library.\n**\n** \\author Andrey Antipov (Andrey.E.Antipov@gmail.com)\n*\/\n\n\/* In this file we provide a tutorial example of how to actually use the\n * pomerol library.\n *\/\n\n\/\/ Include the pomerol library\n#include \n\n\/\/ Use the namespace of Pomerol. Otherwise Pomerol::{name}\n\/\/ calling of the objects would be required\nusing namespace Pomerol;\n\nboost::mpi::communicator world;\n\/\/ Small routine to make fancy screen output for text.\nvoid print_section (const std::string& str);\n\n\/* Generic tips:\n * The calculation is done by computing a set of objects in the following order:\n * Lattice -> IndexClassification -> IndexHamiltonian -> Symmetrizer ->\n * -> StatesClassification -> Hamiltonian -> FieldOperator\n ;\n * (for thermal objects, such as GFs in Matsubara domain)\n * -> DensityMatrix -> Greens Function\n * -> TwoParticle GF -> Vertex4\n * The detailed explanation of each class is given below.\n *\/\n\nint main(int argc, char* argv[])\n{\n boost::mpi::environment MpiEnv(argc, argv);\n world = boost::mpi::communicator();\n\n \/* As pomerol is an ED code, it requires a finite-size lattice to be\n * provided. Here is an example of a lattice of 2 sites. *\/\n \/\/ First, we construct an empty lattice\n Lattice L;\n \/\/ Add a site with a name \"A\", that has 1 orbitals and 2 spins.\n L.addSite(new Lattice::Site(\"A\",1,2));\n \/\/ Add one more site with a name \"B\". It also has 1 orbitals and 2 spins.\n L.addSite(new Lattice::Site(\"B\",1,2));\n\n \/\/ Let us now connect two sites with a hopping term, with matrix element -1.\n RealType t=1.0;\n LatticePresets::addHopping(&L, \"A\",\"B\", -t);\n\n \/* Now add interaction. In order to provide some custom interaction, one can\n * give any custom term of 4,6 operators. This is done via\n * Lattice.addTerm(Lattice::Term) method.\n * We will use Hubbard-type n_{up}n_{down} interaction. For this and some\n * other typical interactions, such as SzSz or SS couplings a shortcut is\n * provided in the LatticePresets class.\n *\/\n RealType U = 2.0;\n RealType mu = 1.0;\n \/\/ LatticePresets::addCoulombS adds Un_{up}n_{down} for 1 orbital and 2 spins.\n LatticePresets::addCoulombS(&L, \"A\", U, -mu);\n LatticePresets::addCoulombS(&L, \"B\", U, -mu);\n\n \/\/ Let us now print which sites and terms are defined.\n if (!world.rank()) {\n INFO(\"Sites\"); \/\/ equivalent to std::cout << \"Sites\" << std::endl;\n L.printSites();\n INFO(\"Terms\");\n L.printTerms(2);\n INFO(\"Terms with 4 operators\");\n L.printTerms(4);\n\n print_section(\"Indices\");\n };\n \/* In order to go further, we need to introduce the index space. An index\n * is a number that uniquely identifies a combination of (site,orbital,spin).\n * The object that takes care of handling indices is called\n * IndexClassification.\n *\/\n\n \/\/ Construct IndexClassification\n IndexClassification IndexInfo(L.getSiteMap());\n\n \/* Important remark 1!\n * Most of the objects that are defined within Pomerol library have the\n * following semantics. They can be constructed, prepared and computed.\n * This means\n * - constructed: No operations are done except from initializing links to\n * other objects that current class depends on.\n * - prepared: Typically, this is when all memory allocation takes place.\n * - computed: The actual computation. This is the most costly operation.\n * When no heavy computation is done, it can be done during\n * preparation stage.\n *\/\n\n \/\/ IndexClassification does not require much computing time, so everything\n \/\/ is calculated during prepare() method.\n IndexInfo.prepare();\n\n \/\/ Print which indices we have\n IndexInfo.printIndices();\n \/\/ Save the total number of indices.\n ParticleIndex IndexSize = IndexInfo.getIndexSize();\n\n print_section(\"Matrix element storage\");\n \/* We now need to construct the actual Hamiltonian. First, we need to create\n * it in the index space, e.g. write down a formula with all terms. It is\n * useful for a subsequent symmetry analysis. The corresponding class is called\n * an IndexHamiltonian. It is inherited from Operator class, which is designed\n * to represent a generic second-quantized fermionic operator and fully model\n * the algebra of fermionic operators. This means one can multiply, add,\n * subtract it, and also calculate the commutator of two operators, etc.\n *\/\n\n \/\/ First construct the IndexHamiltonian object.\n IndexHamiltonian Storage(&L,IndexInfo);\n \/\/ Then prepare it. As previously no long computation required, so everything\n \/\/ is done in the prepare() method.\n Storage.prepare();\n \/\/ Print out the Hamiltonian.\n INFO(\"Terms\");\n INFO(Storage);\n\n \/\/ Let us make a test, that our Hamiltonian commutes with an operator, that\n \/\/ represents the total number of particles. The preset for such operator is\n \/\/ defined in OperatorPresets.h and .cpp files.\n OperatorPresets::N N(IndexSize);\n INFO(\"N terms\");\n N.printAllTerms();\n if ((Storage.commutes(N))) INFO(\"H commutes with N\");\n\n \/* The Hamiltonian that is set now, has a set of symmetries. One can identify\n * them by checking that the IndexHamiltonian commutes with the corresponding\n * symmetry operator. The class that does it is called Symmetrizer.\n *\/\n \/\/ Construct Symmetrizer\n Symmetrizer Symm(IndexInfo, Storage);\n \/* At this stage Symmetrizer checks symmetries with some predefined operators,\n * such as number-of-particles and sz operators.\n *\/\n Symm.compute();\n \/* A custom check for a symmetry can be done using\n * Symmetrizer.checkSymmetry(Operator).\n * After checking all the symmetry operations, Symmetrizer defines a set of\n * quantum numbers, which uniquely identifies the closed region in the\n * phase space.\n * Calling Symmetrizer::compute(true) will skip all symmetry operations and\n * result in a single Hamiltonian block in the end.\n *\/\n\n \/* We shall proceed now with obtaining the spectrum of the Hamiltonian.\n * First, introduce a basis of Fock states and classify them into blocks\n * that correspond to a set of quantum numbers. This is done in the\n * StatesClassification class. It provides all the information about Blocks\n * and FockStates.\n *\/\n StatesClassification S(IndexInfo,Symm);\n S.compute();\n\n \/* We now convert the IndexHamiltonian into the basis of Fock States. The\n * Hamiltonian class is the one, which does it.\n *\/\n Hamiltonian H(IndexInfo, Storage, S);\n \/\/ Enter all blocks of the Hamiltonian.\n H.prepare();\n \/\/ Diagonalize them.\n H.compute(world);\n \/\/ Get ground energy.\n INFO(\"The value of ground energy is \" << H.getGroundEnergy());\n\n \/* Important remark 2!\n * All the calculations done in the pomerol code are done with respect to the\n * block structure of the Hamiltonian. All objects that operate in Fock\n * space and all thermal objects, such as Green's functions are in fact a\n * set of pieces (called \"parts\") that operate on a certain block or set of\n * blocks. As such all actual computations are done within this parts and\n * grand objects like Green's functions or Hamiltonian basically just loops\n * over parts and tells them to run prepare() or compute() methods.\n *\/\n\n \/* At this stage the Hamiltonian, defined in Fock Space is\n * entered and diagonalized and it's spectrum and eigenfunctions can be\n * directly accessed to calculate some observables.\n *\n * We shall now proceed to the calculations of thermal quantities, e.g.\n * assume that our finite-size system was adiabatically connected to a thermal\n * reservoir, that sets certain temperature (in fact, inverse temperature\n * beta). This means, that the observables in the systems should be calculated\n * with a density-matrix exp(-\\beta H), rather than by averaging with the\n * ground state. In the eigenbasis of the Hamiltonian the calculation of\n * a density matrix is straightforward - it is just \\exp(-\\beta (E_i - E_0)),\n * where E_i is an energy of the excited state, and E_0 is the ground energy.\n * The procedure is done as following:\n *\/\n\n \/\/ Define inverse temperature\n RealType beta = 10.0;\n\n \/\/ Create the Density Matrix.\n DensityMatrix rho(S,H,beta);\n \/\/ Allocate all internal parts of density matrix.\n rho.prepare();\n \/\/ Actually compute the density matrix.\n rho.compute();\n \/\/ Truncate blocks that have only small contributions\n \/\/ rho.truncateBlocks(1e-15);\n\n \/* Lehmanns representation of the Green's function required creation and\n * annihilation operators, calculated in the basis of eigenstates of the\n * Hamiltonian. Creation\/AnnihilationOperator are the classes that do it.\n *\/\n\n \/\/ Let us create c^+_{\"A\",up} and c_{\"A\",up}\n ParticleIndex up_index = IndexInfo.getIndex(\"A\",0,up);\n CreationOperator CX(IndexInfo,S,H,up_index);\n CX.prepare();\n CX.compute();\n AnnihilationOperator C(IndexInfo,S,H,up_index);\n C.prepare();\n C.compute();\n\n \/\/ The local Greens function in the Matsubara domain G_{\"A\",up}(i\\omega_n)\n GreensFunction GF(S,H,C,CX, rho);\n GF.prepare();\n \/* Calculate the GF and cache values for 10 Matsubaras.\n * These values will be fast to retrieve. The other values are also\n * accessible, but will require a short calculation to be done.\n *\/\n GF.compute();\n\n for(int n = 0; n<10; ++n) {\n INFO(n << \" | \" << GF(n));\n }\n\n \/* The two particle GF is constructed in analogy to the single-particle GF,\n * it requires 4 operators to be provided though.\n *\/\n TwoParticleGF Chi(S,H,C,C,CX,CX,rho);\n \/* Some knobs to make calc faster - the larger the values of tolerances, the faster is calc, but rounding errors may show.\n Typically these errors are less then 10^{-3} of the value.\n Here are some knobs that give very high-precision. If you want to make things faster, and when many values on\n different frequencies required - change ReduceResonanceTolerance to something like 10^-4. *\/\n \/** A difference in energies with magnitude less than this value is treated as zero. *\/\n Chi.ReduceResonanceTolerance = 1e-8;\n \/** Minimal magnitude of the coefficient of a term to take it into account. *\/\n Chi.CoefficientTolerance = 1e-16;\n \/** Minimal magnitude of the coefficient of a term to take it into account with respect to amount of terms. *\/\n Chi.MultiTermCoefficientTolerance = 1e-6;\n\n Chi.prepare();\n std::vector > freqs_2pgf;\n Chi.compute(false, freqs_2pgf, world);\n\n if (world.rank()==0) {\n int nm = 2;\n for(int n1 = -nm; n1\n print_section(\"Ensemble average\");\n EnsembleAverage EA(S,H, N_up, rho);\n EA.prepare();\n RealType occup_up = real(EA.getResult());\n INFO(\"Occupation number of up spin is \" << occup_up);\n\n \/* The dynamical susceptibility is computed by Susceptibility class.\n * One can obtain either F[ ] or F[ - ],\n * where F denotes Fourier transform from tau to Matsubara frequency.\n * To choose the latter quantity, call subtractDisconnected() method.\n *\n * There are 3 variants of subtractDisconnected() method.\n * 1. and are computed in Susceptibility class\n * 2. use precomputed and \n * 3. use predefined QuadraticOperator instances, A and B\n *\/\n print_section(\"Dynamical susceptibility\");\n Susceptibility Sus(S,H, N_up, N_up, rho);\n Sus.prepare();\n Sus.compute();\n \/\/ subtract \n Sus.subtractDisconnected(); \/\/ 1\n \/\/Sus.subtractDisconnected(occup_up, occup_up); \/\/ 2\n \/\/Sus.subtractDisconnected(N_up, N_up); \/\/ 3\n for(int n=0; n<10; n++){\n INFO(n << \" \" << Sus(n));\n }\n}\n\nvoid print_section (const std::string& str)\n{\n if (!world.rank()) {\n std::cout << std::string(str.size(),'=') << std::endl;\n std::cout << str << std::endl;\n std::cout << std::string(str.size(),'=') << std::endl;\n };\n}\n<|endoftext|>"} {"text":"\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __FreeBSD__\n#include \n#endif\n\n#include \n#include \n\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/load_library.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/platform\/ram_file_system.h\"\n#include \"tensorflow\/core\/platform\/strcat.h\"\n#include \"tensorflow\/core\/protobuf\/error_codes.pb.h\"\n#include \"tensorflow\/tsl\/platform\/default\/posix_file_system.h\"\n\nnamespace tensorflow {\n\nnamespace {\n\nmutex name_mutex(tensorflow::LINKER_INITIALIZED);\n\nstd::map& GetThreadNameRegistry()\n TF_EXCLUSIVE_LOCKS_REQUIRED(name_mutex) {\n static auto* thread_name_registry = new std::map();\n return *thread_name_registry;\n}\n\n\/\/ We use the pthread API instead of std::thread so we can control stack sizes.\nclass PThread : public Thread {\n public:\n PThread(const ThreadOptions& thread_options, const std::string& name,\n std::function fn) {\n ThreadParams* params = new ThreadParams;\n params->name = name;\n params->fn = std::move(fn);\n pthread_attr_t attributes;\n pthread_attr_init(&attributes);\n if (thread_options.stack_size != 0) {\n pthread_attr_setstacksize(&attributes, thread_options.stack_size);\n }\n int ret = pthread_create(&thread_, &attributes, &ThreadFn, params);\n \/\/ There is no mechanism for the thread creation API to fail, so we CHECK.\n CHECK_EQ(ret, 0) << \"Thread \" << name\n << \" creation via pthread_create() failed.\";\n pthread_attr_destroy(&attributes);\n }\n\n ~PThread() override { pthread_join(thread_, nullptr); }\n\n private:\n struct ThreadParams {\n std::string name;\n std::function fn;\n };\n static void* ThreadFn(void* params_arg) {\n std::unique_ptr params(\n reinterpret_cast(params_arg));\n {\n mutex_lock l(name_mutex);\n GetThreadNameRegistry().emplace(std::this_thread::get_id(), params->name);\n }\n params->fn();\n {\n mutex_lock l(name_mutex);\n GetThreadNameRegistry().erase(std::this_thread::get_id());\n }\n return nullptr;\n }\n\n pthread_t thread_;\n};\n\nclass PosixEnv : public Env {\n public:\n PosixEnv() {}\n\n ~PosixEnv() override { LOG(FATAL) << \"Env::Default() must not be destroyed\"; }\n\n bool MatchPath(const string& path, const string& pattern) override {\n return fnmatch(pattern.c_str(), path.c_str(), FNM_PATHNAME) == 0;\n }\n\n void SleepForMicroseconds(int64 micros) override {\n while (micros > 0) {\n timespec sleep_time;\n sleep_time.tv_sec = 0;\n sleep_time.tv_nsec = 0;\n\n if (micros >= 1e6) {\n sleep_time.tv_sec =\n std::min(micros \/ 1e6, std::numeric_limits::max());\n micros -= static_cast(sleep_time.tv_sec) * 1e6;\n }\n if (micros < 1e6) {\n sleep_time.tv_nsec = 1000 * micros;\n micros = 0;\n }\n while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {\n \/\/ Ignore signals and wait for the full interval to elapse.\n }\n }\n }\n\n Thread* StartThread(const ThreadOptions& thread_options, const string& name,\n std::function fn) override {\n return new PThread(thread_options, name, fn);\n }\n\n int32 GetCurrentThreadId() override {\n static thread_local int32 current_thread_id = GetCurrentThreadIdInternal();\n return current_thread_id;\n }\n\n bool GetCurrentThreadName(string* name) override {\n {\n mutex_lock l(name_mutex);\n auto thread_name =\n GetThreadNameRegistry().find(std::this_thread::get_id());\n if (thread_name != GetThreadNameRegistry().end()) {\n *name = strings::StrCat(thread_name->second, \"\/\", GetCurrentThreadId());\n return true;\n }\n }\n#if defined(__GLIBC__) || defined(__FreeBSD__)\n char buf[100];\n#ifdef __FreeBSD__\n int res = 0;\n pthread_get_name_np(pthread_self(), buf, static_cast(100));\n#else\n int res = pthread_getname_np(pthread_self(), buf, static_cast(100));\n#endif\n if (res != 0) {\n return false;\n }\n *name = buf;\n return true;\n#else\n return false;\n#endif\n }\n\n void SchedClosure(std::function closure) override {\n \/\/ TODO(b\/27290852): Spawning a new thread here is wasteful, but\n \/\/ needed to deal with the fact that many `closure` functions are\n \/\/ blocking in the current codebase.\n std::thread closure_thread(closure);\n closure_thread.detach();\n }\n\n void SchedClosureAfter(int64 micros, std::function closure) override {\n \/\/ TODO(b\/27290852): Consuming a thread here is wasteful, but this\n \/\/ code is (currently) only used in the case where a step fails\n \/\/ (AbortStep). This could be replaced by a timer thread\n SchedClosure([this, micros, closure]() {\n SleepForMicroseconds(micros);\n closure();\n });\n }\n\n Status LoadDynamicLibrary(const char* library_filename,\n void** handle) override {\n return tensorflow::internal::LoadDynamicLibrary(library_filename, handle);\n }\n\n Status GetSymbolFromLibrary(void* handle, const char* symbol_name,\n void** symbol) override {\n return tensorflow::internal::GetSymbolFromLibrary(handle, symbol_name,\n symbol);\n }\n\n string FormatLibraryFileName(const string& name,\n const string& version) override {\n return tensorflow::internal::FormatLibraryFileName(name, version);\n }\n\n string GetRunfilesDir() override {\n string bin_path = this->GetExecutablePath();\n string runfiles_suffix = \".runfiles\/org_tensorflow\";\n std::size_t pos = bin_path.find(runfiles_suffix);\n\n \/\/ Sometimes (when executing under python) bin_path returns the full path to\n \/\/ the python scripts under runfiles. Get the substring.\n if (pos != std::string::npos) {\n return bin_path.substr(0, pos + runfiles_suffix.length());\n }\n\n \/\/ See if we have the executable path. if executable.runfiles exists, return\n \/\/ that folder.\n string runfiles_path = bin_path + runfiles_suffix;\n Status s = this->IsDirectory(runfiles_path);\n if (s.ok()) {\n return runfiles_path;\n }\n\n \/\/ If nothing can be found, return something close.\n return bin_path.substr(0, bin_path.find_last_of(\"\/\\\\\"));\n }\n\n private:\n void GetLocalTempDirectories(std::vector* list) override;\n\n int32 GetCurrentThreadIdInternal() {\n#ifdef __APPLE__\n uint64_t tid64;\n pthread_threadid_np(nullptr, &tid64);\n return static_cast(tid64);\n#elif defined(__FreeBSD__)\n return pthread_getthreadid_np();\n#elif defined(__NR_gettid)\n return static_cast(syscall(__NR_gettid));\n#else\n return std::hash()(std::this_thread::get_id());\n#endif\n }\n};\n\n} \/\/ namespace\n\n#if defined(PLATFORM_POSIX) || defined(__APPLE__) || defined(__ANDROID__)\nREGISTER_FILE_SYSTEM(\"\", PosixFileSystem);\nREGISTER_FILE_SYSTEM(\"file\", LocalPosixFileSystem);\nREGISTER_FILE_SYSTEM(\"ram\", RamFileSystem);\n\n\nEnv* Env::Default() {\n static Env* default_env = new PosixEnv;\n return default_env;\n}\n#endif\n\nvoid PosixEnv::GetLocalTempDirectories(std::vector* list) {\n list->clear();\n \/\/ Directories, in order of preference. If we find a dir that\n \/\/ exists, we stop adding other less-preferred dirs\n const char* candidates[] = {\n \/\/ Non-null only during unittest\/regtest\n getenv(\"TEST_TMPDIR\"),\n\n \/\/ Explicitly-supplied temp dirs\n getenv(\"TMPDIR\"),\n getenv(\"TMP\"),\n\n#if defined(__ANDROID__)\n \"\/data\/local\/tmp\",\n#endif\n\n \/\/ If all else fails\n \"\/tmp\",\n };\n\n for (const char* d : candidates) {\n if (!d || d[0] == '\\0') continue; \/\/ Empty env var\n\n \/\/ Make sure we don't surprise anyone who's expecting a '\/'\n string dstr = d;\n if (dstr[dstr.size() - 1] != '\/') {\n dstr += \"\/\";\n }\n\n struct stat statbuf;\n if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode) &&\n !access(dstr.c_str(), 0)) {\n \/\/ We found a dir that exists and is accessible - we're done.\n list->push_back(dstr);\n return;\n }\n }\n}\n\nint setenv(const char* name, const char* value, int overwrite) {\n return ::setenv(name, value, overwrite);\n}\n\nint unsetenv(const char* name) { return ::unsetenv(name); }\n\n} \/\/ namespace tensorflow\nPrint a useful warning if we can't find a directory for temporary files.\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __FreeBSD__\n#include \n#endif\n\n#include \n#include \n\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/load_library.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/platform\/ram_file_system.h\"\n#include \"tensorflow\/core\/platform\/strcat.h\"\n#include \"tensorflow\/core\/protobuf\/error_codes.pb.h\"\n#include \"tensorflow\/tsl\/platform\/default\/posix_file_system.h\"\n\nnamespace tensorflow {\n\nnamespace {\n\nmutex name_mutex(tensorflow::LINKER_INITIALIZED);\n\nstd::map& GetThreadNameRegistry()\n TF_EXCLUSIVE_LOCKS_REQUIRED(name_mutex) {\n static auto* thread_name_registry = new std::map();\n return *thread_name_registry;\n}\n\n\/\/ We use the pthread API instead of std::thread so we can control stack sizes.\nclass PThread : public Thread {\n public:\n PThread(const ThreadOptions& thread_options, const std::string& name,\n std::function fn) {\n ThreadParams* params = new ThreadParams;\n params->name = name;\n params->fn = std::move(fn);\n pthread_attr_t attributes;\n pthread_attr_init(&attributes);\n if (thread_options.stack_size != 0) {\n pthread_attr_setstacksize(&attributes, thread_options.stack_size);\n }\n int ret = pthread_create(&thread_, &attributes, &ThreadFn, params);\n \/\/ There is no mechanism for the thread creation API to fail, so we CHECK.\n CHECK_EQ(ret, 0) << \"Thread \" << name\n << \" creation via pthread_create() failed.\";\n pthread_attr_destroy(&attributes);\n }\n\n ~PThread() override { pthread_join(thread_, nullptr); }\n\n private:\n struct ThreadParams {\n std::string name;\n std::function fn;\n };\n static void* ThreadFn(void* params_arg) {\n std::unique_ptr params(\n reinterpret_cast(params_arg));\n {\n mutex_lock l(name_mutex);\n GetThreadNameRegistry().emplace(std::this_thread::get_id(), params->name);\n }\n params->fn();\n {\n mutex_lock l(name_mutex);\n GetThreadNameRegistry().erase(std::this_thread::get_id());\n }\n return nullptr;\n }\n\n pthread_t thread_;\n};\n\nclass PosixEnv : public Env {\n public:\n PosixEnv() {}\n\n ~PosixEnv() override { LOG(FATAL) << \"Env::Default() must not be destroyed\"; }\n\n bool MatchPath(const string& path, const string& pattern) override {\n return fnmatch(pattern.c_str(), path.c_str(), FNM_PATHNAME) == 0;\n }\n\n void SleepForMicroseconds(int64 micros) override {\n while (micros > 0) {\n timespec sleep_time;\n sleep_time.tv_sec = 0;\n sleep_time.tv_nsec = 0;\n\n if (micros >= 1e6) {\n sleep_time.tv_sec =\n std::min(micros \/ 1e6, std::numeric_limits::max());\n micros -= static_cast(sleep_time.tv_sec) * 1e6;\n }\n if (micros < 1e6) {\n sleep_time.tv_nsec = 1000 * micros;\n micros = 0;\n }\n while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {\n \/\/ Ignore signals and wait for the full interval to elapse.\n }\n }\n }\n\n Thread* StartThread(const ThreadOptions& thread_options, const string& name,\n std::function fn) override {\n return new PThread(thread_options, name, fn);\n }\n\n int32 GetCurrentThreadId() override {\n static thread_local int32 current_thread_id = GetCurrentThreadIdInternal();\n return current_thread_id;\n }\n\n bool GetCurrentThreadName(string* name) override {\n {\n mutex_lock l(name_mutex);\n auto thread_name =\n GetThreadNameRegistry().find(std::this_thread::get_id());\n if (thread_name != GetThreadNameRegistry().end()) {\n *name = strings::StrCat(thread_name->second, \"\/\", GetCurrentThreadId());\n return true;\n }\n }\n#if defined(__GLIBC__) || defined(__FreeBSD__)\n char buf[100];\n#ifdef __FreeBSD__\n int res = 0;\n pthread_get_name_np(pthread_self(), buf, static_cast(100));\n#else\n int res = pthread_getname_np(pthread_self(), buf, static_cast(100));\n#endif\n if (res != 0) {\n return false;\n }\n *name = buf;\n return true;\n#else\n return false;\n#endif\n }\n\n void SchedClosure(std::function closure) override {\n \/\/ TODO(b\/27290852): Spawning a new thread here is wasteful, but\n \/\/ needed to deal with the fact that many `closure` functions are\n \/\/ blocking in the current codebase.\n std::thread closure_thread(closure);\n closure_thread.detach();\n }\n\n void SchedClosureAfter(int64 micros, std::function closure) override {\n \/\/ TODO(b\/27290852): Consuming a thread here is wasteful, but this\n \/\/ code is (currently) only used in the case where a step fails\n \/\/ (AbortStep). This could be replaced by a timer thread\n SchedClosure([this, micros, closure]() {\n SleepForMicroseconds(micros);\n closure();\n });\n }\n\n Status LoadDynamicLibrary(const char* library_filename,\n void** handle) override {\n return tensorflow::internal::LoadDynamicLibrary(library_filename, handle);\n }\n\n Status GetSymbolFromLibrary(void* handle, const char* symbol_name,\n void** symbol) override {\n return tensorflow::internal::GetSymbolFromLibrary(handle, symbol_name,\n symbol);\n }\n\n string FormatLibraryFileName(const string& name,\n const string& version) override {\n return tensorflow::internal::FormatLibraryFileName(name, version);\n }\n\n string GetRunfilesDir() override {\n string bin_path = this->GetExecutablePath();\n string runfiles_suffix = \".runfiles\/org_tensorflow\";\n std::size_t pos = bin_path.find(runfiles_suffix);\n\n \/\/ Sometimes (when executing under python) bin_path returns the full path to\n \/\/ the python scripts under runfiles. Get the substring.\n if (pos != std::string::npos) {\n return bin_path.substr(0, pos + runfiles_suffix.length());\n }\n\n \/\/ See if we have the executable path. if executable.runfiles exists, return\n \/\/ that folder.\n string runfiles_path = bin_path + runfiles_suffix;\n Status s = this->IsDirectory(runfiles_path);\n if (s.ok()) {\n return runfiles_path;\n }\n\n \/\/ If nothing can be found, return something close.\n return bin_path.substr(0, bin_path.find_last_of(\"\/\\\\\"));\n }\n\n private:\n void GetLocalTempDirectories(std::vector* list) override;\n\n int32 GetCurrentThreadIdInternal() {\n#ifdef __APPLE__\n uint64_t tid64;\n pthread_threadid_np(nullptr, &tid64);\n return static_cast(tid64);\n#elif defined(__FreeBSD__)\n return pthread_getthreadid_np();\n#elif defined(__NR_gettid)\n return static_cast(syscall(__NR_gettid));\n#else\n return std::hash()(std::this_thread::get_id());\n#endif\n }\n};\n\n} \/\/ namespace\n\n#if defined(PLATFORM_POSIX) || defined(__APPLE__) || defined(__ANDROID__)\nREGISTER_FILE_SYSTEM(\"\", PosixFileSystem);\nREGISTER_FILE_SYSTEM(\"file\", LocalPosixFileSystem);\nREGISTER_FILE_SYSTEM(\"ram\", RamFileSystem);\n\n\nEnv* Env::Default() {\n static Env* default_env = new PosixEnv;\n return default_env;\n}\n#endif\n\nvoid PosixEnv::GetLocalTempDirectories(std::vector* list) {\n list->clear();\n \/\/ Directories, in order of preference. If we find a dir that\n \/\/ exists, we stop adding other less-preferred dirs\n const char* candidates[] = {\n \/\/ Non-null only during unittest\/regtest\n getenv(\"TEST_TMPDIR\"),\n\n \/\/ Explicitly-supplied temp dirs\n getenv(\"TMPDIR\"),\n getenv(\"TMP\"),\n\n#if defined(__ANDROID__)\n \"\/data\/local\/tmp\",\n#endif\n\n \/\/ If all else fails\n \"\/tmp\",\n };\n\n std::string paths; \/\/ Only in case of errors.\n for (const char* d : candidates) {\n if (!d || d[0] == '\\0') continue; \/\/ Empty env var\n if (!paths.empty()) {\n paths += \", \";\n }\n paths += std::string(d);\n \/\/ Make sure we don't surprise anyone who's expecting a '\/'\n string dstr = d;\n if (dstr[dstr.size() - 1] != '\/') {\n dstr += \"\/\";\n }\n\n struct stat statbuf;\n if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode) &&\n !access(dstr.c_str(), 0)) {\n \/\/ We found a dir that exists and is accessible - we're done.\n list->push_back(dstr);\n return;\n }\n }\n LOG(WARNING) << \"We are not able to find a directory for temporary files.\\n\"\n << \"Verify the directory access and available space under: \"\n << paths << \". \"\n << \"You can also provide a directory for temporary files with\"\n << \" the environment variable TMP or TMPDIR. \"\n << \"Example under bash: `export TMP=\/my_new_temp_directory;`\";\n}\n\nint setenv(const char* name, const char* value, int overwrite) {\n return ::setenv(name, value, overwrite);\n}\n\nint unsetenv(const char* name) { return ::unsetenv(name); }\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace Faunus {\n\n AtomData::AtomData() {\n activity=0;\n charge=0;\n dp=0;\n dprot=0;\n eps=0;\n hydrophobic=0;\n mean=0;\n muscalar=0;\n mw=1.0;\n name=\"UNK\";\n patchtype=0; \n radius=0;\n sigma=0; \n variance=0;\n len=0;\n half_len=0;\n pswitch=0;\n pdis=0;\n pangl=0;\n panglsw=0;\n \/\/rcutwca=0;\n \/\/rcut=0;\n \/\/pcangl=0;\n \/\/pcanglsw=0;\n \/\/pcoshalfi=0;\n \/\/psinhalfi=0;\n chiral_angle=0;\n mu.clear();\n theta.clear();\n alpha.clear();\n }\n\n AtomMap::AtomMap() {\n AtomData a;\n a.id=list.size();\n a.name=\"UNK\";\n list.push_back(a);\n }\n\n AtomData & AtomMap::operator[] (AtomData::Tid i) {\n assert(i(\"atomlist\",filename) );\n }\n\n bool AtomMap::includeJSON(const string& file) {\n int n=0;\n filename=file;\n auto j=json::open(file);\n for (auto &atom : json::object(\"atomlist\", j)) {\n n++;\n AtomData a;\n \/\/Tensor fallback;\n \/\/fallback.clear();\n a.name = atom.first;\n a.activity = json::value(atom.second, \"activity\", 0);\n a.alpha << json::value(atom.second, \"alpha\", \"\");\n a.alpha *= 4*pc::pi*pc::e0*(1e-10)*pc::kT()\/(pc::e*pc::e);\n a.theta << json::value(atom.second, \"theta\", \"\");\n a.theta *= 0.20819434; \/\/ Debye Å -> e Å^2\n a.dp = json::value(atom.second, \"dp\", 0);\n a.dprot = json::value(atom.second, \"dprot\", 0) * pc::pi \/ 180.; \/\/ deg->rads\n a.eps = json::value(atom.second, \"eps\", 0);\n a.hydrophobic = json::value(atom.second, \"hydrophobic\", false);\n a.mu << json::value(atom.second, \"mu\", \"0 0 0\");\n a.muscalar = a.mu.len()*pc::D2eA();\n if (a.mu.len()>1e-6)\n a.mu = a.mu\/a.mu.len();\n a.mw = json::value(atom.second, \"Mw\", 1.);\n a.charge = json::value(atom.second, \"q\", 0);\n a.radius = json::value(atom.second, \"r\", 0);\n a.sigma = 2*a.radius;\n a.sigma = json::value(atom.second, \"sigma\", a.sigma);\n a.radius = a.sigma\/2;\n a.id=AtomData::Tid( list.size() );\n\n a.half_len = 0.5 * json::value(atom.second, \"len\", 0);\n a.patchtype = json::value(atom.second, \"patchtype\", 0);\n a.pswitch = json::value(atom.second, \"patchswitch\", 0);\n a.pdis = json::value(atom.second, \"patchdistance\", 0);\n a.pangl = json::value(atom.second, \"patchangle\", 0)\/180.0*pc::pi;\n a.panglsw = json::value(atom.second, \"patchangleswitch\", 0)\/180.0*pc::pi;\n a.chiral_angle = json::value(atom.second, \"patchchiralangle\", 0)\/180.0*pc::pi;\n a.betaC = json::value(atom.second, \"betaC\", pc::infty);\n a.betaD = json::value(atom.second, \"betaD\", pc::infty);\n a.betaQ = json::value(atom.second, \"betaQ\", pc::infty);\n \n list.push_back(a); \/\/ add to main particle list\n\n \/\/ add to particle list \n bool insert=true;\n for (auto &i : list)\n if (i.name==a.name) {\n a.id=i.id; \/\/ keep old id and\n i=a; \/\/ override existing\n insert=false;\n break;\n }\n if (insert)\n list.push_back(a);\n }\n return (n>0) ? true : false;\n }\n\n \/**\n * This will automatically detect if the file is a JSON\n * file and call includeJSON(). If not, the old restricted\n * file format is used.\n *\/\n bool AtomMap::includefile(string file) {\n \/\/ is it a JSON file?\n if (file.substr(file.find_last_of(\".\") + 1) == \"json\")\n return includeJSON(file);\n AtomData a;\n string t;\n filename=file;\n std::ifstream f(filename.c_str());\n cout << \"Reading atom data from '\" << filename << \"'. \";\n if (f) {\n cout << \"OK!\\n\";\n while (!f.eof()) {\n f >> t;\n if (t==\"Atom\") {\n f >> a.name >> a.charge >> a.radius >> a.eps >> a.mw >> t;\n a.sigma=2*a.radius;\n a.hydrophobic = (t==\"yes\") ? true : false;\n a.id=list.size();\n list.push_back(a);\n }\n }\n return true;\n }\n cout << \"FAILED!\\n\";\n filename+=\" (n\/a)\";\n return false;\n }\n\n string AtomMap::info() {\n using namespace textio;\n char w=25;\n if (filename.empty())\n filename=\"(undefined)\";\n std::ostringstream o;\n o << header(\"Atomic Species\")\n << pad(SUB,w,\"Number of species\") << list.size() << endl\n << pad(SUB,w,\"Parameter file\") << filename << endl\n << indent(SUB) << \"Species:\";\n for (size_t i=0; iconflict#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace Faunus {\n\n AtomData::AtomData() {\n activity=0;\n charge=0;\n dp=0;\n dprot=0;\n eps=0;\n hydrophobic=0;\n mean=0;\n muscalar=0;\n mw=1.0;\n name=\"UNK\";\n patchtype=0; \n radius=0;\n sigma=0; \n variance=0;\n len=0;\n half_len=0;\n pswitch=0;\n pdis=0;\n pangl=0;\n panglsw=0;\n \/\/rcutwca=0;\n \/\/rcut=0;\n \/\/pcangl=0;\n \/\/pcanglsw=0;\n \/\/pcoshalfi=0;\n \/\/psinhalfi=0;\n chiral_angle=0;\n mu.clear();\n theta.clear();\n alpha.clear();\n }\n\n AtomMap::AtomMap() {\n AtomData a;\n a.id=list.size();\n a.name=\"UNK\";\n list.push_back(a);\n }\n\n AtomData & AtomMap::operator[] (AtomData::Tid i) {\n assert(i(\"atomlist\",filename) );\n }\n\n bool AtomMap::includeJSON(const string& file) {\n int n=0;\n filename=file;\n auto j=json::open(file);\n for (auto &atom : json::object(\"atomlist\", j)) {\n n++;\n AtomData a;\n \/\/Tensor fallback;\n \/\/fallback.clear();\n a.name = atom.first;\n a.activity = json::value(atom.second, \"activity\", 0);\n a.alpha << json::value(atom.second, \"alpha\", \"\");\n a.alpha *= 4*pc::pi*pc::e0*(1e-10)*pc::kT()\/(pc::e*pc::e);\n a.theta << json::value(atom.second, \"theta\", \"\");\n a.theta *= 0.20819434; \/\/ Debye Å -> e Å^2\n a.dp = json::value(atom.second, \"dp\", 0);\n a.dprot = json::value(atom.second, \"dprot\", 0) * pc::pi \/ 180.; \/\/ deg->rads\n a.eps = json::value(atom.second, \"eps\", 0);\n a.hydrophobic = json::value(atom.second, \"hydrophobic\", false);\n a.mu << json::value(atom.second, \"mu\", \"0 0 0\");\n a.muscalar = a.mu.len()*pc::D2eA();\n if (a.mu.len()>1e-6)\n a.mu = a.mu\/a.mu.len();\n a.mw = json::value(atom.second, \"Mw\", 1.);\n a.charge = json::value(atom.second, \"q\", 0);\n a.radius = json::value(atom.second, \"r\", 0);\n a.sigma = 2*a.radius;\n a.sigma = json::value(atom.second, \"sigma\", a.sigma);\n a.radius = a.sigma\/2;\n a.id=AtomData::Tid( list.size() );\n a.half_len = 0.5 * json::value(atom.second, \"len\", 0);\n a.patchtype = json::value(atom.second, \"patchtype\", 0);\n a.pswitch = json::value(atom.second, \"patchswitch\", 0);\n a.pdis = json::value(atom.second, \"patchdistance\", 0);\n a.pangl = json::value(atom.second, \"patchangle\", 0)\/180.0*pc::pi;\n a.panglsw = json::value(atom.second, \"patchangleswitch\", 0)\/180.0*pc::pi;\n a.chiral_angle = json::value(atom.second, \"patchchiralangle\", 0)\/180.0*pc::pi;\n a.betaC = json::value(atom.second, \"betaC\", pc::infty);\n a.betaD = json::value(atom.second, \"betaD\", pc::infty);\n a.betaQ = json::value(atom.second, \"betaQ\", pc::infty);\n \/\/ add to particle list \n bool insert=true;\n for (auto &i : list)\n if (i.name==a.name) {\n a.id=i.id; \/\/ keep old id and\n i=a; \/\/ override existing\n insert=false;\n break;\n }\n if (insert)\n list.push_back(a);\n }\n return (n>0) ? true : false;\n }\n\n \/**\n * This will automatically detect if the file is a JSON\n * file and call includeJSON(). If not, the old restricted\n * file format is used.\n *\/\n bool AtomMap::includefile(string file) {\n \/\/ is it a JSON file?\n if (file.substr(file.find_last_of(\".\") + 1) == \"json\")\n return includeJSON(file);\n AtomData a;\n string t;\n filename=file;\n std::ifstream f(filename.c_str());\n cout << \"Reading atom data from '\" << filename << \"'. \";\n if (f) {\n cout << \"OK!\\n\";\n while (!f.eof()) {\n f >> t;\n if (t==\"Atom\") {\n f >> a.name >> a.charge >> a.radius >> a.eps >> a.mw >> t;\n a.sigma=2*a.radius;\n a.hydrophobic = (t==\"yes\") ? true : false;\n a.id=list.size();\n list.push_back(a);\n }\n }\n return true;\n }\n cout << \"FAILED!\\n\";\n filename+=\" (n\/a)\";\n return false;\n }\n\n string AtomMap::info() {\n using namespace textio;\n char w=25;\n if (filename.empty())\n filename=\"(undefined)\";\n std::ostringstream o;\n o << header(\"Atomic Species\")\n << pad(SUB,w,\"Number of species\") << list.size() << endl\n << pad(SUB,w,\"Parameter file\") << filename << endl\n << indent(SUB) << \"Species:\";\n for (size_t i=0; i"} {"text":"\n#include \/\/ for OGRE_THREAD_SUPPORT\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"sleep.h\"\n#include \"BackgroundMeshLoader.h\"\n\n\nBackgroundMeshLoader::BackgroundMeshLoader (void)\n : mNumBastards(0), mThread(NULL), mCurrent(NULL),\n mQuit(false), mAllowance(0)\n{\n OGRE_LOCK_AUTO_MUTEX;\n\n mThread = new boost::thread(boost::ref(*this));\n}\n\nBackgroundMeshLoader::~BackgroundMeshLoader (void)\n{\n shutdown();\n}\n\nvoid BackgroundMeshLoader::shutdown (void)\n{\n \/\/ make sure a later destruction of this object doesn't touch ogre.\n if (mQuit) return;\n {\n OGRE_LOCK_AUTO_MUTEX;\n mQuit = true;\n OGRE_THREAD_NOTIFY_ONE(mCVar);\n }\n mThread->join();\n handleBastards();\n mDeathRow.clear();\n mDemands.clear();\n delete mThread;\n}\n\nvoid BackgroundMeshLoader::add (Demand *d)\n{\n OGRE_LOCK_AUTO_MUTEX;\n\/*\n std::stringstream ss;\n ss << \"adding demand: \\\"\"<mMeshName<<\"\\\" {\";\n typedef std::set::const_iterator I;\n I begin = d->mMatNames.begin();\n I end = d->mMatNames.end();\n for (I i=begin ; i!=end ; ++i) {\n ss << (i==begin?\"\":\", \")<<\"\\\"\"<<*i<<\"\\\"\";\n }\n ss << \"}\";\n APP_VERBOSE(ss.str());\n*\/\n mDemands.insert(d);\n OGRE_THREAD_NOTIFY_ONE(mCVar);\n}\n\nvoid BackgroundMeshLoader::remove (Demand *d)\n{\n OGRE_LOCK_AUTO_MUTEX;\n mDemands.erase(d);\n if (mCurrent == d)\n mCurrent = NULL;\n} \n\nvoid BackgroundMeshLoader::handleBastards (void)\n{\n \/\/ access volatile field without taking lock first\n \/\/ worst case we return early, i.e. will pick up bastards next time\n if (mNumBastards==0) return;\n ResourcePtrSet s;\n {\n OGRE_LOCK_AUTO_MUTEX;\n if (mNumBastards==0) return;\n s = mBastards;\n mBastards.clear();\n mNumBastards = 0;\n }\n\n finishedWith(s);\n}\n\n\nvoid BackgroundMeshLoader::operator() (void)\n{\n \/\/APP_VERBOSE(\"BackgroundMeshLoader: thread started\");\n ResourcePtrs pending;\n while (!mQuit) {\n {\n OGRE_LOCK_AUTO_MUTEX;\n if (mCurrent) {\n \/\/ Usual case:\n \/\/ demand wasn't retracted while we were\n \/\/ processing it\n mCurrent->mProcessed = true;\n \/\/ cache in d to suppress compiler error\n Demand *d = mCurrent;\n mDemands.erase(d);\n mCurrent = NULL;\n } else {\n \/\/ demand was retracted, and we actually\n \/\/ loaded stuff\n for (ResourcePtrs::const_iterator\n i=pending.begin(), i_=pending.end() ;\n i!=i_ ; ++i) {\n mBastards.insert(*i);\n mNumBastards = mBastards.size();\n }\n \/\/asynchronously call sm.finishedWith(resource);\n }\n pending.clear();\n if (mAllowance <= 0 || !nearestDemand(mCurrent)) {\n OGRE_THREAD_WAIT(mCVar,OGRE_AUTO_MUTEX_NAME)\n continue; \n } \n pending = mCurrent->rPtrs;\n }\n \/\/APP_VERBOSE(\"BackgroundMeshLoader: loading: \"+name);\n for (ResourcePtrs::iterator i=pending.begin(),\n i_=pending.end() ; i!=i_ ; ++i) {\n Ogre::ResourcePtr &rp = *i;\n if (!rp->isPrepared()) {\n rp->prepare();\n mAllowance--;\n }\n }\n\n \/\/mysleep(100000);\n }\n \/\/APP_VERBOSE(\"BackgroundMeshLoader: thread terminated\");\n}\n\n\nbool BackgroundMeshLoader::nearestDemand (Demand * volatile &return_demand)\n{\n\n Ogre::Real closest_dist = 0;\n bool found = false;\n\n for (Demands::const_iterator i=mDemands.begin(),\n i_=mDemands.end() ; i!=i_ ; ++i) {\n Demand *d = *i; \n \n Ogre::Real this_dist = (*i)->mDist;\n \n if (!found || this_dist\nstatic inline bool is_unused (const Ogre::SharedPtr& r)\n{\n \/\/ if resource only used here, unload it\n return r.useCount() <=\n Ogre::ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS+1;\n}\n\nvoid BackgroundMeshLoader::finishedWith (const ResourcePtrSet &s) {\n typedef ResourcePtrSet::const_iterator I;\n for (I i=s.begin(), i_=s.end() ; i!=i_ ; ++i) {\n finishedWith(*i);\n }\n}\n\nvoid BackgroundMeshLoader::finishedWith (const Ogre::ResourcePtr &rp)\n{\n if (mQuit) return;\n if (rp.isNull()) return;\n if (!is_unused(rp)) return;\n mDeathRow.push(rp);\n}\n\nvoid BackgroundMeshLoader::finishedWith (const Ogre::MaterialPtr &mat)\n{\n if (mQuit) return;\n if (mat.isNull()) return;\n if (!is_unused(mat)) return;\n mat->unload();\n}\n\nbool BackgroundMeshLoader::isGPUOversubscribed () const\n{\n Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();\n Ogre::MeshManager &mm = Ogre::MeshManager::getSingleton();\n\n size_t budget = tm.getMemoryBudget() + mm.getMemoryBudget();\n\n size_t usage = tm.getMemoryUsage() + mm.getMemoryUsage();\n\n return usage >= budget;\n}\n\nvoid BackgroundMeshLoader::checkGPUUsage ()\n{\n Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();\n Ogre::MeshManager &mm = Ogre::MeshManager::getSingleton();\n\n size_t budget = tm.getMemoryBudget() + mm.getMemoryBudget();\n\n while (true) {\n\n size_t usage = tm.getMemoryUsage() + mm.getMemoryUsage();\n\n if (usage < budget || mDeathRow.size() == 0) break;\n\n Ogre::ResourcePtr r = mDeathRow.pop();\n\n if (is_unused(r))\n r->unload();\n }\n\n}\n\ntemplate<>\nBackgroundMeshLoader *Ogre::Singleton::ms_Singleton =NULL;\n\n\n\/\/ vim: shiftwidth=8:tabstop=8:expandtab\nUpdate for new OGRE svn head\n#include \/\/ for OGRE_THREAD_SUPPORT\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"sleep.h\"\n#include \"BackgroundMeshLoader.h\"\n\n\nBackgroundMeshLoader::BackgroundMeshLoader (void)\n : mNumBastards(0), mThread(NULL), mCurrent(NULL),\n mQuit(false), mAllowance(0)\n{\n OGRE_LOCK_AUTO_MUTEX;\n\n mThread = new boost::thread(boost::ref(*this));\n}\n\nBackgroundMeshLoader::~BackgroundMeshLoader (void)\n{\n shutdown();\n}\n\nvoid BackgroundMeshLoader::shutdown (void)\n{\n \/\/ make sure a later destruction of this object doesn't touch ogre.\n if (mQuit) return;\n {\n OGRE_LOCK_AUTO_MUTEX;\n mQuit = true;\n OGRE_THREAD_NOTIFY_ONE(mCVar);\n }\n mThread->join();\n handleBastards();\n mDeathRow.clear();\n mDemands.clear();\n delete mThread;\n}\n\nvoid BackgroundMeshLoader::add (Demand *d)\n{\n OGRE_LOCK_AUTO_MUTEX;\n\/*\n std::stringstream ss;\n ss << \"adding demand: \\\"\"<mMeshName<<\"\\\" {\";\n typedef std::set::const_iterator I;\n I begin = d->mMatNames.begin();\n I end = d->mMatNames.end();\n for (I i=begin ; i!=end ; ++i) {\n ss << (i==begin?\"\":\", \")<<\"\\\"\"<<*i<<\"\\\"\";\n }\n ss << \"}\";\n APP_VERBOSE(ss.str());\n*\/\n mDemands.insert(d);\n OGRE_THREAD_NOTIFY_ONE(mCVar);\n}\n\nvoid BackgroundMeshLoader::remove (Demand *d)\n{\n OGRE_LOCK_AUTO_MUTEX;\n mDemands.erase(d);\n if (mCurrent == d)\n mCurrent = NULL;\n} \n\nvoid BackgroundMeshLoader::handleBastards (void)\n{\n \/\/ access volatile field without taking lock first\n \/\/ worst case we return early, i.e. will pick up bastards next time\n if (mNumBastards==0) return;\n ResourcePtrSet s;\n {\n OGRE_LOCK_AUTO_MUTEX;\n if (mNumBastards==0) return;\n s = mBastards;\n mBastards.clear();\n mNumBastards = 0;\n }\n\n finishedWith(s);\n}\n\n\nvoid BackgroundMeshLoader::operator() (void)\n{\n \/\/APP_VERBOSE(\"BackgroundMeshLoader: thread started\");\n ResourcePtrs pending;\n while (!mQuit) {\n {\n OGRE_LOCK_AUTO_MUTEX;\n if (mCurrent) {\n \/\/ Usual case:\n \/\/ demand wasn't retracted while we were\n \/\/ processing it\n mCurrent->mProcessed = true;\n \/\/ cache in d to suppress compiler error\n Demand *d = mCurrent;\n mDemands.erase(d);\n mCurrent = NULL;\n } else {\n \/\/ demand was retracted, and we actually\n \/\/ loaded stuff\n for (ResourcePtrs::const_iterator\n i=pending.begin(), i_=pending.end() ;\n i!=i_ ; ++i) {\n mBastards.insert(*i);\n mNumBastards = mBastards.size();\n }\n \/\/asynchronously call sm.finishedWith(resource);\n }\n pending.clear();\n if (mAllowance <= 0 || !nearestDemand(mCurrent)) {\n OGRE_THREAD_WAIT(mCVar,OGRE_AUTO_MUTEX_NAME,ogreAutoMutexLock)\n continue; \n } \n pending = mCurrent->rPtrs;\n }\n \/\/APP_VERBOSE(\"BackgroundMeshLoader: loading: \"+name);\n for (ResourcePtrs::iterator i=pending.begin(),\n i_=pending.end() ; i!=i_ ; ++i) {\n Ogre::ResourcePtr &rp = *i;\n if (!rp->isPrepared()) {\n rp->prepare();\n mAllowance--;\n }\n }\n\n \/\/mysleep(100000);\n }\n \/\/APP_VERBOSE(\"BackgroundMeshLoader: thread terminated\");\n}\n\n\nbool BackgroundMeshLoader::nearestDemand (Demand * volatile &return_demand)\n{\n\n Ogre::Real closest_dist = 0;\n bool found = false;\n\n for (Demands::const_iterator i=mDemands.begin(),\n i_=mDemands.end() ; i!=i_ ; ++i) {\n Demand *d = *i; \n \n Ogre::Real this_dist = (*i)->mDist;\n \n if (!found || this_dist\nstatic inline bool is_unused (const Ogre::SharedPtr& r)\n{\n \/\/ if resource only used here, unload it\n return r.useCount() <=\n Ogre::ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS+1;\n}\n\nvoid BackgroundMeshLoader::finishedWith (const ResourcePtrSet &s) {\n typedef ResourcePtrSet::const_iterator I;\n for (I i=s.begin(), i_=s.end() ; i!=i_ ; ++i) {\n finishedWith(*i);\n }\n}\n\nvoid BackgroundMeshLoader::finishedWith (const Ogre::ResourcePtr &rp)\n{\n if (mQuit) return;\n if (rp.isNull()) return;\n if (!is_unused(rp)) return;\n mDeathRow.push(rp);\n}\n\nvoid BackgroundMeshLoader::finishedWith (const Ogre::MaterialPtr &mat)\n{\n if (mQuit) return;\n if (mat.isNull()) return;\n if (!is_unused(mat)) return;\n mat->unload();\n}\n\nbool BackgroundMeshLoader::isGPUOversubscribed () const\n{\n Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();\n Ogre::MeshManager &mm = Ogre::MeshManager::getSingleton();\n\n size_t budget = tm.getMemoryBudget() + mm.getMemoryBudget();\n\n size_t usage = tm.getMemoryUsage() + mm.getMemoryUsage();\n\n return usage >= budget;\n}\n\nvoid BackgroundMeshLoader::checkGPUUsage ()\n{\n Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();\n Ogre::MeshManager &mm = Ogre::MeshManager::getSingleton();\n\n size_t budget = tm.getMemoryBudget() + mm.getMemoryBudget();\n\n while (true) {\n\n size_t usage = tm.getMemoryUsage() + mm.getMemoryUsage();\n\n if (usage < budget || mDeathRow.size() == 0) break;\n\n Ogre::ResourcePtr r = mDeathRow.pop();\n\n if (is_unused(r))\n r->unload();\n }\n\n}\n\ntemplate<>\nBackgroundMeshLoader *Ogre::Singleton::ms_Singleton =NULL;\n\n\n\/\/ vim: shiftwidth=8:tabstop=8:expandtab\n<|endoftext|>"} {"text":"\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/conv_weights_converter.h\"\n\n#include \n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/util.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/work_group_picking.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\nnamespace {\n\nstd::string GetConverterToConvWeightsCode(\n const OperationDef& op_def,\n const ConvWeightsDescription& conv_weights_desc) {\n TensorCodeGenerator src_tensor(\n \"src_data\",\n WHSBPoint{\"src_size.x\", \"src_size.y\", \"src_size.z\", \"src_size.w\"},\n op_def.src_tensors[0]);\n TensorCodeGenerator dst_tensor(\n \"dst_data\",\n WHSBPoint{\"dst_size.x\", \"dst_size.y\", \"dst_size.z\", \"dst_size.w\"},\n op_def.dst_tensors[0]);\n\n std::string c = GetCommonDefines(op_def.precision);\n c += \"__kernel void main_function(\\n\";\n c += src_tensor.GetDeclaration(AccessType::READ) + \",\\n\";\n c += dst_tensor.GetDeclaration(AccessType::WRITE) + \",\\n\";\n c += \" int4 src_size, \\n\";\n c += \" float4 mask\\n\";\n c += \") {\\n\";\n c += \" int GROUP_SIZE = \" +\n std::to_string(conv_weights_desc.output_group_size) + \";\\n\";\n c += \" int O = get_global_id(0) * 4;\\n\";\n c += \" int I = get_global_id(1);\\n\";\n c += \" int Z = get_global_id(2);\\n\";\n c += \" int W = Z % src_size.x;\\n\";\n c += \" int H = Z \/ src_size.x;\\n\";\n c += \" if (O >= src_size.w || I >= src_size.z || H >= src_size.y) return;\\n\";\n c += \" FLT4 v0 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 0\") + \";\\n\";\n c += \" FLT4 v1 = (FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\\n\";\n c += \" FLT4 v2 = (FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\\n\";\n c += \" FLT4 v3 = (FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\\n\";\n c += \" if (O + 1 < src_size.w) {\\n\";\n c += \" v1 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 1\") + \";\\n\";\n c += \" }\\n\";\n c += \" if (O + 2 < src_size.w) {\\n\";\n c += \" v2 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 2\") + \";\\n\";\n c += \" }\\n\";\n c += \" if (O + 3 < src_size.w) {\\n\";\n c += \" v3 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 3\") + \";\\n\";\n c += \" }\\n\";\n c += \" if (I == src_size.z - 1) {\\n\";\n c += \" FLT4 mask_t = TO_FLT4(mask);\\n\";\n c += \" v0 *= mask_t;\\n\";\n c += \" v1 *= mask_t;\\n\";\n c += \" v2 *= mask_t;\\n\";\n c += \" v3 *= mask_t;\\n\";\n c += \" }\\n\";\n c += \" FLT4 r0 = (FLT4)(v0.x, v1.x, v2.x, v3.x);\\n\";\n c += \" FLT4 r1 = (FLT4)(v0.y, v1.y, v2.y, v3.y);\\n\";\n c += \" FLT4 r2 = (FLT4)(v0.z, v1.z, v2.z, v3.z);\\n\";\n c += \" FLT4 r3 = (FLT4)(v0.w, v1.w, v2.w, v3.w);\\n\";\n c += \" int d_index = O \/ (GROUP_SIZE * 4);\\n\";\n c += \" int k_index = (O % (GROUP_SIZE * 4)) \/ 4;\\n\";\n c += \" int dst_offset = (((d_index * src_size.y + H) * src_size.x + W) * \"\n \"src_size.z + I) * GROUP_SIZE + \"\n \"k_index;\\n\";\n c += \" int address0 = dst_offset * 4 + 0;\\n\";\n c += \" int address1 = dst_offset * 4 + 1;\\n\";\n c += \" int address2 = dst_offset * 4 + 2;\\n\";\n c += \" int address3 = dst_offset * 4 + 3;\\n\";\n c += \" \" + dst_tensor.Write(\"r0\", \"address0\");\n c += \" \" + dst_tensor.Write(\"r1\", \"address1\");\n c += \" \" + dst_tensor.Write(\"r2\", \"address2\");\n c += \" \" + dst_tensor.Write(\"r3\", \"address3\");\n c += \"}\\n\";\n return c;\n}\n} \/\/ namespace\n\nConverterToConvWeights::ConverterToConvWeights(\n ConverterToConvWeights&& operation)\n : GPUOperation(std::move(operation)),\n conv_weights_desc_(operation.conv_weights_desc_),\n kernel_(std::move(operation.kernel_)),\n work_group_size_(operation.work_group_size_) {}\n\nConverterToConvWeights& ConverterToConvWeights::operator=(\n ConverterToConvWeights&& operation) {\n if (this != &operation) {\n conv_weights_desc_ = operation.conv_weights_desc_;\n kernel_ = std::move(operation.kernel_);\n std::swap(work_group_size_, operation.work_group_size_);\n GPUOperation::operator=(std::move(operation));\n }\n return *this;\n}\n\nabsl::Status ConverterToConvWeights::Compile(\n const CreationContext& creation_context) {\n std::string code =\n GetConverterToConvWeightsCode(definition_, conv_weights_desc_);\n return creation_context.cache->GetOrCreateCLKernel(\n code, \"main_function\", *creation_context.context,\n *creation_context.device, &kernel_);\n}\n\nabsl::Status ConverterToConvWeights::BindArguments() {\n kernel_.ResetBindingCounter();\n RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[0]->GetMemoryPtr()));\n RETURN_IF_ERROR(kernel_.SetMemoryAuto(dst_[0]->GetMemoryPtrForWriting()));\n RETURN_IF_ERROR(kernel_.SetBytesAuto(src_[0]->GetWHSB()));\n RETURN_IF_ERROR(\n kernel_.SetBytesAuto(GetMaskForLastPlane(src_[0]->Channels())));\n return absl::OkStatus();\n}\n\nint3 ConverterToConvWeights::GetGridSize() const {\n const int grid_x = DivideRoundUp(src_[0]->Batch(), 4);\n const int grid_y = src_[0]->Slices();\n const int grid_z = src_[0]->Width() * src_[0]->Height();\n return int3(grid_x, grid_y, grid_z);\n}\n\nabsl::Status ConverterToConvWeights::Tune(const TuningParameters& params) {\n RETURN_IF_ERROR(BindArguments());\n return GetBestWorkGroup(params, kernel_, GetGridSize(), &work_group_size_);\n}\n\nabsl::Status ConverterToConvWeights::AddToQueue(CLCommandQueue* queue) {\n RETURN_IF_ERROR(BindArguments());\n return queue->DispatchImplicit(kernel_, GetGridSize(), work_group_size_);\n}\n\nConverterToConvWeights CreateConverterToConvWeights(\n const OperationDef& definition,\n const ConvWeightsDescription& conv_weights_desc) {\n return ConverterToConvWeights(definition, conv_weights_desc);\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\nInternal change\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/conv_weights_converter.h\"\n\n#include \n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/util.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/work_group_picking.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\nnamespace {\n\nstd::string GetConverterToConvWeightsCode(\n const OperationDef& op_def,\n const ConvWeightsDescription& conv_weights_desc) {\n TensorCodeGenerator src_tensor(\n \"src_data\",\n WHSBPoint{\"src_size.x\", \"src_size.y\", \"src_size.z\", \"src_size.w\"},\n op_def.src_tensors[0]);\n TensorCodeGenerator dst_tensor(\n \"dst_data\",\n WHSBPoint{\"dst_size.x\", \"dst_size.y\", \"dst_size.z\", \"dst_size.w\"},\n op_def.dst_tensors[0]);\n\n std::string c = GetCommonDefines(op_def.precision);\n c += \"__kernel void main_function(\\n\";\n c += src_tensor.GetDeclaration(AccessType::READ) + \",\\n\";\n c += dst_tensor.GetDeclaration(AccessType::WRITE) + \",\\n\";\n c += \" int4 src_size, \\n\";\n c += \" float4 mask\\n\";\n c += \") {\\n\";\n c += \" int GROUP_SIZE = \" +\n std::to_string(conv_weights_desc.output_group_size) + \";\\n\";\n c += \" int O = get_global_id(0) * 4;\\n\";\n c += \" int I = get_global_id(1);\\n\";\n c += \" int Z = get_global_id(2);\\n\";\n c += \" int W = Z % src_size.x;\\n\";\n c += \" int H = Z \/ src_size.x;\\n\";\n c += \" if (O >= src_size.w || I >= src_size.z || H >= src_size.y) return;\\n\";\n c += \" FLT4 v0 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 0\") + \";\\n\";\n c += \" FLT4 v1 = (FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\\n\";\n c += \" FLT4 v2 = (FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\\n\";\n c += \" FLT4 v3 = (FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\\n\";\n c += \" if (O + 1 < src_size.w) {\\n\";\n c += \" v1 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 1\") + \";\\n\";\n c += \" }\\n\";\n c += \" if (O + 2 < src_size.w) {\\n\";\n c += \" v2 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 2\") + \";\\n\";\n c += \" }\\n\";\n c += \" if (O + 3 < src_size.w) {\\n\";\n c += \" v3 =\" + src_tensor.ReadWHSB(\"W\", \"H\", \"I\", \"O + 3\") + \";\\n\";\n c += \" }\\n\";\n c += \" if (I == src_size.z - 1) {\\n\";\n c += \" FLT4 mask_t = TO_FLT4(mask);\\n\";\n c += \" v0 *= mask_t;\\n\";\n c += \" v1 *= mask_t;\\n\";\n c += \" v2 *= mask_t;\\n\";\n c += \" v3 *= mask_t;\\n\";\n c += \" }\\n\";\n c += \" FLT4 r0 = (FLT4)(v0.x, v1.x, v2.x, v3.x);\\n\";\n c += \" FLT4 r1 = (FLT4)(v0.y, v1.y, v2.y, v3.y);\\n\";\n c += \" FLT4 r2 = (FLT4)(v0.z, v1.z, v2.z, v3.z);\\n\";\n c += \" FLT4 r3 = (FLT4)(v0.w, v1.w, v2.w, v3.w);\\n\";\n c += \" int d_index = O \/ (GROUP_SIZE * 4);\\n\";\n c += \" int k_index = (O % (GROUP_SIZE * 4)) \/ 4;\\n\";\n c += \" int dst_offset = (((d_index * src_size.y + H) * src_size.x + W) * \"\n \"src_size.z + I) * GROUP_SIZE + \"\n \"k_index;\\n\";\n c += \" int address0 = dst_offset * 4 + 0;\\n\";\n c += \" int address1 = dst_offset * 4 + 1;\\n\";\n c += \" int address2 = dst_offset * 4 + 2;\\n\";\n c += \" int address3 = dst_offset * 4 + 3;\\n\";\n c += \" \" + dst_tensor.Write(\"r0\", \"address0\");\n c += \" \" + dst_tensor.Write(\"r1\", \"address1\");\n c += \" \" + dst_tensor.Write(\"r2\", \"address2\");\n c += \" \" + dst_tensor.Write(\"r3\", \"address3\");\n c += \"}\\n\";\n return c;\n}\n} \/\/ namespace\n\nConverterToConvWeights::ConverterToConvWeights(\n ConverterToConvWeights&& operation)\n : GPUOperation(std::move(operation)),\n conv_weights_desc_(operation.conv_weights_desc_),\n kernel_(std::move(operation.kernel_)),\n work_group_size_(operation.work_group_size_) {}\n\nConverterToConvWeights& ConverterToConvWeights::operator=(\n ConverterToConvWeights&& operation) {\n if (this != &operation) {\n conv_weights_desc_ = operation.conv_weights_desc_;\n kernel_ = std::move(operation.kernel_);\n std::swap(work_group_size_, operation.work_group_size_);\n GPUOperation::operator=(std::move(operation));\n }\n return *this;\n}\n\nabsl::Status ConverterToConvWeights::Compile(\n const CreationContext& creation_context) {\n std::string code =\n GetConverterToConvWeightsCode(definition_, conv_weights_desc_);\n return creation_context.cache->GetOrCreateCLKernel(\n code, \"main_function\", *creation_context.context,\n *creation_context.device, &kernel_);\n}\n\nabsl::Status ConverterToConvWeights::BindArguments() {\n kernel_.ResetBindingCounter();\n RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[0]->GetMemoryPtr()));\n RETURN_IF_ERROR(kernel_.SetMemoryAuto(dst_[0]->GetMemoryPtrForWriting()));\n RETURN_IF_ERROR(kernel_.SetBytesAuto(src_[0]->GetWHSB()));\n RETURN_IF_ERROR(\n kernel_.SetBytesAuto(GetMaskForLastPlane(src_[0]->Channels())));\n return absl::OkStatus();\n}\n\nint3 ConverterToConvWeights::GetGridSize() const {\n const int grid_x = DivideRoundUp(\n AlignByN(src_[0]->Batch(), 4 * conv_weights_desc_.output_group_size), 4);\n const int grid_y = src_[0]->Slices();\n const int grid_z = src_[0]->Width() * src_[0]->Height();\n return int3(grid_x, grid_y, grid_z);\n}\n\nabsl::Status ConverterToConvWeights::Tune(const TuningParameters& params) {\n RETURN_IF_ERROR(BindArguments());\n return GetBestWorkGroup(params, kernel_, GetGridSize(), &work_group_size_);\n}\n\nabsl::Status ConverterToConvWeights::AddToQueue(CLCommandQueue* queue) {\n RETURN_IF_ERROR(BindArguments());\n return queue->DispatchImplicit(kernel_, GetGridSize(), work_group_size_);\n}\n\nConverterToConvWeights CreateConverterToConvWeights(\n const OperationDef& definition,\n const ConvWeightsDescription& conv_weights_desc) {\n return ConverterToConvWeights(definition, conv_weights_desc);\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"\/\/===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===\/\/\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 file implements the LLVM Pass infrastructure. It is primarily\n\/\/ responsible with ensuring that passes are executed and batched together\n\/\/ optimally.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/TypeInfo.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Pass Implementation\n\/\/\n\n\/\/ Force out-of-line virtual method.\nPass::~Pass() { \n delete Resolver; \n}\n\n\/\/ Force out-of-line virtual method.\nModulePass::~ModulePass() { }\n\nbool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {\n return Resolver->getAnalysisToUpdate(AnalysisID, true) != 0;\n}\n\n\/\/ dumpPassStructure - Implement the -debug-passes=Structure option\nvoid Pass::dumpPassStructure(unsigned Offset) {\n cerr << std::string(Offset*2, ' ') << getPassName() << \"\\n\";\n}\n\n\/\/ getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.\n\/\/\nconst char *Pass::getPassName() const {\n if (const PassInfo *PI = getPassInfo())\n return PI->getPassName();\n return typeid(*this).name();\n}\n\n\/\/ print - Print out the internal state of the pass. This is called by Analyze\n\/\/ to print out the contents of an analysis. Otherwise it is not necessary to\n\/\/ implement this method.\n\/\/\nvoid Pass::print(std::ostream &O,const Module*) const {\n O << \"Pass::print not implemented for pass: '\" << getPassName() << \"'!\\n\";\n}\n\n\/\/ dump - call print(cerr);\nvoid Pass::dump() const {\n print(*cerr.stream(), 0);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ImmutablePass Implementation\n\/\/\n\/\/ Force out-of-line virtual method.\nImmutablePass::~ImmutablePass() { }\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ FunctionPass Implementation\n\/\/\n\n\/\/ run - On a module, we run this pass by initializing, runOnFunction'ing once\n\/\/ for every function in the module, then by finalizing.\n\/\/\nbool FunctionPass::runOnModule(Module &M) {\n bool Changed = doInitialization(M);\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isDeclaration()) \/\/ Passes are not run on external functions!\n Changed |= runOnFunction(*I);\n\n return Changed | doFinalization(M);\n}\n\n\/\/ run - On a function, we simply initialize, run the function, then finalize.\n\/\/\nbool FunctionPass::run(Function &F) {\n if (F.isDeclaration()) return false;\/\/ Passes are not run on external functions!\n\n bool Changed = doInitialization(*F.getParent());\n Changed |= runOnFunction(F);\n return Changed | doFinalization(*F.getParent());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ BasicBlockPass Implementation\n\/\/\n\n\/\/ To run this pass on a function, we simply call runOnBasicBlock once for each\n\/\/ function.\n\/\/\nbool BasicBlockPass::runOnFunction(Function &F) {\n bool Changed = doInitialization(F);\n for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)\n Changed |= runOnBasicBlock(*I);\n return Changed | doFinalization(F);\n}\n\n\/\/ To run directly on the basic block, we initialize, runOnBasicBlock, then\n\/\/ finalize.\n\/\/\nbool BasicBlockPass::runPass(BasicBlock &BB) {\n Function &F = *BB.getParent();\n Module &M = *F.getParent();\n bool Changed = doInitialization(M);\n Changed |= doInitialization(F);\n Changed |= runOnBasicBlock(BB);\n Changed |= doFinalization(F);\n Changed |= doFinalization(M);\n return Changed;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Pass Registration mechanism\n\/\/\nnamespace {\nclass PassRegistrar {\n \/\/\/ PassInfoMap - Keep track of the passinfo object for each registered llvm\n \/\/\/ pass.\n std::map PassInfoMap;\n \n \/\/\/ AnalysisGroupInfo - Keep track of information for each analysis group.\n struct AnalysisGroupInfo {\n const PassInfo *DefaultImpl;\n std::set Implementations;\n AnalysisGroupInfo() : DefaultImpl(0) {}\n };\n \n \/\/\/ AnalysisGroupInfoMap - Information for each analysis group.\n std::map AnalysisGroupInfoMap;\n\npublic:\n \n const PassInfo *GetPassInfo(intptr_t TI) const {\n std::map::const_iterator I = PassInfoMap.find(TI);\n return I != PassInfoMap.end() ? I->second : 0;\n }\n \n void RegisterPass(PassInfo &PI) {\n bool Inserted =\n PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;\n assert(Inserted && \"Pass registered multiple times!\");\n }\n \n void UnregisterPass(PassInfo &PI) {\n std::map::iterator I =\n PassInfoMap.find(PI.getTypeInfo());\n assert(I != PassInfoMap.end() && \"Pass registered but not in map!\");\n \n \/\/ Remove pass from the map.\n PassInfoMap.erase(I);\n }\n \n void EnumerateWith(PassRegistrationListener *L) {\n for (std::map::const_iterator I = PassInfoMap.begin(),\n E = PassInfoMap.end(); I != E; ++I)\n L->passEnumerate(I->second);\n }\n \n \n \/\/\/ Analysis Group Mechanisms.\n void RegisterAnalysisGroup(PassInfo *InterfaceInfo,\n const PassInfo *ImplementationInfo,\n bool isDefault) {\n AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];\n assert(AGI.Implementations.count(ImplementationInfo) == 0 &&\n \"Cannot add a pass to the same analysis group more than once!\");\n AGI.Implementations.insert(ImplementationInfo);\n if (isDefault) {\n assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&\n \"Default implementation for analysis group already specified!\");\n assert(ImplementationInfo->getNormalCtor() &&\n \"Cannot specify pass as default if it does not have a default ctor\");\n AGI.DefaultImpl = ImplementationInfo;\n InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());\n }\n }\n};\n}\n\nstatic std::vector *Listeners = 0;\n\n\/\/ FIXME: This should use ManagedStatic to manage the pass registrar.\n\/\/ Unfortunately, we can't do this, because passes are registered with static\n\/\/ ctors, and having llvm_shutdown clear this map prevents successful\n\/\/ ressurection after llvm_shutdown is run.\nstatic PassRegistrar *getPassRegistrar() {\n static PassRegistrar *PassRegistrarObj = 0;\n if (!PassRegistrarObj)\n PassRegistrarObj = new PassRegistrar();\n return PassRegistrarObj;\n}\n\n\/\/ getPassInfo - Return the PassInfo data structure that corresponds to this\n\/\/ pass...\nconst PassInfo *Pass::getPassInfo() const {\n return lookupPassInfo(PassID);\n}\n\nconst PassInfo *Pass::lookupPassInfo(intptr_t TI) {\n return getPassRegistrar()->GetPassInfo(TI);\n}\n\nvoid RegisterPassBase::registerPass() {\n getPassRegistrar()->RegisterPass(PIObj);\n\n \/\/ Notify any listeners.\n if (Listeners)\n for (std::vector::iterator\n I = Listeners->begin(), E = Listeners->end(); I != E; ++I)\n (*I)->passRegistered(&PIObj);\n}\n\nvoid RegisterPassBase::unregisterPass() {\n getPassRegistrar()->UnregisterPass(PIObj);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Analysis Group Implementation Code\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ RegisterAGBase implementation\n\/\/\nRegisterAGBase::RegisterAGBase(intptr_t InterfaceID,\n intptr_t PassID, bool isDefault)\n : RegisterPassBase(InterfaceID),\n ImplementationInfo(0), isDefaultImplementation(isDefault) {\n\n InterfaceInfo = const_cast(Pass::lookupPassInfo(InterfaceID));\n if (InterfaceInfo == 0) {\n \/\/ First reference to Interface, register it now.\n registerPass();\n InterfaceInfo = &PIObj;\n }\n assert(PIObj.isAnalysisGroup() &&\n \"Trying to join an analysis group that is a normal pass!\");\n\n if (PassID) {\n ImplementationInfo = Pass::lookupPassInfo(PassID);\n assert(ImplementationInfo &&\n \"Must register pass before adding to AnalysisGroup!\");\n\n \/\/ Make sure we keep track of the fact that the implementation implements\n \/\/ the interface.\n PassInfo *IIPI = const_cast(ImplementationInfo);\n IIPI->addInterfaceImplemented(InterfaceInfo);\n \n getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);\n }\n}\n\nvoid RegisterAGBase::setGroupName(const char *Name) {\n assert(InterfaceInfo->getPassName()[0] == 0 && \"Interface Name already set!\");\n InterfaceInfo->setPassName(Name);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PassRegistrationListener implementation\n\/\/\n\n\/\/ PassRegistrationListener ctor - Add the current object to the list of\n\/\/ PassRegistrationListeners...\nPassRegistrationListener::PassRegistrationListener() {\n if (!Listeners) Listeners = new std::vector();\n Listeners->push_back(this);\n}\n\n\/\/ dtor - Remove object from list of listeners...\nPassRegistrationListener::~PassRegistrationListener() {\n std::vector::iterator I =\n std::find(Listeners->begin(), Listeners->end(), this);\n assert(Listeners && I != Listeners->end() &&\n \"PassRegistrationListener not registered!\");\n Listeners->erase(I);\n\n if (Listeners->empty()) {\n delete Listeners;\n Listeners = 0;\n }\n}\n\n\/\/ enumeratePasses - Iterate over the registered passes, calling the\n\/\/ passEnumerate callback on each PassInfo object.\n\/\/\nvoid PassRegistrationListener::enumeratePasses() {\n getPassRegistrar()->EnumerateWith(this);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ AnalysisUsage Class Implementation\n\/\/\n\nnamespace {\n struct GetCFGOnlyPasses : public PassRegistrationListener {\n std::vector &CFGOnlyList;\n GetCFGOnlyPasses(std::vector &L) : CFGOnlyList(L) {}\n \n void passEnumerate(const PassInfo *P) {\n if (P->isCFGOnlyPass())\n CFGOnlyList.push_back(P);\n }\n };\n}\n\n\/\/ setPreservesCFG - This function should be called to by the pass, iff they do\n\/\/ not:\n\/\/\n\/\/ 1. Add or remove basic blocks from the function\n\/\/ 2. Modify terminator instructions in any way.\n\/\/\n\/\/ This function annotates the AnalysisUsage info object to say that analyses\n\/\/ that only depend on the CFG are preserved by this pass.\n\/\/\nvoid AnalysisUsage::setPreservesCFG() {\n \/\/ Since this transformation doesn't modify the CFG, it preserves all analyses\n \/\/ that only depend on the CFG (like dominators, loop info, etc...)\n GetCFGOnlyPasses(Preserved).enumeratePasses();\n}\n\n\ndisable this assertion as a hack to get the build more unbroken :(\/\/===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===\/\/\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 file implements the LLVM Pass infrastructure. It is primarily\n\/\/ responsible with ensuring that passes are executed and batched together\n\/\/ optimally.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/TypeInfo.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Pass Implementation\n\/\/\n\n\/\/ Force out-of-line virtual method.\nPass::~Pass() { \n delete Resolver; \n}\n\n\/\/ Force out-of-line virtual method.\nModulePass::~ModulePass() { }\n\nbool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {\n return Resolver->getAnalysisToUpdate(AnalysisID, true) != 0;\n}\n\n\/\/ dumpPassStructure - Implement the -debug-passes=Structure option\nvoid Pass::dumpPassStructure(unsigned Offset) {\n cerr << std::string(Offset*2, ' ') << getPassName() << \"\\n\";\n}\n\n\/\/ getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.\n\/\/\nconst char *Pass::getPassName() const {\n if (const PassInfo *PI = getPassInfo())\n return PI->getPassName();\n return typeid(*this).name();\n}\n\n\/\/ print - Print out the internal state of the pass. This is called by Analyze\n\/\/ to print out the contents of an analysis. Otherwise it is not necessary to\n\/\/ implement this method.\n\/\/\nvoid Pass::print(std::ostream &O,const Module*) const {\n O << \"Pass::print not implemented for pass: '\" << getPassName() << \"'!\\n\";\n}\n\n\/\/ dump - call print(cerr);\nvoid Pass::dump() const {\n print(*cerr.stream(), 0);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ImmutablePass Implementation\n\/\/\n\/\/ Force out-of-line virtual method.\nImmutablePass::~ImmutablePass() { }\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ FunctionPass Implementation\n\/\/\n\n\/\/ run - On a module, we run this pass by initializing, runOnFunction'ing once\n\/\/ for every function in the module, then by finalizing.\n\/\/\nbool FunctionPass::runOnModule(Module &M) {\n bool Changed = doInitialization(M);\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isDeclaration()) \/\/ Passes are not run on external functions!\n Changed |= runOnFunction(*I);\n\n return Changed | doFinalization(M);\n}\n\n\/\/ run - On a function, we simply initialize, run the function, then finalize.\n\/\/\nbool FunctionPass::run(Function &F) {\n if (F.isDeclaration()) return false;\/\/ Passes are not run on external functions!\n\n bool Changed = doInitialization(*F.getParent());\n Changed |= runOnFunction(F);\n return Changed | doFinalization(*F.getParent());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ BasicBlockPass Implementation\n\/\/\n\n\/\/ To run this pass on a function, we simply call runOnBasicBlock once for each\n\/\/ function.\n\/\/\nbool BasicBlockPass::runOnFunction(Function &F) {\n bool Changed = doInitialization(F);\n for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)\n Changed |= runOnBasicBlock(*I);\n return Changed | doFinalization(F);\n}\n\n\/\/ To run directly on the basic block, we initialize, runOnBasicBlock, then\n\/\/ finalize.\n\/\/\nbool BasicBlockPass::runPass(BasicBlock &BB) {\n Function &F = *BB.getParent();\n Module &M = *F.getParent();\n bool Changed = doInitialization(M);\n Changed |= doInitialization(F);\n Changed |= runOnBasicBlock(BB);\n Changed |= doFinalization(F);\n Changed |= doFinalization(M);\n return Changed;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Pass Registration mechanism\n\/\/\nnamespace {\nclass PassRegistrar {\n \/\/\/ PassInfoMap - Keep track of the passinfo object for each registered llvm\n \/\/\/ pass.\n std::map PassInfoMap;\n \n \/\/\/ AnalysisGroupInfo - Keep track of information for each analysis group.\n struct AnalysisGroupInfo {\n const PassInfo *DefaultImpl;\n std::set Implementations;\n AnalysisGroupInfo() : DefaultImpl(0) {}\n };\n \n \/\/\/ AnalysisGroupInfoMap - Information for each analysis group.\n std::map AnalysisGroupInfoMap;\n\npublic:\n \n const PassInfo *GetPassInfo(intptr_t TI) const {\n std::map::const_iterator I = PassInfoMap.find(TI);\n return I != PassInfoMap.end() ? I->second : 0;\n }\n \n void RegisterPass(PassInfo &PI) {\n bool Inserted =\n PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;\n \/\/assert(Inserted && \"Pass registered multiple times!\");\n }\n \n void UnregisterPass(PassInfo &PI) {\n std::map::iterator I =\n PassInfoMap.find(PI.getTypeInfo());\n assert(I != PassInfoMap.end() && \"Pass registered but not in map!\");\n \n \/\/ Remove pass from the map.\n PassInfoMap.erase(I);\n }\n \n void EnumerateWith(PassRegistrationListener *L) {\n for (std::map::const_iterator I = PassInfoMap.begin(),\n E = PassInfoMap.end(); I != E; ++I)\n L->passEnumerate(I->second);\n }\n \n \n \/\/\/ Analysis Group Mechanisms.\n void RegisterAnalysisGroup(PassInfo *InterfaceInfo,\n const PassInfo *ImplementationInfo,\n bool isDefault) {\n AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];\n assert(AGI.Implementations.count(ImplementationInfo) == 0 &&\n \"Cannot add a pass to the same analysis group more than once!\");\n AGI.Implementations.insert(ImplementationInfo);\n if (isDefault) {\n assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&\n \"Default implementation for analysis group already specified!\");\n assert(ImplementationInfo->getNormalCtor() &&\n \"Cannot specify pass as default if it does not have a default ctor\");\n AGI.DefaultImpl = ImplementationInfo;\n InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());\n }\n }\n};\n}\n\nstatic std::vector *Listeners = 0;\n\n\/\/ FIXME: This should use ManagedStatic to manage the pass registrar.\n\/\/ Unfortunately, we can't do this, because passes are registered with static\n\/\/ ctors, and having llvm_shutdown clear this map prevents successful\n\/\/ ressurection after llvm_shutdown is run.\nstatic PassRegistrar *getPassRegistrar() {\n static PassRegistrar *PassRegistrarObj = 0;\n if (!PassRegistrarObj)\n PassRegistrarObj = new PassRegistrar();\n return PassRegistrarObj;\n}\n\n\/\/ getPassInfo - Return the PassInfo data structure that corresponds to this\n\/\/ pass...\nconst PassInfo *Pass::getPassInfo() const {\n return lookupPassInfo(PassID);\n}\n\nconst PassInfo *Pass::lookupPassInfo(intptr_t TI) {\n return getPassRegistrar()->GetPassInfo(TI);\n}\n\nvoid RegisterPassBase::registerPass() {\n getPassRegistrar()->RegisterPass(PIObj);\n\n \/\/ Notify any listeners.\n if (Listeners)\n for (std::vector::iterator\n I = Listeners->begin(), E = Listeners->end(); I != E; ++I)\n (*I)->passRegistered(&PIObj);\n}\n\nvoid RegisterPassBase::unregisterPass() {\n getPassRegistrar()->UnregisterPass(PIObj);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Analysis Group Implementation Code\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ RegisterAGBase implementation\n\/\/\nRegisterAGBase::RegisterAGBase(intptr_t InterfaceID,\n intptr_t PassID, bool isDefault)\n : RegisterPassBase(InterfaceID),\n ImplementationInfo(0), isDefaultImplementation(isDefault) {\n\n InterfaceInfo = const_cast(Pass::lookupPassInfo(InterfaceID));\n if (InterfaceInfo == 0) {\n \/\/ First reference to Interface, register it now.\n registerPass();\n InterfaceInfo = &PIObj;\n }\n assert(PIObj.isAnalysisGroup() &&\n \"Trying to join an analysis group that is a normal pass!\");\n\n if (PassID) {\n ImplementationInfo = Pass::lookupPassInfo(PassID);\n assert(ImplementationInfo &&\n \"Must register pass before adding to AnalysisGroup!\");\n\n \/\/ Make sure we keep track of the fact that the implementation implements\n \/\/ the interface.\n PassInfo *IIPI = const_cast(ImplementationInfo);\n IIPI->addInterfaceImplemented(InterfaceInfo);\n \n getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);\n }\n}\n\nvoid RegisterAGBase::setGroupName(const char *Name) {\n assert(InterfaceInfo->getPassName()[0] == 0 && \"Interface Name already set!\");\n InterfaceInfo->setPassName(Name);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PassRegistrationListener implementation\n\/\/\n\n\/\/ PassRegistrationListener ctor - Add the current object to the list of\n\/\/ PassRegistrationListeners...\nPassRegistrationListener::PassRegistrationListener() {\n if (!Listeners) Listeners = new std::vector();\n Listeners->push_back(this);\n}\n\n\/\/ dtor - Remove object from list of listeners...\nPassRegistrationListener::~PassRegistrationListener() {\n std::vector::iterator I =\n std::find(Listeners->begin(), Listeners->end(), this);\n assert(Listeners && I != Listeners->end() &&\n \"PassRegistrationListener not registered!\");\n Listeners->erase(I);\n\n if (Listeners->empty()) {\n delete Listeners;\n Listeners = 0;\n }\n}\n\n\/\/ enumeratePasses - Iterate over the registered passes, calling the\n\/\/ passEnumerate callback on each PassInfo object.\n\/\/\nvoid PassRegistrationListener::enumeratePasses() {\n getPassRegistrar()->EnumerateWith(this);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ AnalysisUsage Class Implementation\n\/\/\n\nnamespace {\n struct GetCFGOnlyPasses : public PassRegistrationListener {\n std::vector &CFGOnlyList;\n GetCFGOnlyPasses(std::vector &L) : CFGOnlyList(L) {}\n \n void passEnumerate(const PassInfo *P) {\n if (P->isCFGOnlyPass())\n CFGOnlyList.push_back(P);\n }\n };\n}\n\n\/\/ setPreservesCFG - This function should be called to by the pass, iff they do\n\/\/ not:\n\/\/\n\/\/ 1. Add or remove basic blocks from the function\n\/\/ 2. Modify terminator instructions in any way.\n\/\/\n\/\/ This function annotates the AnalysisUsage info object to say that analyses\n\/\/ that only depend on the CFG are preserved by this pass.\n\/\/\nvoid AnalysisUsage::setPreservesCFG() {\n \/\/ Since this transformation doesn't modify the CFG, it preserves all analyses\n \/\/ that only depend on the CFG (like dominators, loop info, etc...)\n GetCFGOnlyPasses(Preserved).enumeratePasses();\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * TableSelectionTx.cpp\n *\n * Copyright (C) 2020 by VISUS (University of Stuttgart)\n * Alle Rechte vorbehalten.\n *\/\n\n#include \"stdafx.h\"\n#include \"TableSelectionTx.h\"\n\n#include \"mmcore\/param\/BoolParam.h\"\n#include \"vislib\/sys\/Log.h\"\n\nusing namespace megamol::stdplugin::datatools;\nusing namespace megamol::stdplugin::datatools::table;\nusing namespace megamol;\n\nTableSelectionTx::TableSelectionTx()\n : core::Module()\n , tableInSlot(\"getTableIn\", \"Float table input\")\n , flagStorageReadInSlot(\"readFlagStorageIn\", \"Flag storage read input\")\n , flagStorageWriteInSlot(\"writeFlagStorageIn\", \"Flag storage write input\")\n , flagStorageReadOutSlot(\"readFlagStorageOut\", \"Flag storage read output\")\n , flagStorageWriteOutSlot(\"writeFlagStorageOut\", \"Flag storage write output\")\n , updateSelectionParam(\"updateSelectionParam\", \"Enable selection update\")\n , senderThreadQuit_(false)\n , senderThreadNotified_(false)\n , receiverThreadQuit_(false)\n , receivedSelectionUpdate_(false)\n{\n this->tableInSlot.SetCompatibleCall();\n this->MakeSlotAvailable(&this->tableInSlot);\n\n this->flagStorageReadInSlot.SetCompatibleCall();\n this->MakeSlotAvailable(&this->flagStorageReadInSlot);\n\n this->flagStorageWriteInSlot.SetCompatibleCall();\n this->MakeSlotAvailable(&this->flagStorageWriteInSlot);\n\n this->flagStorageReadOutSlot.SetCallback(core::FlagCallRead_GL::ClassName(), core::FlagCallRead_GL::FunctionName(core::FlagCallRead_GL::CallGetData), &TableSelectionTx::readDataCallback);\n this->flagStorageReadOutSlot.SetCallback(core::FlagCallRead_GL::ClassName(), core::FlagCallRead_GL::FunctionName(core::FlagCallRead_GL::CallGetMetaData), &TableSelectionTx::readMetaDataCallback);\n this->MakeSlotAvailable(&this->flagStorageReadOutSlot);\n\n this->flagStorageWriteOutSlot.SetCallback(core::FlagCallWrite_GL::ClassName(), core::FlagCallWrite_GL::FunctionName(core::FlagCallWrite_GL::CallGetData), &TableSelectionTx::writeDataCallback);\n this->flagStorageWriteOutSlot.SetCallback(core::FlagCallWrite_GL::ClassName(), core::FlagCallWrite_GL::FunctionName(core::FlagCallWrite_GL::CallGetMetaData), &TableSelectionTx::writeMetaDataCallback);\n this->MakeSlotAvailable(&this->flagStorageWriteOutSlot);\n\n this->updateSelectionParam << new core::param::BoolParam(true);\n this->MakeSlotAvailable(&this->updateSelectionParam);\n}\n\nTableSelectionTx::~TableSelectionTx() {\n this->Release();\n}\n\nbool TableSelectionTx::create() {\n context_ = std::make_unique(1);\n\n senderThreadQuit_ = false;\n if (!senderThread_.joinable()) {\n senderThread_ = std::thread(&TableSelectionTx::selectionSender, this);\n }\n\n receiverThreadQuit_ = false;\n if (!receiverThread_.joinable()) {\n receiverThread_ = std::thread(&TableSelectionTx::selectionReceiver, this);\n }\n\n return true;\n}\n\nvoid TableSelectionTx::release() {\n senderThreadQuit_ = true;\n receiverThreadQuit_ = true;\n senderThreadNotified_ = true;\n condVar_.notify_one();\n context_->close();\n context_.reset();\n if (senderThread_.joinable()) {\n senderThread_.join();\n }\n if (receiverThread_.joinable()) {\n receiverThread_.join();\n }\n}\n\nbool TableSelectionTx::readDataCallback(core::Call& call) {\n auto *flagsReadOutCall = dynamic_cast(&call);\n if (flagsReadOutCall == nullptr) {\n return false;\n }\n\n if (!validateCalls()) {\n return false;\n }\n\n if (!validateSelectionUpdate()) {\n return false;\n }\n\n auto *flagsReadInCall = this->flagStorageReadInSlot.CallAs();\n\n (*flagsReadInCall)(core::FlagCallRead_GL::CallGetData);\n flagsReadOutCall->setData(flagsReadInCall->getData(), flagsReadInCall->version());\n\n return true;\n}\n\nbool TableSelectionTx::readMetaDataCallback(core::Call& call) {\n \/\/ FlagCall_GL has empty meta data\n return true;\n}\n\nbool TableSelectionTx::writeDataCallback(core::Call& call) {\n auto *flagsWriteOutCall = dynamic_cast(&call);\n if (flagsWriteOutCall == nullptr) {\n return false;\n }\n\n if (!validateCalls()) {\n return false;\n }\n\n auto *flagsWriteInCall = this->flagStorageWriteInSlot.CallAs();\n\n flagsWriteInCall->setData(flagsWriteOutCall->getData(), flagsWriteOutCall->version());\n (*flagsWriteInCall)(core::FlagCallWrite_GL::CallGetData);\n\n \/\/ Send data\n\n auto *tableInCall = this->tableInSlot.CallAs();\n\n tableInCall->SetFrameID(0);\n (*tableInCall)(1);\n (*tableInCall)(0);\n\n auto flags = flagsWriteOutCall->getData()->flags;\n size_t numberOfFlags = flags->getByteSize() \/ sizeof(uint32_t);\n size_t numberOfRows = tableInCall->GetRowsCount();\n\n \/\/ validateFlagCount() only increases the buffer, therefore numberOfFlags > numberOfRows is also valid.\n if (numberOfFlags < numberOfRows) {\n vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, \"TableSelectionTx: invalid table\/flag storage size!\");\n return false;\n }\n\n std::vector flagsData(numberOfFlags);\n flags->bind();\n glGetBufferSubData(flags->getTarget(), 0, flags->getByteSize(), flagsData.data());\n\n core::FlagStorage::FlagItemType testMask = core::FlagStorage::ENABLED | core::FlagStorage::FILTERED;\n core::FlagStorage::FlagItemType passMask = core::FlagStorage::ENABLED;\n\n std::unique_lock lock(selectedMutex_);\n selected_.clear();\n for (size_t i = 0; i < numberOfRows; ++i) {\n if ((flagsData[i] & testMask) == passMask) {\n if (flagsData[i] & core::FlagStorage::SELECTED) {\n selected_.push_back(static_cast(i));\n } else {\n \/\/ not selected\n }\n }\n }\n senderThreadNotified_ = true;\n condVar_.notify_one();\n lock.unlock();\n\n return true;\n}\n\nbool TableSelectionTx::writeMetaDataCallback(core::Call& call) {\n \/\/ FlagCall_GL has empty meta data\n return true;\n}\n\nbool TableSelectionTx::validateCalls() {\n auto *tableInCall = this->tableInSlot.CallAs();\n auto *flagsReadInCall = this->flagStorageReadInSlot.CallAs();\n auto *flagsWriteInCall = this->flagStorageWriteInSlot.CallAs();\n\n if (tableInCall == nullptr) {\n vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, \"TableSelectionTx requires a table!\");\n return false;\n }\n\n if (flagsReadInCall == nullptr) {\n vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, \"TableSelectionTx requires a read flag storage!\");\n return false;\n }\n\n if (flagsWriteInCall == nullptr) {\n vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, \"TableSelectionTx requires a write flag storage!\");\n return false;\n }\n\n return true;\n}\n\nbool TableSelectionTx::validateSelectionUpdate() {\n std::lock_guard lock(receivedSelectionMutex_);\n if (!receivedSelectionUpdate_) {\n return true;\n }\n\n receivedSelectionUpdate_ = false;\n\n if (!this->updateSelectionParam.Param()->Value()) {\n return true;\n }\n\n auto *flagsReadInCall = this->flagStorageReadInSlot.CallAs();\n (*flagsReadInCall)(core::FlagCallRead_GL::CallGetData);\n auto flagCollection = flagsReadInCall->getData();\n auto version = flagsReadInCall->version();\n\n auto *tableInCall = this->tableInSlot.CallAs();\n tableInCall->SetFrameID(0);\n (*tableInCall)(1);\n (*tableInCall)(0);\n\n size_t numberOfRows = tableInCall->GetRowsCount();\n\n std::vector flags_data(numberOfRows, core::FlagStorage::ENABLED);\n\n \/\/ Select received rows\n for (auto id : receivedSelection_) {\n if (id >= 0 && id < numberOfRows) {\n flags_data[id] = core::FlagStorage::ENABLED | core::FlagStorage::SELECTED;\n }\n }\n\n flagCollection->flags = std::make_shared(GL_SHADER_STORAGE_BUFFER, flags_data, GL_DYNAMIC_DRAW);\n\n auto *flagsWriteInCall = this->flagStorageWriteInSlot.CallAs();\n flagsWriteInCall->setData(flagCollection, version + 1);\n (*flagsWriteInCall)(core::FlagCallWrite_GL::CallGetData);\n\n return true;\n}\n\nvoid TableSelectionTx::selectionSender() {\n zmq::socket_t socket{*context_, ZMQ_REQ};\n socket.setsockopt(ZMQ_LINGER, 0);\n socket.connect(\"tcp:\/\/localhost:10001\");\n\n std::unique_lock lock(selectedMutex_);\n while (!senderThreadQuit_) {\n while (!senderThreadNotified_ && !senderThreadQuit_) {\n condVar_.wait(lock);\n }\n while (senderThreadNotified_ && !senderThreadQuit_) {\n senderThreadNotified_ = false;\n try {\n zmq::message_t request{selected_.cbegin(), selected_.cend()};\n lock.unlock();\n socket.send(request, zmq::send_flags::none);\n\n zmq::message_t reply{};\n socket.recv(reply, zmq::recv_flags::none);\n } catch (const zmq::error_t& e) {\n if (e.num() != ETERM) {\n std::cerr << e.what() << std::endl;\n }\n }\n lock.lock();\n }\n }\n}\n\nvoid TableSelectionTx::selectionReceiver() {\n zmq::socket_t socket{*context_, ZMQ_REP};\n socket.bind(\"tcp:\/\/*:10002\");\n\n const std::string okString{\"Ok!\"};\n\n while (!receiverThreadQuit_) {\n try {\n zmq::message_t request;\n socket.recv(request, zmq::recv_flags::none);\n size_t size = request.size() \/ sizeof(uint64_t);\n\n if (size > 0) {\n std::lock_guard lock(receivedSelectionMutex_);\n uint64_t* data_ptr = static_cast(request.data());\n receivedSelection_ = std::vector(data_ptr, data_ptr + size);\n receivedSelectionUpdate_ = true;\n }\n\n zmq::message_t reply{okString.cbegin(), okString.cend()};\n socket.send(reply, zmq::send_flags::none);\n } catch (const zmq::error_t& e) {\n if (e.num() != ETERM) {\n std::cerr << e.what() << std::endl;\n }\n }\n }\n}\nUpdate log for TableSelectionTx\/*\n * TableSelectionTx.cpp\n *\n * Copyright (C) 2020 by VISUS (University of Stuttgart)\n * Alle Rechte vorbehalten.\n *\/\n\n#include \"stdafx.h\"\n#include \"TableSelectionTx.h\"\n\n#include \"mmcore\/param\/BoolParam.h\"\n#include \"mmcore\/utility\/log\/Log.h\"\n\nusing namespace megamol::stdplugin::datatools;\nusing namespace megamol::stdplugin::datatools::table;\nusing namespace megamol;\n\nTableSelectionTx::TableSelectionTx()\n : core::Module()\n , tableInSlot(\"getTableIn\", \"Float table input\")\n , flagStorageReadInSlot(\"readFlagStorageIn\", \"Flag storage read input\")\n , flagStorageWriteInSlot(\"writeFlagStorageIn\", \"Flag storage write input\")\n , flagStorageReadOutSlot(\"readFlagStorageOut\", \"Flag storage read output\")\n , flagStorageWriteOutSlot(\"writeFlagStorageOut\", \"Flag storage write output\")\n , updateSelectionParam(\"updateSelectionParam\", \"Enable selection update\")\n , senderThreadQuit_(false)\n , senderThreadNotified_(false)\n , receiverThreadQuit_(false)\n , receivedSelectionUpdate_(false)\n{\n this->tableInSlot.SetCompatibleCall();\n this->MakeSlotAvailable(&this->tableInSlot);\n\n this->flagStorageReadInSlot.SetCompatibleCall();\n this->MakeSlotAvailable(&this->flagStorageReadInSlot);\n\n this->flagStorageWriteInSlot.SetCompatibleCall();\n this->MakeSlotAvailable(&this->flagStorageWriteInSlot);\n\n this->flagStorageReadOutSlot.SetCallback(core::FlagCallRead_GL::ClassName(), core::FlagCallRead_GL::FunctionName(core::FlagCallRead_GL::CallGetData), &TableSelectionTx::readDataCallback);\n this->flagStorageReadOutSlot.SetCallback(core::FlagCallRead_GL::ClassName(), core::FlagCallRead_GL::FunctionName(core::FlagCallRead_GL::CallGetMetaData), &TableSelectionTx::readMetaDataCallback);\n this->MakeSlotAvailable(&this->flagStorageReadOutSlot);\n\n this->flagStorageWriteOutSlot.SetCallback(core::FlagCallWrite_GL::ClassName(), core::FlagCallWrite_GL::FunctionName(core::FlagCallWrite_GL::CallGetData), &TableSelectionTx::writeDataCallback);\n this->flagStorageWriteOutSlot.SetCallback(core::FlagCallWrite_GL::ClassName(), core::FlagCallWrite_GL::FunctionName(core::FlagCallWrite_GL::CallGetMetaData), &TableSelectionTx::writeMetaDataCallback);\n this->MakeSlotAvailable(&this->flagStorageWriteOutSlot);\n\n this->updateSelectionParam << new core::param::BoolParam(true);\n this->MakeSlotAvailable(&this->updateSelectionParam);\n}\n\nTableSelectionTx::~TableSelectionTx() {\n this->Release();\n}\n\nbool TableSelectionTx::create() {\n context_ = std::make_unique(1);\n\n senderThreadQuit_ = false;\n if (!senderThread_.joinable()) {\n senderThread_ = std::thread(&TableSelectionTx::selectionSender, this);\n }\n\n receiverThreadQuit_ = false;\n if (!receiverThread_.joinable()) {\n receiverThread_ = std::thread(&TableSelectionTx::selectionReceiver, this);\n }\n\n return true;\n}\n\nvoid TableSelectionTx::release() {\n senderThreadQuit_ = true;\n receiverThreadQuit_ = true;\n senderThreadNotified_ = true;\n condVar_.notify_one();\n context_->close();\n context_.reset();\n if (senderThread_.joinable()) {\n senderThread_.join();\n }\n if (receiverThread_.joinable()) {\n receiverThread_.join();\n }\n}\n\nbool TableSelectionTx::readDataCallback(core::Call& call) {\n auto *flagsReadOutCall = dynamic_cast(&call);\n if (flagsReadOutCall == nullptr) {\n return false;\n }\n\n if (!validateCalls()) {\n return false;\n }\n\n if (!validateSelectionUpdate()) {\n return false;\n }\n\n auto *flagsReadInCall = this->flagStorageReadInSlot.CallAs();\n\n (*flagsReadInCall)(core::FlagCallRead_GL::CallGetData);\n flagsReadOutCall->setData(flagsReadInCall->getData(), flagsReadInCall->version());\n\n return true;\n}\n\nbool TableSelectionTx::readMetaDataCallback(core::Call& call) {\n \/\/ FlagCall_GL has empty meta data\n return true;\n}\n\nbool TableSelectionTx::writeDataCallback(core::Call& call) {\n auto *flagsWriteOutCall = dynamic_cast(&call);\n if (flagsWriteOutCall == nullptr) {\n return false;\n }\n\n if (!validateCalls()) {\n return false;\n }\n\n auto *flagsWriteInCall = this->flagStorageWriteInSlot.CallAs();\n\n flagsWriteInCall->setData(flagsWriteOutCall->getData(), flagsWriteOutCall->version());\n (*flagsWriteInCall)(core::FlagCallWrite_GL::CallGetData);\n\n \/\/ Send data\n\n auto *tableInCall = this->tableInSlot.CallAs();\n\n tableInCall->SetFrameID(0);\n (*tableInCall)(1);\n (*tableInCall)(0);\n\n auto flags = flagsWriteOutCall->getData()->flags;\n size_t numberOfFlags = flags->getByteSize() \/ sizeof(uint32_t);\n size_t numberOfRows = tableInCall->GetRowsCount();\n\n \/\/ validateFlagCount() only increases the buffer, therefore numberOfFlags > numberOfRows is also valid.\n if (numberOfFlags < numberOfRows) {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"TableSelectionTx: invalid table\/flag storage size!\");\n return false;\n }\n\n std::vector flagsData(numberOfFlags);\n flags->bind();\n glGetBufferSubData(flags->getTarget(), 0, flags->getByteSize(), flagsData.data());\n\n core::FlagStorage::FlagItemType testMask = core::FlagStorage::ENABLED | core::FlagStorage::FILTERED;\n core::FlagStorage::FlagItemType passMask = core::FlagStorage::ENABLED;\n\n std::unique_lock lock(selectedMutex_);\n selected_.clear();\n for (size_t i = 0; i < numberOfRows; ++i) {\n if ((flagsData[i] & testMask) == passMask) {\n if (flagsData[i] & core::FlagStorage::SELECTED) {\n selected_.push_back(static_cast(i));\n } else {\n \/\/ not selected\n }\n }\n }\n senderThreadNotified_ = true;\n condVar_.notify_one();\n lock.unlock();\n\n return true;\n}\n\nbool TableSelectionTx::writeMetaDataCallback(core::Call& call) {\n \/\/ FlagCall_GL has empty meta data\n return true;\n}\n\nbool TableSelectionTx::validateCalls() {\n auto *tableInCall = this->tableInSlot.CallAs();\n auto *flagsReadInCall = this->flagStorageReadInSlot.CallAs();\n auto *flagsWriteInCall = this->flagStorageWriteInSlot.CallAs();\n\n if (tableInCall == nullptr) {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"TableSelectionTx requires a table!\");\n return false;\n }\n\n if (flagsReadInCall == nullptr) {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"TableSelectionTx requires a read flag storage!\");\n return false;\n }\n\n if (flagsWriteInCall == nullptr) {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"TableSelectionTx requires a write flag storage!\");\n return false;\n }\n\n return true;\n}\n\nbool TableSelectionTx::validateSelectionUpdate() {\n std::lock_guard lock(receivedSelectionMutex_);\n if (!receivedSelectionUpdate_) {\n return true;\n }\n\n receivedSelectionUpdate_ = false;\n\n if (!this->updateSelectionParam.Param()->Value()) {\n return true;\n }\n\n auto *flagsReadInCall = this->flagStorageReadInSlot.CallAs();\n (*flagsReadInCall)(core::FlagCallRead_GL::CallGetData);\n auto flagCollection = flagsReadInCall->getData();\n auto version = flagsReadInCall->version();\n\n auto *tableInCall = this->tableInSlot.CallAs();\n tableInCall->SetFrameID(0);\n (*tableInCall)(1);\n (*tableInCall)(0);\n\n size_t numberOfRows = tableInCall->GetRowsCount();\n\n std::vector flags_data(numberOfRows, core::FlagStorage::ENABLED);\n\n \/\/ Select received rows\n for (auto id : receivedSelection_) {\n if (id >= 0 && id < numberOfRows) {\n flags_data[id] = core::FlagStorage::ENABLED | core::FlagStorage::SELECTED;\n }\n }\n\n flagCollection->flags = std::make_shared(GL_SHADER_STORAGE_BUFFER, flags_data, GL_DYNAMIC_DRAW);\n\n auto *flagsWriteInCall = this->flagStorageWriteInSlot.CallAs();\n flagsWriteInCall->setData(flagCollection, version + 1);\n (*flagsWriteInCall)(core::FlagCallWrite_GL::CallGetData);\n\n return true;\n}\n\nvoid TableSelectionTx::selectionSender() {\n zmq::socket_t socket{*context_, ZMQ_REQ};\n socket.setsockopt(ZMQ_LINGER, 0);\n socket.connect(\"tcp:\/\/localhost:10001\");\n\n std::unique_lock lock(selectedMutex_);\n while (!senderThreadQuit_) {\n while (!senderThreadNotified_ && !senderThreadQuit_) {\n condVar_.wait(lock);\n }\n while (senderThreadNotified_ && !senderThreadQuit_) {\n senderThreadNotified_ = false;\n try {\n zmq::message_t request{selected_.cbegin(), selected_.cend()};\n lock.unlock();\n socket.send(request, zmq::send_flags::none);\n\n zmq::message_t reply{};\n socket.recv(reply, zmq::recv_flags::none);\n } catch (const zmq::error_t& e) {\n if (e.num() != ETERM) {\n std::cerr << e.what() << std::endl;\n }\n }\n lock.lock();\n }\n }\n}\n\nvoid TableSelectionTx::selectionReceiver() {\n zmq::socket_t socket{*context_, ZMQ_REP};\n socket.bind(\"tcp:\/\/*:10002\");\n\n const std::string okString{\"Ok!\"};\n\n while (!receiverThreadQuit_) {\n try {\n zmq::message_t request;\n socket.recv(request, zmq::recv_flags::none);\n size_t size = request.size() \/ sizeof(uint64_t);\n\n if (size > 0) {\n std::lock_guard lock(receivedSelectionMutex_);\n uint64_t* data_ptr = static_cast(request.data());\n receivedSelection_ = std::vector(data_ptr, data_ptr + size);\n receivedSelectionUpdate_ = true;\n }\n\n zmq::message_t reply{okString.cbegin(), okString.cend()};\n socket.send(reply, zmq::send_flags::none);\n } catch (const zmq::error_t& e) {\n if (e.num() != ETERM) {\n std::cerr << e.what() << std::endl;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved.\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\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_hoofs\/internal\/posix_wrapper\/shared_memory_object.hpp\"\n#include \"iceoryx_hoofs\/cxx\/attributes.hpp\"\n#include \"iceoryx_hoofs\/cxx\/helplets.hpp\"\n#include \"iceoryx_hoofs\/log\/logging.hpp\"\n#include \"iceoryx_hoofs\/posix_wrapper\/signal_handler.hpp\"\n#include \"iceoryx_hoofs\/posix_wrapper\/types.hpp\"\n#include \"iceoryx_platform\/fcntl.hpp\"\n#include \"iceoryx_platform\/unistd.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iox\n{\nnamespace posix\n{\nconstexpr const void* const SharedMemoryObject::NO_ADDRESS_HINT;\nconstexpr uint64_t SIGBUS_ERROR_MESSAGE_LENGTH = 1024U + platform::IOX_MAX_SHM_NAME_LENGTH;\n\n\/\/\/ NOLINTJUSTIFICATION global variables are only accessible from within this compilation unit\n\/\/\/ NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)\n\/\/\/\n\/\/\/ NOLINTJUSTIFICATION c array required to print a signal safe error message in memsetSigbusHandler\n\/\/\/ NOLINTNEXTLINE(hicpp-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)\nstatic char sigbusErrorMessage[SIGBUS_ERROR_MESSAGE_LENGTH];\nstatic std::mutex sigbusHandlerMutex;\n\/\/\/ NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)\n\nstatic void memsetSigbusHandler(int) noexcept\n{\n auto result =\n write(STDERR_FILENO, &sigbusErrorMessage[0], strnlen(&sigbusErrorMessage[0], SIGBUS_ERROR_MESSAGE_LENGTH));\n IOX_DISCARD_RESULT(result);\n _exit(EXIT_FAILURE);\n}\n\n\/\/ NOLINTJUSTIFICATION the function size is related to the error handling and the cognitive complexity\n\/\/ results from the expanded log macro\n\/\/ NOLINTNEXTLINE(readability-function-size,readability-function-cognitive-complexity)\ncxx::expected SharedMemoryObjectBuilder::create() noexcept\n{\n auto printErrorDetails = [this] {\n LogError() << \"Unable to create a shared memory object with the following properties [ name = \" << m_name\n << \", sizeInBytes = \" << m_memorySizeInBytes << \", access mode = \" << asStringLiteral(m_accessMode)\n << \", open mode = \" << asStringLiteral(m_openMode) << \", baseAddressHint = \"\n << ((m_baseAddressHint) ? iox::log::hex(m_baseAddressHint.value())\n : iox::log::hex(static_cast(0U)))\n << ((m_baseAddressHint) ? \"\" : \" (no hint set)\")\n << \", permissions = \" << iox::log::hex(static_cast(m_permissions)) << \" ]\";\n };\n\n auto sharedMemory = SharedMemoryBuilder()\n .name(m_name)\n .accessMode(m_accessMode)\n .openMode(m_openMode)\n .filePermissions(m_permissions)\n .size(m_memorySizeInBytes)\n .create();\n\n if (!sharedMemory)\n {\n printErrorDetails();\n LogError() << \"Unable to create SharedMemoryObject since we could not acquire a SharedMemory resource\";\n return cxx::error(SharedMemoryObjectError::SHARED_MEMORY_CREATION_FAILED);\n }\n\n auto memoryMap = MemoryMapBuilder()\n .baseAddressHint((m_baseAddressHint) ? *m_baseAddressHint : nullptr)\n .length(m_memorySizeInBytes)\n .fileDescriptor(sharedMemory->getHandle())\n .accessMode(m_accessMode)\n .flags(MemoryMapFlags::SHARE_CHANGES)\n .offset(0)\n .create();\n\n if (!memoryMap)\n {\n printErrorDetails();\n LogError() << \"Failed to map created shared memory into process!\";\n return cxx::error(SharedMemoryObjectError::MAPPING_SHARED_MEMORY_FAILED);\n }\n\n Allocator allocator(memoryMap->getBaseAddress(), m_memorySizeInBytes);\n\n if (sharedMemory->hasOwnership())\n {\n LogDebug() << \"Trying to reserve \" << m_memorySizeInBytes << \" bytes in the shared memory [\" << m_name << \"]\";\n if (platform::IOX_SHM_WRITE_ZEROS_ON_CREATION)\n {\n \/\/ this lock is required for the case that multiple threads are creating multiple\n \/\/ shared memory objects concurrently\n std::lock_guard lock(sigbusHandlerMutex);\n auto memsetSigbusGuard = registerSignalHandler(Signal::BUS, memsetSigbusHandler);\n if (memsetSigbusGuard.has_error())\n {\n printErrorDetails();\n LogError() << \"Failed to temporarily override SIGBUS to safely zero the shared memory\";\n return cxx::error(SharedMemoryObjectError::INTERNAL_LOGIC_FAILURE);\n }\n\n \/\/ NOLINTJUSTIFICATION snprintf required to populate char array so that it can be used signal safe in\n \/\/ a possible signal call\n \/\/ NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n IOX_DISCARD_RESULT(snprintf(\n &sigbusErrorMessage[0],\n SIGBUS_ERROR_MESSAGE_LENGTH,\n \"While setting the acquired shared memory to zero a fatal SIGBUS signal appeared caused by memset. The \"\n \"shared memory object with the following properties [ name = %s, sizeInBytes = %llu, access mode = %s, \"\n \"open mode = %s, baseAddressHint = %p, permissions = %lu ] maybe requires more memory than it is \"\n \"currently available in the system.\\n\",\n m_name.c_str(),\n static_cast(m_memorySizeInBytes),\n asStringLiteral(m_accessMode),\n asStringLiteral(m_openMode),\n (m_baseAddressHint) ? *m_baseAddressHint : nullptr,\n std::bitset(static_cast(m_permissions)).to_ulong()));\n\n memset(memoryMap->getBaseAddress(), 0, m_memorySizeInBytes);\n }\n LogDebug() << \"Acquired \" << m_memorySizeInBytes << \" bytes successfully in the shared memory [\" << m_name\n << \"]\";\n }\n\n return cxx::success(\n SharedMemoryObject(std::move(*sharedMemory), std::move(*memoryMap), std::move(allocator), m_memorySizeInBytes));\n}\n\nSharedMemoryObject::SharedMemoryObject(SharedMemory&& sharedMemory,\n MemoryMap&& memoryMap,\n Allocator&& allocator,\n const uint64_t memorySizeInBytes) noexcept\n : m_memorySizeInBytes(memorySizeInBytes)\n , m_sharedMemory(std::move(sharedMemory))\n , m_memoryMap(std::move(memoryMap))\n , m_allocator(std::move(allocator))\n{\n}\n\nvoid* SharedMemoryObject::allocate(const uint64_t size, const uint64_t alignment) noexcept\n{\n return m_allocator.allocate(size, alignment);\n}\n\nvoid SharedMemoryObject::finalizeAllocation() noexcept\n{\n m_allocator.finalizeAllocation();\n}\n\nAllocator& SharedMemoryObject::getAllocator() noexcept\n{\n return m_allocator;\n}\n\nconst void* SharedMemoryObject::getBaseAddress() const noexcept\n{\n return m_memoryMap.getBaseAddress();\n}\n\nvoid* SharedMemoryObject::getBaseAddress() noexcept\n{\n return m_memoryMap.getBaseAddress();\n}\n\nuint64_t SharedMemoryObject::getSizeInBytes() const noexcept\n{\n return m_memorySizeInBytes;\n}\n\nint32_t SharedMemoryObject::getFileHandle() const noexcept\n{\n return m_sharedMemory.getHandle();\n}\n\nbool SharedMemoryObject::hasOwnership() const noexcept\n{\n return m_sharedMemory.hasOwnership();\n}\n\n\n} \/\/ namespace posix\n} \/\/ namespace iox\niox-#1345 Use octal format to print permission\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved.\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\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_hoofs\/internal\/posix_wrapper\/shared_memory_object.hpp\"\n#include \"iceoryx_hoofs\/cxx\/attributes.hpp\"\n#include \"iceoryx_hoofs\/cxx\/helplets.hpp\"\n#include \"iceoryx_hoofs\/log\/logging.hpp\"\n#include \"iceoryx_hoofs\/posix_wrapper\/signal_handler.hpp\"\n#include \"iceoryx_hoofs\/posix_wrapper\/types.hpp\"\n#include \"iceoryx_platform\/fcntl.hpp\"\n#include \"iceoryx_platform\/unistd.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iox\n{\nnamespace posix\n{\nconstexpr const void* const SharedMemoryObject::NO_ADDRESS_HINT;\nconstexpr uint64_t SIGBUS_ERROR_MESSAGE_LENGTH = 1024U + platform::IOX_MAX_SHM_NAME_LENGTH;\n\n\/\/\/ NOLINTJUSTIFICATION global variables are only accessible from within this compilation unit\n\/\/\/ NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)\n\/\/\/\n\/\/\/ NOLINTJUSTIFICATION c array required to print a signal safe error message in memsetSigbusHandler\n\/\/\/ NOLINTNEXTLINE(hicpp-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)\nstatic char sigbusErrorMessage[SIGBUS_ERROR_MESSAGE_LENGTH];\nstatic std::mutex sigbusHandlerMutex;\n\/\/\/ NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)\n\nstatic void memsetSigbusHandler(int) noexcept\n{\n auto result =\n write(STDERR_FILENO, &sigbusErrorMessage[0], strnlen(&sigbusErrorMessage[0], SIGBUS_ERROR_MESSAGE_LENGTH));\n IOX_DISCARD_RESULT(result);\n _exit(EXIT_FAILURE);\n}\n\n\/\/ NOLINTJUSTIFICATION the function size is related to the error handling and the cognitive complexity\n\/\/ results from the expanded log macro\n\/\/ NOLINTNEXTLINE(readability-function-size,readability-function-cognitive-complexity)\ncxx::expected SharedMemoryObjectBuilder::create() noexcept\n{\n auto printErrorDetails = [this] {\n LogError() << \"Unable to create a shared memory object with the following properties [ name = \" << m_name\n << \", sizeInBytes = \" << m_memorySizeInBytes << \", access mode = \" << asStringLiteral(m_accessMode)\n << \", open mode = \" << asStringLiteral(m_openMode) << \", baseAddressHint = \"\n << ((m_baseAddressHint) ? iox::log::hex(m_baseAddressHint.value())\n : iox::log::hex(static_cast(0U)))\n << ((m_baseAddressHint) ? \"\" : \" (no hint set)\")\n << \", permissions = \" << iox::log::oct(static_cast(m_permissions)) << \" ]\";\n };\n\n auto sharedMemory = SharedMemoryBuilder()\n .name(m_name)\n .accessMode(m_accessMode)\n .openMode(m_openMode)\n .filePermissions(m_permissions)\n .size(m_memorySizeInBytes)\n .create();\n\n if (!sharedMemory)\n {\n printErrorDetails();\n LogError() << \"Unable to create SharedMemoryObject since we could not acquire a SharedMemory resource\";\n return cxx::error(SharedMemoryObjectError::SHARED_MEMORY_CREATION_FAILED);\n }\n\n auto memoryMap = MemoryMapBuilder()\n .baseAddressHint((m_baseAddressHint) ? *m_baseAddressHint : nullptr)\n .length(m_memorySizeInBytes)\n .fileDescriptor(sharedMemory->getHandle())\n .accessMode(m_accessMode)\n .flags(MemoryMapFlags::SHARE_CHANGES)\n .offset(0)\n .create();\n\n if (!memoryMap)\n {\n printErrorDetails();\n LogError() << \"Failed to map created shared memory into process!\";\n return cxx::error(SharedMemoryObjectError::MAPPING_SHARED_MEMORY_FAILED);\n }\n\n Allocator allocator(memoryMap->getBaseAddress(), m_memorySizeInBytes);\n\n if (sharedMemory->hasOwnership())\n {\n LogDebug() << \"Trying to reserve \" << m_memorySizeInBytes << \" bytes in the shared memory [\" << m_name << \"]\";\n if (platform::IOX_SHM_WRITE_ZEROS_ON_CREATION)\n {\n \/\/ this lock is required for the case that multiple threads are creating multiple\n \/\/ shared memory objects concurrently\n std::lock_guard lock(sigbusHandlerMutex);\n auto memsetSigbusGuard = registerSignalHandler(Signal::BUS, memsetSigbusHandler);\n if (memsetSigbusGuard.has_error())\n {\n printErrorDetails();\n LogError() << \"Failed to temporarily override SIGBUS to safely zero the shared memory\";\n return cxx::error(SharedMemoryObjectError::INTERNAL_LOGIC_FAILURE);\n }\n\n \/\/ NOLINTJUSTIFICATION snprintf required to populate char array so that it can be used signal safe in\n \/\/ a possible signal call\n \/\/ NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n IOX_DISCARD_RESULT(snprintf(\n &sigbusErrorMessage[0],\n SIGBUS_ERROR_MESSAGE_LENGTH,\n \"While setting the acquired shared memory to zero a fatal SIGBUS signal appeared caused by memset. The \"\n \"shared memory object with the following properties [ name = %s, sizeInBytes = %llu, access mode = %s, \"\n \"open mode = %s, baseAddressHint = %p, permissions = %lu ] maybe requires more memory than it is \"\n \"currently available in the system.\\n\",\n m_name.c_str(),\n static_cast(m_memorySizeInBytes),\n asStringLiteral(m_accessMode),\n asStringLiteral(m_openMode),\n (m_baseAddressHint) ? *m_baseAddressHint : nullptr,\n std::bitset(static_cast(m_permissions)).to_ulong()));\n\n memset(memoryMap->getBaseAddress(), 0, m_memorySizeInBytes);\n }\n LogDebug() << \"Acquired \" << m_memorySizeInBytes << \" bytes successfully in the shared memory [\" << m_name\n << \"]\";\n }\n\n return cxx::success(\n SharedMemoryObject(std::move(*sharedMemory), std::move(*memoryMap), std::move(allocator), m_memorySizeInBytes));\n}\n\nSharedMemoryObject::SharedMemoryObject(SharedMemory&& sharedMemory,\n MemoryMap&& memoryMap,\n Allocator&& allocator,\n const uint64_t memorySizeInBytes) noexcept\n : m_memorySizeInBytes(memorySizeInBytes)\n , m_sharedMemory(std::move(sharedMemory))\n , m_memoryMap(std::move(memoryMap))\n , m_allocator(std::move(allocator))\n{\n}\n\nvoid* SharedMemoryObject::allocate(const uint64_t size, const uint64_t alignment) noexcept\n{\n return m_allocator.allocate(size, alignment);\n}\n\nvoid SharedMemoryObject::finalizeAllocation() noexcept\n{\n m_allocator.finalizeAllocation();\n}\n\nAllocator& SharedMemoryObject::getAllocator() noexcept\n{\n return m_allocator;\n}\n\nconst void* SharedMemoryObject::getBaseAddress() const noexcept\n{\n return m_memoryMap.getBaseAddress();\n}\n\nvoid* SharedMemoryObject::getBaseAddress() noexcept\n{\n return m_memoryMap.getBaseAddress();\n}\n\nuint64_t SharedMemoryObject::getSizeInBytes() const noexcept\n{\n return m_memorySizeInBytes;\n}\n\nint32_t SharedMemoryObject::getFileHandle() const noexcept\n{\n return m_sharedMemory.getHandle();\n}\n\nbool SharedMemoryObject::hasOwnership() const noexcept\n{\n return m_sharedMemory.hasOwnership();\n}\n\n\n} \/\/ namespace posix\n} \/\/ namespace iox\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev \n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Sema.h\"\n#include \"clang\/Serialization\/ASTReader.h\"\n#include \"clang\/Serialization\/ASTDeserializationListener.h\"\n\nusing namespace clang;\n\nnamespace cling {\n\n \/\/\/\\brief Translates 'interesting' for the interpreter\n \/\/\/ ASTDeserializationListener events into interpreter callback.\n \/\/\/\n class InterpreterPPCallbacks : public PPCallbacks {\n private:\n cling::InterpreterCallbacks* m_Callbacks;\n public:\n InterpreterPPCallbacks(InterpreterCallbacks* C) : m_Callbacks(C) { }\n ~InterpreterPPCallbacks() { }\n\n virtual void InclusionDirective(clang::SourceLocation HashLoc,\n const clang::Token &IncludeTok,\n llvm::StringRef FileName,\n bool IsAngled,\n clang::CharSourceRange FilenameRange,\n const clang::FileEntry *File,\n llvm::StringRef SearchPath,\n llvm::StringRef RelativePath,\n const clang::Module *Imported) {\n m_Callbacks->InclusionDirective(HashLoc, IncludeTok, FileName,\n IsAngled, FilenameRange, File,\n SearchPath, RelativePath, Imported);\n }\n\n virtual bool FileNotFound(llvm::StringRef FileName,\n llvm::SmallVectorImpl& RecoveryPath) {\n if (m_Callbacks)\n return m_Callbacks->FileNotFound(FileName, RecoveryPath);\n\n \/\/ Returning true would mean that the preprocessor should try to recover.\n return false;\n }\n };\n\n \/\/\/\\brief Translates 'interesting' for the interpreter\n \/\/\/ ASTDeserializationListener events into interpreter callback.\n \/\/\/\n class InterpreterDeserializationListener : public ASTDeserializationListener {\n private:\n cling::InterpreterCallbacks* m_Callbacks;\n public:\n InterpreterDeserializationListener(InterpreterCallbacks* C)\n : m_Callbacks(C) {}\n\n virtual void DeclRead(serialization::DeclID, const Decl *D) {\n if (m_Callbacks)\n m_Callbacks->DeclDeserialized(D);\n }\n\n virtual void TypeRead(serialization::TypeIdx, QualType T) {\n if (m_Callbacks)\n m_Callbacks->TypeDeserialized(T.getTypePtr());\n }\n };\n\n \/\/\/\\brief Translates 'interesting' for the interpreter ExternalSemaSource\n \/\/\/ events into interpreter callbacks.\n \/\/\/\n class InterpreterExternalSemaSource : public clang::ExternalSemaSource {\n protected:\n \/\/\/\\brief The interpreter callback which are subscribed for the events.\n \/\/\/\n \/\/\/ Usually the callbacks is the owner of the class and the interpreter owns\n \/\/\/ the callbacks so they can't be out of sync. Eg we notifying the wrong\n \/\/\/ callback class.\n \/\/\/\n InterpreterCallbacks* m_Callbacks; \/\/ we don't own it.\n\n Sema* m_Sema; \/\/ we don't own \/\/ FIXME: once we remove ForgetSema delete.\n\n public:\n InterpreterExternalSemaSource(InterpreterCallbacks* C)\n : m_Callbacks(C), m_Sema(0) {}\n\n ~InterpreterExternalSemaSource() {\n \/\/ FIXME: Another gross hack due to the missing multiplexing AST external\n \/\/ source see Interpreter::setCallbacks.\n if (m_Sema) {\n ASTContext& C = m_Sema->getASTContext();\n \/\/ tell the owning ptr to not delete it, the callbacks will delete it.\n if (C.ExternalSource.get() == this)\n C.ExternalSource.resetWithoutRelease();\n }\n }\n\n virtual void InitializeSema(Sema& S) {\n m_Sema = &S;\n }\n\n virtual void ForgetSema() {\n m_Sema = 0;\n }\n\n InterpreterCallbacks* getCallbacks() const { return m_Callbacks; }\n\n \/\/\/ \\brief Provides last resort lookup for failed unqualified lookups.\n \/\/\/\n \/\/\/ This gets translated into InterpreterCallback's call.\n \/\/\/\n \/\/\/\\param[out] R The recovered symbol.\n \/\/\/\\param[in] S The scope in which the lookup failed.\n \/\/\/\n \/\/\/\\returns true if a suitable declaration is found.\n \/\/\/\n virtual bool LookupUnqualified(clang::LookupResult& R, clang::Scope* S) {\n if (m_Callbacks) {\n return m_Callbacks->LookupObject(R, S);\n }\n\n return false;\n }\n\n virtual bool FindExternalVisibleDeclsByName(const clang::DeclContext* DC,\n clang::DeclarationName Name) {\n if (m_Callbacks)\n return m_Callbacks->LookupObject(DC, Name);\n\n return false;\n }\n\n \/\/ Silence warning virtual function was hidden.\n using ExternalASTSource::CompleteType;\n virtual void CompleteType(TagDecl* Tag) {\n if (m_Callbacks)\n m_Callbacks->LookupObject(Tag);\n }\n\n void UpdateWithNewDeclsFwd(const DeclContext *DC, DeclarationName Name,\n llvm::ArrayRef Decls) {\n SetExternalVisibleDeclsForName(DC, Name, Decls);\n }\n };\n\n InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,\n bool enableExternalSemaSourceCallbacks\/* = false*\/,\n bool enableDeserializationListenerCallbacks\/* = false*\/,\n bool enablePPCallbacks\/* = false*\/)\n : m_Interpreter(interp), m_IsRuntime(false) {\n Sema& SemaRef = interp->getSema();\n if (enableExternalSemaSourceCallbacks && SemaRef.getExternalSource()) {\n m_ExternalSemaSource.reset(new InterpreterExternalSemaSource(this));\n m_ExternalSemaSource->InitializeSema(SemaRef);\n m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());\n\n \/\/ FIXME: We should add a multiplexer in the ASTContext, too.\n llvm::IntrusiveRefCntPtr\n astContextExternalSource(SemaRef.getExternalSource());\n clang::ASTContext& Ctx = SemaRef.getASTContext();\n \/\/ FIXME: This is a gross hack. We must make multiplexer in the astcontext\n \/\/ or a derived class that extends what we need.\n Ctx.ExternalSource.resetWithoutRelease(); \/\/FIXME: make sure we delete it.\n Ctx.setExternalSource(astContextExternalSource);\n }\n\n ASTReader* Reader = m_Interpreter->getCI()->getModuleManager().get();\n if (enableDeserializationListenerCallbacks && Reader) {\n \/\/ FIXME: need to create a multiplexer if a DeserializationListener is\n \/\/ alreday present.\n m_DeserializationListener.\n reset(new InterpreterDeserializationListener(this));\n Reader->setDeserializationListener(m_DeserializationListener.get());\n }\n\n if (enablePPCallbacks) {\n m_PPCallbacks = new InterpreterPPCallbacks(this);\n Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();\n PP.addPPCallbacks(m_PPCallbacks);\n }\n }\n\n \/\/ pin the vtable here\n InterpreterCallbacks::~InterpreterCallbacks() {\n \/\/ FIXME: we have to remove the external source at destruction time. Needs\n \/\/ further tweaks of the patch in clang. This will be done later once the\n \/\/ patch is in clang's mainline.\n }\n\n void InterpreterCallbacks::SetIsRuntime(bool val) {\n m_IsRuntime = val;\n }\n\n ExternalSemaSource*\n InterpreterCallbacks::getInterpreterExternalSemaSource() const {\n return m_ExternalSemaSource.get();\n }\n\n ASTDeserializationListener*\n InterpreterCallbacks::getInterpreterDeserializationListener() const {\n return m_DeserializationListener.get();\n }\n\n bool InterpreterCallbacks::FileNotFound(llvm::StringRef FileName,\n llvm::SmallVectorImpl& RecoveryPath) {\n \/\/ Default implementation is no op.\n return false;\n }\n\n bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) {\n \/\/ Default implementation is no op.\n return false;\n }\n\n bool InterpreterCallbacks::LookupObject(const DeclContext*, DeclarationName) {\n \/\/ Default implementation is no op.\n return false;\n }\n\n bool InterpreterCallbacks::LookupObject(TagDecl*) {\n \/\/ Default implementation is no op.\n return false;\n }\n\n void InterpreterCallbacks::UpdateWithNewDecls(const DeclContext *DC,\n DeclarationName Name,\n llvm::ArrayRef Decls) {\n if (m_ExternalSemaSource)\n m_ExternalSemaSource->UpdateWithNewDeclsFwd(DC, Name, Decls);\n }\n} \/\/ end namespace cling\n\n\/\/ TODO: Make the build system in the testsuite aware how to build that class\n\/\/ and extract it out there again.\n#include \"DynamicLookup.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\nnamespace cling {\nnamespace test {\n TestProxy* Tester = 0;\n\n extern \"C\" int printf(const char* fmt, ...);\n TestProxy::TestProxy(){}\n int TestProxy::Draw(){ return 12; }\n const char* TestProxy::getVersion(){ return \"Interpreter.cpp\"; }\n\n int TestProxy::Add10(int num) { return num + 10;}\n\n int TestProxy::Add(int a, int b) {\n return a + b;\n }\n\n void TestProxy::PrintString(std::string s) { printf(\"%s\\n\", s.c_str()); }\n\n bool TestProxy::PrintArray(int a[], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n printf(\"%i\", a[i]);\n\n printf(\"%s\", \"\\n\");\n\n return true;\n }\n\n void TestProxy::PrintArray(float a[][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 5; ++j)\n printf(\"%i\", (int)a[i][j]);\n\n printf(\"%s\", \"\\n\");\n }\n\n void TestProxy::PrintArray(int a[][4][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 4; ++j)\n for (unsigned k = 0; k < 5; ++k)\n printf(\"%i\", a[i][j][k]);\n\n printf(\"%s\", \"\\n\");\n }\n\n SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp)\n : InterpreterCallbacks(interp), m_TesterDecl(0) {\n m_Interpreter->process(\"cling::test::Tester = new cling::test::TestProxy();\");\n }\n\n SymbolResolverCallback::~SymbolResolverCallback() { }\n\n bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) {\n if (m_IsRuntime) {\n \/\/ Only for demo resolve all unknown objects to cling::test::Tester\n if (!m_TesterDecl) {\n clang::Sema& SemaR = m_Interpreter->getSema();\n clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaR, \"cling\");\n NSD = utils::Lookup::Namespace(&SemaR, \"test\", NSD);\n m_TesterDecl = utils::Lookup::Named(&SemaR, \"Tester\", NSD);\n }\n assert (m_TesterDecl && \"Tester not found!\");\n R.addDecl(m_TesterDecl);\n return true; \/\/ Tell clang to continue.\n }\n\n if (ShouldResolveAtRuntime(R, S)) {\n ASTContext& C = R.getSema().getASTContext();\n DeclContext* DC = 0;\n \/\/ For DeclContext-less scopes like if (dyn_expr) {}\n while (!DC) {\n DC = static_cast(S->getEntity());\n S = S->getParent();\n }\n DeclarationName Name = R.getLookupName();\n IdentifierInfo* II = Name.getAsIdentifierInfo();\n SourceLocation Loc = R.getNameLoc();\n VarDecl* Res = VarDecl::Create(C, DC, Loc, Loc, II, C.DependentTy,\n \/*TypeSourceInfo*\/0, SC_None);\n\n \/\/ Annotate the decl to give a hint in cling. FIXME: Current implementation\n \/\/ is a gross hack, because TClingCallbacks shouldn't know about\n \/\/ EvaluateTSynthesizer at all!\n SourceRange invalidRange;\n Res->addAttr(new (C) AnnotateAttr(invalidRange, C, \"__ResolveAtRuntime\", 0));\n R.addDecl(Res);\n DC->addDecl(Res);\n \/\/ Say that we can handle the situation. Clang should try to recover\n return true;\n }\n\n return false;\n }\n\n bool SymbolResolverCallback::ShouldResolveAtRuntime(LookupResult& R,\n Scope* S) {\n\n if (R.getLookupKind() != Sema::LookupOrdinaryName)\n return false;\n\n if (R.isForRedeclaration())\n return false;\n\n if (!R.empty())\n return false;\n\n \/\/ FIXME: Figure out better way to handle:\n \/\/ C++ [basic.lookup.classref]p1:\n \/\/ In a class member access expression (5.2.5), if the . or -> token is\n \/\/ immediately followed by an identifier followed by a <, the\n \/\/ identifier must be looked up to determine whether the < is the\n \/\/ beginning of a template argument list (14.2) or a less-than operator.\n \/\/ The identifier is first looked up in the class of the object\n \/\/ expression. If the identifier is not found, it is then looked up in\n \/\/ the context of the entire postfix-expression and shall name a class\n \/\/ or function template.\n \/\/\n \/\/ We want to ignore object(.|->)member