{"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkJPEGReader.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \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 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n 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 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 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 \"vtkJPEGReader.h\"\n#include \"vtkObjectFactory.h\"\n\nextern \"C\" {\n#include \n#include \n}\n\nvtkCxxRevisionMacro(vtkJPEGReader, \"1.4\");\nvtkStandardNewMacro(vtkJPEGReader);\n\nvoid vtkJPEGReader::ExecuteInformation()\n{\n this->ComputeInternalFileName(this->DataExtent[4]);\n if (this->InternalFileName == NULL)\n {\n return;\n }\n\n FILE *fp = fopen(this->InternalFileName, \"rb\");\n if (!fp)\n {\n vtkErrorMacro(\"Unable to open file \" << this->InternalFileName);\n return;\n }\n\n \/\/ create jpeg decompression object and error handler\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n\n cinfo.err = jpeg_std_error(&jerr);\n jpeg_create_decompress(&cinfo);\n\n \/\/ set the source file\n jpeg_stdio_src(&cinfo, fp);\n\n \/\/ read the header\n jpeg_read_header(&cinfo, TRUE);\n\n \/\/ force the output image size to be calculated (we could have used\n \/\/ cinfo.image_height etc. but that would preclude using libjpeg's\n \/\/ ability to scale an image on input).\n jpeg_calc_output_dimensions(&cinfo);\n\n \/\/ pull out the width\/height, etc.\n this->DataExtent[0] = 0;\n this->DataExtent[1] = cinfo.output_width - 1;\n this->DataExtent[2] = 0;\n this->DataExtent[3] = cinfo.output_height - 1;\n\n this->SetDataScalarTypeToUnsignedChar();\n this->SetNumberOfScalarComponents( cinfo.output_components );\n\n this->vtkImageReader2::ExecuteInformation();\n\n \/\/ close the file\n jpeg_destroy_decompress(&cinfo);\n fclose(fp);\n}\n\n\ntemplate \nstatic void vtkJPEGReaderUpdate2(vtkJPEGReader *self, OT *outPtr,\n int *outExt, int *outInc, long)\n{\n unsigned int ui;\n int i;\n FILE *fp = fopen(self->GetInternalFileName(), \"rb\");\n if (!fp)\n {\n return;\n }\n\n \/\/ create jpeg decompression object and error handler\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n\n cinfo.err = jpeg_std_error(&jerr);\n jpeg_create_decompress(&cinfo);\n\n \/\/ set the source file\n jpeg_stdio_src(&cinfo, fp);\n\n \/\/ read the header\n jpeg_read_header(&cinfo, TRUE);\n\n \/\/ prepare to read the bulk data\n jpeg_start_decompress(&cinfo);\n\n \n int rowbytes = cinfo.output_components * cinfo.output_width;\n unsigned char *tempImage = new unsigned char [rowbytes*cinfo.output_height];\n JSAMPROW *row_pointers = new JSAMPROW [cinfo.output_height];\n for (ui = 0; ui < cinfo.output_height; ++ui)\n {\n row_pointers[ui] = tempImage + rowbytes*ui;\n }\n\n \/\/ read the bulk data\n unsigned int remainingRows = cinfo.output_height;\n while (cinfo.output_scanline < cinfo.output_height)\n {\n remainingRows = cinfo.output_height - cinfo.output_scanline;\n jpeg_read_scanlines(&cinfo, &row_pointers[cinfo.output_scanline],\n remainingRows);\n }\n\n \/\/ finish the decompression step\n jpeg_finish_decompress(&cinfo);\n\n \/\/ destroy the decompression object\n jpeg_destroy_decompress(&cinfo);\n\n \/\/ copy the data into the outPtr\n OT *outPtr2;\n outPtr2 = outPtr;\n long outSize = cinfo.output_components*(outExt[1] - outExt[0] + 1);\n for (i = outExt[2]; i <= outExt[3]; ++i)\n {\n memcpy(outPtr2,\n row_pointers[cinfo.output_height - i - 1]\n + outExt[0]*cinfo.output_components,\n outSize);\n outPtr2 += outInc[1];\n }\n delete [] tempImage;\n delete [] row_pointers;\n\n \/\/ close the file\n fclose(fp);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ This function reads in one data of data.\n\/\/ templated to handle different data types.\ntemplate \nstatic void vtkJPEGReaderUpdate(vtkJPEGReader *self, vtkImageData *data, \n OT *outPtr)\n{\n int outIncr[3];\n int outExtent[6];\n OT *outPtr2;\n\n data->GetExtent(outExtent);\n data->GetIncrements(outIncr);\n\n long pixSize = data->GetNumberOfScalarComponents()*sizeof(OT); \n \n outPtr2 = outPtr;\n int idx2;\n for (idx2 = outExtent[4]; idx2 <= outExtent[5]; ++idx2)\n {\n self->ComputeInternalFileName(idx2);\n \/\/ read in a JPEG file\n vtkJPEGReaderUpdate2(self, outPtr2, outExtent, outIncr, pixSize);\n self->UpdateProgress((idx2 - outExtent[4])\/\n (outExtent[5] - outExtent[4] + 1.0));\n outPtr2 += outIncr[2];\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This function reads a data from a file. The datas extent\/axes\n\/\/ are assumed to be the same as the file extent\/order.\nvoid vtkJPEGReader::ExecuteData(vtkDataObject *output)\n{\n vtkImageData *data = this->AllocateOutputData(output);\n\n if (this->InternalFileName == NULL)\n {\n vtkErrorMacro(<< \"Either a FileName or FilePrefix must be specified.\");\n return;\n }\n\n this->ComputeDataIncrements();\n \n \/\/ Call the correct templated function for the output\n void *outPtr;\n\n \/\/ Call the correct templated function for the input\n outPtr = data->GetScalarPointer();\n switch (data->GetScalarType())\n {\n vtkTemplateMacro3(vtkJPEGReaderUpdate, this, data, (VTK_TT *)(outPtr));\n default:\n vtkErrorMacro(<< \"UpdateFromFile: Unknown data type\");\n } \n}\n\n\n\/\/ create an error handler for jpeg that\n\/\/ can longjmp out of the jpeg library \nstruct my_error_mgr \n{\n struct jpeg_error_mgr pub; \/* \"public\" fields *\/\n jmp_buf setjmp_buffer; \/* for return to caller *\/\n};\n\ntypedef struct my_error_mgr * my_error_ptr;\n\/*\n * Here's the routine that will replace the standard error_exit method:\n *\/\n\nMETHODDEF(void)\nmy_error_exit (j_common_ptr cinfo)\n{\n \/* cinfo->err really points to a my_error_mgr struct, so coerce pointer *\/\n my_error_ptr myerr = (my_error_ptr) cinfo->err;\n\n \/* Return control to the setjmp point *\/\n longjmp(myerr->setjmp_buffer, 1);\n}\n\nMETHODDEF(void)\nmy_emit_message (j_common_ptr cinfo, int)\n{\n \/* cinfo->err really points to a my_error_mgr struct, so coerce pointer *\/\n my_error_ptr myerr = (my_error_ptr) cinfo->err;\n\n \/* Return control to the setjmp point *\/\n longjmp(myerr->setjmp_buffer, 1);\n}\n\nMETHODDEF(void)\nmy_format_message (j_common_ptr cinfo, char*)\n{\n \/* cinfo->err really points to a my_error_mgr struct, so coerce pointer *\/\n my_error_ptr myerr = (my_error_ptr) cinfo->err;\n\n \/* Return control to the setjmp point *\/\n longjmp(myerr->setjmp_buffer, 1);\n}\n\n\nint vtkJPEGReader::CanReadFile(const char* fname)\n{\n \/\/ open the file\n FILE *fp = fopen(fname, \"rb\");\n if (!fp)\n {\n return 0;\n }\n \/\/ read the first two bytes\n char magic[2];\n int n = fread(magic, sizeof(magic), 1, fp);\n if (n != sizeof(magic)) \n {\n fclose(fp);\n return 0;\n }\n \/\/ check for the magic stuff:\n \/\/ 0xFF followed by 0xD8\n if( ( (magic[0] != char(0xFF)) || (magic[1] != char(0xD8)) ))\n {\n fclose(fp);\n return 0;\n }\n \n \/\/ magic number is ok, try and read the header\n struct my_error_mgr jerr;\n struct jpeg_decompress_struct cinfo;\n cinfo.err = jpeg_std_error(&jerr.pub);\n \/\/ for any error condition exit\n jerr.pub.error_exit = my_error_exit;\n jerr.pub.emit_message = my_emit_message;\n jerr.pub.output_message = my_error_exit;\n jerr.pub.format_message = my_format_message;\n if (setjmp(jerr.setjmp_buffer))\n {\n \/* If we get here, the JPEG code has signaled an error.\n * We need to clean up the JPEG object, close the input file, and return.\n *\/\n jpeg_destroy_decompress(&cinfo);\n fclose(fp);\n return 0;\n }\n \/* Now we can initialize the JPEG decompression object. *\/\n jpeg_create_decompress(&cinfo);\n \/* Step 2: specify data source (eg, a file) *\/\n jpeg_stdio_src(&cinfo, fp);\n \/* Step 3: read file parameters with jpeg_read_header() *\/\n jpeg_read_header(&cinfo, TRUE);\n \n \/\/ if no errors have occurred yet, then it must be jpeg\n jpeg_destroy_decompress(&cinfo);\n fclose(fp);\n return 1;\n}\nbetter error checking\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkJPEGReader.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \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 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n 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 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 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 \"vtkJPEGReader.h\"\n#include \"vtkObjectFactory.h\"\n\nextern \"C\" {\n#include \n#include \n}\n\n\nvtkCxxRevisionMacro(vtkJPEGReader, \"1.5\");\nvtkStandardNewMacro(vtkJPEGReader);\n\n\n\/\/ create an error handler for jpeg that\n\/\/ can longjmp out of the jpeg library \nstruct vtk_jpeg_error_mgr \n{\n struct jpeg_error_mgr pub; \/* \"public\" fields *\/\n jmp_buf setjmp_buffer; \/* for return to caller *\/\n vtkJPEGReader* JPEGReader;\n};\n\n\/\/ this is called on jpeg error conditions\nMETHODDEF(void)\nvtk_jpeg_error_exit (j_common_ptr cinfo)\n{\n \/* cinfo->err really points to a my_error_mgr struct, so coerce pointer *\/\n vtk_jpeg_error_mgr * err = reinterpret_cast(cinfo->err);\n\n \/* Return control to the setjmp point *\/\n longjmp(err->setjmp_buffer, 1);\n}\n\nMETHODDEF(void)\nvtk_jpeg_output_message (j_common_ptr cinfo)\n{\n char buffer[JMSG_LENGTH_MAX];\n\n \/* Create the message *\/\n (*cinfo->err->format_message) (cinfo, buffer);\n vtk_jpeg_error_mgr * err = reinterpret_cast(cinfo->err);\n vtkWarningWithObjectMacro(err->JPEGReader,\n \"libjpeg error: \" << buffer);\n}\n\n\nvoid vtkJPEGReader::ExecuteInformation()\n{\n this->ComputeInternalFileName(this->DataExtent[4]);\n if (this->InternalFileName == NULL)\n {\n return;\n }\n\n FILE *fp = fopen(this->InternalFileName, \"rb\");\n if (!fp)\n {\n vtkErrorWithObjectMacro(this, \n \"Unable to open file \" \n << this->InternalFileName);\n return;\n }\n\n \/\/ create jpeg decompression object and error handler\n struct jpeg_decompress_struct cinfo;\n struct vtk_jpeg_error_mgr jerr;\n jerr.JPEGReader = this;\n\n cinfo.err = jpeg_std_error(&jerr.pub); \n \/\/ for any jpeg error call vtk_jpeg_error_exit\n jerr.pub.error_exit = vtk_jpeg_error_exit;\n \/\/ for any output message call vtk_jpeg_output_message\n jerr.pub.output_message = vtk_jpeg_output_message;\n if (setjmp(jerr.setjmp_buffer))\n {\n \/\/ clean up\n jpeg_destroy_decompress(&cinfo);\n \/\/ close the file\n fclose(fp);\n \/\/ this is not a valid jpeg file \n vtkErrorWithObjectMacro(this, \"libjpeg could not read file: \"\n << this->InternalFileName);\n return;\n }\n jpeg_create_decompress(&cinfo);\n\n \/\/ set the source file\n jpeg_stdio_src(&cinfo, fp);\n\n \/\/ read the header\n jpeg_read_header(&cinfo, TRUE);\n\n \/\/ force the output image size to be calculated (we could have used\n \/\/ cinfo.image_height etc. but that would preclude using libjpeg's\n \/\/ ability to scale an image on input).\n jpeg_calc_output_dimensions(&cinfo);\n\n \/\/ pull out the width\/height, etc.\n this->DataExtent[0] = 0;\n this->DataExtent[1] = cinfo.output_width - 1;\n this->DataExtent[2] = 0;\n this->DataExtent[3] = cinfo.output_height - 1;\n\n this->SetDataScalarTypeToUnsignedChar();\n this->SetNumberOfScalarComponents( cinfo.output_components );\n\n this->vtkImageReader2::ExecuteInformation();\n\n \/\/ close the file\n jpeg_destroy_decompress(&cinfo);\n fclose(fp);\n}\n\n\ntemplate \nstatic void vtkJPEGReaderUpdate2(vtkJPEGReader *self, OT *outPtr,\n int *outExt, int *outInc, long)\n{\n unsigned int ui;\n int i;\n FILE *fp = fopen(self->GetInternalFileName(), \"rb\");\n if (!fp)\n {\n return;\n }\n\n \/\/ create jpeg decompression object and error handler\n struct jpeg_decompress_struct cinfo;\n struct vtk_jpeg_error_mgr jerr;\n jerr.JPEGReader = self;\n\n cinfo.err = jpeg_std_error(&jerr.pub);\n \/\/ for any jpeg error call vtk_jpeg_error_exit\n jerr.pub.error_exit = vtk_jpeg_error_exit;\n \/\/ for any output message call vtk_jpeg_output_message\n jerr.pub.output_message = vtk_jpeg_output_message;\n if (setjmp(jerr.setjmp_buffer))\n {\n \/\/ clean up\n jpeg_destroy_decompress(&cinfo);\n \/\/ close the file\n fclose(fp);\n vtkErrorWithObjectMacro(self, \"libjpeg could not read file: \"\n << self->GetInternalFileName());\n \/\/ this is not a valid jpeg file\n return;\n }\n jpeg_create_decompress(&cinfo);\n\n \/\/ set the source file\n jpeg_stdio_src(&cinfo, fp);\n\n \/\/ read the header\n jpeg_read_header(&cinfo, TRUE);\n\n \/\/ prepare to read the bulk data\n jpeg_start_decompress(&cinfo);\n\n \n int rowbytes = cinfo.output_components * cinfo.output_width;\n unsigned char *tempImage = new unsigned char [rowbytes*cinfo.output_height];\n JSAMPROW *row_pointers = new JSAMPROW [cinfo.output_height];\n for (ui = 0; ui < cinfo.output_height; ++ui)\n {\n row_pointers[ui] = tempImage + rowbytes*ui;\n }\n\n \/\/ read the bulk data\n unsigned int remainingRows = cinfo.output_height;\n while (cinfo.output_scanline < cinfo.output_height)\n {\n remainingRows = cinfo.output_height - cinfo.output_scanline;\n jpeg_read_scanlines(&cinfo, &row_pointers[cinfo.output_scanline],\n remainingRows);\n }\n\n \/\/ finish the decompression step\n jpeg_finish_decompress(&cinfo);\n\n \/\/ destroy the decompression object\n jpeg_destroy_decompress(&cinfo);\n\n \/\/ copy the data into the outPtr\n OT *outPtr2;\n outPtr2 = outPtr;\n long outSize = cinfo.output_components*(outExt[1] - outExt[0] + 1);\n for (i = outExt[2]; i <= outExt[3]; ++i)\n {\n memcpy(outPtr2,\n row_pointers[cinfo.output_height - i - 1]\n + outExt[0]*cinfo.output_components,\n outSize);\n outPtr2 += outInc[1];\n }\n delete [] tempImage;\n delete [] row_pointers;\n\n \/\/ close the file\n fclose(fp);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ This function reads in one data of data.\n\/\/ templated to handle different data types.\ntemplate \nstatic void vtkJPEGReaderUpdate(vtkJPEGReader *self, vtkImageData *data, \n OT *outPtr)\n{\n int outIncr[3];\n int outExtent[6];\n OT *outPtr2;\n\n data->GetExtent(outExtent);\n data->GetIncrements(outIncr);\n\n long pixSize = data->GetNumberOfScalarComponents()*sizeof(OT); \n \n outPtr2 = outPtr;\n int idx2;\n for (idx2 = outExtent[4]; idx2 <= outExtent[5]; ++idx2)\n {\n self->ComputeInternalFileName(idx2);\n \/\/ read in a JPEG file\n vtkJPEGReaderUpdate2(self, outPtr2, outExtent, outIncr, pixSize);\n self->UpdateProgress((idx2 - outExtent[4])\/\n (outExtent[5] - outExtent[4] + 1.0));\n outPtr2 += outIncr[2];\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This function reads a data from a file. The datas extent\/axes\n\/\/ are assumed to be the same as the file extent\/order.\nvoid vtkJPEGReader::ExecuteData(vtkDataObject *output)\n{\n vtkImageData *data = this->AllocateOutputData(output);\n\n if (this->InternalFileName == NULL)\n {\n vtkErrorMacro(<< \"Either a FileName or FilePrefix must be specified.\");\n return;\n }\n\n this->ComputeDataIncrements();\n \n \/\/ Call the correct templated function for the output\n void *outPtr;\n\n \/\/ Call the correct templated function for the input\n outPtr = data->GetScalarPointer();\n switch (data->GetScalarType())\n {\n vtkTemplateMacro3(vtkJPEGReaderUpdate, this, data, (VTK_TT *)(outPtr));\n default:\n vtkErrorMacro(<< \"UpdateFromFile: Unknown data type\");\n } \n}\n\n\n\nint vtkJPEGReader::CanReadFile(const char* fname)\n{\n \/\/ open the file\n FILE *fp = fopen(fname, \"rb\");\n if (!fp)\n {\n return 0;\n }\n \/\/ read the first two bytes\n char magic[2];\n int n = fread(magic, sizeof(magic), 1, fp);\n if (n != 1) \n {\n fclose(fp);\n return 0;\n }\n \/\/ check for the magic stuff:\n \/\/ 0xFF followed by 0xD8\n if( ( (magic[0] != char(0xFF)) || (magic[1] != char(0xD8)) ))\n {\n fclose(fp);\n return 0;\n }\n \/\/ go back to the start of the file\n fseek(fp, 0, SEEK_SET);\n \/\/ magic number is ok, try and read the header\n struct vtk_jpeg_error_mgr jerr;\n jerr.JPEGReader = this;\n struct jpeg_decompress_struct cinfo;\n cinfo.err = jpeg_std_error(&jerr.pub);\n \/\/ for any jpeg error call vtk_jpeg_error_exit\n jerr.pub.error_exit = vtk_jpeg_error_exit;\n \/\/ for any output message call vtk_jpeg_error_exit\n jerr.pub.output_message = vtk_jpeg_error_exit;\n \/\/ set the jump point, if there is a jpeg error or warning\n \/\/ this will evaluate to true\n if (setjmp(jerr.setjmp_buffer))\n {\n \/\/ clean up\n jpeg_destroy_decompress(&cinfo);\n \/\/ close the file\n fclose(fp);\n \/\/ this is not a valid jpeg file\n return 0;\n }\n \/* Now we can initialize the JPEG decompression object. *\/\n jpeg_create_decompress(&cinfo);\n \/* Step 2: specify data source (eg, a file) *\/\n jpeg_stdio_src(&cinfo, fp);\n \/* Step 3: read file parameters with jpeg_read_header() *\/\n jpeg_read_header(&cinfo, TRUE);\n \n \/\/ if no errors have occurred yet, then it must be jpeg\n jpeg_destroy_decompress(&cinfo);\n fclose(fp);\n return 1;\n}\n<|endoftext|>"} {"text":"\n\/*\n * Copyright 2009 The Android Open Source Project\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 \"SkColorTable.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n\nSK_DEFINE_INST_COUNT(SkColorTable)\n\nSkColorTable::SkColorTable(int count)\n : f16BitCache(NULL), fFlags(0)\n{\n if (count < 0)\n count = 0;\n else if (count > 256)\n count = 256;\n\n fCount = SkToU16(count);\n fColors = (SkPMColor*)sk_malloc_throw(count * sizeof(SkPMColor));\n memset(fColors, 0, count * sizeof(SkPMColor));\n\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n}\n\n\/\/ As copy constructor is hidden in the class hierarchy, we need to call\n\/\/ default constructor explicitly to suppress a compiler warning.\nSkColorTable::SkColorTable(const SkColorTable& src) : INHERITED() {\n f16BitCache = NULL;\n fFlags = src.fFlags;\n int count = src.count();\n fCount = SkToU16(count);\n fColors = reinterpret_cast(\n sk_malloc_throw(count * sizeof(SkPMColor)));\n memcpy(fColors, src.fColors, count * sizeof(SkPMColor));\n\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n}\n\nSkColorTable::SkColorTable(const SkPMColor colors[], int count)\n : f16BitCache(NULL), fFlags(0)\n{\n if (count < 0)\n count = 0;\n else if (count > 256)\n count = 256;\n\n fCount = SkToU16(count);\n fColors = reinterpret_cast(\n sk_malloc_throw(count * sizeof(SkPMColor)));\n\n if (colors)\n memcpy(fColors, colors, count * sizeof(SkPMColor));\n\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n}\n\nSkColorTable::~SkColorTable()\n{\n SkASSERT(fColorLockCount == 0);\n SkASSERT(f16BitCacheLockCount == 0);\n\n sk_free(fColors);\n sk_free(f16BitCache);\n}\n\nvoid SkColorTable::setFlags(unsigned flags)\n{\n fFlags = SkToU8(flags);\n}\n\nvoid SkColorTable::unlockColors(bool changed)\n{\n SkASSERT(fColorLockCount != 0);\n SkDEBUGCODE(sk_atomic_dec(&fColorLockCount);)\n if (changed)\n this->inval16BitCache();\n}\n\nvoid SkColorTable::inval16BitCache()\n{\n SkASSERT(f16BitCacheLockCount == 0);\n if (f16BitCache)\n {\n sk_free(f16BitCache);\n f16BitCache = NULL;\n }\n}\n\n#include \"SkColorPriv.h\"\n\nstatic inline void build_16bitcache(uint16_t dst[], const SkPMColor src[], int count)\n{\n while (--count >= 0)\n *dst++ = SkPixel32ToPixel16_ToU16(*src++);\n}\n\nconst uint16_t* SkColorTable::lock16BitCache()\n{\n if (fFlags & kColorsAreOpaque_Flag)\n {\n if (f16BitCache == NULL) \/\/ build the cache\n {\n f16BitCache = (uint16_t*)sk_malloc_throw(fCount * sizeof(uint16_t));\n build_16bitcache(f16BitCache, fColors, fCount);\n }\n }\n else \/\/ our colors have alpha, so no cache\n {\n this->inval16BitCache();\n if (f16BitCache)\n {\n sk_free(f16BitCache);\n f16BitCache = NULL;\n }\n }\n\n SkDEBUGCODE(f16BitCacheLockCount += 1);\n return f16BitCache;\n}\n\nvoid SkColorTable::setIsOpaque(bool isOpaque) {\n if (isOpaque) {\n fFlags |= kColorsAreOpaque_Flag;\n } else {\n fFlags &= ~kColorsAreOpaque_Flag;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkColorTable::SkColorTable(SkFlattenableReadBuffer& buffer) {\n f16BitCache = NULL;\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n\n fFlags = buffer.readUInt();\n fCount = buffer.getArrayCount();\n fColors = (SkPMColor*)sk_malloc_throw(fCount * sizeof(SkPMColor));\n const uint32_t countRead = buffer.readColorArray(fColors);\n SkASSERT((unsigned)fCount <= 256);\n SkASSERT(countRead == fCount);\n}\n\nvoid SkColorTable::flatten(SkFlattenableWriteBuffer& buffer) const {\n buffer.writeUInt(fFlags);\n buffer.writeColorArray(fColors, fCount);\n}\nFix warning-as-error for var used only in an assert (and therefore not in the release build).\n\/*\n * Copyright 2009 The Android Open Source Project\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 \"SkColorTable.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n\nSK_DEFINE_INST_COUNT(SkColorTable)\n\nSkColorTable::SkColorTable(int count)\n : f16BitCache(NULL), fFlags(0)\n{\n if (count < 0)\n count = 0;\n else if (count > 256)\n count = 256;\n\n fCount = SkToU16(count);\n fColors = (SkPMColor*)sk_malloc_throw(count * sizeof(SkPMColor));\n memset(fColors, 0, count * sizeof(SkPMColor));\n\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n}\n\n\/\/ As copy constructor is hidden in the class hierarchy, we need to call\n\/\/ default constructor explicitly to suppress a compiler warning.\nSkColorTable::SkColorTable(const SkColorTable& src) : INHERITED() {\n f16BitCache = NULL;\n fFlags = src.fFlags;\n int count = src.count();\n fCount = SkToU16(count);\n fColors = reinterpret_cast(\n sk_malloc_throw(count * sizeof(SkPMColor)));\n memcpy(fColors, src.fColors, count * sizeof(SkPMColor));\n\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n}\n\nSkColorTable::SkColorTable(const SkPMColor colors[], int count)\n : f16BitCache(NULL), fFlags(0)\n{\n if (count < 0)\n count = 0;\n else if (count > 256)\n count = 256;\n\n fCount = SkToU16(count);\n fColors = reinterpret_cast(\n sk_malloc_throw(count * sizeof(SkPMColor)));\n\n if (colors)\n memcpy(fColors, colors, count * sizeof(SkPMColor));\n\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n}\n\nSkColorTable::~SkColorTable()\n{\n SkASSERT(fColorLockCount == 0);\n SkASSERT(f16BitCacheLockCount == 0);\n\n sk_free(fColors);\n sk_free(f16BitCache);\n}\n\nvoid SkColorTable::setFlags(unsigned flags)\n{\n fFlags = SkToU8(flags);\n}\n\nvoid SkColorTable::unlockColors(bool changed)\n{\n SkASSERT(fColorLockCount != 0);\n SkDEBUGCODE(sk_atomic_dec(&fColorLockCount);)\n if (changed)\n this->inval16BitCache();\n}\n\nvoid SkColorTable::inval16BitCache()\n{\n SkASSERT(f16BitCacheLockCount == 0);\n if (f16BitCache)\n {\n sk_free(f16BitCache);\n f16BitCache = NULL;\n }\n}\n\n#include \"SkColorPriv.h\"\n\nstatic inline void build_16bitcache(uint16_t dst[], const SkPMColor src[], int count)\n{\n while (--count >= 0)\n *dst++ = SkPixel32ToPixel16_ToU16(*src++);\n}\n\nconst uint16_t* SkColorTable::lock16BitCache()\n{\n if (fFlags & kColorsAreOpaque_Flag)\n {\n if (f16BitCache == NULL) \/\/ build the cache\n {\n f16BitCache = (uint16_t*)sk_malloc_throw(fCount * sizeof(uint16_t));\n build_16bitcache(f16BitCache, fColors, fCount);\n }\n }\n else \/\/ our colors have alpha, so no cache\n {\n this->inval16BitCache();\n if (f16BitCache)\n {\n sk_free(f16BitCache);\n f16BitCache = NULL;\n }\n }\n\n SkDEBUGCODE(f16BitCacheLockCount += 1);\n return f16BitCache;\n}\n\nvoid SkColorTable::setIsOpaque(bool isOpaque) {\n if (isOpaque) {\n fFlags |= kColorsAreOpaque_Flag;\n } else {\n fFlags &= ~kColorsAreOpaque_Flag;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkColorTable::SkColorTable(SkFlattenableReadBuffer& buffer) {\n f16BitCache = NULL;\n SkDEBUGCODE(fColorLockCount = 0;)\n SkDEBUGCODE(f16BitCacheLockCount = 0;)\n\n fFlags = buffer.readUInt();\n fCount = buffer.getArrayCount();\n fColors = (SkPMColor*)sk_malloc_throw(fCount * sizeof(SkPMColor));\n SkDEBUGCODE(const uint32_t countRead =) buffer.readColorArray(fColors);\n#ifdef SK_DEBUG\n SkASSERT((unsigned)fCount <= 256);\n SkASSERT(countRead == fCount);\n#endif\n}\n\nvoid SkColorTable::flatten(SkFlattenableWriteBuffer& buffer) const {\n buffer.writeUInt(fFlags);\n buffer.writeColorArray(fColors, fCount);\n}\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2014, 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 *\/\n\n#include \"src\/cpp\/client\/channel.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/cpp\/proto\/proto_utils.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace grpc {\n\nChannel::Channel(const grpc::string &target, const ChannelArguments &args)\n : target_(target) {\n grpc_channel_args channel_args;\n args.SetChannelArgs(&channel_args);\n c_channel_ = grpc_channel_create(\n target_.c_str(), channel_args.num_args > 0 ? &channel_args : nullptr);\n}\n\nChannel::Channel(const grpc::string &target,\n const std::unique_ptr &creds,\n const ChannelArguments &args)\n : target_(args.GetSslTargetNameOverride().empty()\n ? target\n : args.GetSslTargetNameOverride()) {\n grpc_channel_args channel_args;\n args.SetChannelArgs(&channel_args);\n grpc_credentials *c_creds = creds ? creds->GetRawCreds() : nullptr;\n c_channel_ = grpc_secure_channel_create(\n c_creds, target.c_str(),\n channel_args.num_args > 0 ? &channel_args : nullptr);\n}\n\nChannel::~Channel() { grpc_channel_destroy(c_channel_); }\n\nCall Channel::CreateCall(const RpcMethod &method, ClientContext *context,\n CompletionQueue *cq) {\n auto c_call =\n grpc_channel_create_call(\n c_channel_, cq->cq(), method.name(),\n context->authority().empty() ? target_.c_str()\n : context->authority(),\n context->RawDeadline());\n context->set_call(c_call);\n return Call(c_call, this, cq);\n}\n\nvoid Channel::PerformOpsOnCall(CallOpBuffer *buf, Call *call) {\n static const size_t MAX_OPS = 8;\n size_t nops = MAX_OPS;\n grpc_op ops[MAX_OPS];\n buf->FillOps(ops, &nops);\n GPR_ASSERT(GRPC_CALL_OK ==\n grpc_call_start_batch(call->call(), ops, nops, buf));\n}\n\n} \/\/ namespace grpc\nshould use c_str\/*\n *\n * Copyright 2014, 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 *\/\n\n#include \"src\/cpp\/client\/channel.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/cpp\/proto\/proto_utils.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace grpc {\n\nChannel::Channel(const grpc::string &target, const ChannelArguments &args)\n : target_(target) {\n grpc_channel_args channel_args;\n args.SetChannelArgs(&channel_args);\n c_channel_ = grpc_channel_create(\n target_.c_str(), channel_args.num_args > 0 ? &channel_args : nullptr);\n}\n\nChannel::Channel(const grpc::string &target,\n const std::unique_ptr &creds,\n const ChannelArguments &args)\n : target_(args.GetSslTargetNameOverride().empty()\n ? target\n : args.GetSslTargetNameOverride()) {\n grpc_channel_args channel_args;\n args.SetChannelArgs(&channel_args);\n grpc_credentials *c_creds = creds ? creds->GetRawCreds() : nullptr;\n c_channel_ = grpc_secure_channel_create(\n c_creds, target.c_str(),\n channel_args.num_args > 0 ? &channel_args : nullptr);\n}\n\nChannel::~Channel() { grpc_channel_destroy(c_channel_); }\n\nCall Channel::CreateCall(const RpcMethod &method, ClientContext *context,\n CompletionQueue *cq) {\n auto c_call =\n grpc_channel_create_call(\n c_channel_, cq->cq(), method.name(),\n context->authority().empty() ? target_.c_str()\n : context->authority().c_str(),\n context->RawDeadline());\n context->set_call(c_call);\n return Call(c_call, this, cq);\n}\n\nvoid Channel::PerformOpsOnCall(CallOpBuffer *buf, Call *call) {\n static const size_t MAX_OPS = 8;\n size_t nops = MAX_OPS;\n grpc_op ops[MAX_OPS];\n buf->FillOps(ops, &nops);\n GPR_ASSERT(GRPC_CALL_OK ==\n grpc_call_start_batch(call->call(), ops, nops, buf));\n}\n\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"\/*\n * FileLock.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \n\n\/\/ #define RSTUDIO_ENABLE_DEBUG_MACROS\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace rstudio {\nnamespace core {\n\nnamespace file_lock {\nvoid initialize()\n{\n FileLock::initialize();\n}\n} \/\/ end namespace file_lock\n\nnamespace {\n\nconst char * const kLockTypeAdvisory = \"advisory\";\nconst char * const kLockTypeLinkBased = \"linkbased\";\n\nconst char * const kLocksConfPath = \"\/etc\/rstudio\/file-locks\";\n#define kDefaultRefreshRate 20.0\n#define kDefaultTimeoutInterval 30.0\n\nstd::string lockTypeToString(FileLock::LockType type)\n{\n switch (type)\n {\n case FileLock::LOCKTYPE_ADVISORY: return kLockTypeAdvisory;\n case FileLock::LOCKTYPE_LINKBASED: return kLockTypeLinkBased;\n }\n \n \/\/ not reached\n return std::string();\n}\n\nFileLock::LockType stringToLockType(const std::string& lockType)\n{\n using namespace boost::algorithm;\n \n if (boost::iequals(lockType, kLockTypeAdvisory))\n return FileLock::LOCKTYPE_ADVISORY;\n else if (boost::iequals(lockType, kLockTypeLinkBased))\n return FileLock::LOCKTYPE_LINKBASED;\n \n LOG_WARNING_MESSAGE(\"unrecognized lock type '\" + lockType + \"'\");\n return FileLock::LOCKTYPE_ADVISORY;\n}\n\ndouble getFieldPositive(const Settings& settings,\n const std::string& name,\n double defaultValue)\n{\n double value = settings.getDouble(name, defaultValue);\n if (value < 0)\n {\n LOG_WARNING_MESSAGE(\"invalid field '\" + name + \"': must be positive\");\n return defaultValue;\n }\n \n return value;\n}\n\n} \/\/ end anonymous namespace\n\nbool s_isInitialized = false;\n\nvoid FileLock::ensureInitialized()\n{\n if (s_isInitialized)\n return;\n \n FileLock::initialize();\n}\n\nvoid FileLock::initialize(FilePath locksConfPath)\n{\n s_isInitialized = true;\n \n if (locksConfPath.empty())\n locksConfPath = FilePath(kLocksConfPath);\n \n if (!locksConfPath.exists())\n return;\n \n Settings settings;\n Error error = settings.initialize(locksConfPath);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n \n FileLock::initialize(settings);\n}\n\nvoid FileLock::initialize(const Settings& settings)\n{\n s_isInitialized = true;\n \n \/\/ default lock type\n FileLock::s_defaultType = stringToLockType(settings.get(\"lock-type\", kLockTypeAdvisory));\n \n \/\/ timeout interval\n double timeoutInterval = getFieldPositive(settings, \"timeout-interval\", kDefaultTimeoutInterval);\n FileLock::s_timeoutInterval = boost::posix_time::seconds(timeoutInterval);\n \n \/\/ refresh rate\n double refreshRate = getFieldPositive(settings, \"refresh-rate\", kDefaultRefreshRate);\n FileLock::s_refreshRate = boost::posix_time::seconds(refreshRate);\n \n DEBUG_BLOCK(\"lock initialization\")\n {\n std::cerr << \"Type: \" << lockTypeToString(FileLock::s_defaultType) << std::endl;\n std::cerr << \"Timeout: \" << FileLock::s_timeoutInterval.total_seconds() << std::endl;\n std::cerr << \"Refresh: \" << FileLock::s_refreshRate.total_seconds() << std::endl;\n }\n}\n\n\/\/ default values for static members\nFileLock::LockType FileLock::s_defaultType(FileLock::LOCKTYPE_ADVISORY);\nboost::posix_time::seconds FileLock::s_timeoutInterval(kDefaultTimeoutInterval);\nboost::posix_time::seconds FileLock::s_refreshRate(kDefaultRefreshRate);\n\nboost::shared_ptr FileLock::create(LockType type)\n{\n switch (type)\n {\n case LOCKTYPE_ADVISORY: return boost::shared_ptr(new AdvisoryFileLock());\n case LOCKTYPE_LINKBASED: return boost::shared_ptr(new LinkBasedFileLock());\n }\n \n \/\/ shouldn't be reached\n return boost::shared_ptr(new AdvisoryFileLock());\n}\n\nboost::shared_ptr FileLock::createDefault()\n{\n return FileLock::create(s_defaultType);\n}\n\nvoid FileLock::refresh()\n{\n AdvisoryFileLock::refresh();\n LinkBasedFileLock::refresh();\n}\n\nvoid FileLock::cleanUp()\n{\n AdvisoryFileLock::cleanUp();\n LinkBasedFileLock::cleanUp();\n}\n\nnamespace {\n\nvoid schedulePeriodicExecution(\n const boost::system::error_code& ec,\n boost::asio::deadline_timer& timer,\n boost::posix_time::seconds interval,\n boost::function callback)\n{\n try\n {\n \/\/ bail on boost errors (these are very unexpected)\n if (ec)\n {\n LOG_ERROR(core::Error(ec, ERROR_LOCATION));\n return;\n }\n \n \/\/ execute callback\n callback();\n\n \/\/ reschedule\n boost::system::error_code errc;\n timer.expires_at(timer.expires_at() + interval, errc);\n if (errc)\n {\n LOG_ERROR(Error(errc, ERROR_LOCATION));\n return;\n }\n \n timer.async_wait(boost::bind(\n schedulePeriodicExecution,\n boost::asio::placeholders::error,\n boost::ref(timer),\n interval,\n callback));\n }\n catch (...)\n {\n \/\/ swallow errors\n }\n}\n\n} \/\/ end anonymous namespace\n\nvoid FileLock::refreshPeriodically(boost::asio::io_service& service,\n boost::posix_time::seconds interval)\n{\n \/\/ protect against re-entrancy\n static bool s_isRefreshing = false;\n if (s_isRefreshing)\n return;\n s_isRefreshing = true;\n \n static boost::asio::deadline_timer timer(service, interval);\n timer.async_wait(boost::bind(\n schedulePeriodicExecution,\n boost::asio::placeholders::error,\n boost::ref(timer),\n interval,\n FileLock::refresh));\n}\n\n} \/\/ end namespace core\n} \/\/ end namespace rstudio\nuse double rather than macro for defaults\/*\n * FileLock.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \n\n\/\/ #define RSTUDIO_ENABLE_DEBUG_MACROS\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace rstudio {\nnamespace core {\n\nnamespace file_lock {\nvoid initialize()\n{\n FileLock::initialize();\n}\n} \/\/ end namespace file_lock\n\nnamespace {\n\nconst char * const kLockTypeAdvisory = \"advisory\";\nconst char * const kLockTypeLinkBased = \"linkbased\";\n\nconst char * const kLocksConfPath = \"\/etc\/rstudio\/file-locks\";\nconst double kDefaultRefreshRate = 20.0;\nconst double kDefaultTimeoutInterval = 30.0;\n\nstd::string lockTypeToString(FileLock::LockType type)\n{\n switch (type)\n {\n case FileLock::LOCKTYPE_ADVISORY: return kLockTypeAdvisory;\n case FileLock::LOCKTYPE_LINKBASED: return kLockTypeLinkBased;\n }\n \n \/\/ not reached\n return std::string();\n}\n\nFileLock::LockType stringToLockType(const std::string& lockType)\n{\n using namespace boost::algorithm;\n \n if (boost::iequals(lockType, kLockTypeAdvisory))\n return FileLock::LOCKTYPE_ADVISORY;\n else if (boost::iequals(lockType, kLockTypeLinkBased))\n return FileLock::LOCKTYPE_LINKBASED;\n \n LOG_WARNING_MESSAGE(\"unrecognized lock type '\" + lockType + \"'\");\n return FileLock::LOCKTYPE_ADVISORY;\n}\n\ndouble getFieldPositive(const Settings& settings,\n const std::string& name,\n double defaultValue)\n{\n double value = settings.getDouble(name, defaultValue);\n if (value < 0)\n {\n LOG_WARNING_MESSAGE(\"invalid field '\" + name + \"': must be positive\");\n return defaultValue;\n }\n \n return value;\n}\n\n} \/\/ end anonymous namespace\n\nbool s_isInitialized = false;\n\nvoid FileLock::ensureInitialized()\n{\n if (s_isInitialized)\n return;\n \n FileLock::initialize();\n}\n\nvoid FileLock::initialize(FilePath locksConfPath)\n{\n s_isInitialized = true;\n \n if (locksConfPath.empty())\n locksConfPath = FilePath(kLocksConfPath);\n \n if (!locksConfPath.exists())\n return;\n \n Settings settings;\n Error error = settings.initialize(locksConfPath);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n \n FileLock::initialize(settings);\n}\n\nvoid FileLock::initialize(const Settings& settings)\n{\n s_isInitialized = true;\n \n \/\/ default lock type\n FileLock::s_defaultType = stringToLockType(settings.get(\"lock-type\", kLockTypeAdvisory));\n \n \/\/ timeout interval\n double timeoutInterval = getFieldPositive(settings, \"timeout-interval\", kDefaultTimeoutInterval);\n FileLock::s_timeoutInterval = boost::posix_time::seconds(timeoutInterval);\n \n \/\/ refresh rate\n double refreshRate = getFieldPositive(settings, \"refresh-rate\", kDefaultRefreshRate);\n FileLock::s_refreshRate = boost::posix_time::seconds(refreshRate);\n \n DEBUG_BLOCK(\"lock initialization\")\n {\n std::cerr << \"Type: \" << lockTypeToString(FileLock::s_defaultType) << std::endl;\n std::cerr << \"Timeout: \" << FileLock::s_timeoutInterval.total_seconds() << std::endl;\n std::cerr << \"Refresh: \" << FileLock::s_refreshRate.total_seconds() << std::endl;\n }\n}\n\n\/\/ default values for static members\nFileLock::LockType FileLock::s_defaultType(FileLock::LOCKTYPE_ADVISORY);\nboost::posix_time::seconds FileLock::s_timeoutInterval(kDefaultTimeoutInterval);\nboost::posix_time::seconds FileLock::s_refreshRate(kDefaultRefreshRate);\n\nboost::shared_ptr FileLock::create(LockType type)\n{\n switch (type)\n {\n case LOCKTYPE_ADVISORY: return boost::shared_ptr(new AdvisoryFileLock());\n case LOCKTYPE_LINKBASED: return boost::shared_ptr(new LinkBasedFileLock());\n }\n \n \/\/ shouldn't be reached\n return boost::shared_ptr(new AdvisoryFileLock());\n}\n\nboost::shared_ptr FileLock::createDefault()\n{\n return FileLock::create(s_defaultType);\n}\n\nvoid FileLock::refresh()\n{\n AdvisoryFileLock::refresh();\n LinkBasedFileLock::refresh();\n}\n\nvoid FileLock::cleanUp()\n{\n AdvisoryFileLock::cleanUp();\n LinkBasedFileLock::cleanUp();\n}\n\nnamespace {\n\nvoid schedulePeriodicExecution(\n const boost::system::error_code& ec,\n boost::asio::deadline_timer& timer,\n boost::posix_time::seconds interval,\n boost::function callback)\n{\n try\n {\n \/\/ bail on boost errors (these are very unexpected)\n if (ec)\n {\n LOG_ERROR(core::Error(ec, ERROR_LOCATION));\n return;\n }\n \n \/\/ execute callback\n callback();\n\n \/\/ reschedule\n boost::system::error_code errc;\n timer.expires_at(timer.expires_at() + interval, errc);\n if (errc)\n {\n LOG_ERROR(Error(errc, ERROR_LOCATION));\n return;\n }\n \n timer.async_wait(boost::bind(\n schedulePeriodicExecution,\n boost::asio::placeholders::error,\n boost::ref(timer),\n interval,\n callback));\n }\n catch (...)\n {\n \/\/ swallow errors\n }\n}\n\n} \/\/ end anonymous namespace\n\nvoid FileLock::refreshPeriodically(boost::asio::io_service& service,\n boost::posix_time::seconds interval)\n{\n \/\/ protect against re-entrancy\n static bool s_isRefreshing = false;\n if (s_isRefreshing)\n return;\n s_isRefreshing = true;\n \n static boost::asio::deadline_timer timer(service, interval);\n timer.async_wait(boost::bind(\n schedulePeriodicExecution,\n boost::asio::placeholders::error,\n boost::ref(timer),\n interval,\n FileLock::refresh));\n}\n\n} \/\/ end namespace core\n} \/\/ end namespace rstudio\n<|endoftext|>"} {"text":"\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2020 Romain JANVIER\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#ifndef OPENMVG_MATCHING_METRIC_HNSW_HPP\n#define OPENMVG_MATCHING_METRIC_HNSW_HPP\n\n#include \"openMVG\/matching\/metric_hamming.hpp\"\n\n#include \"third_party\/hnswlib\/hnswlib.h\"\n\n\/*\n* This file define specialized HNSW kernels for differents metrics\/spaces\n*\/\nnamespace openMVG {\nnamespace matching {\nnamespace custom_hnsw{\n\ntemplate \nstatic unsigned int HammingKernel(const void *__restrict pVect1, const void *__restrict pVect2, const void *__restrict qty_ptr) \n{\n constexpr openMVG::matching::Hamming hamming{};\n const U *a = reinterpret_cast(pVect1);\n const U *b = reinterpret_cast(pVect2);\n return hamming(a, b,*(reinterpret_cast(qty_ptr)));\n}\n\ntemplate \nclass HammingSpace : public hnswlib::SpaceInterface\n{\n hnswlib::DISTFUNC fstdistfunc_;\n size_t data_size_;\n size_t dim_;\n\npublic:\n explicit HammingSpace(size_t dim)\n {\n fstdistfunc_ = HammingKernel;\n dim_ = dim;\n data_size_ = dim_ * sizeof(U);\n }\n\n ~HammingSpace() {}\n\n size_t get_data_size() override\n {\n return data_size_;\n }\n\n hnswlib::DISTFUNC get_dist_func() override\n {\n return fstdistfunc_;\n }\n\n void *get_dist_func_param() override\n {\n return &dim_;\n }\n};\n\nstatic int L1Kernel(const void *__restrict pVect1, const void *__restrict pVect2, const void *__restrict qty_ptr) \n{\n size_t size = *(reinterpret_cast(qty_ptr));\n size = size >> 2;\n int result = 0;\n uint8_t *a = (uint8_t *)(pVect1); \/\/ discard const\n uint8_t *b = (uint8_t *)(pVect2); \/\/ discard const\n\n \/\/ Process 4 items for each loop for efficiency.\n for (size_t i = 0; i < size; i++) {\n result += std::abs(*a - *b);\n a++;b++;\n result += std::abs(*a - *b);\n a++;b++;\n result += std::abs(*a - *b);\n a++;b++;\n result += std::abs(*a - *b);\n a++;b++;\n }\n return result;\n}\n#ifdef __SSE2__\nstatic int L1Kernel_SSE2(const void *__restrict pVect1, const void *__restrict pVect2, const void *__restrict qty_ptr) \n{\n const uint8_t *a = reinterpret_cast(pVect1);\n const uint8_t *b = reinterpret_cast(pVect2);\n return L1_SSE2(a, b, 128);\n}\n#endif\n\n#ifdef __AVX2__\nstatic int L1Kernel_AVX2(const void *__restrict pVect1, const void *__restrict pVect2, const void *__restrict qty_ptr) \n{\n const uint8_t *a = reinterpret_cast(pVect1);\n const uint8_t *b = reinterpret_cast(pVect2);\n return L1_AVX2(a, b, 128);\n}\n#endif\n\nclass L1SpaceInteger : public hnswlib::SpaceInterface\n{\n hnswlib::DISTFUNC fstdistfunc_;\n size_t data_size_;\n size_t dim_;\n\npublic:\n explicit L1SpaceInteger(size_t dim)\n {\n fstdistfunc_ = L1Kernel;\n #ifdef __SSE2__\n \/\/FIXME (RJ): Kernel disabled since there are some troubles on my Linux computer\n \/*if(dim == 128) {\n fstdistfunc_ = L1Kernel_SSE2;\n }*\/\n #endif\n #ifdef __AVX2__\n if(dim == 128) {\n fstdistfunc_ = L1Kernel_AVX2;\n }\n #endif\n dim_ = dim;\n data_size_ = dim_ * sizeof(uint8_t);\n }\n\n ~L1SpaceInteger() {}\n\n size_t get_data_size() override\n {\n return data_size_;\n }\n\n hnswlib::DISTFUNC get_dist_func() override\n {\n return fstdistfunc_;\n }\n\n void *get_dist_func_param() override\n {\n return &dim_;\n }\n};\n\n#ifdef __AVX2__\nstatic int L2Kernel_AVX2(const void *__restrict pVect1, const void *__restrict pVect2, const void *__restrict qty_ptr) \n{\n const uint8_t *a = reinterpret_cast(pVect1);\n const uint8_t *b = reinterpret_cast(pVect2);\n return L2_AVX2(a, b, 128);\n}\n#endif\n\nclass L2SpaceInteger : public hnswlib::SpaceInterface\n{\n hnswlib::DISTFUNC fstdistfunc_;\n size_t data_size_;\n size_t dim_;\n\npublic:\n explicit L2SpaceInteger(size_t dim)\n {\n fstdistfunc_ = hnswlib::L2SqrI;\n #ifdef __AVX2__\n if(dim == 128) {\n fstdistfunc_ = L2Kernel_AVX2;\n }\n #endif\n dim_ = dim;\n data_size_ = dim_ * sizeof(uint8_t);\n }\n\n ~L2SpaceInteger() {}\n\n size_t get_data_size() override\n {\n return data_size_;\n }\n\n hnswlib::DISTFUNC get_dist_func() override\n {\n return fstdistfunc_;\n }\n\n void *get_dist_func_param() override\n {\n return &dim_;\n }\n};\n\n} \/\/ namespace custom_hnsw\n} \/\/ namespace matching\n} \/\/ namespace openMVG\n#endif \/\/ OPENMVG_MATCHING_METRIC_HNSW_HPP[Matching] Fix L1 metric\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2020 Romain JANVIER\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#ifndef OPENMVG_MATCHING_METRIC_HNSW_HPP\n#define OPENMVG_MATCHING_METRIC_HNSW_HPP\n\n#include \"openMVG\/matching\/metric_hamming.hpp\"\n\n#include \"third_party\/hnswlib\/hnswlib.h\"\n\n\/*\n* This file define specialized HNSW kernels for differents metrics\/spaces\n*\/\nnamespace openMVG {\nnamespace matching {\nnamespace custom_hnsw{\n\ntemplate \nstatic unsigned int HammingKernel(const void * pVect1, const void * pVect2, const void * qty_ptr) \n{\n constexpr openMVG::matching::Hamming hamming{};\n const U *a = reinterpret_cast(pVect1);\n const U *b = reinterpret_cast(pVect2);\n return hamming(a, b,*(reinterpret_cast(qty_ptr)));\n}\n\ntemplate \nclass HammingSpace : public hnswlib::SpaceInterface\n{\n hnswlib::DISTFUNC fstdistfunc_;\n size_t data_size_;\n size_t dim_;\n\npublic:\n explicit HammingSpace(size_t dim)\n {\n fstdistfunc_ = HammingKernel;\n dim_ = dim;\n data_size_ = dim_ * sizeof(U);\n }\n\n ~HammingSpace() {}\n\n size_t get_data_size() override\n {\n return data_size_;\n }\n\n hnswlib::DISTFUNC get_dist_func() override\n {\n return fstdistfunc_;\n }\n\n void *get_dist_func_param() override\n {\n return &dim_;\n }\n};\n\nstatic int L1Kernel(const void *__restrict pVect1, const void *__restrict pVect2, const void *__restrict qty_ptr) \n{\n size_t size = *(reinterpret_cast(qty_ptr));\n size = size >> 2;\n int result = 0;\n uint8_t *a = (uint8_t *)(pVect1); \/\/ discard const\n uint8_t *b = (uint8_t *)(pVect2); \/\/ discard const\n\n \/\/ Process 4 items for each loop for efficiency.\n for (size_t i = 0; i < size; i++) {\n result += std::abs(*a - *b);\n a++;b++;\n result += std::abs(*a - *b);\n a++;b++;\n result += std::abs(*a - *b);\n a++;b++;\n result += std::abs(*a - *b);\n a++;b++;\n }\n return result;\n}\n#ifdef __SSE2__\nstatic int L1Kernel_SSE2(const void * pVect1, const void * pVect2, const void * qty_ptr) \n{\n const uint8_t *a = reinterpret_cast(pVect1);\n const uint8_t *b = reinterpret_cast(pVect2);\n return L1_SSE2(a, b, 128);\n}\n#endif\n\n#ifdef __AVX2__\nstatic int L1Kernel_AVX2(const void * pVect1, const void * pVect2, const void * qty_ptr) \n{\n const uint8_t *a = reinterpret_cast(pVect1);\n const uint8_t *b = reinterpret_cast(pVect2);\n return L1_AVX2(a, b, 128);\n}\n#endif\n\nclass L1SpaceInteger : public hnswlib::SpaceInterface\n{\n hnswlib::DISTFUNC fstdistfunc_;\n size_t data_size_;\n size_t dim_;\n\npublic:\n explicit L1SpaceInteger(size_t dim)\n {\n fstdistfunc_ = L1Kernel;\n #ifdef __SSE2__\n \/\/FIXME (RJ): Kernel disabled since there are some troubles on my Linux computer\n \/*if(dim == 128) {\n fstdistfunc_ = L1Kernel_SSE2;\n }*\/\n #endif\n #ifdef __AVX2__\n if(dim == 128) {\n fstdistfunc_ = L1Kernel_AVX2;\n }\n #endif\n dim_ = dim;\n data_size_ = dim_ * sizeof(uint8_t);\n }\n\n ~L1SpaceInteger() {}\n\n size_t get_data_size() override\n {\n return data_size_;\n }\n\n hnswlib::DISTFUNC get_dist_func() override\n {\n return fstdistfunc_;\n }\n\n void *get_dist_func_param() override\n {\n return &dim_;\n }\n};\n\n#ifdef __AVX2__\nstatic int L2Kernel_AVX2(const void * pVect1, const void * pVect2, const void * qty_ptr) \n{\n const uint8_t *a = reinterpret_cast(pVect1);\n const uint8_t *b = reinterpret_cast(pVect2);\n return L2_AVX2(a, b, 128);\n}\n#endif\n\nclass L2SpaceInteger : public hnswlib::SpaceInterface\n{\n hnswlib::DISTFUNC fstdistfunc_;\n size_t data_size_;\n size_t dim_;\n\npublic:\n explicit L2SpaceInteger(size_t dim)\n {\n fstdistfunc_ = hnswlib::L2SqrI;\n #ifdef __AVX2__\n if(dim == 128) {\n fstdistfunc_ = L2Kernel_AVX2;\n }\n #endif\n dim_ = dim;\n data_size_ = dim_ * sizeof(uint8_t);\n }\n\n ~L2SpaceInteger() {}\n\n size_t get_data_size() override\n {\n return data_size_;\n }\n\n hnswlib::DISTFUNC get_dist_func() override\n {\n return fstdistfunc_;\n }\n\n void *get_dist_func_param() override\n {\n return &dim_;\n }\n};\n\n} \/\/ namespace custom_hnsw\n} \/\/ namespace matching\n} \/\/ namespace openMVG\n#endif \/\/ OPENMVG_MATCHING_METRIC_HNSW_HPP<|endoftext|>"} {"text":"#ifndef PRE_VARIANT_GET_TRAIT_HPP\n#define PRE_VARIANT_GET_TRAIT_HPP\n\n#include \n#include \n\n#include \n#include \n\nnamespace pre { namespace variant { \n\n namespace detail {\n template class TraitMetafunction>\n struct get_trait_visitor : public boost::static_visitor {\n\n \n\n template< class U, \n typename boost::disable_if<\n assignable_from::type>\n >::type* = nullptr\n > ResultVariant operator()(const U&) const {\n return ResultVariant{};\n }\n\n template< class U, \n typename boost::enable_if<\n assignable_from::type>\n >::type* = nullptr\n > ResultVariant operator()(const U&) const { \n return typename TraitMetafunction::type{};\n }\n };\n\n\n template class TraitMetafunction>\n struct get_value_trait_visitor : public boost::static_visitor {\n\n template< class U >\n Result operator()(const U&) const { \n return typename TraitMetafunction::type{};\n }\n\n\n };\n }\n\n \/**\n * \\brief Runtime compile time traits access. \n * This function gets the active type of a variant and return a runtime\n * instantiation of the associated type found by\n * TraitMetafunction. \n *\n * \\param variant The variant whose active type will be queried for the given\n * TraitMetafunction\n *\n * \\param Result A boost::variant or any type capable to hold the runtime \n * instance of the TraitMetafunction result.\n *\n * \\param TraitMetafunction Template metafunction which will be called on the \n * active type of the runtime parameter : variant.\n *\n * \\param InspectedVariant A boost::variant to apply the TraitMetafunction on it's\n * active field.\n *\n *\/\n template class TraitMetafunction, class InspectedVariant,\n typename std::enable_if< \n pre::json::traits::is_boost_variant::value \n >::type* = nullptr\n > \n inline Result get_trait(const InspectedVariant& variant) {\n return boost::apply_visitor(detail::get_trait_visitor{}, variant);\n }\n\n template class TraitMetafunction, class InspectedVariant,\n typename std::enable_if< \n !pre::json::traits::is_boost_variant::value \n >::type* = nullptr\n >\n inline Result get_trait(const InspectedVariant& variant) {\n return boost::apply_visitor(detail::get_value_trait_visitor{}, variant);\n }\n \n}}\n\n#endif\nBUGFIX: Only mpl value have a default constructor, other metaprogramming library provide value via ::value, so take the one size fits-all. :D#ifndef PRE_VARIANT_GET_TRAIT_HPP\n#define PRE_VARIANT_GET_TRAIT_HPP\n\n#include \n#include \n\n#include \n#include \n\nnamespace pre { namespace variant { \n\n namespace detail {\n template class TraitMetafunction>\n struct get_trait_visitor : public boost::static_visitor {\n\n \n\n template< class U, \n typename boost::disable_if<\n assignable_from::type>\n >::type* = nullptr\n > ResultVariant operator()(const U&) const {\n return ResultVariant{};\n }\n\n template< class U, \n typename boost::enable_if<\n assignable_from::type>\n >::type* = nullptr\n > ResultVariant operator()(const U&) const { \n return typename TraitMetafunction::type{};\n }\n };\n\n\n template class TraitMetafunction>\n struct get_value_trait_visitor : public boost::static_visitor {\n\n template< class U >\n Result operator()(const U&) const { \n return TraitMetafunction::type::value;\n }\n\n\n };\n }\n\n \/**\n * \\brief Runtime compile time traits access. \n * This function gets the active type of a variant and return a runtime\n * instantiation of the associated type found by\n * TraitMetafunction. \n *\n * \\param variant The variant whose active type will be queried for the given\n * TraitMetafunction\n *\n * \\param Result A boost::variant or any type capable to hold the runtime \n * instance of the TraitMetafunction result.\n *\n * \\param TraitMetafunction Template metafunction which will be called on the \n * active type of the runtime parameter : variant.\n *\n * \\param InspectedVariant A boost::variant to apply the TraitMetafunction on it's\n * active field.\n *\n *\/\n template class TraitMetafunction, class InspectedVariant,\n typename std::enable_if< \n pre::json::traits::is_boost_variant::value \n >::type* = nullptr\n > \n inline Result get_trait(const InspectedVariant& variant) {\n return boost::apply_visitor(detail::get_trait_visitor{}, variant);\n }\n\n template class TraitMetafunction, class InspectedVariant,\n typename std::enable_if< \n !pre::json::traits::is_boost_variant::value \n >::type* = nullptr\n >\n inline Result get_trait(const InspectedVariant& variant) {\n return boost::apply_visitor(detail::get_value_trait_visitor{}, variant);\n }\n \n}}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n@title: BinaryHeap 二叉堆\n@description:\n 一个普通的二叉堆\n@structure:\n BinaryHeap:\n T *buffer: 数组首地址 - 1\n int size: 数组长度\n@note:\n 需要手动指定 buffer, size\n 指定 buffer 为 a[] 时 => buffer = a - 1;\n*\/\nstruct BinaryHeap {\n int *buffer;\n int size;\n \/\/ 转移函数 O(1)\n int parent(int index);\n int left(int index);\n int right(int index);\n \/\/ shiftDown\n \/\/ 对节点 n 进行下降操作\n \/\/ 将 buffer[n] 向下交换到叶子节点上。\n \/\/ 每次与孩子中较小的一个交换。 O(log(size))\n void shiftDown(int index);\n \/\/ insert\n \/\/ 插入元素 O(log(size))\n void insert(int key);\n \/\/ Find Min\n \/\/ 获取最小值 O(1)\n int findMin();\n \/\/ Remove\n \/\/ 删除 index 位置上的点 O(log(size))\n void remove(int index);\n \/\/ Delete Min\n \/\/ 删除最小值 O(log(size))\n void deleteMin();\n \/\/ Extract Min\n \/\/ 取最小值并弹出 O(log(size))\n int extractMin();\n \/\/ updateKey\n \/\/ 更新键值\n \/\/ shift down or shift up O(log(size))\n void updateKey(int index, int key);\n void IterativeMaintenance(int index);\n \/\/ 离线迭代建堆\n \/\/ Bottom-Up O(size)\n void IterativeHeapify();\n};\n\ninline int BinaryHeap::parent(int index) { return index >> 1; }\ninline int BinaryHeap::left(int index) { return index << 1; }\ninline int BinaryHeap::right(int index) { return (index << 1) + 1; }\n\nvoid BinaryHeap::shiftDown(int index) {\n while (true) {\n if (right(index) <= size) { \/\/ left(n) < right(n) <= size\n if (compare(buffer[left(index)], buffer[right(index)])) {\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n } else {\n std::swap(buffer[index], buffer[right(index)]);\n index = right(index);\n }\n } else if (left(index) <= size) { \/\/ left(n) <= size < right(n)\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n } else { \/\/ size < left(n) < right(n)\n break;\n }\n }\n}\n\nvoid BinaryHeap::insert(int key) {\n int index = ++size;\n while (index > 1 && compare(key, buffer[parent(index)])) {\n buffer[index] = buffer[parent(index)];\n index = parent(index);\n }\n buffer[index] = key;\n}\n\nint BinaryHeap::findMin() { return buffer[1]; }\n\nvoid BinaryHeap::remove(int index) {\n buffer[index] = buffer[size--];\n shiftDown(index);\n}\n\nvoid BinaryHeap::deleteMin() { remove(1); }\n\nint BinaryHeap::extractMin() {\n int min = findMin();\n remove(1);\n return min;\n}\n\nvoid updateKey(int index, int key) {\n if (compare(buffer[index], key)) { \/\/ buffer[index] < key\n \/\/ increasing\n buffer[index] = key;\n IterativeMaintenance(index);\n } else if (compare(key, buffer[index])) { \/\/ key < buffer[index]\n buffer[index] = key;\n \/\/ shift up\n int p = parent(index);\n while (p >= 1) {\n if (compare(buffer[p], buffer[index])) {\n \/\/ 满足堆性质\n break;\n }\n std::swap(buffer[p], buffer[index]);\n index = p;\n p = parent(p);\n }\n } else {\n \/\/ buffer[index] == key, do nothing\n }\n}\n\nvoid BinaryHeap::IterativeHeapify() {\n for (int i = size; i > 0; i--) {\n IterativeMaintenance(i);\n }\n}\n\nvoid BinaryHeap::IterativeMaintenance(int index) {\n \/\/ heapify the heap whose root is index\n while (true) {\n if (right(index) <= size) { \/\/ left < right <= size\n if (compare(buffer[left(index)], buffer[right(index)])) {\n if (!compare(buffer[index], buffer[left(index)])) {\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n } else {\n break;\n }\n } else {\n if (!compare(buffer[index], buffer[right(index)])) {\n std::swap(buffer[index], buffer[right(index)]);\n index = right(index);\n } else {\n break;\n }\n }\n } else if (left(index) <= size) { \/\/ left <= size < right\n if (!compare(buffer[index], buffer[left(index)])) {\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n \/\/ the next one must be leaf, so we can break it\n \/\/ break;\n } else {\n break;\n }\n } else { \/\/ size < left < right: leaf\n break;\n }\n }\n}FIX: BinaryHeap dependence\/*\n@title: BinaryHeap 二叉堆\n@description:\n 一个普通的二叉堆\n@structure:\n BinaryHeap:\n T *buffer: 数组首地址 - 1\n int size: 数组长度\n@dependence:\n bool compare(int a, int b); \/\/ 给出比较关系\n@note:\n 需要手动指定 buffer, size\n 指定 buffer 为 a[] 时 => buffer = a - 1;\n*\/\nstruct BinaryHeap {\n int *buffer;\n int size;\n \/\/ 转移函数 O(1)\n int parent(int index);\n int left(int index);\n int right(int index);\n \/\/ shiftDown\n \/\/ 对节点 n 进行下降操作\n \/\/ 将 buffer[n] 向下交换到叶子节点上。\n \/\/ 每次与孩子中较小的一个交换。 O(log(size))\n void shiftDown(int index);\n \/\/ insert\n \/\/ 插入元素 O(log(size))\n void insert(int key);\n \/\/ Find Min\n \/\/ 获取最小值 O(1)\n int findMin();\n \/\/ Remove\n \/\/ 删除 index 位置上的点 O(log(size))\n void remove(int index);\n \/\/ Delete Min\n \/\/ 删除最小值 O(log(size))\n void deleteMin();\n \/\/ Extract Min\n \/\/ 取最小值并弹出 O(log(size))\n int extractMin();\n \/\/ updateKey\n \/\/ 更新键值\n \/\/ shift down or shift up O(log(size))\n void updateKey(int index, int key);\n void IterativeMaintenance(int index);\n \/\/ 离线迭代建堆\n \/\/ Bottom-Up O(size)\n void IterativeHeapify();\n};\n\ninline int BinaryHeap::parent(int index) { return index >> 1; }\ninline int BinaryHeap::left(int index) { return index << 1; }\ninline int BinaryHeap::right(int index) { return (index << 1) + 1; }\n\nvoid BinaryHeap::shiftDown(int index) {\n while (true) {\n if (right(index) <= size) { \/\/ left(n) < right(n) <= size\n if (compare(buffer[left(index)], buffer[right(index)])) {\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n } else {\n std::swap(buffer[index], buffer[right(index)]);\n index = right(index);\n }\n } else if (left(index) <= size) { \/\/ left(n) <= size < right(n)\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n } else { \/\/ size < left(n) < right(n)\n break;\n }\n }\n}\n\nvoid BinaryHeap::insert(int key) {\n int index = ++size;\n while (index > 1 && compare(key, buffer[parent(index)])) {\n buffer[index] = buffer[parent(index)];\n index = parent(index);\n }\n buffer[index] = key;\n}\n\nint BinaryHeap::findMin() { return buffer[1]; }\n\nvoid BinaryHeap::remove(int index) {\n buffer[index] = buffer[size--];\n shiftDown(index);\n}\n\nvoid BinaryHeap::deleteMin() { remove(1); }\n\nint BinaryHeap::extractMin() {\n int min = findMin();\n remove(1);\n return min;\n}\n\nvoid updateKey(int index, int key) {\n if (compare(buffer[index], key)) { \/\/ buffer[index] < key\n \/\/ increasing\n buffer[index] = key;\n IterativeMaintenance(index);\n } else if (compare(key, buffer[index])) { \/\/ key < buffer[index]\n buffer[index] = key;\n \/\/ shift up\n int p = parent(index);\n while (p >= 1) {\n if (compare(buffer[p], buffer[index])) {\n \/\/ 满足堆性质\n break;\n }\n std::swap(buffer[p], buffer[index]);\n index = p;\n p = parent(p);\n }\n } else {\n \/\/ buffer[index] == key, do nothing\n }\n}\n\nvoid BinaryHeap::IterativeHeapify() {\n for (int i = size; i > 0; i--) {\n IterativeMaintenance(i);\n }\n}\n\nvoid BinaryHeap::IterativeMaintenance(int index) {\n \/\/ heapify the heap whose root is index\n while (true) {\n if (right(index) <= size) { \/\/ left < right <= size\n if (compare(buffer[left(index)], buffer[right(index)])) {\n if (!compare(buffer[index], buffer[left(index)])) {\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n } else {\n break;\n }\n } else {\n if (!compare(buffer[index], buffer[right(index)])) {\n std::swap(buffer[index], buffer[right(index)]);\n index = right(index);\n } else {\n break;\n }\n }\n } else if (left(index) <= size) { \/\/ left <= size < right\n if (!compare(buffer[index], buffer[left(index)])) {\n std::swap(buffer[index], buffer[left(index)]);\n index = left(index);\n \/\/ the next one must be leaf, so we can break it\n \/\/ break;\n } else {\n break;\n }\n } else { \/\/ size < left < right: leaf\n break;\n }\n }\n}<|endoftext|>"} {"text":"#define UNICODE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"FSAPI.h\"\n#include \"dictationbridge-core\/master\/master.h\"\n#include \"combool.h\"\n\n#pragma comment(lib, \"ole32.lib\")\n#pragma comment(lib, \"oleacc.lib\")\n\n\n#define ERR(x, msg) do { \\\nif(x != S_OK) {\\\nMessageBox(NULL, msg L\"\\n\", NULL, NULL);\\\nexit(1);\\\n}\\\n} while(0)\n\nCComPtr pJfw =nullptr;\n\nvoid initSpeak() {\n\tCLSID JFWClass;\n\tauto res = CLSIDFromProgID(L\"FreedomSci.JawsApi\", &JFWClass);\n\tERR(res, L\"Couldn't get Jaws interface ID\");\nres =pJfw.CoCreateInstance(JFWClass);\n\tERR(res, L\"Couldn't create Jaws interface\");\n}\n\nvoid speak(std::wstring text) {\nCComBSTR bS =CComBSTR(text.size(), text.data());\nCComBool silence =false;\nCComBool bResult;\n\tpJfw->SayString(bS, silence, &bResult);\n}\n\nvoid WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {\n\t\/\/We need to replace \\r with nothing.\nstd::wstring text =textUnprocessed;\ntext.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) {\n\t\treturn checkingCharacter == '\\r';\n\t}), end(text));\n\n\tif(text.compare(L\"\\n\\n\") ==0 \n|| text.compare(L\"\") ==0 \/\/new paragraph in word.\n\t) {\n\t\tspeak(L\"New paragraph.\");\n\t}\n\telse if(text.compare(L\"\\n\") ==0) {\n\t\tspeak(L\"New line.\");\n\t}\n\telse {\nspeak(text.c_str());\n}\n}\n\nvoid WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {\nstd::wstringstream deletedText;\ndeletedText << \"Deleted \";\ndeletedText << text;\n\tspeak(deletedText.str().c_str());\n}\n\n\/\/These are string constants for the microphone status, as well as the status itself:\n\/\/The pointer below is set to the last one we saw.\nstd::wstring MICROPHONE_OFF = L\"Dragon's microphone is off;\";\nstd::wstring MICROPHONE_ON = L\"Normal mode: You can dictate and use voice\";\nstd::wstring MICROPHONE_SLEEPING = L\"The microphone is asleep;\";\n\nstd::wstring microphoneState;\n\nvoid announceMicrophoneState(const std::wstring state) {\n\tif(state == MICROPHONE_ON) speak(L\"Microphone on.\");\n\telse if(state == MICROPHONE_OFF) speak(L\"Microphone off.\");\n\telse if(state == MICROPHONE_SLEEPING) speak(L\"Microphone sleeping.\");\n\telse speak(L\"Microphone in unknown state.\");\n}\n\nwchar_t processNameBuffer[1024] = {0};\n\nvoid CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {\n\t\/\/First, is it coming from natspeak.exe?\n\tDWORD procId;\n\tGetWindowThreadProcessId(hwnd, &procId);\n\tauto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);\n\t\/\/We can't recover from this failing, so abort.\n\tif(procHandle == NULL) return;\n\tDWORD len = 1024;\n\tauto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);\n\tCloseHandle(procHandle);\n\tif(res == 0) return;\nstd::wstring processName =processNameBuffer;\n\tif(processName.find(L\"dragonbar.exe\") == std::string::npos\n\t\t&& processName.find(L\"natspeak.exe\") == std::string::npos) return;\n\t\/\/Attempt to get the new text.\nCComPtr pAcc;\nCComVariant vChild;\n\tHRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &vChild);\n\tif(hres != S_OK) return;\nCComBSTR bName;\n\thres = pAcc->get_accName(vChild, &bName);\n\tif(hres != S_OK) return;\nstd::wstring name =bName;\n\tconst std::wstring possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};\nstd::wstring newState = microphoneState;\n\tfor(int i = 0; i < 3; i++) {\n\t\tif(name.find(possibles[i]) != std::string::npos) {\n\t\t\tnewState = possibles[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(newState != microphoneState) {\n\t\tannounceMicrophoneState(newState);\n\t\tmicrophoneState = newState;\n\t}\n}\n\nint keepRunning = 1; \/\/ Goes to 0 on WM_CLOSE.\nLPCTSTR msgWindowClassName = L\"DictationBridgeJFWHelper\";\n\nLRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) {\n\tif(msg == WM_CLOSE) keepRunning = 0;\n\treturn DefWindowProc(hwnd, msg, wparam, lparam);\n}\n\nint CALLBACK WinMain(_In_ HINSTANCE hInstance,\n\t_In_ HINSTANCE hPrevInstance,\n\t_In_ LPSTR lpCmdLine,\n\t_In_ int nCmdShow) {\n\t\/\/ First, is a core running?\n\tif(FindWindow(msgWindowClassName, NULL)) {\n\t\tMessageBox(NULL, L\"Core already running.\", NULL, NULL);\n\t\treturn 0;\n\t}\n\tWNDCLASS windowClass = {0};\n\twindowClass.lpfnWndProc = exitProc;\n\twindowClass.hInstance = hInstance;\n\twindowClass.lpszClassName = msgWindowClassName;\n\tauto msgWindowClass = RegisterClass(&windowClass);\n\tif(msgWindowClass == 0) {\n\t\tMessageBox(NULL, L\"Failed to register window class.\", NULL, NULL);\n\t\treturn 0;\n\t}\n\tauto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);\n\tif(msgWindowHandle == 0) {\n\t\tMessageBox(NULL, L\"Failed to create message-only window.\", NULL, NULL);\n\t\treturn 0;\n\t}\n\tHRESULT res;\n\tres = OleInitialize(NULL);\n\tERR(res, L\"Couldn't initialize OLE\");\n\tinitSpeak();\n\tauto started = DBMaster_Start();\n\tif(!started) {\n\t\tprintf(\"Couldn't start DictationBridge-core\\n\");\n\t\treturn 1;\n\t}\n\tDBMaster_SetTextInsertedCallback(textCallback);\n\tDBMaster_SetTextDeletedCallback(textDeletedCallback);\n\tif(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {\n\t\tprintf(\"Couldn't register to receive events\\n\");\n\t\treturn 1;\n\t}\n\tMSG msg;\n\twhile(GetMessage(&msg, NULL, NULL, NULL) > 0) {\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t\tif(keepRunning == 0) break;\n\t}\n\tDBMaster_Stop();\n\tOleUninitialize();\n\tDestroyWindow(msgWindowHandle);\n\treturn 0;\n}\nAdd notification when dragon hasn't understood the dictation.#define UNICODE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"FSAPI.h\"\n#include \"dictationbridge-core\/master\/master.h\"\n#include \"combool.h\"\n\n#pragma comment(lib, \"ole32.lib\")\n#pragma comment(lib, \"oleacc.lib\")\n\n\n#define ERR(x, msg) do { \\\nif(x != S_OK) {\\\nMessageBox(NULL, msg L\"\\n\", NULL, NULL);\\\nexit(1);\\\n}\\\n} while(0)\n\nCComPtr pJfw =nullptr;\n\nvoid initSpeak() {\n\tCLSID JFWClass;\n\tauto res = CLSIDFromProgID(L\"FreedomSci.JawsApi\", &JFWClass);\n\tERR(res, L\"Couldn't get Jaws interface ID\");\nres =pJfw.CoCreateInstance(JFWClass);\n\tERR(res, L\"Couldn't create Jaws interface\");\n}\n\nvoid speak(std::wstring text) {\nCComBSTR bS =CComBSTR(text.size(), text.data());\nCComBool silence =false;\nCComBool bResult;\n\tpJfw->SayString(bS, silence, &bResult);\n}\n\nvoid WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {\n\t\/\/We need to replace \\r with nothing.\nstd::wstring text =textUnprocessed;\ntext.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) {\n\t\treturn checkingCharacter == '\\r';\n\t}), end(text));\n\n\tif(text.compare(L\"\\n\\n\") ==0 \n|| text.compare(L\"\") ==0 \/\/new paragraph in word.\n\t) {\n\t\tspeak(L\"New paragraph.\");\n\t}\n\telse if(text.compare(L\"\\n\") ==0) {\n\t\tspeak(L\"New line.\");\n\t}\n\telse {\nspeak(text.c_str());\n}\n}\n\nvoid WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {\nstd::wstringstream deletedText;\ndeletedText << \"Deleted \";\ndeletedText << text;\n\tspeak(deletedText.str().c_str());\n}\n\n\/\/These are string constants for the microphone status, as well as the status itself:\n\/\/The pointer below is set to the last one we saw.\nstd::wstring MICROPHONE_OFF = L\"Dragon's microphone is off;\";\nstd::wstring MICROPHONE_ON = L\"Normal mode: You can dictate and use voice\";\nstd::wstring MICROPHONE_SLEEPING = L\"The microphone is asleep;\";\n\nstd::wstring microphoneState;\n\/\/This is a constant for the text indicating dragon hasn't understood what a user has dictated.\nconst std::wstring DictationWasNotUnderstood =L\"\";\n\nvoid announceMicrophoneState(const std::wstring state) {\n\tif(state == MICROPHONE_ON) speak(L\"Microphone on.\");\n\telse if(state == MICROPHONE_OFF) speak(L\"Microphone off.\");\n\telse if(state == MICROPHONE_SLEEPING) speak(L\"Microphone sleeping.\");\n\telse speak(L\"Microphone in unknown state.\");\n}\n\nwchar_t processNameBuffer[1024] = {0};\n\nvoid CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {\n\t\/\/First, is it coming from natspeak.exe?\n\tDWORD procId;\n\tGetWindowThreadProcessId(hwnd, &procId);\n\tauto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);\n\t\/\/We can't recover from this failing, so abort.\n\tif(procHandle == NULL) return;\n\tDWORD len = 1024;\n\tauto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);\n\tCloseHandle(procHandle);\n\tif(res == 0) return;\nstd::wstring processName =processNameBuffer;\n\tif(processName.find(L\"dragonbar.exe\") == std::string::npos\n\t\t&& processName.find(L\"natspeak.exe\") == std::string::npos) return;\n\t\/\/Attempt to get the new text.\nCComPtr pAcc;\nCComVariant vChild;\n\tHRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &vChild);\n\tif(hres != S_OK) return;\nCComBSTR bName;\n\thres = pAcc->get_accName(vChild, &bName);\n\tif(hres != S_OK) return;\nstd::wstring name =bName;\n\/\/check to see whether Dragon understood the user.\nif (name .compare(DictationWasNotUnderstood) ==0)\n{\nspeak(L\"I do not understand.\");\nreturn;\n}\n\tconst std::wstring possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};\nstd::wstring newState = microphoneState;\n\tfor(int i = 0; i < 3; i++) {\n\t\tif(name.find(possibles[i]) != std::string::npos) {\n\t\t\tnewState = possibles[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(newState != microphoneState) {\n\t\tannounceMicrophoneState(newState);\n\t\tmicrophoneState = newState;\n\t}\n}\n\nint keepRunning = 1; \/\/ Goes to 0 on WM_CLOSE.\nLPCTSTR msgWindowClassName = L\"DictationBridgeJFWHelper\";\n\nLRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) {\n\tif(msg == WM_CLOSE) keepRunning = 0;\n\treturn DefWindowProc(hwnd, msg, wparam, lparam);\n}\n\nint CALLBACK WinMain(_In_ HINSTANCE hInstance,\n\t_In_ HINSTANCE hPrevInstance,\n\t_In_ LPSTR lpCmdLine,\n\t_In_ int nCmdShow) {\n\t\/\/ First, is a core running?\n\tif(FindWindow(msgWindowClassName, NULL)) {\n\t\tMessageBox(NULL, L\"Core already running.\", NULL, NULL);\n\t\treturn 0;\n\t}\n\tWNDCLASS windowClass = {0};\n\twindowClass.lpfnWndProc = exitProc;\n\twindowClass.hInstance = hInstance;\n\twindowClass.lpszClassName = msgWindowClassName;\n\tauto msgWindowClass = RegisterClass(&windowClass);\n\tif(msgWindowClass == 0) {\n\t\tMessageBox(NULL, L\"Failed to register window class.\", NULL, NULL);\n\t\treturn 0;\n\t}\n\tauto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);\n\tif(msgWindowHandle == 0) {\n\t\tMessageBox(NULL, L\"Failed to create message-only window.\", NULL, NULL);\n\t\treturn 0;\n\t}\n\tHRESULT res;\n\tres = OleInitialize(NULL);\n\tERR(res, L\"Couldn't initialize OLE\");\n\tinitSpeak();\n\tauto started = DBMaster_Start();\n\tif(!started) {\n\t\tprintf(\"Couldn't start DictationBridge-core\\n\");\n\t\treturn 1;\n\t}\n\tDBMaster_SetTextInsertedCallback(textCallback);\n\tDBMaster_SetTextDeletedCallback(textDeletedCallback);\n\tif(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {\n\t\tprintf(\"Couldn't register to receive events\\n\");\n\t\treturn 1;\n\t}\n\tMSG msg;\n\twhile(GetMessage(&msg, NULL, NULL, NULL) > 0) {\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t\tif(keepRunning == 0) break;\n\t}\n\tDBMaster_Stop();\n\tOleUninitialize();\n\tDestroyWindow(msgWindowHandle);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"kernel.h\"\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"rasterinterpolator.h\"\n#include \"resampleraster.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nREGISTER_OPERATION(ResampleRaster)\n\nIlwis::OperationImplementation *ResampleRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new ResampleRaster(metaid, expr);\n}\n\nResampleRaster::ResampleRaster()\n{\n}\n\nResampleRaster::ResampleRaster(quint64 metaid, const Ilwis::OperationExpression &expr) :\n OperationImplementation(metaid, expr),\n _method(RasterInterpolator::ipBICUBIC)\n{\n}\n\nbool ResampleRaster::execute(ExecutionContext *ctx, SymbolTable& symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx,symTable)) != sPREPARED)\n return false;\n IRasterCoverage outputRaster = _outputObj.as();\n IRasterCoverage inputRaster = _inputObj.as();\n SPTranquilizer trq = kernel()->createTrq(\"resample\", \"\", outputRaster->size().ysize(),1);\n\n BoxedAsyncFunc resampleFun = [&](const BoundingBox& box) -> bool {\n PixelIterator iterOut(outputRaster,box);\n iterOut.setTranquilizer(trq);\n RasterInterpolator interpolator(inputRaster, _method);\n PixelIterator iterEnd = iterOut.end();\n bool equalCsy = inputRaster->coordinateSystem()->isEqual(outputRaster->coordinateSystem().ptr());\n while(iterOut != iterEnd) {\n Pixel position = iterOut.position();\n Coordinate coord = outputRaster->georeference()->pixel2Coord(Pixeld(position.x,(position.y)));\n if ( !equalCsy)\n coord = inputRaster->coordinateSystem()->coord2coord(outputRaster->coordinateSystem(),coord);\n *iterOut = interpolator.coord2value(coord, iterOut.position().z);\n ++iterOut;\n }\n return true;\n };\n\n bool resource = OperationHelperRaster::execute(ctx, resampleFun, outputRaster);\n\n if ( resource && ctx != 0) {\n QVariant value;\n value.setValue(outputRaster);\n ctx->setOutput(symTable,value,outputRaster->name(), itRASTER, outputRaster->source() );\n }\n return resource;\n}\n\nIlwis::OperationImplementation::State ResampleRaster::prepare(ExecutionContext *, const SymbolTable & )\n{\n QString raster = _expression.parm(0).value();\n QString outputName = _expression.parm(0,false).value();\n\n if (!_inputObj.prepare(raster, itRASTER)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,raster,\"\");\n return sPREPAREFAILED;\n }\n _outputObj = OperationHelperRaster::initialize(_inputObj,itRASTER, itDOMAIN);\n if ( !_outputObj.isValid()) {\n ERROR1(ERR_NO_INITIALIZED_1, \"output rastercoverage\");\n return sPREPAREFAILED;\n }\n IGeoReference grf;\n grf.prepare(_expression.parm(1).value());\n if ( !grf.isValid()) {\n return sPREPAREFAILED;\n }\n IRasterCoverage outputRaster = _outputObj.as();\n outputRaster->georeference(grf);\n Size<> sz = grf->size();\n if ( sz.isNull()){\n ERROR1(ERR_NO_INITIALIZED_1, \"output georeference\");\n return sPREPAREFAILED;\n }\n sz.zsize(_inputObj.as()->size().zsize());\n outputRaster->size(sz);\n Envelope env = grf->pixel2Coord(grf->size());\n outputRaster->envelope(env);\n if ( outputName != sUNDEF)\n outputRaster->name(outputName);\n\n QString method = _expression.parm(2).value();\n if ( method.toLower() == \"nearestneighbour\")\n _method = RasterInterpolator::ipNEARESTNEIGHBOUR;\n else if ( method.toLower() == \"bilinear\")\n _method = RasterInterpolator::ipBILINEAR;\n else if ( method.toLower() == \"bicubic\")\n _method =RasterInterpolator::ipBICUBIC;\n else {\n ERROR3(ERR_ILLEGAL_PARM_3,\"method\",method,\"resample\");\n return sPREPAREFAILED;\n }\n\n return sPREPARED;\n}\n\nquint64 ResampleRaster::createMetadata()\n{\n\n OperationResource operation({\"ilwis:\/\/operations\/resample\"});\n operation.setSyntax(\"resample(inputgridcoverage,targetgeoref,nearestneighbour|bilinear|bicubic)\");\n operation.setDescription(TR(\"translates a rastercoverage from one geometry (coordinatesystem+georeference) to another\"));\n operation.setInParameterCount({3});\n operation.addInParameter(0,itRASTER, TR(\"input rastercoverage\"),TR(\"input rastercoverage with domain any domain\"));\n operation.addInParameter(1,itGEOREF, TR(\"target georeference\"),TR(\"the georeference to which the input coverage will be morphed\"));\n operation.addInParameter(2,itSTRING, TR(\"Resampling method\"),TR(\"The method used to aggregate pixels from the input map in the geometry of the output map\") );\n operation.setOutParameterCount({1});\n operation.addOutParameter(0,itRASTER, TR(\"output rastercoverage\"), TR(\"output rastercoverage with the domain of the input map\"));\n operation.setKeywords(\"raster, geometry, transformation\");\n\n mastercatalog()->addItems({operation});\n return operation.id();\n}\n\n\ngenerates an error message when trying to use csy unknown for a resample#include \n#include \n#include \"kernel.h\"\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"rasterinterpolator.h\"\n#include \"resampleraster.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nREGISTER_OPERATION(ResampleRaster)\n\nIlwis::OperationImplementation *ResampleRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new ResampleRaster(metaid, expr);\n}\n\nResampleRaster::ResampleRaster()\n{\n}\n\nResampleRaster::ResampleRaster(quint64 metaid, const Ilwis::OperationExpression &expr) :\n OperationImplementation(metaid, expr),\n _method(RasterInterpolator::ipBICUBIC)\n{\n}\n\nbool ResampleRaster::execute(ExecutionContext *ctx, SymbolTable& symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx,symTable)) != sPREPARED)\n return false;\n IRasterCoverage outputRaster = _outputObj.as();\n IRasterCoverage inputRaster = _inputObj.as();\n SPTranquilizer trq = kernel()->createTrq(\"resample\", \"\", outputRaster->size().ysize(),1);\n\n BoxedAsyncFunc resampleFun = [&](const BoundingBox& box) -> bool {\n PixelIterator iterOut(outputRaster,box);\n iterOut.setTranquilizer(trq);\n RasterInterpolator interpolator(inputRaster, _method);\n PixelIterator iterEnd = iterOut.end();\n bool equalCsy = inputRaster->coordinateSystem()->isEqual(outputRaster->coordinateSystem().ptr());\n while(iterOut != iterEnd) {\n Pixel position = iterOut.position();\n Coordinate coord = outputRaster->georeference()->pixel2Coord(Pixeld(position.x,(position.y)));\n if ( !equalCsy)\n coord = inputRaster->coordinateSystem()->coord2coord(outputRaster->coordinateSystem(),coord);\n *iterOut = interpolator.coord2value(coord, iterOut.position().z);\n ++iterOut;\n }\n return true;\n };\n\n bool resource = OperationHelperRaster::execute(ctx, resampleFun, outputRaster);\n\n if ( resource && ctx != 0) {\n QVariant value;\n value.setValue(outputRaster);\n ctx->setOutput(symTable,value,outputRaster->name(), itRASTER, outputRaster->source() );\n }\n return resource;\n}\n\nIlwis::OperationImplementation::State ResampleRaster::prepare(ExecutionContext *, const SymbolTable & )\n{\n QString raster = _expression.parm(0).value();\n QString outputName = _expression.parm(0,false).value();\n\n if (!_inputObj.prepare(raster, itRASTER)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,raster,\"\");\n return sPREPAREFAILED;\n }\n _outputObj = OperationHelperRaster::initialize(_inputObj,itRASTER, itDOMAIN);\n if ( !_outputObj.isValid()) {\n ERROR1(ERR_NO_INITIALIZED_1, \"output rastercoverage\");\n return sPREPAREFAILED;\n }\n IGeoReference grf;\n grf.prepare(_expression.parm(1).value());\n if ( !grf.isValid()) {\n return sPREPAREFAILED;\n }\n IRasterCoverage outputRaster = _outputObj.as();\n outputRaster->georeference(grf);\n Size<> sz = grf->size();\n if ( sz.isNull()){\n ERROR1(ERR_NO_INITIALIZED_1, \"output georeference\");\n return sPREPAREFAILED;\n }\n sz.zsize(_inputObj.as()->size().zsize());\n outputRaster->size(sz);\n Envelope env = grf->pixel2Coord(grf->size());\n outputRaster->envelope(env);\n if ( outputName != sUNDEF)\n outputRaster->name(outputName);\n\n if ( outputRaster->coordinateSystem()->code() == \"unknown\" || _inputObj.as()->coordinateSystem()->code() == \"unknown\"){\n ERROR2(ERR_OPERATION_NOTSUPPORTED2,\"resample\",\"coordinatesystem unknown\");\n return sPREPAREFAILED;\n }\n\n QString method = _expression.parm(2).value();\n if ( method.toLower() == \"nearestneighbour\")\n _method = RasterInterpolator::ipNEARESTNEIGHBOUR;\n else if ( method.toLower() == \"bilinear\")\n _method = RasterInterpolator::ipBILINEAR;\n else if ( method.toLower() == \"bicubic\")\n _method =RasterInterpolator::ipBICUBIC;\n else {\n ERROR3(ERR_ILLEGAL_PARM_3,\"method\",method,\"resample\");\n return sPREPAREFAILED;\n }\n\n return sPREPARED;\n}\n\nquint64 ResampleRaster::createMetadata()\n{\n\n OperationResource operation({\"ilwis:\/\/operations\/resample\"});\n operation.setSyntax(\"resample(inputgridcoverage,targetgeoref,nearestneighbour|bilinear|bicubic)\");\n operation.setDescription(TR(\"translates a rastercoverage from one geometry (coordinatesystem+georeference) to another\"));\n operation.setInParameterCount({3});\n operation.addInParameter(0,itRASTER, TR(\"input rastercoverage\"),TR(\"input rastercoverage with domain any domain\"));\n operation.addInParameter(1,itGEOREF, TR(\"target georeference\"),TR(\"the georeference to which the input coverage will be morphed\"));\n operation.addInParameter(2,itSTRING, TR(\"Resampling method\"),TR(\"The method used to aggregate pixels from the input map in the geometry of the output map\") );\n operation.setOutParameterCount({1});\n operation.addOutParameter(0,itRASTER, TR(\"output rastercoverage\"), TR(\"output rastercoverage with the domain of the input map\"));\n operation.setKeywords(\"raster, geometry, transformation\");\n\n mastercatalog()->addItems({operation});\n return operation.id();\n}\n\n\n<|endoftext|>"} {"text":"\/\/====== Graph Benchmark Suites ======\/\/\n\/\/========== Shortest Path ===========\/\/\n\/\/ \n\/\/ Single-source shortest path\n\/\/ \n\/\/ Usage: .\/sssp --dataset \n\/\/ --root \n\/\/ --target \n\n#include \"common.h\"\n#include \"def.h\"\n#include \"openG.h\"\n#include \"omp.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#ifdef HMC\n#include \"HMC.h\"\n#endif\n\n#ifdef SIM\n#include \"SIM.h\"\n#endif\n\n\/\/#define VERIFY_RESULTS \/\/ if compare serial results with parallel results\n#define MY_INFINITY 0xfff0 \/\/ for unsigned i.e., 65520\n\nsize_t beginiter = 0;\nsize_t enditer = 0;\n\ntypedef pair pair_IntFlt; \/\/ \/\/typedef pair pair_IntFlt; \/\/\ntypedef pair pair_FltInt; \/\/ \/\/typedef pair pair_IntFlt; \/\/\ntypedef pair pair_IntInt; \/\/ \/\/typedef pair pair_IntFlt; \/\/\n\nclass vertex_property \/\/ new\n{\npublic: \/\/ sum_distance(0),sum_hops(0){}\n vertex_property():min_cost(FLT_MAX),successor(MY_INFINITY),sum_distance(FLT_MAX),sum_hops(MY_INFINITY),weight(FLT_MAX),occurrence(0){}\n float min_cost; \/\/ for shortest path\n \/\/ predecessor; \/\/ for shortest path successor,\n uint64_t successor; \/\/ for shortest path \n float sum_distance; \/\/ new\n uint64_t sum_hops; \/\/ new \n\tfloat weight; \/\/ new\n\tuint64_t occurrence; \/\/ new\n\t\n vector sorted_edges_of_vertex; \/\/ pair: id (outedge), reduced_cost\n};\n\nclass edge_property \/\/ new\n{\npublic:\n edge_property():cost(FLT_MAX),phy_dist(FLT_MAX),reduced_cost(FLT_MAX){} \/\/ new: Note: \n\n float cost; \/\/ note: here cost means cost\n float phy_dist; \/\/new\n\n float reduced_cost; \/\/ \n};\n\ntypedef openG::extGraph graph_t;\ntypedef graph_t::vertex_iterator vertex_iterator;\ntypedef graph_t::edge_iterator edge_iterator;\n\n\nvoid reset_graph(graph_t & g)\n{\n vertex_iterator vit;\n for (vit=g.vertices_begin(); vit!=g.vertices_end(); vit++)\n {\n vit->property().min_cost = FLT_MAX;\n vit->property().successor = MY_INFINITY;\n vit->property().sum_distance = FLT_MAX;\n vit->property().sum_hops = MY_INFINITY;\n\t\tvit->property().weight = FLT_MAX;\n\t\tvit->property().occurrence = 0;\n vit->property().sorted_edges_of_vertex.clear();\n\n for (edge_iterator eit = vit->in_edges_begin(); eit != vit->in_edges_end(); eit++) \/\/ new for in edge\n {\n eit->property().reduced_cost = FLT_MAX;\n }\n }\n}\n\n\nclass vertex_property_tau \n{\npublic: \n vertex_property_tau():at_KSPaths(false),predecessor(MY_INFINITY),internel_id_of_g(MY_INFINITY),min_cost(0),sum_distance(0),sum_hops(0),weight(0),occurrence(0){}\n\n bool at_KSPaths; \/\/vector KSPaths_record;\n uint64_t predecessor; \/\/ for shortest path, store the id of the graph tau\n uint64_t internel_id_of_g; \/\/ internel id of orginal graph g\n\n float min_cost; \/\/ for shortest path\n float sum_distance; \/\/ for shortest path\n size_t sum_hops; \/\/ for shortest path\n\tfloat weight; \/\/ for shortest path\n\tuint64_t occurrence; \/\/ counting the occurrence of a node\n};\n\n\nclass edge_property_tau \/\/ new\n{\npublic:\n edge_property_tau(){} \/\/edge_property_tau():cost(FLT_MAX),phy_dist(FLT_MAX),reduced_cost(FLT_MAX){} \n \/\/float cost; \n \/\/float phy_dist;\n};\n\ntypedef openG::extGraph graph_tau;\ntypedef graph_tau::vertex_iterator vertex_iterator_tau;\ntypedef graph_tau::edge_iterator edge_iterator_tau;\n\n\nclass min_comp_IntFlt\n{\npublic:\n bool operator()(pair_IntFlt a, pair_IntFlt b)\n {\n return a.second > b.second;\n }\n};\n\nclass min_comp_FltInt\n{\npublic:\n bool operator()(pair_FltInt a, pair_FltInt b)\n {\n return a.first > b.first;\n }\n};\n\n\n#ifdef TOPKSP_DEBUG\n template \n void displayVectorOrListContents(const T& input)\n {\n for (auto idx = input.cbegin(); idx != input.cend(); ++ idx)\n {\n cout << *idx << \",\";\n }\n cout << endl;\n }\n template \n void displayVectorOrListOfPairContents(const T& input) \n {\n for (auto idx = input.cbegin(); idx != input.cend(); ++ idx)\n {\n cout << \"(\" << idx->first << \",\" << idx->second << \")\" << \",\";\n }\n cout << endl;\n }\n\n\n void output_shorest_path(graph_t& g, size_t src, size_t dest) \/\/for test, src and dest is exID, dest is the input dest of top_ksp func.\n {\n cout<<\"the shortest path is: \";\n uint64_t internel_dest = g.external_to_internel_id(to_string(dest)); \n uint64_t curr_id_g = g.external_to_internel_id(to_string(src)); \n\n uint64_t curr_exID = src;\n cout<property().successor; \n\n if (curr_exID==289)\n {\n cout<<\"curr_id_g=\"<\"<\"<property().internel_id_of_g == src_id_g); \/\/ this is a require for the following code to work\n\n uint64_t tau_tmp_id = start_id_tau;\n src_vit_g = g.find_vertex(src_id_g); \n while (src_vit_g->id() != dest_id_g) \/\/ note: dest_id_g should be the internel_dest\n {\n dest_vit_g = g.find_vertex( src_vit_g->property().successor ); \/\/ new, ori is predecessor\n\n\n \/\/cout << \"src_vit_g->id()= \" << src_vit_g->id() << endl;\n \/\/cout << \"dest_vit_g->id()= \" << dest_vit_g->id() << endl;\n bool find_result = g.find_out_edge_2id(src_vit_g->id(), dest_vit_g->id(), eit_g); \/\/ for eit_g->property().cost and eit_g->property().phy_dist\n assert(find_result);\n\n\n \/\/ add point and edge at tau\n dest_vit_tau = tau.add_vertex();\n dest_vit_tau->property().at_KSPaths = false;\/\/ \n dest_vit_tau->property().predecessor = tau_tmp_id; \/\/ \n dest_vit_tau->property().internel_id_of_g = dest_vit_g->id(); \n dest_vit_tau->property().min_cost = src_vit_tau->property().min_cost + eit_g->property().cost; \/\/ \n dest_vit_tau->property().sum_distance = src_vit_tau->property().sum_distance + eit_g->property().phy_dist; \/\/ \n dest_vit_tau->property().sum_hops = src_vit_tau->property().sum_hops + 1;\n\t\tdest_vit_tau->property().occurrence = dest_vit_g->property().occurrence;\n\t\t\n\t\tunsigned int alpha_occur = (dest_vit_tau->property().occurrence > 7000) ? int(alpha*10) : int(alpha*10);\n\t\tdest_vit_tau->property().weight = dest_vit_tau->property().min_cost + dest_vit_tau->property().sum_hops*alpha + dest_vit_tau->property().occurrence*alpha_occur; \/\/weight\n\t\t\n\n \/\/cout<<\"the new added node (idx_g,idx_tau) in Tau is (\"<property().internel_id_of_g<<\",\"<id()<<\")\"<property().min_cost<<\",\"<property().sum_distance<<\",\"<property().sum_hops<<\")\";\n \/\/cout<id(),dest_vit_tau->id(),eit_tau); \/\/ note: put all info at vertex, see dest_vit_tau\n \n \/\/new \n \/\/\/\/if (dest_vit_tau->property().sum_distance >= max_phy_dist || dest_vit_tau->property().sum_hops >= max_phy_hops)\n \/\/\/\/ this following is only for single-layer real data\n if (dest_vit_tau->property().sum_hops >= max_phy_hops)\n break;\n\n \/\/ for next iteration use\n tau_tmp_id = dest_vit_tau->id(); \n src_vit_g = dest_vit_g; \n src_vit_tau = dest_vit_tau; \n }\n return dest_vit_tau;\n}\n\nbool is_loopless_path(graph_t& g, graph_tau& tau, size_t path_last_id_tau, size_t path_first_id_tau)\/\/based on sorted vector\n{\n size_t tmpId = path_last_id_tau; \n vertex_iterator_tau vit_tau_tmp = tau.find_vertex(tmpId); \n\n vector path_id_set_g; \n path_id_set_g.push_back( vit_tau_tmp->property().internel_id_of_g );\n while (tmpId != path_first_id_tau)\n {\n tmpId = vit_tau_tmp->property().predecessor; \n vit_tau_tmp = tau.find_vertex(tmpId);\n path_id_set_g.push_back( vit_tau_tmp->property().internel_id_of_g );\n }\n sort(path_id_set_g.begin(), path_id_set_g.end());\n return adjacent_find(path_id_set_g.begin(), path_id_set_g.end()) == path_id_set_g.end();\n}\n\n\nvoid top_ksp_subFun(bool trueMinCost, size_t trueMinCost_Iter, size_t& curr_kValue, ofstream& myfile, \\\ngraph_t& g, size_t src, size_t dest, size_t Kvalue, double max_phy_dist, size_t max_phy_hops, \\\nsize_t min_phy_hops, size_t alpha, unordered_set& paths) \/\/ src and dest are exID\n{\n uint64_t internel_src = g.external_to_internel_id(to_string(src)); \n uint64_t internel_dest = g.external_to_internel_id(to_string(dest)); \n\n\n \/\/\/\/ Now all processing is based on internel id first.\n \/\/\/\/ (1) sssp sub-procedure -->for vertex: update v_vit->property().min_cost and v_vit->property().successor \n priority_queue, min_comp_IntFlt> PQ;\n\n vertex_iterator dest_vit = g.find_vertex(internel_dest); \/\/ note: here the source of sssp is internel_dest, \n dest_vit->property().min_cost = 0;\n dest_vit->property().sum_hops = 0; \/\/ new\n dest_vit->property().sum_distance = 0; \/\/ new\n\tdest_vit->property().weight = 0; \/\/ new\n\t\/\/dest_vit->property().occurrence = dest_vit->property().occurrence; \/\/ new\n\t\n PQ.push(pair_IntFlt(internel_dest,0));\n\n \/\/ vit->property().successor is used to construct sssp, where the ancestor of all nodes is internel_dest, \n \/\/ by using vit->property().successor recursively, we can find the shortest path of any node to internel_dest\n while (!PQ.empty()) \/\/ sum_distance sum_hops\n {\n size_t u = PQ.top().first; \/\/id\n PQ.pop();\n\n vertex_iterator u_vit = g.find_vertex(u);\n for (edge_iterator eit = u_vit->in_edges_begin(); eit != u_vit->in_edges_end(); eit++) \/\/ new for in edge\n {\n size_t v = eit->target();\n vertex_iterator v_vit = g.find_vertex(v);\n\n \/\/ for every vertex, try relaxing the path\n if (trueMinCost)\n {\n float alt = u_vit->property().min_cost + eit->property().cost; \/\/ \n if (alt < v_vit->property().min_cost) \n {\n v_vit->property().successor = u; \/\/ new, ori is predecessor\n v_vit->property().min_cost = alt; \n v_vit->property().sum_hops = u_vit->property().sum_hops + 1; \n v_vit->property().sum_distance = u_vit->property().sum_distance + eit->property().phy_dist; \n PQ.push(pair_IntFlt(v,alt));\n }\n }\n else\n {\n \/\/ min_cost -- sum_hops exchange\n unsigned int alt = u_vit->property().sum_hops + 1; \/\/ \n\t\t\t\tfloat alt_cost = u_vit->property().min_cost + eit->property().cost; \/\/ \n\t\t\t\tunsigned int occur = v_vit->property().occurrence;\n\t\t\t\t\n\t\t\t\tunsigned int alpha_occur = (occur > 7000) ? int(alpha*10) : int(alpha*10);\n\t\t\t\tunsigned int weight = alt*alpha + alt_cost + occur*alpha_occur;\n\t\t\t\t\n \/\/if (alt < v_vit->property().sum_hops) \n\t\t\t\tif (weight < v_vit->property().weight) \n {\n v_vit->property().successor = u; \/\/ new, ori is predecessor\n v_vit->property().sum_hops = alt; \n v_vit->property().min_cost = u_vit->property().min_cost + eit->property().cost; \n v_vit->property().sum_distance = u_vit->property().sum_distance + eit->property().phy_dist; \n\t\t\t\t\tv_vit->property().weight = weight;\n\t\t\t\t\t\n PQ.push(pair_IntFlt(v,weight));\n }\n }\n\n }\n }\n\n \/\/\/\/(2) reduced_cost computing procedure -->for edge: update eit->property().reduced_cost\n \/\/\/\/(3) rearrange the arcs\n for (vertex_iterator u_vit=g.vertices_begin(); u_vit!=g.vertices_end(); u_vit++) \/\/ for each vertex u\n {\n for (edge_iterator eit = u_vit->edges_begin(); eit != u_vit->edges_end(); eit++) \/\/ for each outedge u->v from vertex u\n {\n size_t v = eit->target();\n vertex_iterator v_vit = g.find_vertex(v);\n\n float reduced_cost;\n if (trueMinCost)\n {\n reduced_cost= v_vit->property().min_cost - u_vit->property().min_cost + eit->property().cost;\n }\n else\n {\n \/\/reduced_cost = v_vit->property().sum_hops - u_vit->property().sum_hops + 1; \/\/ min_cost -- sum_hops exchange\n\t\t\t\tunsigned int hops_gap = v_vit->property().sum_hops - u_vit->property().sum_hops + 1; \n\t\t\t\t\/\/generalized reduced_cost = edge_weight + edge_cost\/alpha + alpha*(num_hops=1) + dest_v.occurrence *(alpha*10.0)\n\t\t\t\t\n\t\t\t\tunsigned int alpha_occur = (v_vit->property().occurrence > 7000) ? int(alpha*10.0) : int(alpha*10.0);\n\t\t\t\treduced_cost = v_vit->property().min_cost - u_vit->property().min_cost + eit->property().cost + alpha*(hops_gap) + v_vit->property().occurrence*alpha_occur; \n }\n eit->property().reduced_cost = reduced_cost;\n u_vit->property().sorted_edges_of_vertex.push_back(pair_IntFlt(v,reduced_cost)); \/\/ pair: id (outedge), reduced_cost\n }\n sort(u_vit->property().sorted_edges_of_vertex.begin(), u_vit->property().sorted_edges_of_vertex.end(),\n [](pair_IntFlt vecInput_1, pair_IntFlt vecInput_2) {return (vecInput_1.second < vecInput_2.second);} );\n }\n\n \/\/\/\/ (4) construct the pseudo-tree T\n graph_tau tau; \/\/T.\n priority_queue, min_comp_FltInt> PQ_KSP_candidates_tau; \/\/ X. only store the minCost and interenl ID of tau (the last id). \n vector KSPaths_lastID_tau; \/\/ for output, store the top k shortest path id of tau.\n\n\n \/\/ add the internel_src as the first node in tau\n vertex_iterator_tau src_vit_tau = tau.add_vertex();\n src_vit_tau->property().at_KSPaths = false;\/\/src_vit_tau->property().KSPaths_record.push_back(1); \/\/ this node is at the 1st shortest path.\n src_vit_tau->property().internel_id_of_g = internel_src; \/\/ this is internel_src\n src_vit_tau->property().predecessor = MY_INFINITY;\n src_vit_tau->property().min_cost = 0; \n src_vit_tau->property().sum_distance = 0; \n src_vit_tau->property().sum_hops = 0;\n\tsrc_vit_tau->property().weight = 0;\n\tsrc_vit_tau->property().occurrence = g.find_vertex(internel_src)->property().occurrence;\n\t\n \/\/ construct the first shortest path constructed in tau\n uint64_t internel_src_tau = src_vit_tau->id();\n src_vit_tau->property().min_cost += g.find_vertex( src_vit_tau->property().internel_id_of_g )->property().min_cost;\n\tsrc_vit_tau->property().weight += g.find_vertex( src_vit_tau->property().internel_id_of_g )->property().weight;\n PQ_KSP_candidates_tau.push( pair_FltInt(src_vit_tau->property().weight, src_vit_tau->id()) ); \/\/????\n src_vit_tau->property().min_cost -= g.find_vertex( src_vit_tau->property().internel_id_of_g )->property().min_cost;\n\tsrc_vit_tau->property().weight -= g.find_vertex( src_vit_tau->property().internel_id_of_g )->property().weight;\n\n\n size_t max_iter;\n if (trueMinCost)\n {\n max_iter = trueMinCost_Iter;\n }\n else\n {\n \/\/max_iter = Kvalue*100000;;\n\t\tmax_iter = trueMinCost_Iter;\n }\n size_t k = curr_kValue;\n size_t iter = 0; \n while (kproperty().internel_id_of_g; \n if (cur_Gnode_atTau != internel_dest)\n {\n vertex_iterator_tau dest_vit_tau = add_partialSP_totau(g, cur_Gnode_atTau, internel_dest, tau, candi_last_id, max_phy_dist, max_phy_hops, alpha);\n candi_last_id = dest_vit_tau->id();\n }\n \n \/\/ if p is loopless and within max_phy_dist and max_phy_hops, add it to the final KSP, \n bool is_valid_candidate = (tau.find_vertex(candi_last_id)->property().internel_id_of_g == internel_dest); \/\/ new for the break in add_partial_candi \n bool within_max_phy_dist = tau.find_vertex(candi_last_id)->property().sum_distance <= max_phy_dist;\n bool within_max_phy_hops = tau.find_vertex(candi_last_id)->property().sum_hops <= max_phy_hops;\n bool largerthan_min_phy_hops = tau.find_vertex(candi_last_id)->property().sum_hops >= min_phy_hops;\n\n within_max_phy_dist = true; \/\/Note!!! for single-layer since no dist in this case.\n if ( is_valid_candidate && within_max_phy_dist && within_max_phy_hops && largerthan_min_phy_hops && is_loopless_path(g, tau, candi_last_id, internel_src_tau) ) \n {\n\t\t\t\/\/Obtain the key for the path\n\t\t\tuint64_t candi_id_tau = candi_last_id; \n\t\t\tbool overused = 0;\n\t\t\tstring key = \"\";\n\t\t\tvertex_iterator_tau vit_tau = tau.find_vertex(candi_id_tau);\n\t\t\tvector iters_candi_path;\n\n\t\t\tuint64_t candi_id_g = vit_tau->property().internel_id_of_g; \n\t\t\tuint64_t candi_exID = atoi(g.internal_to_externel_id(candi_id_g).c_str());\n\t\t\tkey += to_string(candi_exID);\n\t\t\tdo\n\t\t\t{\n\t\t\t\tcandi_id_tau = vit_tau->property().predecessor;\n\t\t\t\tvit_tau = tau.find_vertex(candi_id_tau);\n\t\t\t\tcandi_id_g = vit_tau->property().internel_id_of_g; \n\t\t\t\tcandi_exID = atoi(g.internal_to_externel_id(candi_id_g).c_str());\n\t\t\t\t\n\t\t\t\t\/\/Obtain the key for the path\n\t\t\t\tkey += to_string(candi_exID);\n\t\t\t\t\/\/Obtain iterators for all vertexs in the path\n\t\t\t\tvertex_iterator v_iter_candi_path = g.find_vertex(candi_exID);\n\t\t\t\titers_candi_path.push_back(v_iter_candi_path);\n\t\t\t\t\/\/check if there exits an overused node\n\t\t\t\tif (v_iter_candi_path->property().occurrence > 40000)\n\t\t\t\t{\n\t\t\t\t\t\/\/cout<property().occurrence<<\"?\\n\";\n\t\t\t\t\toverused = 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} while (candi_id_tau != internel_src_tau);\n\t\t\t\n\t\t\tif (paths.find(key) == paths.end() and !overused)\n\t\t\t{\n\t\t\t\tKSPaths_lastID_tau.push_back(candi_last_id);\n\t\t\t\tk++;\n\t\t\t\t\/\/insert a new key\n\t\t\t\tpaths.insert(key);\n\t\t\t\tvector::iterator v_iter;\n\t\t\t\t\/\/update occurrence of each vertex\n\t\t\t\tfor (v_iter = iters_candi_path.begin(); v_iter != iters_candi_path.end(); v_iter++)\n\t\t\t\t{\n\t\t\t\t\t(*v_iter)->property().occurrence += 1;\n\t\t\t\t}\n\t\t\t}\n }\n\n \/\/note: even the current shortest path p may have loop, the new generated candidates based on p may have no loop.\n \/\/ find the deviation path pk_vkt_nodes, the top of pk_vkt_nodes is the deviation node\n stack pk_vkt_nodes;\n size_t tmp_id = candi_last_id; \/\/ KSPaths_lastID_tau.back()\n vertex_iterator_tau dest_vit_tau = tau.find_vertex(tmp_id);\n dest_vit_tau->property().at_KSPaths = true; \n while (tmp_id != internel_src_tau) \n {\n tmp_id = dest_vit_tau->property().predecessor;\n\n pk_vkt_nodes.push(tmp_id);\n dest_vit_tau = tau.find_vertex(tmp_id);\n if (dest_vit_tau->property().at_KSPaths == true) \n {\n break;\n }\n dest_vit_tau->property().at_KSPaths = true; \n }\n\n \/\/ for each node in deviation path, try to find a candidate\n while (!pk_vkt_nodes.empty()) \/\/ for each node at pk_vkt\n {\n \/\/ find current deviation point: pk_top_id\n size_t pk_top_id = pk_vkt_nodes.top(); \/\/ tmp_id--> pk_top_id\n pk_vkt_nodes.pop();\n\n \/\/ get out if there is loop to save time\n if ( !is_loopless_path(g, tau, pk_top_id, internel_src_tau) )\n {\n break;\n }\n\n \/\/ find A(v), which is stored in neighborNodes_g (the first of each pair in the vector) and sorted based on reduced cost \n vertex_iterator_tau pk_top_vit = tau.find_vertex(pk_top_id); \/\/vit_tau_tmp--> pk_top_vit\n size_t cur_deviation_id_g = pk_top_vit->property().internel_id_of_g; \/\/ cur_deviation_id_g is the v in MPS\n vertex_iterator tmp_vit = g.find_vertex(cur_deviation_id_g); \n vector neighborNodes_g = tmp_vit->property().sorted_edges_of_vertex;\n\n\n \/\/ (new version )find A_Tk_(v), now further update it that A_Tk_(v) contains out edges (sucsessors) and all predecessors up to internel_src_tau\n \/\/ this update is to reduce the number of loop paths\n vector neighborNodes_tau; \n \/\/ vector neighborNodes_tau_at_g; \/\/ori: \n unordered_set neighborNodes_tau_at_g; \/\/ to speed up the find operation later\n tau.find_vertex_out_neighborNodes(pk_top_id, neighborNodes_tau); \/\/ here only need out neigbor, the\n for (size_t idx=0; idxproperty().internel_id_of_g );\n neighborNodes_tau_at_g.insert( vit_tau_tmptmp->property().internel_id_of_g );\n }\n tmp_id = pk_top_id;\n vertex_iterator_tau vit_tau_tmp = pk_top_vit;\n while (tmp_id != internel_src_tau)\n {\n tmp_id = vit_tau_tmp->property().predecessor; \n vit_tau_tmp = tau.find_vertex(tmp_id);\n \/\/neighborNodes_tau_at_g.push_back(vit_tau_tmp->property().internel_id_of_g);\n neighborNodes_tau_at_g.insert(vit_tau_tmp->property().internel_id_of_g);\n }\nDelete sssp_rc.cpp<|endoftext|>"} {"text":"DevTools: only supported event types are forwarded to the client. Unsupported events may cause additional troubles. E.g. ScriptCollected event handling crashes on call to GetEventContext(this should be fixed on v8 side). Review URL: http:\/\/codereview.chromium.org\/113695<|endoftext|>"} {"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011-2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"local_storage_mixture.hpp\"\n#include \n#include \n#include \n#include \n#include \"jubatus\/util\/data\/intern.h\"\n\nusing std::string;\n\nnamespace jubatus {\nnamespace core {\nnamespace storage {\n\nnamespace {\n\nvoid increase(val3_t& a, const val3_t& b) {\n a.v1 += b.v1;\n a.v2 += b.v2;\n a.v3 += b.v3;\n}\n\nvoid delete_label_from_weight(uint64_t delete_id, id_features3_t& tbl) {\n for (id_features3_t::iterator it = tbl.begin(); it != tbl.end(); ++it) {\n it->second.erase(delete_id);\n if (it->second.empty()) {\n tbl.erase(it);\n }\n }\n}\n\n} \/\/ namespace\n\nlocal_storage_mixture::local_storage_mixture() {\n}\n\nlocal_storage_mixture::~local_storage_mixture() {\n}\n\nbool local_storage_mixture::get_internal(\n const string& feature,\n id_feature_val3_t& ret) const {\n ret.clear();\n id_features3_t::const_iterator it = tbl_.find(feature);\n\n bool found = false;\n if (it != tbl_.end()) {\n ret = it->second;\n found = true;\n }\n\n id_features3_t::const_iterator it_diff = tbl_diff_.find(feature);\n if (it_diff != tbl_diff_.end()) {\n found = true;\n for (id_feature_val3_t::const_iterator it2 = it_diff->second.begin();\n it2 != it_diff->second.end(); ++it2) {\n val3_t& val3 = ret[it2->first]; \/\/ may create\n increase(val3, it2->second);\n }\n }\n return found;\n}\n\nvoid local_storage_mixture::get(\n const std::string& feature,\n feature_val1_t& ret) const {\n ret.clear();\n id_feature_val3_t m3;\n get_internal(feature, m3);\n for (id_feature_val3_t::const_iterator it = m3.begin(); it != m3.end();\n ++it) {\n ret.push_back(make_pair(class2id_.get_key(it->first), it->second.v1));\n }\n}\n\nvoid local_storage_mixture::get2(\n const std::string& feature,\n feature_val2_t& ret) const {\n ret.clear();\n id_feature_val3_t m3;\n get_internal(feature, m3);\n for (id_feature_val3_t::const_iterator it = m3.begin(); it != m3.end();\n ++it) {\n ret.push_back(\n make_pair(class2id_.get_key(it->first),\n val2_t(it->second.v1, it->second.v2)));\n }\n}\n\nvoid local_storage_mixture::get3(\n const std::string& feature,\n feature_val3_t& ret) const {\n ret.clear();\n id_feature_val3_t m3;\n get_internal(feature, m3);\n for (id_feature_val3_t::const_iterator it = m3.begin(); it != m3.end();\n ++it) {\n ret.push_back(make_pair(class2id_.get_key(it->first), it->second));\n }\n}\n\nvoid local_storage_mixture::inp(const common::sfv_t& sfv,\n map_feature_val1_t& ret) const {\n ret.clear();\n\n \/\/ Use uin64_t map instead of string map as hash function for string is slow\n jubatus::util::data::unordered_map ret_id;\n for (common::sfv_t::const_iterator it = sfv.begin(); it != sfv.end(); ++it) {\n const string& feature = it->first;\n const float val = it->second;\n id_feature_val3_t m;\n get_internal(feature, m);\n for (id_feature_val3_t::const_iterator it3 = m.begin(); it3 != m.end();\n ++it3) {\n ret_id[it3->first] += it3->second.v1 * val;\n }\n }\n\n std::vector labels = class2id_.get_all_id2key();\n for (size_t i = 0; i < labels.size(); ++i) {\n const std::string& label = labels[i];\n uint64_t id = class2id_.get_id_const(label);\n if (id == common::key_manager::NOTFOUND || ret_id.count(id) == 0) {\n ret[label] = 0.0;\n } else {\n ret[label] = ret_id[id];\n }\n }\n}\n\nvoid local_storage_mixture::set(\n const string& feature,\n const string& klass,\n const val1_t& w) {\n uint64_t class_id = class2id_.get_id(klass);\n float w_in_table = tbl_[feature][class_id].v1;\n tbl_diff_[feature][class_id].v1 = w - w_in_table;\n}\n\nvoid local_storage_mixture::set2(\n const string& feature,\n const string& klass,\n const val2_t& w) {\n uint64_t class_id = class2id_.get_id(klass);\n float w1_in_table = tbl_[feature][class_id].v1;\n float w2_in_table = tbl_[feature][class_id].v2;\n\n val3_t& triple = tbl_diff_[feature][class_id];\n triple.v1 = w.v1 - w1_in_table;\n triple.v2 = w.v2 - w2_in_table;\n}\n\nvoid local_storage_mixture::set3(\n const string& feature,\n const string& klass,\n const val3_t& w) {\n uint64_t class_id = class2id_.get_id(klass);\n val3_t v = tbl_[feature][class_id];\n tbl_diff_[feature][class_id] = w - v;\n}\n\nvoid local_storage_mixture::get_status(\n std::map& status) const {\n status[\"num_features\"] =\n jubatus::util::lang::lexical_cast(tbl_.size());\n status[\"num_classes\"] = jubatus::util::lang::lexical_cast(\n class2id_.size());\n status[\"diff_size\"] =\n jubatus::util::lang::lexical_cast(tbl_diff_.size());\n}\n\nvoid local_storage_mixture::update(\n const string& feature,\n const string& inc_class,\n const string& dec_class,\n const val1_t& v) {\n id_feature_val3_t& feature_row = tbl_diff_[feature];\n feature_row[class2id_.get_id(inc_class)].v1 += v;\n feature_row[class2id_.get_id(dec_class)].v1 -= v;\n}\n\nvoid local_storage_mixture::bulk_update(\n const common::sfv_t& sfv,\n float step_width,\n const string& inc_class,\n const string& dec_class) {\n uint64_t inc_id = class2id_.get_id(inc_class);\n typedef common::sfv_t::const_iterator iter_t;\n if (dec_class != \"\") {\n uint64_t dec_id = class2id_.get_id(dec_class);\n for (iter_t it = sfv.begin(); it != sfv.end(); ++it) {\n float val = it->second * step_width;\n id_feature_val3_t& feature_row = tbl_diff_[it->first];\n feature_row[inc_id].v1 += val;\n feature_row[dec_id].v1 -= val;\n }\n } else {\n for (iter_t it = sfv.begin(); it != sfv.end(); ++it) {\n float val = it->second * step_width;\n id_feature_val3_t& feature_row = tbl_diff_[it->first];\n feature_row[inc_id].v1 += val;\n }\n }\n}\n\nvoid local_storage_mixture::get_diff(diff_t& ret) const {\n ret.diff.clear();\n for (jubatus::util::data::unordered_map::\n const_iterator it = tbl_diff_.begin(); it != tbl_diff_.end(); ++it) {\n id_feature_val3_t::const_iterator it2 = it->second.begin();\n feature_val3_t fv3;\n for (; it2 != it->second.end(); ++it2) {\n fv3.push_back(make_pair(class2id_.get_key(it2->first), it2->second));\n }\n ret.diff.push_back(make_pair(it->first, fv3));\n }\n ret.expect_version = model_version_;\n}\n\nbool local_storage_mixture::set_average_and_clear_diff(\n const diff_t& average) {\n if (average.expect_version == model_version_) {\n for (features3_t::const_iterator it = average.diff.begin();\n it != average.diff.end();\n ++it) {\n const feature_val3_t& avg = it->second;\n id_feature_val3_t& orig = tbl_[it->first];\n for (feature_val3_t::const_iterator it2 = avg.begin(); it2 != avg.end();\n ++it2) {\n val3_t& triple = orig[class2id_.get_id(it2->first)]; \/\/ may create\n increase(triple, it2->second);\n }\n }\n model_version_.increment();\n tbl_diff_.clear();\n return true;\n } else {\n return false;\n }\n}\n\nvoid local_storage_mixture::register_label(const std::string& label) {\n \/\/ get_id method creates an entry when the label doesn't exist\n class2id_.get_id(label);\n}\n\nbool local_storage_mixture::delete_label(const std::string& label) {\n uint64_t delete_id = class2id_.get_id_const(label);\n if (delete_id == common::key_manager::NOTFOUND) {\n return false;\n }\n delete_label_from_weight(delete_id, tbl_);\n delete_label_from_weight(delete_id, tbl_diff_);\n class2id_.delete_key(label);\n return true;\n}\n\nvoid local_storage_mixture::clear() {\n \/\/ Clear and minimize\n id_features3_t().swap(tbl_);\n common::key_manager().swap(class2id_);\n id_features3_t().swap(tbl_diff_);\n}\n\nstd::vector local_storage_mixture::get_labels() const {\n return class2id_.get_all_id2key();\n}\n\nbool local_storage_mixture::set_label(const std::string& label) {\n return class2id_.set_key(label);\n}\n\nvoid local_storage_mixture::pack(framework::packer& packer) const {\n packer.pack(*this);\n}\n\nvoid local_storage_mixture::unpack(msgpack::object o) {\n o.convert(this);\n}\n\nstd::string local_storage_mixture::type() const {\n return \"local_storage_mixture\";\n}\n\n} \/\/ namespace storage\n} \/\/ namespace core\n} \/\/ namespace jubatus\nFix misusing iterator.\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011-2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"local_storage_mixture.hpp\"\n#include \n#include \n#include \n#include \n#include \"jubatus\/util\/data\/intern.h\"\n\nusing std::string;\n\nnamespace jubatus {\nnamespace core {\nnamespace storage {\n\nnamespace {\n\nvoid increase(val3_t& a, const val3_t& b) {\n a.v1 += b.v1;\n a.v2 += b.v2;\n a.v3 += b.v3;\n}\n\nvoid delete_label_from_weight(uint64_t delete_id, id_features3_t& tbl) {\n for (id_features3_t::iterator it = tbl.begin(); it != tbl.end(); ) {\n it->second.erase(delete_id);\n if (it->second.empty()) {\n it = tbl.erase(it);\n } else {\n ++it;\n }\n }\n}\n\n} \/\/ namespace\n\nlocal_storage_mixture::local_storage_mixture() {\n}\n\nlocal_storage_mixture::~local_storage_mixture() {\n}\n\nbool local_storage_mixture::get_internal(\n const string& feature,\n id_feature_val3_t& ret) const {\n ret.clear();\n id_features3_t::const_iterator it = tbl_.find(feature);\n\n bool found = false;\n if (it != tbl_.end()) {\n ret = it->second;\n found = true;\n }\n\n id_features3_t::const_iterator it_diff = tbl_diff_.find(feature);\n if (it_diff != tbl_diff_.end()) {\n found = true;\n for (id_feature_val3_t::const_iterator it2 = it_diff->second.begin();\n it2 != it_diff->second.end(); ++it2) {\n val3_t& val3 = ret[it2->first]; \/\/ may create\n increase(val3, it2->second);\n }\n }\n return found;\n}\n\nvoid local_storage_mixture::get(\n const std::string& feature,\n feature_val1_t& ret) const {\n ret.clear();\n id_feature_val3_t m3;\n get_internal(feature, m3);\n for (id_feature_val3_t::const_iterator it = m3.begin(); it != m3.end();\n ++it) {\n ret.push_back(make_pair(class2id_.get_key(it->first), it->second.v1));\n }\n}\n\nvoid local_storage_mixture::get2(\n const std::string& feature,\n feature_val2_t& ret) const {\n ret.clear();\n id_feature_val3_t m3;\n get_internal(feature, m3);\n for (id_feature_val3_t::const_iterator it = m3.begin(); it != m3.end();\n ++it) {\n ret.push_back(\n make_pair(class2id_.get_key(it->first),\n val2_t(it->second.v1, it->second.v2)));\n }\n}\n\nvoid local_storage_mixture::get3(\n const std::string& feature,\n feature_val3_t& ret) const {\n ret.clear();\n id_feature_val3_t m3;\n get_internal(feature, m3);\n for (id_feature_val3_t::const_iterator it = m3.begin(); it != m3.end();\n ++it) {\n ret.push_back(make_pair(class2id_.get_key(it->first), it->second));\n }\n}\n\nvoid local_storage_mixture::inp(const common::sfv_t& sfv,\n map_feature_val1_t& ret) const {\n ret.clear();\n\n \/\/ Use uin64_t map instead of string map as hash function for string is slow\n jubatus::util::data::unordered_map ret_id;\n for (common::sfv_t::const_iterator it = sfv.begin(); it != sfv.end(); ++it) {\n const string& feature = it->first;\n const float val = it->second;\n id_feature_val3_t m;\n get_internal(feature, m);\n for (id_feature_val3_t::const_iterator it3 = m.begin(); it3 != m.end();\n ++it3) {\n ret_id[it3->first] += it3->second.v1 * val;\n }\n }\n\n std::vector labels = class2id_.get_all_id2key();\n for (size_t i = 0; i < labels.size(); ++i) {\n const std::string& label = labels[i];\n uint64_t id = class2id_.get_id_const(label);\n if (id == common::key_manager::NOTFOUND || ret_id.count(id) == 0) {\n ret[label] = 0.0;\n } else {\n ret[label] = ret_id[id];\n }\n }\n}\n\nvoid local_storage_mixture::set(\n const string& feature,\n const string& klass,\n const val1_t& w) {\n uint64_t class_id = class2id_.get_id(klass);\n float w_in_table = tbl_[feature][class_id].v1;\n tbl_diff_[feature][class_id].v1 = w - w_in_table;\n}\n\nvoid local_storage_mixture::set2(\n const string& feature,\n const string& klass,\n const val2_t& w) {\n uint64_t class_id = class2id_.get_id(klass);\n float w1_in_table = tbl_[feature][class_id].v1;\n float w2_in_table = tbl_[feature][class_id].v2;\n\n val3_t& triple = tbl_diff_[feature][class_id];\n triple.v1 = w.v1 - w1_in_table;\n triple.v2 = w.v2 - w2_in_table;\n}\n\nvoid local_storage_mixture::set3(\n const string& feature,\n const string& klass,\n const val3_t& w) {\n uint64_t class_id = class2id_.get_id(klass);\n val3_t v = tbl_[feature][class_id];\n tbl_diff_[feature][class_id] = w - v;\n}\n\nvoid local_storage_mixture::get_status(\n std::map& status) const {\n status[\"num_features\"] =\n jubatus::util::lang::lexical_cast(tbl_.size());\n status[\"num_classes\"] = jubatus::util::lang::lexical_cast(\n class2id_.size());\n status[\"diff_size\"] =\n jubatus::util::lang::lexical_cast(tbl_diff_.size());\n}\n\nvoid local_storage_mixture::update(\n const string& feature,\n const string& inc_class,\n const string& dec_class,\n const val1_t& v) {\n id_feature_val3_t& feature_row = tbl_diff_[feature];\n feature_row[class2id_.get_id(inc_class)].v1 += v;\n feature_row[class2id_.get_id(dec_class)].v1 -= v;\n}\n\nvoid local_storage_mixture::bulk_update(\n const common::sfv_t& sfv,\n float step_width,\n const string& inc_class,\n const string& dec_class) {\n uint64_t inc_id = class2id_.get_id(inc_class);\n typedef common::sfv_t::const_iterator iter_t;\n if (dec_class != \"\") {\n uint64_t dec_id = class2id_.get_id(dec_class);\n for (iter_t it = sfv.begin(); it != sfv.end(); ++it) {\n float val = it->second * step_width;\n id_feature_val3_t& feature_row = tbl_diff_[it->first];\n feature_row[inc_id].v1 += val;\n feature_row[dec_id].v1 -= val;\n }\n } else {\n for (iter_t it = sfv.begin(); it != sfv.end(); ++it) {\n float val = it->second * step_width;\n id_feature_val3_t& feature_row = tbl_diff_[it->first];\n feature_row[inc_id].v1 += val;\n }\n }\n}\n\nvoid local_storage_mixture::get_diff(diff_t& ret) const {\n ret.diff.clear();\n for (jubatus::util::data::unordered_map::\n const_iterator it = tbl_diff_.begin(); it != tbl_diff_.end(); ++it) {\n id_feature_val3_t::const_iterator it2 = it->second.begin();\n feature_val3_t fv3;\n for (; it2 != it->second.end(); ++it2) {\n fv3.push_back(make_pair(class2id_.get_key(it2->first), it2->second));\n }\n ret.diff.push_back(make_pair(it->first, fv3));\n }\n ret.expect_version = model_version_;\n}\n\nbool local_storage_mixture::set_average_and_clear_diff(\n const diff_t& average) {\n if (average.expect_version == model_version_) {\n for (features3_t::const_iterator it = average.diff.begin();\n it != average.diff.end();\n ++it) {\n const feature_val3_t& avg = it->second;\n id_feature_val3_t& orig = tbl_[it->first];\n for (feature_val3_t::const_iterator it2 = avg.begin(); it2 != avg.end();\n ++it2) {\n val3_t& triple = orig[class2id_.get_id(it2->first)]; \/\/ may create\n increase(triple, it2->second);\n }\n }\n model_version_.increment();\n tbl_diff_.clear();\n return true;\n } else {\n return false;\n }\n}\n\nvoid local_storage_mixture::register_label(const std::string& label) {\n \/\/ get_id method creates an entry when the label doesn't exist\n class2id_.get_id(label);\n}\n\nbool local_storage_mixture::delete_label(const std::string& label) {\n uint64_t delete_id = class2id_.get_id_const(label);\n if (delete_id == common::key_manager::NOTFOUND) {\n return false;\n }\n delete_label_from_weight(delete_id, tbl_);\n delete_label_from_weight(delete_id, tbl_diff_);\n class2id_.delete_key(label);\n return true;\n}\n\nvoid local_storage_mixture::clear() {\n \/\/ Clear and minimize\n id_features3_t().swap(tbl_);\n common::key_manager().swap(class2id_);\n id_features3_t().swap(tbl_diff_);\n}\n\nstd::vector local_storage_mixture::get_labels() const {\n return class2id_.get_all_id2key();\n}\n\nbool local_storage_mixture::set_label(const std::string& label) {\n return class2id_.set_key(label);\n}\n\nvoid local_storage_mixture::pack(framework::packer& packer) const {\n packer.pack(*this);\n}\n\nvoid local_storage_mixture::unpack(msgpack::object o) {\n o.convert(this);\n}\n\nstd::string local_storage_mixture::type() const {\n return \"local_storage_mixture\";\n}\n\n} \/\/ namespace storage\n} \/\/ namespace core\n} \/\/ namespace jubatus\n<|endoftext|>"} {"text":"#include \n#include \n\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n Var x, y, z, w;\n Image full(80, 60, 10, 10);\n\n buffer_t cropped = *full.raw_buffer();\n cropped.host = (uint8_t *)&(full(4, 8, 2, 4));\n cropped.min[0] = 0;\n cropped.min[1] = 0;\n cropped.min[2] = 0;\n cropped.min[3] = 0;\n cropped.extent[0] = 16;\n cropped.extent[1] = 16;\n cropped.extent[2] = 3;\n cropped.extent[3] = 3;\n cropped.stride[0] *= 2;\n cropped.stride[1] *= 2;\n cropped.stride[2] *= 2;\n cropped.stride[3] *= 2;\n Buffer out(Int(32), &cropped);\n\n Func f;\n\n f(x, y, z, w) = 3*x + 2*y + z + 4*w;\n f.gpu_tile(x, y, 16, 16);\n f.output_buffer().set_stride(0, Expr());\n f.realize(out);\n\n \/\/ Put some data in the full host buffer.\n lambda(x, y, z, w, 4*x + 3*y + 2*z + w).realize(full);\n\n \/\/ Copy back the output subset from the GPU.\n out.copy_to_host();\n\n for (int w = 0; w < full.extent(3); ++w) {\n for (int z = 0; z < full.extent(2); ++z) {\n for (int y = 0; y < full.extent(1); ++y) {\n for (int x = 0; x < full.extent(0); ++x) {\n int correct = 4*x + 3*y + 2*z + w;\n\n int w_ = (w - 4)\/2;\n int z_ = (z - 2)\/2;\n int y_ = (y - 8)\/2;\n int x_ = (x - 4)\/2;\n\n if (cropped.min[3] <= w_ && w_ < cropped.min[3] + cropped.extent[3] &&\n cropped.min[2] <= z_ && z_ < cropped.min[2] + cropped.extent[2] &&\n cropped.min[1] <= y_ && y_ < cropped.min[1] + cropped.extent[1] &&\n cropped.min[0] <= x_ && x_ < cropped.min[0] + cropped.extent[0] &&\n x % 2 == 0 && y % 2 == 0 && z % 2 == 0 && w % 2 == 0) {\n correct = 3*x_ + 2*y_ + z_ + 4*w_;\n }\n if (full(x, y, z, w) != correct) {\n printf(\"Error! Incorrect value %i != %i at %i, %i, %i, %i\\n\", full(x, y, z, w), correct, x, y, z, w);\n return -1;\n }\n }\n }\n }\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\nFix non-contiguous copy test#include \n#include \n\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n Var x, y, z, w;\n Image full(80, 60, 10, 10);\n\n const int x_off = 4, y_off = 8, z_off = 2, w_off = 4;\n const int x_size = 16, y_size = 16, z_size = 3, w_size = 3;\n\n buffer_t cropped = *full.raw_buffer();\n cropped.host = (uint8_t *)&(full(x_off, y_off, z_off, w_off));\n cropped.min[0] = 0;\n cropped.min[1] = 0;\n cropped.min[2] = 0;\n cropped.min[3] = 0;\n cropped.extent[0] = x_size;\n cropped.extent[1] = y_size;\n cropped.extent[2] = z_size;\n cropped.extent[3] = w_size;\n cropped.stride[0] *= 2;\n cropped.stride[1] *= 2;\n cropped.stride[2] *= 2;\n cropped.stride[3] *= 2;\n Buffer out(Int(32), &cropped);\n\n \/\/ Make a bitmask representing the region inside the crop.\n Image in_subregion(80, 60, 10, 10);\n Expr test = ((x >= x_off) && (x < x_off + x_size*2) &&\n (y >= y_off) && (y < y_off + y_size*2) &&\n (z >= z_off) && (z < z_off + z_size*2) &&\n (w >= w_off) && (w < w_off + w_size*2) &&\n (x % 2 == 0) &&\n (y % 2 == 0) &&\n (z % 2 == 0) &&\n (w % 2 == 0));\n Func test_func;\n test_func(x, y, z, w) = test;\n test_func.realize(in_subregion);\n\n Func f;\n f(x, y, z, w) = 3*x + 2*y + z + 4*w;\n f.gpu_tile(x, y, 16, 16);\n f.output_buffer().set_stride(0, Expr());\n f.realize(out);\n\n\n \/\/ Put some data in the full host buffer, avoiding the region\n \/\/ being evaluated above.\n Expr change_out_of_subregion = select(test, undef(), 4*x + 3*y + 2*z + w);\n lambda(x, y, z, w, change_out_of_subregion).realize(full);\n\n \/\/ Copy back the output subset from the GPU.\n out.copy_to_host();\n\n for (int w = 0; w < full.extent(3); ++w) {\n for (int z = 0; z < full.extent(2); ++z) {\n for (int y = 0; y < full.extent(1); ++y) {\n for (int x = 0; x < full.extent(0); ++x) {\n int correct;\n if (in_subregion(x, y, z, w)) {\n int x_ = (x - x_off)\/2;\n int y_ = (y - y_off)\/2;\n int z_ = (z - z_off)\/2;\n int w_ = (w - w_off)\/2;\n correct = 3*x_ + 2*y_ + z_ + 4*w_;\n } else {\n correct = 4*x + 3*y + 2*z + w;\n }\n if (full(x, y, z, w) != correct) {\n printf(\"Error! Incorrect value %i != %i at %i, %i, %i, %i\\n\", full(x, y, z, w), correct, x, y, z, w);\n return -1;\n }\n }\n }\n }\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2007 Volker Krause \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 along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*\/\n\n#include \"timelineitem.h\"\n#include \"koprefs.h\"\n#include \"kohelper.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace KOrg;\nusing namespace KCal;\n\nTimelineItem::TimelineItem( const QString &label, KDGanttView *parent )\n : KDGanttViewTaskItem( parent )\n{\n setListViewText( 0, label );\n setDisplaySubitemsAsGroup( true );\n if ( listView() ) {\n listView()->setRootIsDecorated( false );\n }\n}\n\nvoid TimelineItem::insertIncidence( KCal::Incidence *incidence,\n const KDateTime & _start, const KDateTime & _end )\n{\n KDateTime start = incidence->dtStart().toTimeSpec( KOPrefs::instance()->timeSpec() );\n KDateTime end = incidence->dtEnd().toTimeSpec( KOPrefs::instance()->timeSpec() );\n\n if ( _start.isValid() ) {\n start = _start;\n }\n if ( _end.isValid() ) {\n end = _end;\n }\n if ( incidence->allDay() ) {\n end = end.addDays( 1 );\n }\n\n typedef QList ItemList;\n ItemList list = mItemMap[incidence];\n for ( ItemList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) {\n if ( KDateTime( (*it)->startTime() ) == start &&\n KDateTime( (*it)->endTime() ) == end ) {\n return;\n }\n }\n\n TimelineSubItem * item = new TimelineSubItem( incidence, this );\n QColor c1, c2, c3;\n colors( c1, c2, c3 );\n item->setColors( c1, c2, c3 );\n\n item->setStartTime( start.dateTime() );\n item->setOriginalStart( start );\n item->setEndTime( end.dateTime() );\n\n mItemMap[incidence].append( item );\n}\n\nvoid TimelineItem::removeIncidence( KCal::Incidence *incidence )\n{\n typedef QList ItemList;\n ItemList list = mItemMap[incidence];\n for ( ItemList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) {\n delete *it;\n }\n mItemMap.remove( incidence );\n}\n\nvoid TimelineItem::moveItems( KCal::Incidence *incidence, int delta, int duration )\n{\n typedef QList ItemList;\n ItemList list = mItemMap[incidence];\n for ( ItemList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) {\n QDateTime start = (*it)->originalStart().dateTime();\n start = start.addSecs( delta );\n (*it)->setStartTime( start );\n (*it)->setOriginalStart( KDateTime(start) );\n (*it)->setEndTime( start.addSecs( duration ) );\n }\n}\n\nTimelineSubItem::TimelineSubItem( KCal::Incidence *incidence, TimelineItem *parent )\n : KDGanttViewTaskItem( parent ), mIncidence( incidence ),\n mLeft( 0 ), mRight( 0 ), mMarkerWidth( 0 )\n{\n setTooltipText( IncidenceFormatter::toolTipString( incidence ) );\n if ( !incidence->isReadOnly() ) {\n setMoveable( true );\n setResizeable( true );\n }\n}\n\nTimelineSubItem::~TimelineSubItem()\n{\n delete mLeft;\n delete mRight;\n}\n\nvoid TimelineSubItem::showItem( bool show, int coordY )\n{\n KDGanttViewTaskItem::showItem( show, coordY );\n int y;\n if ( coordY != 0 ) {\n y = coordY;\n } else {\n y = getCoordY();\n }\n int startX = myGanttView->timeHeaderWidget()->getCoordX( myStartTime );\n int endX = myGanttView->timeHeaderWidget()->getCoordX( myEndTime );\n\n const int mw = qMax( 1, qMin( 4, endX - startX ) );\n if ( !mLeft || mw != mMarkerWidth ) {\n if ( !mLeft ) {\n mLeft = new KDCanvasPolygon( myGanttView->timeTableWidget(), this, Type_is_KDGanttViewItem );\n mLeft->setBrush( Qt::black );\n }\n QPointArray a = QPointArray( 4 );\n a.setPoint( 0, 0, -mw -myItemSize \/ 2 - 2 );\n a.setPoint( 1, mw, -myItemSize \/ 2 - 2 );\n a.setPoint( 2, mw, myItemSize \/ 2 + 2 );\n a.setPoint( 3, 0, myItemSize \/ 2 + mw + 2 );\n mLeft->setPoints( a );\n }\n if ( !mRight || mw != mMarkerWidth ) {\n if ( !mRight ) {\n mRight = new KDCanvasPolygon( myGanttView->timeTableWidget(), this, Type_is_KDGanttViewItem );\n mRight->setBrush( Qt::black );\n }\n QPointArray a = QPointArray( 4 );\n a.setPoint( 0, -mw, -myItemSize \/ 2 - 2 );\n a.setPoint( 1, 0, -myItemSize \/ 2 - mw - 2 );\n a.setPoint( 2, 0, myItemSize \/ 2 + mw + 2 );\n a.setPoint( 3, -mw, myItemSize \/ 2 + 2 );\n mRight->setPoints( a );\n }\n mMarkerWidth = mw;\n mLeft->setX( startX );\n mLeft->setY( y );\n mLeft->setZ( startShape->z() - 1 );\n mLeft->show();\n mRight->setX( endX );\n mRight->setY( y );\n mRight->setZ( startShape->z() - 1 );\n mRight->show();\n}\ndeprecated--\/*\n Copyright (c) 2007 Volker Krause \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 along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*\/\n\n#include \"timelineitem.h\"\n#include \"koprefs.h\"\n#include \"kohelper.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace KOrg;\nusing namespace KCal;\n\nTimelineItem::TimelineItem( const QString &label, KDGanttView *parent )\n : KDGanttViewTaskItem( parent )\n{\n setListViewText( 0, label );\n setDisplaySubitemsAsGroup( true );\n if ( listView() ) {\n listView()->setRootIsDecorated( false );\n }\n}\n\nvoid TimelineItem::insertIncidence( KCal::Incidence *incidence,\n const KDateTime & _start, const KDateTime & _end )\n{\n KDateTime start = incidence->dtStart().toTimeSpec( KOPrefs::instance()->timeSpec() );\n KDateTime end = incidence->dtEnd().toTimeSpec( KOPrefs::instance()->timeSpec() );\n\n if ( _start.isValid() ) {\n start = _start;\n }\n if ( _end.isValid() ) {\n end = _end;\n }\n if ( incidence->allDay() ) {\n end = end.addDays( 1 );\n }\n\n typedef QList ItemList;\n ItemList list = mItemMap[incidence];\n for ( ItemList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) {\n if ( KDateTime( (*it)->startTime() ) == start &&\n KDateTime( (*it)->endTime() ) == end ) {\n return;\n }\n }\n\n TimelineSubItem * item = new TimelineSubItem( incidence, this );\n QColor c1, c2, c3;\n colors( c1, c2, c3 );\n item->setColors( c1, c2, c3 );\n\n item->setStartTime( start.dateTime() );\n item->setOriginalStart( start );\n item->setEndTime( end.dateTime() );\n\n mItemMap[incidence].append( item );\n}\n\nvoid TimelineItem::removeIncidence( KCal::Incidence *incidence )\n{\n typedef QList ItemList;\n ItemList list = mItemMap[incidence];\n for ( ItemList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) {\n delete *it;\n }\n mItemMap.remove( incidence );\n}\n\nvoid TimelineItem::moveItems( KCal::Incidence *incidence, int delta, int duration )\n{\n typedef QList ItemList;\n ItemList list = mItemMap[incidence];\n for ( ItemList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) {\n QDateTime start = (*it)->originalStart().dateTime();\n start = start.addSecs( delta );\n (*it)->setStartTime( start );\n (*it)->setOriginalStart( KDateTime(start) );\n (*it)->setEndTime( start.addSecs( duration ) );\n }\n}\n\nTimelineSubItem::TimelineSubItem( KCal::Incidence *incidence, TimelineItem *parent )\n : KDGanttViewTaskItem( parent ), mIncidence( incidence ),\n mLeft( 0 ), mRight( 0 ), mMarkerWidth( 0 )\n{\n setTooltipText( IncidenceFormatter::toolTipStr(\n incidence, true, KOPrefs::instance()->timeSpec() ) );\n if ( !incidence->isReadOnly() ) {\n setMoveable( true );\n setResizeable( true );\n }\n}\n\nTimelineSubItem::~TimelineSubItem()\n{\n delete mLeft;\n delete mRight;\n}\n\nvoid TimelineSubItem::showItem( bool show, int coordY )\n{\n KDGanttViewTaskItem::showItem( show, coordY );\n int y;\n if ( coordY != 0 ) {\n y = coordY;\n } else {\n y = getCoordY();\n }\n int startX = myGanttView->timeHeaderWidget()->getCoordX( myStartTime );\n int endX = myGanttView->timeHeaderWidget()->getCoordX( myEndTime );\n\n const int mw = qMax( 1, qMin( 4, endX - startX ) );\n if ( !mLeft || mw != mMarkerWidth ) {\n if ( !mLeft ) {\n mLeft = new KDCanvasPolygon( myGanttView->timeTableWidget(), this, Type_is_KDGanttViewItem );\n mLeft->setBrush( Qt::black );\n }\n QPointArray a = QPointArray( 4 );\n a.setPoint( 0, 0, -mw -myItemSize \/ 2 - 2 );\n a.setPoint( 1, mw, -myItemSize \/ 2 - 2 );\n a.setPoint( 2, mw, myItemSize \/ 2 + 2 );\n a.setPoint( 3, 0, myItemSize \/ 2 + mw + 2 );\n mLeft->setPoints( a );\n }\n if ( !mRight || mw != mMarkerWidth ) {\n if ( !mRight ) {\n mRight = new KDCanvasPolygon( myGanttView->timeTableWidget(), this, Type_is_KDGanttViewItem );\n mRight->setBrush( Qt::black );\n }\n QPointArray a = QPointArray( 4 );\n a.setPoint( 0, -mw, -myItemSize \/ 2 - 2 );\n a.setPoint( 1, 0, -myItemSize \/ 2 - mw - 2 );\n a.setPoint( 2, 0, myItemSize \/ 2 + mw + 2 );\n a.setPoint( 3, -mw, myItemSize \/ 2 + 2 );\n mRight->setPoints( a );\n }\n mMarkerWidth = mw;\n mLeft->setX( startX );\n mLeft->setY( y );\n mLeft->setZ( startShape->z() - 1 );\n mLeft->show();\n mRight->setX( endX );\n mRight->setY( y );\n mRight->setZ( startShape->z() - 1 );\n mRight->show();\n}\n<|endoftext|>"} {"text":"\/\/ Test the handle_sigill option.\n\/\/ RUN: %clang %s -o %t -O1\n\/\/ RUN: not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s\n\/\/ RUN: %env_tool_opts=handle_sigill=0 not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s\n\/\/ RUN: %env_tool_opts=handle_sigill=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK1 %s\n\/\/ FIXME: implement in other sanitizers, not just asan.\n\/\/ XFAIL: msan\n\/\/ XFAIL: lsan\n\/\/ XFAIL: tsan\n\/\/\n#include \n#include \n#include \n\nvoid death() {\n fprintf(stderr, \"DEATH CALLBACK\\n\");\n}\n\nint main(int argc, char **argv) {\n __sanitizer_set_death_callback(death);\n __builtin_trap();\n}\n\/\/ CHECK1: ERROR: {{.*}}Sanitizer:\n\/\/ CHECK1: DEATH CALLBACK\n\/\/ CHECK0-NOT: Sanitizer\n[asan] try to fix ARM bots\/\/ Test the handle_sigill option.\n\/\/ RUN: %clang %s -o %t -O1\n\/\/ RUN: not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s\n\/\/ RUN: %env_tool_opts=handle_sigill=0 not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s\n\/\/ RUN: %env_tool_opts=handle_sigill=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK1 %s\n\/\/ FIXME: implement in other sanitizers, not just asan.\n\/\/ XFAIL: msan\n\/\/ XFAIL: lsan\n\/\/ XFAIL: tsan\n\/\/\n\/\/ FIXME: seems to fail on ARM\n\/\/ REQUIRES: x86_64-supported-target\n#include \n#include \n#include \n\nvoid death() {\n fprintf(stderr, \"DEATH CALLBACK\\n\");\n}\n\nint main(int argc, char **argv) {\n __sanitizer_set_death_callback(death);\n __builtin_trap();\n}\n\/\/ CHECK1: ERROR: {{.*}}Sanitizer:\n\/\/ CHECK1: DEATH CALLBACK\n\/\/ CHECK0-NOT: Sanitizer\n<|endoftext|>"} {"text":"\/*!\n * \\page DemandGenerationTestSuite_cpp Command-Line Test to Demonstrate How To Use TraDemGen elements\n * \\code\n *\/\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n#include \n#include \n\/\/ Boost Unit Test Framework (UTF)\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE DemandGenerationTest\n#include \n\/\/ StdAir\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ TraDemGen\n#include \n#include \n#include \n\nnamespace boost_utf = boost::unit_test;\n\n\/\/ (Boost) Unit Test XML Report\nstd::ofstream utfReportStream (\"DemandGenerationTestSuite_utfresults.xml\");\n\n\/**\n * Configuration for the Boost Unit Test Framework (UTF)\n *\/\nstruct UnitTestConfig {\n \/** Constructor. *\/\n UnitTestConfig() {\n boost_utf::unit_test_log.set_stream (utfReportStream);\n boost_utf::unit_test_log.set_format (boost_utf::XML);\n boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);\n \/\/boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);\n }\n \n \/** Destructor. *\/\n ~UnitTestConfig() {\n }\n};\n\n\/\/ Specific type definitions\ntypedef std::pair NbOfEventsPair_T;\ntypedef std::map NbOfEventsByDemandStreamMap_T;\n\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Main: Unit Test Suite \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Set the UTF configuration (re-direct the output to a specific file)\nBOOST_GLOBAL_FIXTURE (UnitTestConfig);\n\n\/\/ Start the test suite\nBOOST_AUTO_TEST_SUITE (master_test_suite)\n\n\/**\n * Test a simple simulation\n *\/\nBOOST_AUTO_TEST_CASE (trademgen_simple_simulation_test) {\n\n \/\/ Input file name\n const stdair::Filename_T lInputFilename (STDAIR_SAMPLE_DIR \"\/demand01.csv\");\n\n \/\/ Check that the file path given as input corresponds to an actual file\n const bool doesExistAndIsReadable =\n stdair::BasFileMgr::doesExistAndIsReadable (lInputFilename);\n BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,\n \"The '\" << lInputFilename\n << \"' input file can not be open and read\");\n \n \/\/ Output log File\n const stdair::Filename_T lLogFilename (\"DemandGenerationTestSuite.log\");\n \n \/\/ Set the log parameters\n std::ofstream logOutputFile;\n \/\/ open and clean the log outputfile\n logOutputFile.open (lLogFilename.c_str());\n logOutputFile.clear();\n \n \/\/ Initialise the TraDemGen service object\n const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);\n\n \/**\n Initialise the current number of generated events and the\n expected total numbers of requests to be generated, depending on\n the demand streams.\n
The current number of generated events starts at one, for each demand\n stream, because the initialisation step generates exactly one event\n for each demand stream.\n *\/\n NbOfEventsByDemandStreamMap_T lNbOfEventsMap;\n lNbOfEventsMap.insert (NbOfEventsByDemandStreamMap_T::\n value_type (\"SIN-HND 2010-Feb-08 Y\",\n NbOfEventsPair_T (1, 10)));\n lNbOfEventsMap.insert (NbOfEventsByDemandStreamMap_T::\n value_type (\"SIN-BKK 2010-Feb-08 Y\",\n NbOfEventsPair_T (1, 10)));\n \/\/ Total number of events, for all the demand streams: 20 (10 + 10)\n const stdair::Count_T lRefExpectedNbOfEvents (20);\n \n \/\/ Retrieve the expected (mean value of the) number of events to be\n \/\/ generated\n const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =\n trademgenService.getExpectedTotalNumberOfRequestsToBeGenerated();\n\n \/\/ TODO: understand why the tests fail, and uncomment them\n \/*\n BOOST_CHECK_EQUAL (lRefExpectedNbOfEvents,\n std::floor (lExpectedNbOfEventsToBeGenerated));\n \n BOOST_CHECK_MESSAGE (lRefExpectedNbOfEvents ==\n std::floor (lExpectedNbOfEventsToBeGenerated),\n \"Expected total number of requests to be generated: \"\n << lExpectedNbOfEventsToBeGenerated\n << \" (=> \"\n << std::floor (lExpectedNbOfEventsToBeGenerated)\n << \"). Reference value: \" << lRefExpectedNbOfEvents);\n *\/\n\n \/**\n * Initialisation step.\n *\n * Generate the first event for each demand stream.\n *\n * \\note For that demand (CSV) file (i.e., demand01.csv), the\n * expected and actual numbers of events to be generated are\n * the same (and equal to 20).\n *\/\n const stdair::Count_T& lActualNbOfEventsToBeGenerated =\n trademgenService.generateFirstRequests();\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Expected number of events: \"\n << lExpectedNbOfEventsToBeGenerated << \", actual: \"\n << lActualNbOfEventsToBeGenerated);\n \n BOOST_CHECK_EQUAL (lRefExpectedNbOfEvents, lActualNbOfEventsToBeGenerated);\n \n BOOST_CHECK_MESSAGE (lRefExpectedNbOfEvents == lActualNbOfEventsToBeGenerated,\n \"Actual total number of requests to be generated: \"\n << lExpectedNbOfEventsToBeGenerated\n << \" (=> \"\n << std::floor (lExpectedNbOfEventsToBeGenerated)\n << \"). Reference value: \" << lRefExpectedNbOfEvents);\n\n \/** Is the queue empty? *\/\n const bool isQueueDone = trademgenService.isQueueDone();\n BOOST_REQUIRE_MESSAGE (isQueueDone == false,\n \"The event queue should not be empty. You may check \"\n << \"the input file: '\" << lInputFilename << \"'\");\n\n \/**\n Main loop.\n