text
stringlengths
54
60.6k
<commit_before>// Generator builder // This is the device that builds generators. #include <boost/filesystem.hpp> #include <boost/range/iterator_range.hpp> #include <gtk/gtk.h> #include <ifstream> #include <libxml/parser.h> #include <string> #include <vector> namespace fs = boost::filesystem; using namespace std; // Add element to document. // elementLabel is the label for the element, and // listFile is the name of the list file. void addElement(string elementToAdd, string elementLabel, string listFile) { xmlNodePtr elementLabelNodePtr; xmlNodePtr elementNodePtr; elementLabelNodePtr = xmlNewNode(NULL, BAD_CAST "root"); xmlNodeSetContent(n, BAD_CAST elementToAdd); xmlDocSetRootElement(doc, elementLabelNodePtr); } // Remove element from document. void removeElement(xmlNodePtr elementToRemove) { xmlUnlinkNode(elementToRemove); xmlFreeNode(elementToRemove); } // GTK void activate(GtkApplication *app, gpointer user_data) { GtkWidget *window; GtkWidget *button; GtkWidget *textTagTable; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "Generator Editor"); gtk_window_set_default_size(GTK_WINDOW(window), 200, 200); g_signal_connect(window, "delete-event", G_CALLBACK(delete_event), NULL); g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL); } int main(void) { gtk_init(); // Build a list of directories. string dirPath = "/ListFiles"; // Path to directory fs::path p(dirPath); vector<string> fileNames = ""; if(fs::is_directory(p)) int i = 0; for (auto & p : fs::make_iterator_range(fs::directory_iterator(p), {})) { fileNames[i] = fs::entry; i++; } // Display the list of files. // CList // Vertical Scrollbar fileListBuffer = gtk_text_buffer_new (GTKTextTagTable *table); fileListWindow = gtk_text_view_new_with_buffer (fileListBuffer); fileListScrollbar = gtk_scrollbar_new(vertical); i xmlChar *xmlbuffer; int buffersize; // Create the XML document to store the generator. xmlDocPtr doc; doc = xmlNewDoc(BAD_CAST "1.0"); // Generate the menu for selecting a list file. return(0); } <commit_msg>Delete genbuilder.cpp<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. #include "../general/okina.hpp" #include <bitset> #include <cassert> namespace mfem { // ***************************************************************************** // * Tests if ptr is a known address // ***************************************************************************** static bool Known(const mm::ledger &maps, const void *ptr) { const mm::memory_map::const_iterator found = maps.memories.find(ptr); const bool known = found != maps.memories.end(); if (known) { return true; } return false; } // ***************************************************************************** bool mm::Known(const void *ptr) { return mfem::Known(maps,ptr); } // ***************************************************************************** // * Looks if ptr is an alias of one memory // ***************************************************************************** static const void* IsAlias(const mm::ledger &maps, const void *ptr) { MFEM_ASSERT(!Known(maps, ptr), "Ptr is an already known address!"); for (mm::memory_map::const_iterator mem = maps.memories.begin(); mem != maps.memories.end(); mem++) { const void *b_ptr = mem->first; if (b_ptr > ptr) { continue; } const void *end = static_cast<const char*>(b_ptr) + mem->second.bytes; if (ptr < end) { return b_ptr; } } return nullptr; } // ***************************************************************************** static const void* InsertAlias(mm::ledger &maps, const void *base, const void *ptr) { mm::memory &mem = maps.memories.at(base); const long offset = static_cast<const char*>(ptr) - static_cast<const char*> (base); const mm::alias *alias = new mm::alias{&mem, offset}; maps.aliases.emplace(ptr, alias); #ifdef MFEM_DEBUG_MM { mem.aliases.sort(); for (const mm::alias *a : mem.aliases) { if (a->mem == &mem ) { if (a->offset == offset){ mfem_error("a->offset == offset"); } } } } #endif mem.aliases.push_back(alias); return ptr; } // ***************************************************************************** // * Tests if ptr is an alias address // ***************************************************************************** static bool Alias(mm::ledger &maps, const void *ptr) { const mm::alias_map::const_iterator found = maps.aliases.find(ptr); const bool alias = found != maps.aliases.end(); if (alias) { return true; } const void *base = IsAlias(maps, ptr); if (!base) { return false; } InsertAlias(maps, base, ptr); return true; } // ***************************************************************************** bool mm::Alias(const void *ptr) { return mfem::Alias(maps,ptr); } // ***************************************************************************** static void DumpMode(void) { static bool env_ini = false; static bool env_dbg = false; if (!env_ini) { env_dbg = getenv("DBG"); env_ini = true; } if (!env_dbg) { return; } static std::bitset<8+1> mode; std::bitset<8+1> cfg; cfg.set(config::UsingMM()?8:0); cfg.set(config::DeviceHasBeenEnabled()?7:0); cfg.set(config::DeviceEnabled()?6:0); cfg.set(config::DeviceDisabled()?5:0); cfg.set(config::UsingHost()?4:0); cfg.set(config::UsingDevice()?3:0); cfg.set(config::UsingCuda()?2:0); cfg.set(config::UsingOcca()?1:0); cfg>>=1; if (cfg==mode) { return; } mode=cfg; printf("\033[1K\r[0x%lx] %sMM %sHasBeenEnabled %sEnabled %sDisabled " "%sHOST %sDEVICE %sCUDA %sOCCA\033[m", mode.to_ulong(), config::UsingMM()?"\033[32m":"\033[31m", config::DeviceHasBeenEnabled()?"\033[32m":"\033[31m", config::DeviceEnabled()?"\033[32m":"\033[31m", config::DeviceDisabled()?"\033[32m":"\033[31m", config::UsingHost()?"\033[32m":"\033[31m", config::UsingDevice()?"\033[32m":"\033[31m", config::UsingCuda()?"\033[32m":"\033[31m", config::UsingOcca()?"\033[32m":"\033[31m"); } // ***************************************************************************** // * Adds an address // ***************************************************************************** void* mm::Insert(void *ptr, const size_t bytes) { if (!config::UsingMM()) { return ptr; } const bool known = Known(ptr); if (known) { mfem_error("Trying to add an already present address!"); } DumpMode(); // ex1p comes with (bytes==0) maps.memories.emplace(ptr, memory(ptr, bytes)); return ptr; } // ***************************************************************************** // * Remove the address from the map, as well as all the address' aliases // ***************************************************************************** void *mm::Erase(void *ptr) { if (!config::UsingMM()) { return ptr; } const bool known = Known(ptr); if (!known) { mfem_error("Trying to erase an unknown pointer!"); } memory &mem = maps.memories.at(ptr); for (const alias* const alias : mem.aliases) { maps.aliases.erase(alias); } mem.aliases.clear(); maps.memories.erase(ptr); return ptr; } // ***************************************************************************** static inline bool MmDeviceIniFilter(void) { if (!config::UsingMM()) { return true; } if (config::DeviceDisabled()) { return true; } if (!config::DeviceHasBeenEnabled()) { return true; } if (config::UsingOcca()) { mfem_error("config::UsingOcca()"); } return false; } // ***************************************************************************** // * Turn a known address to the right host or device one // * Alloc, Push or Pull it if required // ***************************************************************************** static void *PtrKnown(mm::ledger &maps, void *ptr) { mm::memory &base = maps.memories.at(ptr); const bool host = base.host; const bool device = !host; const size_t bytes = base.bytes; const bool gpu = config::UsingDevice(); if (host && !gpu) { return ptr; } if (bytes==0) { mfem_error("PtrKnown bytes==0"); } if (!base.d_ptr) { cuMemAlloc(&base.d_ptr, bytes); } if (!base.d_ptr) { mfem_error("PtrKnown !base->d_ptr"); } if (device && gpu) { return base.d_ptr; } if (!ptr) { mfem_error("PtrKnown !ptr"); } if (device && !gpu) // Pull { mfem::cuMemcpyDtoH(ptr, base.d_ptr, bytes); base.host = true; return ptr; } // Push if (!(host && gpu)) { mfem_error("PtrKnown !(host && gpu)"); } cuMemcpyHtoD(base.d_ptr, ptr, bytes); base.host = false; return base.d_ptr; } // ***************************************************************************** // * Turn an alias to the right host or device one // * Alloc, Push or Pull it if required // ***************************************************************************** static void *PtrAlias(mm::ledger &maps, void *ptr) { const bool gpu = config::UsingDevice(); const mm::alias *alias = maps.aliases.at(ptr); assert(alias->offset >0); const mm::memory *base = alias->mem; assert(base); const bool host = base->host; const bool device = !base->host; const size_t bytes = base->bytes; if (host && !gpu) { return ptr; } if (bytes==0) { mfem_error("PtrAlias bytes==0"); } if (!base->d_ptr) { cuMemAlloc(&(alias->mem->d_ptr), bytes); } if (!base->d_ptr) { mfem_error("PtrAlias !base->d_ptr"); } void *a_ptr = static_cast<char*>(base->d_ptr) + alias->offset; if (device && gpu) { return a_ptr; } if (!base->h_ptr) { mfem_error("PtrAlias !base->h_ptr"); } if (device && !gpu) // Pull { mfem::cuMemcpyDtoH(base->h_ptr, base->d_ptr, bytes); alias->mem->host = true; return ptr; } // Push if (!(host && gpu)) { mfem_error("PtrAlias !(host && gpu)"); } mfem::cuMemcpyHtoD(base->d_ptr, base->h_ptr, bytes); alias->mem->host = false; return a_ptr; } // ***************************************************************************** // * Turn an address to the right host or device one // * If the pointer is NULL the companion pointer // * will be too. // ***************************************************************************** void *mm::Ptr(void *ptr) { if (MmDeviceIniFilter()) { return ptr; } if (Known(ptr)) { return PtrKnown(maps, ptr); } if (Alias(ptr)) { return PtrAlias(maps, ptr); } if (ptr==NULL) { return NULL; } else { mfem_error("Trying to use unknown pointer on the DEVICE!"); } return ptr; } // ***************************************************************************** const void *mm::Ptr(const void *ptr) { return static_cast<const void*>(Ptr(const_cast<void*>(ptr))); } // ***************************************************************************** static void PushKnown(mm::ledger &maps, const void *ptr, const size_t bytes) { mm::memory &base = maps.memories.at(ptr); if (!base.d_ptr) { cuMemAlloc(&base.d_ptr, base.bytes); } mfem::cuMemcpyHtoD(base.d_ptr, ptr, bytes == 0 ? base.bytes : bytes); } // ***************************************************************************** static void PushAlias(const mm::ledger &maps, const void *ptr, const size_t bytes) { const mm::alias *alias = maps.aliases.at(ptr); void *dst = static_cast<char*>(alias->mem->d_ptr) + alias->offset; mfem::cuMemcpyHtoD(dst, ptr, bytes); } // ***************************************************************************** void mm::Push(const void *ptr, const size_t bytes) { if (bytes==0) { mfem_error("Push bytes==0"); } if (MmDeviceIniFilter()) { return; } if (Known(ptr)) { return PushKnown(maps, ptr, bytes); } if (Alias(ptr)) { return PushAlias(maps, ptr, bytes); } if (config::UsingDevice()) { mfem_error("Unknown pointer to push to!"); } } // ***************************************************************************** static void PullKnown(const mm::ledger &maps, const void *ptr, const size_t bytes) { const mm::memory &base = maps.memories.at(ptr); const bool host = base.host; if (host) { return; } assert(base.h_ptr); assert(base.d_ptr); mfem::cuMemcpyDtoH(base.h_ptr, base.d_ptr, bytes == 0 ? base.bytes : bytes); } // ***************************************************************************** static void PullAlias(const mm::ledger &maps, const void *ptr, const size_t bytes) { const mm::alias *alias = maps.aliases.at(ptr); const bool host = alias->mem->host; if (host) { return; } if (!ptr) { mfem_error("PullAlias !ptr"); } if (!alias->mem->d_ptr) { mfem_error("PullAlias !alias->mem->d_ptr"); } mfem::cuMemcpyDtoH(const_cast<void*>(ptr), static_cast<char*>(alias->mem->d_ptr) + alias->offset, bytes); } // ***************************************************************************** void mm::Pull(const void *ptr, const size_t bytes) { if (MmDeviceIniFilter()) { return; } if (Known(ptr)) { return PullKnown(maps, ptr, bytes); } if (Alias(ptr)) { return PullAlias(maps, ptr, bytes); } if (config::UsingDevice()) { mfem_error("Unknown pointer to pull from!"); } } // ***************************************************************************** // * Data will be pushed/pulled before the copy happens on the H or the D // ***************************************************************************** void* mm::memcpy(void *dst, const void *src, const size_t bytes, const bool async) { void *d_dst = mm::ptr(dst); const void *d_src = mm::ptr(src); const bool host = config::UsingHost(); if (bytes == 0) return dst; if (host) { return std::memcpy(dst, src, bytes); } if (!async) { return mfem::cuMemcpyDtoD(d_dst, const_cast<void*>(d_src), bytes); } return mfem::cuMemcpyDtoDAsync(d_dst, const_cast<void*>(d_src), bytes, config::Stream()); } // ***************************************************************************** static OccaMemory occaMemory(mm::ledger &maps, const void *ptr) { OccaDevice occaDevice = config::GetOccaDevice(); if (!config::UsingMM()) { OccaMemory o_ptr = occaWrapMemory(occaDevice, const_cast<void*>(ptr), 0); return o_ptr; } const bool known = mm::known(ptr); if (!known) { mfem_error("occaMemory: Unknown address!"); } mm::memory &base = maps.memories.at(ptr); const size_t bytes = base.bytes; const bool gpu = config::UsingDevice(); if (!config::UsingOcca()) { mfem_error("Using OCCA without support!"); } if (!base.d_ptr) { base.host = false; // This address is no more on the host if (gpu) { cuMemAlloc(&base.d_ptr, bytes); void *stream = config::Stream(); cuMemcpyHtoDAsync(base.d_ptr, base.h_ptr, bytes, stream); } else { base.o_ptr = occaDeviceMalloc(occaDevice, bytes); base.d_ptr = occaMemoryPtr(base.o_ptr); occaCopyFrom(base.o_ptr, base.h_ptr); } } if (gpu) { return occaWrapMemory(occaDevice, base.d_ptr, bytes); } return base.o_ptr; } // ***************************************************************************** void RegisterCheck(void *ptr) { if(ptr != NULL){ if(!mm::known(ptr)) { assert(0 && "Pointer is not registered!"); mfem_error("Trying use an unregistered pointer!"); } } } // ***************************************************************************** OccaMemory mm::Memory(const void *ptr) { return occaMemory(maps, ptr); } } // namespace mfem <commit_msg>add guard in case mm is not being used<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. #include "../general/okina.hpp" #include <bitset> #include <cassert> namespace mfem { // ***************************************************************************** // * Tests if ptr is a known address // ***************************************************************************** static bool Known(const mm::ledger &maps, const void *ptr) { const mm::memory_map::const_iterator found = maps.memories.find(ptr); const bool known = found != maps.memories.end(); if (known) { return true; } return false; } // ***************************************************************************** bool mm::Known(const void *ptr) { return mfem::Known(maps,ptr); } // ***************************************************************************** // * Looks if ptr is an alias of one memory // ***************************************************************************** static const void* IsAlias(const mm::ledger &maps, const void *ptr) { MFEM_ASSERT(!Known(maps, ptr), "Ptr is an already known address!"); for (mm::memory_map::const_iterator mem = maps.memories.begin(); mem != maps.memories.end(); mem++) { const void *b_ptr = mem->first; if (b_ptr > ptr) { continue; } const void *end = static_cast<const char*>(b_ptr) + mem->second.bytes; if (ptr < end) { return b_ptr; } } return nullptr; } // ***************************************************************************** static const void* InsertAlias(mm::ledger &maps, const void *base, const void *ptr) { mm::memory &mem = maps.memories.at(base); const long offset = static_cast<const char*>(ptr) - static_cast<const char*> (base); const mm::alias *alias = new mm::alias{&mem, offset}; maps.aliases.emplace(ptr, alias); #ifdef MFEM_DEBUG_MM { mem.aliases.sort(); for (const mm::alias *a : mem.aliases) { if (a->mem == &mem ) { if (a->offset == offset){ mfem_error("a->offset == offset"); } } } } #endif mem.aliases.push_back(alias); return ptr; } // ***************************************************************************** // * Tests if ptr is an alias address // ***************************************************************************** static bool Alias(mm::ledger &maps, const void *ptr) { const mm::alias_map::const_iterator found = maps.aliases.find(ptr); const bool alias = found != maps.aliases.end(); if (alias) { return true; } const void *base = IsAlias(maps, ptr); if (!base) { return false; } InsertAlias(maps, base, ptr); return true; } // ***************************************************************************** bool mm::Alias(const void *ptr) { return mfem::Alias(maps,ptr); } // ***************************************************************************** static void DumpMode(void) { static bool env_ini = false; static bool env_dbg = false; if (!env_ini) { env_dbg = getenv("DBG"); env_ini = true; } if (!env_dbg) { return; } static std::bitset<8+1> mode; std::bitset<8+1> cfg; cfg.set(config::UsingMM()?8:0); cfg.set(config::DeviceHasBeenEnabled()?7:0); cfg.set(config::DeviceEnabled()?6:0); cfg.set(config::DeviceDisabled()?5:0); cfg.set(config::UsingHost()?4:0); cfg.set(config::UsingDevice()?3:0); cfg.set(config::UsingCuda()?2:0); cfg.set(config::UsingOcca()?1:0); cfg>>=1; if (cfg==mode) { return; } mode=cfg; printf("\033[1K\r[0x%lx] %sMM %sHasBeenEnabled %sEnabled %sDisabled " "%sHOST %sDEVICE %sCUDA %sOCCA\033[m", mode.to_ulong(), config::UsingMM()?"\033[32m":"\033[31m", config::DeviceHasBeenEnabled()?"\033[32m":"\033[31m", config::DeviceEnabled()?"\033[32m":"\033[31m", config::DeviceDisabled()?"\033[32m":"\033[31m", config::UsingHost()?"\033[32m":"\033[31m", config::UsingDevice()?"\033[32m":"\033[31m", config::UsingCuda()?"\033[32m":"\033[31m", config::UsingOcca()?"\033[32m":"\033[31m"); } // ***************************************************************************** // * Adds an address // ***************************************************************************** void* mm::Insert(void *ptr, const size_t bytes) { if (!config::UsingMM()) { return ptr; } const bool known = Known(ptr); if (known) { mfem_error("Trying to add an already present address!"); } DumpMode(); // ex1p comes with (bytes==0) maps.memories.emplace(ptr, memory(ptr, bytes)); return ptr; } // ***************************************************************************** // * Remove the address from the map, as well as all the address' aliases // ***************************************************************************** void *mm::Erase(void *ptr) { if (!config::UsingMM()) { return ptr; } const bool known = Known(ptr); if (!known) { mfem_error("Trying to erase an unknown pointer!"); } memory &mem = maps.memories.at(ptr); for (const alias* const alias : mem.aliases) { maps.aliases.erase(alias); } mem.aliases.clear(); maps.memories.erase(ptr); return ptr; } // ***************************************************************************** static inline bool MmDeviceIniFilter(void) { if (!config::UsingMM()) { return true; } if (config::DeviceDisabled()) { return true; } if (!config::DeviceHasBeenEnabled()) { return true; } if (config::UsingOcca()) { mfem_error("config::UsingOcca()"); } return false; } // ***************************************************************************** // * Turn a known address to the right host or device one // * Alloc, Push or Pull it if required // ***************************************************************************** static void *PtrKnown(mm::ledger &maps, void *ptr) { mm::memory &base = maps.memories.at(ptr); const bool host = base.host; const bool device = !host; const size_t bytes = base.bytes; const bool gpu = config::UsingDevice(); if (host && !gpu) { return ptr; } if (bytes==0) { mfem_error("PtrKnown bytes==0"); } if (!base.d_ptr) { cuMemAlloc(&base.d_ptr, bytes); } if (!base.d_ptr) { mfem_error("PtrKnown !base->d_ptr"); } if (device && gpu) { return base.d_ptr; } if (!ptr) { mfem_error("PtrKnown !ptr"); } if (device && !gpu) // Pull { mfem::cuMemcpyDtoH(ptr, base.d_ptr, bytes); base.host = true; return ptr; } // Push if (!(host && gpu)) { mfem_error("PtrKnown !(host && gpu)"); } cuMemcpyHtoD(base.d_ptr, ptr, bytes); base.host = false; return base.d_ptr; } // ***************************************************************************** // * Turn an alias to the right host or device one // * Alloc, Push or Pull it if required // ***************************************************************************** static void *PtrAlias(mm::ledger &maps, void *ptr) { const bool gpu = config::UsingDevice(); const mm::alias *alias = maps.aliases.at(ptr); assert(alias->offset >0); const mm::memory *base = alias->mem; assert(base); const bool host = base->host; const bool device = !base->host; const size_t bytes = base->bytes; if (host && !gpu) { return ptr; } if (bytes==0) { mfem_error("PtrAlias bytes==0"); } if (!base->d_ptr) { cuMemAlloc(&(alias->mem->d_ptr), bytes); } if (!base->d_ptr) { mfem_error("PtrAlias !base->d_ptr"); } void *a_ptr = static_cast<char*>(base->d_ptr) + alias->offset; if (device && gpu) { return a_ptr; } if (!base->h_ptr) { mfem_error("PtrAlias !base->h_ptr"); } if (device && !gpu) // Pull { mfem::cuMemcpyDtoH(base->h_ptr, base->d_ptr, bytes); alias->mem->host = true; return ptr; } // Push if (!(host && gpu)) { mfem_error("PtrAlias !(host && gpu)"); } mfem::cuMemcpyHtoD(base->d_ptr, base->h_ptr, bytes); alias->mem->host = false; return a_ptr; } // ***************************************************************************** // * Turn an address to the right host or device one // * If the pointer is NULL the companion pointer // * will be too. // ***************************************************************************** void *mm::Ptr(void *ptr) { if (MmDeviceIniFilter()) { return ptr; } if (Known(ptr)) { return PtrKnown(maps, ptr); } if (Alias(ptr)) { return PtrAlias(maps, ptr); } if (ptr==NULL) { return NULL; } else { mfem_error("Trying to use unknown pointer on the DEVICE!"); } return ptr; } // ***************************************************************************** const void *mm::Ptr(const void *ptr) { return static_cast<const void*>(Ptr(const_cast<void*>(ptr))); } // ***************************************************************************** static void PushKnown(mm::ledger &maps, const void *ptr, const size_t bytes) { mm::memory &base = maps.memories.at(ptr); if (!base.d_ptr) { cuMemAlloc(&base.d_ptr, base.bytes); } mfem::cuMemcpyHtoD(base.d_ptr, ptr, bytes == 0 ? base.bytes : bytes); } // ***************************************************************************** static void PushAlias(const mm::ledger &maps, const void *ptr, const size_t bytes) { const mm::alias *alias = maps.aliases.at(ptr); void *dst = static_cast<char*>(alias->mem->d_ptr) + alias->offset; mfem::cuMemcpyHtoD(dst, ptr, bytes); } // ***************************************************************************** void mm::Push(const void *ptr, const size_t bytes) { if (bytes==0) { mfem_error("Push bytes==0"); } if (MmDeviceIniFilter()) { return; } if (Known(ptr)) { return PushKnown(maps, ptr, bytes); } if (Alias(ptr)) { return PushAlias(maps, ptr, bytes); } if (config::UsingDevice()) { mfem_error("Unknown pointer to push to!"); } } // ***************************************************************************** static void PullKnown(const mm::ledger &maps, const void *ptr, const size_t bytes) { const mm::memory &base = maps.memories.at(ptr); const bool host = base.host; if (host) { return; } assert(base.h_ptr); assert(base.d_ptr); mfem::cuMemcpyDtoH(base.h_ptr, base.d_ptr, bytes == 0 ? base.bytes : bytes); } // ***************************************************************************** static void PullAlias(const mm::ledger &maps, const void *ptr, const size_t bytes) { const mm::alias *alias = maps.aliases.at(ptr); const bool host = alias->mem->host; if (host) { return; } if (!ptr) { mfem_error("PullAlias !ptr"); } if (!alias->mem->d_ptr) { mfem_error("PullAlias !alias->mem->d_ptr"); } mfem::cuMemcpyDtoH(const_cast<void*>(ptr), static_cast<char*>(alias->mem->d_ptr) + alias->offset, bytes); } // ***************************************************************************** void mm::Pull(const void *ptr, const size_t bytes) { if (MmDeviceIniFilter()) { return; } if (Known(ptr)) { return PullKnown(maps, ptr, bytes); } if (Alias(ptr)) { return PullAlias(maps, ptr, bytes); } if (config::UsingDevice()) { mfem_error("Unknown pointer to pull from!"); } } // ***************************************************************************** // * Data will be pushed/pulled before the copy happens on the H or the D // ***************************************************************************** void* mm::memcpy(void *dst, const void *src, const size_t bytes, const bool async) { void *d_dst = mm::ptr(dst); const void *d_src = mm::ptr(src); const bool host = config::UsingHost(); if (bytes == 0) return dst; if (host) { return std::memcpy(dst, src, bytes); } if (!async) { return mfem::cuMemcpyDtoD(d_dst, const_cast<void*>(d_src), bytes); } return mfem::cuMemcpyDtoDAsync(d_dst, const_cast<void*>(d_src), bytes, config::Stream()); } // ***************************************************************************** static OccaMemory occaMemory(mm::ledger &maps, const void *ptr) { OccaDevice occaDevice = config::GetOccaDevice(); if (!config::UsingMM()) { OccaMemory o_ptr = occaWrapMemory(occaDevice, const_cast<void*>(ptr), 0); return o_ptr; } const bool known = mm::known(ptr); if (!known) { mfem_error("occaMemory: Unknown address!"); } mm::memory &base = maps.memories.at(ptr); const size_t bytes = base.bytes; const bool gpu = config::UsingDevice(); if (!config::UsingOcca()) { mfem_error("Using OCCA without support!"); } if (!base.d_ptr) { base.host = false; // This address is no more on the host if (gpu) { cuMemAlloc(&base.d_ptr, bytes); void *stream = config::Stream(); cuMemcpyHtoDAsync(base.d_ptr, base.h_ptr, bytes, stream); } else { base.o_ptr = occaDeviceMalloc(occaDevice, bytes); base.d_ptr = occaMemoryPtr(base.o_ptr); occaCopyFrom(base.o_ptr, base.h_ptr); } } if (gpu) { return occaWrapMemory(occaDevice, base.d_ptr, bytes); } return base.o_ptr; } // ***************************************************************************** void RegisterCheck(void *ptr) { if(ptr != NULL && config::UsingMM()){ if(!mm::known(ptr)) { assert(0 && "Pointer is not registered!"); mfem_error("Trying use an unregistered pointer!"); } } } // ***************************************************************************** OccaMemory mm::Memory(const void *ptr) { return occaMemory(maps, ptr); } } // namespace mfem <|endoftext|>
<commit_before>/* * smallargs.hpp * * Created on: 2 Dec 2016 * Author: Fabian Meyer * * LICENSE * ======= * * The MIT License (MIT) * * Copyright (c) 2016 Fabian Meyer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef INCLUDE_SMALLARGS_HPP_ #define INCLUDE_SMALLARGS_HPP_ #include <cassert> #include <string> #include <stdexcept> #include <sstream> #include <vector> extern "C" { #include "smallargs.h" } namespace sarg { typedef sarg_opt_type optType; typedef sarg_opt opt; typedef sarg_result result; typedef sarg_opt_cb optCallback; class Error : public std::exception { private: int errVal_; std::string errMsg_; public: Error(const int errVal) throw() : errVal_(errVal), errMsg_() { std::stringstream ss; ss << errVal_ << ": " << sarg_strerror(errVal); errMsg_ = ss.str(); } ~Error() throw() { } const char* what() const throw() { return errMsg_.c_str(); } int errval() { return errVal_; } }; class Root { private: std::string name_; sarg_root root_; std::vector<opt> opts_; bool init_; public: Root(const std::string& name) :name_(name), init_(false) {} Root(const Root& root) :name_(root.name_), init_(false) { //TODO _SARG_UNUSED(root); assert(false); } ~Root() { unsigned int i; sarg_destroy(&root_); for(i = 0; i < opts_.size(); ++i) _sarg_opt_destroy(&opts_[i]); } Root &add(const std::string &shortName, const std::string &longName, const std::string &help, const optType type, const optCallback cb) { if(init_) throw std::logic_error("root was already initialized"); int ret; opts_.resize(opts_.size() + 1); ret = _sarg_opt_init(&opts_.back(), shortName.c_str(), longName.c_str(), help.c_str(), type, cb); if(ret != SARG_ERR_SUCCESS) throw Error(ret); return *this; } void init() { int ret; opt nullOpt = {NULL, NULL, NULL, INT, NULL}; opts_.push_back(nullOpt); ret = sarg_init(&root_, &opts_[0], name_.c_str()); if(ret != SARG_ERR_SUCCESS) throw Error(ret); init_ = true; } const result& operator[](const std::string &key) { int ret; result *res; ret = sarg_get(&root_, key.c_str(), &res); if(ret != SARG_ERR_SUCCESS) throw Error(ret); return *res; } void parse(const char **argv, const int argc) { int ret; ret = sarg_parse(&root_, argv, argc); if(ret != SARG_ERR_SUCCESS) throw Error(ret); } #ifndef SARG_NO_PRINT std::string getHelp() { std::string result; char *text; int ret; ret = sarg_help_text(&root_, &text); if(ret != SARG_ERR_SUCCESS) throw Error(ret); result = std::string(text); free(text); return result; } void printHelp() { int ret; ret = sarg_help_print(&root_); if(ret != SARG_ERR_SUCCESS) throw Error(ret); } #endif #ifndef SARG_NO_FILE void fromFile(const std::string &filename) { int ret; ret = sarg_parse_file(&root_, filename.c_str()); if(ret != SARG_ERR_SUCCESS) throw Error(ret); } #endif }; } #endif <commit_msg>Fix NULL string issue<commit_after>/* * smallargs.hpp * * Created on: 2 Dec 2016 * Author: Fabian Meyer * * LICENSE * ======= * * The MIT License (MIT) * * Copyright (c) 2016 Fabian Meyer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef INCLUDE_SMALLARGS_HPP_ #define INCLUDE_SMALLARGS_HPP_ #include <cassert> #include <string> #include <stdexcept> #include <sstream> #include <vector> extern "C" { #include "smallargs.h" } namespace sarg { typedef sarg_opt_type optType; typedef sarg_opt opt; typedef sarg_result result; typedef sarg_opt_cb optCallback; class Error : public std::exception { private: int errVal_; std::string errMsg_; public: Error(const int errVal) throw() : errVal_(errVal), errMsg_() { std::stringstream ss; ss << errVal_ << ": " << sarg_strerror(errVal); errMsg_ = ss.str(); } ~Error() throw() { } const char* what() const throw() { return errMsg_.c_str(); } int errval() { return errVal_; } }; class Root { private: std::string name_; sarg_root root_; std::vector<opt> opts_; bool init_; public: Root(const std::string& name) :name_(name), init_(false) {} Root(const Root& root) :name_(root.name_), init_(false) { //TODO _SARG_UNUSED(root); assert(false); } ~Root() { unsigned int i; sarg_destroy(&root_); for(i = 0; i < opts_.size(); ++i) _sarg_opt_destroy(&opts_[i]); } Root &add(const char *shortName, const char *longName, const char *help, const optType type, const optCallback cb) { if(init_) throw std::logic_error("root was already initialized"); int ret; opts_.resize(opts_.size() + 1); ret = _sarg_opt_init(&opts_.back(), shortName, longName, help, type, cb); if(ret != SARG_ERR_SUCCESS) throw Error(ret); return *this; } void init() { int ret; opt nullOpt = {NULL, NULL, NULL, INT, NULL}; opts_.push_back(nullOpt); ret = sarg_init(&root_, &opts_[0], name_.c_str()); if(ret != SARG_ERR_SUCCESS) throw Error(ret); init_ = true; } const result& operator[](const std::string &key) { int ret; result *res; ret = sarg_get(&root_, key.c_str(), &res); if(ret != SARG_ERR_SUCCESS) throw Error(ret); return *res; } void parse(const char **argv, const int argc) { int ret; ret = sarg_parse(&root_, argv, argc); if(ret != SARG_ERR_SUCCESS) throw Error(ret); } #ifndef SARG_NO_PRINT std::string getHelp() { std::string result; char *text; int ret; ret = sarg_help_text(&root_, &text); if(ret != SARG_ERR_SUCCESS) throw Error(ret); result = std::string(text); free(text); return result; } void printHelp() { int ret; ret = sarg_help_print(&root_); if(ret != SARG_ERR_SUCCESS) throw Error(ret); } #endif #ifndef SARG_NO_FILE void fromFile(const std::string &filename) { int ret; ret = sarg_parse_file(&root_, filename.c_str()); if(ret != SARG_ERR_SUCCESS) throw Error(ret); } #endif }; } #endif <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /** @file AliFMDPreprocessor.cxx @author Hans Hjersing Dalsgaard <[email protected]> @date Mon Mar 27 12:39:09 2006 @brief Shuttle "preprocessor" for the FMD */ //___________________________________________________________________ // // The class processes data points from DCS (via Amanada), and DAQ DA // files (via FXS) to make calibration data for the FMD. // // Data points: // * Nothing yet. // // DAQ FXS file: // * pedestals - a (ASCII) Comma Separated Values files with the // fields // rcu DDL number // board FEC board number // chip ALTRO chip number on FEC // channel ALTRO channel number // strip VA1 strip number // sample Sample number // ped Mean of ADC spectra // noise Spread of ADC spectra // mu Mean of Gaussian fit to ADC spectra // sigma Variance of Gaussian fit to ADC spectra // chi2 Chi^2 per degrees of freedom of fit // * Gains - a (ASCII) Comma Separated Values files with the // fields // rcu DDL number // board FEC board number // chip ALTRO chip number on FEC // channel ALTRO channel number // strip VA1 strip number // gain Slope of gain // error Error on gain // chi2 Chi^2 per degrees of freedom of fit // // See also // // http://aliceinfo.cern.ch/Offline/Activities/Shuttle.html // // Latest changes by Christian Holm Christensen // // #include <iostream> #include <fstream> #include "AliFMDPreprocessor.h" #include "AliFMDCalibPedestal.h" #include "AliFMDCalibGain.h" #include "AliFMDCalibStripRange.h" #include "AliFMDCalibSampleRate.h" #include "AliFMDParameters.h" #include "AliCDBMetaData.h" #include "AliCDBManager.h" // #include "AliDCSValue.h" #include "AliLog.h" #include <TTimeStamp.h> // #include <TFile.h> #include <TObjString.h> #include <TString.h> #include <TNamed.h> ClassImp(AliFMDPreprocessor) #if 0 // Do not remove - here to make Emacs happy ; #endif //____________________________________________________ Bool_t AliFMDPreprocessor::GetAndCheckFileSources(TList*& list, Int_t system, const char* id) { // Convinience function // Parameters: // list On return, list of files. // system Alice system (DAQ, DCS, ...) // id File id // Return: // kTRUE on success. list = GetFileSources(system, id); if (!list) { TString sys; switch (system) { case kDAQ: sys = "DAQ"; break; case kDCS: sys = "DCS"; break; default: sys = "unknown"; break; } Log(Form("Failed to get file sources for %s/%s", sys.Data(), system)); return kFALSE; } return kTRUE; } //____________________________________________________ AliCDBEntry* AliFMDPreprocessor::GetFromCDB(const char* second, const char* third) { return GetFromOCDB(second, third); } //____________________________________________________ UInt_t AliFMDPreprocessor::Process(TMap* /* dcsAliasMap */) { // Main member function. // Parameters: // dcsAliassMap Map of DCS data point aliases. // Return // 0 on success, >0 otherwise Bool_t resultPed = kTRUE; Bool_t resultGain = kTRUE; Bool_t resultRange = kTRUE; Bool_t resultRate = kTRUE; Bool_t resultZero = kTRUE; // Do we need this ? // if(!dcsAliasMap) return 1; // // Invoking the cdb manager and the FMD parameters class // AliCDBManager* cdb = AliCDBManager::Instance(); // cdb->SetDefaultStorage("local://$ALICE_ROOT"); // cdb->SetRun(0); AliFMDParameters* pars = AliFMDParameters::Instance(); pars->Init(this, false, AliFMDParameters::kAltroMap); // This is if the SOR contains Fee parameters, and we run a DA to // extract these parameters. The same code could work if we get // the information from DCS via the FXS TList* files = 0; AliFMDCalibSampleRate* calibRate = 0; AliFMDCalibStripRange* calibRange = 0; AliFMDCalibZeroSuppression* calibZero = 0; // Disabled for now. #if 0 if (GetAndCheckFileSources(files, kDAQ,"info")) GetInfoCalibration(files, calibRate, calibRange, calibZero); resultRate = (!calibRate ? kFALSE : kTRUE); resultRange = (!calibRange ? kFALSE : kTRUE); resultZero = (!calibZero ? kFALSE : kTRUE); #endif // Gt the run type TString runType(GetRunType()); //Creating calibration objects AliFMDCalibPedestal* calibPed = 0; AliFMDCalibGain* calibGain = 0; if (runType.Contains("PEDESTAL", TString::kIgnoreCase)) { if (GetAndCheckFileSources(files, kDAQ, "pedestals")) { if(files->GetSize()) calibPed = GetPedestalCalibration(files); } resultPed = (calibPed ? kTRUE : kFALSE); } if (runType.Contains("PULSER", TString::kIgnoreCase)) { if (GetAndCheckFileSources(files, kDAQ, "gains")) { if(files->GetSize()) calibGain = GetGainCalibration(files); } resultGain = (calibGain ? kTRUE : kFALSE); } //Storing Calibration objects AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("Hans H. Dalsgaard"); metaData.SetComment("Preprocessor stores pedestals and gains for the FMD."); if(calibPed) { resultPed = Store("Calib","Pedestal", calibPed, &metaData, 0, kTRUE); delete calibPed; } if(calibGain) { resultGain = Store("Calib","PulseGain", calibGain, &metaData, 0, kTRUE); delete calibGain; } if(calibRange) { resultRange = Store("Calib","StripRange", calibRange, &metaData, 0, kTRUE); delete calibRange; } if(calibRate) { resultRate = Store("Calib","SampleRate", calibRate, &metaData, 0, kTRUE); delete calibRate; } if(calibZero) { resultZero = Store("Calib","ZeroSuppression", calibZero,&metaData,0,kTRUE); delete calibZero; } #if 0 // Disabled until we implement GetInfoCalibration properly Bool_t success = (resultPed && resultGain && resultRange && resultRate && resultZero); #endif Bool_t success = resultPed && resultGain; Log(Form("FMD preprocessor was %s", (success ? "successful" : "failed"))); return (success ? 0 : 1); } //____________________________________________________________________ Bool_t AliFMDPreprocessor::GetInfoCalibration(TList* files, AliFMDCalibSampleRate*& s, AliFMDCalibStripRange*& r, AliFMDCalibZeroSuppression*& z) { // Get info calibrations. // Parameters: // files List of files. // s On return, newly allocated object // r On return, newly allocated object // z On return, newly allocated object // Return: // kTRUE on success if (!files) return kTRUE; // Should really be false if (files->GetEntries() <= 0) return kTRUE; s = new AliFMDCalibSampleRate(); r = new AliFMDCalibStripRange(); z = new AliFMDCalibZeroSuppression(); // AliFMDParameters* pars = AliFMDParameters::Instance(); TIter iter(files); TObjString* fileSource; while((fileSource = dynamic_cast<TObjString*>(iter.Next()))) { const Char_t* filename = GetFile(kDAQ, "info", fileSource->GetName()); std::ifstream in(filename); if(!in) { Log(Form("File %s not found!", filename)); continue; } } return kTRUE; } //____________________________________________________________________ AliFMDCalibPedestal* AliFMDPreprocessor::GetPedestalCalibration(TList* pedFiles) { // Read DAQ DA produced CSV files of pedestals, and return a // calibration object. // Parameters: // pedFiles List of pedestal files // Return // A pointer to a newly allocated AliFMDCalibPedestal object, or // null in case of errors. if(!pedFiles) return 0; AliFMDCalibPedestal* calibPed = new AliFMDCalibPedestal(); AliFMDParameters* pars = AliFMDParameters::Instance(); TIter iter(pedFiles); TObjString* fileSource; while((fileSource = dynamic_cast<TObjString*>(iter.Next()))) { const Char_t* filename = GetFile(kDAQ, "pedestals", fileSource->GetName()); std::ifstream in(filename); if(!in) { Log(Form("File %s not found!", filename)); continue; } // Get header (how long is it ?) TString header; header.ReadLine(in); header.ToLower(); if(!header.Contains("pedestal")) { Log("File header is not from pedestal!"); continue; } Log("File contains data from pedestals"); // Read columns line int lineno = 2; header.ReadLine(in); // Loop until EOF while(in.peek()!=EOF) { if(in.bad()) { Log(Form("Bad read at line %d in %s", lineno, filename)); break; } UInt_t ddl=2, board, chip, channel, strip, sample, tb; Float_t ped, noise, mu, sigma, chi2ndf; Char_t c[11]; in >> ddl >> c[0] >> board >> c[1] >> chip >> c[2] >> channel >> c[3] >> strip >> c[4] >> sample >> c[5] >> tb >> c[6] >> ped >> c[7] >> noise >> c[8] >> mu >> c[9] >> sigma >> c[10] >> chi2ndf; lineno++; // Ignore trailing garbage if (strip > 127) continue; //Setting DDL to comply with the FMD in DAQ UInt_t FmdDDLBase = 3072; ddl = ddl - FmdDDLBase; //Setting the pedestals via the hardware address UShort_t det, sec, str; Char_t ring; pars->Hardware2Detector(ddl,board,chip,channel,det,ring,sec,str); strip += str; calibPed->Set(det,ring,sec,strip,ped,noise); } } return calibPed; } //____________________________________________________________________ AliFMDCalibGain* AliFMDPreprocessor::GetGainCalibration(TList* gainFiles) { // Read DAQ DA produced CSV files of pedestals, and return a // calibration object. // Parameters: // pedFiles List of pedestal files // Return // A pointer to a newly allocated AliFMDCalibPedestal object, or // null in case of errors. if(!gainFiles) return 0; AliFMDCalibGain* calibGain = new AliFMDCalibGain(); AliFMDParameters* pars = AliFMDParameters::Instance(); TIter iter(gainFiles); TObjString* fileSource; while((fileSource = dynamic_cast<TObjString *>(iter.Next()))) { const Char_t* filename = GetFile(kDAQ, "gains", fileSource->GetName()); std::ifstream in(filename); if(!in) { Log(Form("File %s not found!", filename)); continue; } //Get header (how long is it ?) TString header; header.ReadLine(in); header.ToLower(); if(!header.Contains("gain")) { Log("File header is not from gain!"); continue; } Log("File contains data from pulse gain"); // Read column headers header.ReadLine(in); int lineno = 2; // Read until EOF while(in.peek()!=EOF) { if(in.bad()) { Log(Form("Bad read at line %d in %s", lineno, filename)); break; } UInt_t ddl=2, board, chip, channel, strip; Float_t gain,error, chi2ndf; Char_t c[7]; in >> ddl >> c[0] >> board >> c[1] >> chip >> c[2] >> channel >> c[3] >> strip >> c[4] >> gain >> c[5] >> error >> c[6] >> chi2ndf; lineno++; // Ignore trailing garbage if(strip > 127) continue; //Setting DDL to comply with the FMD in DAQ UInt_t FmdDDLBase = 3072; ddl = ddl - FmdDDLBase; //Setting the pedestals via the hardware address UShort_t det, sec, str; Char_t ring; pars->Hardware2Detector(ddl,board,chip,channel,det,ring,sec,str); strip += str; calibGain->Set(det,ring,sec,strip,gain); } } return calibGain; } //____________________________________________________________________ // // EOF // <commit_msg>Changed the constructor to include calls to AddRunType(...). This change was required by the shuttle team at CERN.<commit_after>/************************************************************************** * Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /** @file AliFMDPreprocessor.cxx @author Hans Hjersing Dalsgaard <[email protected]> @date Mon Mar 27 12:39:09 2006 @brief Shuttle "preprocessor" for the FMD */ //___________________________________________________________________ // // The class processes data points from DCS (via Amanada), and DAQ DA // files (via FXS) to make calibration data for the FMD. // // Data points: // * Nothing yet. // // DAQ FXS file: // * pedestals - a (ASCII) Comma Separated Values files with the // fields // rcu DDL number // board FEC board number // chip ALTRO chip number on FEC // channel ALTRO channel number // strip VA1 strip number // sample Sample number // ped Mean of ADC spectra // noise Spread of ADC spectra // mu Mean of Gaussian fit to ADC spectra // sigma Variance of Gaussian fit to ADC spectra // chi2 Chi^2 per degrees of freedom of fit // * Gains - a (ASCII) Comma Separated Values files with the // fields // rcu DDL number // board FEC board number // chip ALTRO chip number on FEC // channel ALTRO channel number // strip VA1 strip number // gain Slope of gain // error Error on gain // chi2 Chi^2 per degrees of freedom of fit // // See also // // http://aliceinfo.cern.ch/Offline/Activities/Shuttle.html // // Latest changes by Christian Holm Christensen // // #include <iostream> #include <fstream> #include "AliFMDPreprocessor.h" #include "AliFMDCalibPedestal.h" #include "AliFMDCalibGain.h" #include "AliFMDCalibStripRange.h" #include "AliFMDCalibSampleRate.h" #include "AliFMDParameters.h" #include "AliCDBMetaData.h" #include "AliCDBManager.h" // #include "AliDCSValue.h" #include "AliLog.h" #include <TTimeStamp.h> // #include <TFile.h> #include <TObjString.h> #include <TString.h> #include <TNamed.h> ClassImp(AliFMDPreprocessor) #if 0 // Do not remove - here to make Emacs happy ; #endif //____________________________________________________ AliFMDPreprocessor::AliFMDPreprocessor(AliShuttleInterface* shuttle) : AliPreprocessor("FMD", shuttle) { AddRunType("PHYSICS"); AddRunType("STANDALONE"); AddRunType("PEDESTAL"); AddRunType("GAIN"); } //____________________________________________________ Bool_t AliFMDPreprocessor::GetAndCheckFileSources(TList*& list, Int_t system, const char* id) { // Convinience function // Parameters: // list On return, list of files. // system Alice system (DAQ, DCS, ...) // id File id // Return: // kTRUE on success. list = GetFileSources(system, id); if (!list) { TString sys; switch (system) { case kDAQ: sys = "DAQ"; break; case kDCS: sys = "DCS"; break; default: sys = "unknown"; break; } Log(Form("Failed to get file sources for %s/%s", sys.Data(), system)); return kFALSE; } return kTRUE; } //____________________________________________________ AliCDBEntry* AliFMDPreprocessor::GetFromCDB(const char* second, const char* third) { return GetFromOCDB(second, third); } //____________________________________________________ UInt_t AliFMDPreprocessor::Process(TMap* /* dcsAliasMap */) { // Main member function. // Parameters: // dcsAliassMap Map of DCS data point aliases. // Return // 0 on success, >0 otherwise Bool_t resultPed = kTRUE; Bool_t resultGain = kTRUE; Bool_t resultRange = kTRUE; Bool_t resultRate = kTRUE; Bool_t resultZero = kTRUE; // Do we need this ? // if(!dcsAliasMap) return 1; // // Invoking the cdb manager and the FMD parameters class // AliCDBManager* cdb = AliCDBManager::Instance(); // cdb->SetDefaultStorage("local://$ALICE_ROOT"); // cdb->SetRun(0); AliFMDParameters* pars = AliFMDParameters::Instance(); pars->Init(this, false, AliFMDParameters::kAltroMap); // This is if the SOR contains Fee parameters, and we run a DA to // extract these parameters. The same code could work if we get // the information from DCS via the FXS TList* files = 0; AliFMDCalibSampleRate* calibRate = 0; AliFMDCalibStripRange* calibRange = 0; AliFMDCalibZeroSuppression* calibZero = 0; // Disabled for now. #if 0 if (GetAndCheckFileSources(files, kDAQ,"info")) GetInfoCalibration(files, calibRate, calibRange, calibZero); resultRate = (!calibRate ? kFALSE : kTRUE); resultRange = (!calibRange ? kFALSE : kTRUE); resultZero = (!calibZero ? kFALSE : kTRUE); #endif // Gt the run type TString runType(GetRunType()); //Creating calibration objects AliFMDCalibPedestal* calibPed = 0; AliFMDCalibGain* calibGain = 0; if (runType.Contains("PEDESTAL", TString::kIgnoreCase)) { if (GetAndCheckFileSources(files, kDAQ, "pedestals")) { if(files->GetSize()) calibPed = GetPedestalCalibration(files); } resultPed = (calibPed ? kTRUE : kFALSE); } if (runType.Contains("GAIN", TString::kIgnoreCase)) { if (GetAndCheckFileSources(files, kDAQ, "gains")) { if(files->GetSize()) calibGain = GetGainCalibration(files); } resultGain = (calibGain ? kTRUE : kFALSE); } //Storing Calibration objects AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("Hans H. Dalsgaard"); metaData.SetComment("Preprocessor stores pedestals and gains for the FMD."); if(calibPed) { resultPed = Store("Calib","Pedestal", calibPed, &metaData, 0, kTRUE); delete calibPed; } if(calibGain) { resultGain = Store("Calib","PulseGain", calibGain, &metaData, 0, kTRUE); delete calibGain; } if(calibRange) { resultRange = Store("Calib","StripRange", calibRange, &metaData, 0, kTRUE); delete calibRange; } if(calibRate) { resultRate = Store("Calib","SampleRate", calibRate, &metaData, 0, kTRUE); delete calibRate; } if(calibZero) { resultZero = Store("Calib","ZeroSuppression", calibZero,&metaData,0,kTRUE); delete calibZero; } #if 0 // Disabled until we implement GetInfoCalibration properly Bool_t success = (resultPed && resultGain && resultRange && resultRate && resultZero); #endif Bool_t success = resultPed && resultGain; Log(Form("FMD preprocessor was %s", (success ? "successful" : "failed"))); return (success ? 0 : 1); } //____________________________________________________________________ Bool_t AliFMDPreprocessor::GetInfoCalibration(TList* files, AliFMDCalibSampleRate*& s, AliFMDCalibStripRange*& r, AliFMDCalibZeroSuppression*& z) { // Get info calibrations. // Parameters: // files List of files. // s On return, newly allocated object // r On return, newly allocated object // z On return, newly allocated object // Return: // kTRUE on success if (!files) return kTRUE; // Should really be false if (files->GetEntries() <= 0) return kTRUE; s = new AliFMDCalibSampleRate(); r = new AliFMDCalibStripRange(); z = new AliFMDCalibZeroSuppression(); // AliFMDParameters* pars = AliFMDParameters::Instance(); TIter iter(files); TObjString* fileSource; while((fileSource = dynamic_cast<TObjString*>(iter.Next()))) { const Char_t* filename = GetFile(kDAQ, "info", fileSource->GetName()); std::ifstream in(filename); if(!in) { Log(Form("File %s not found!", filename)); continue; } } return kTRUE; } //____________________________________________________________________ AliFMDCalibPedestal* AliFMDPreprocessor::GetPedestalCalibration(TList* pedFiles) { // Read DAQ DA produced CSV files of pedestals, and return a // calibration object. // Parameters: // pedFiles List of pedestal files // Return // A pointer to a newly allocated AliFMDCalibPedestal object, or // null in case of errors. if(!pedFiles) return 0; AliFMDCalibPedestal* calibPed = new AliFMDCalibPedestal(); AliFMDParameters* pars = AliFMDParameters::Instance(); TIter iter(pedFiles); TObjString* fileSource; while((fileSource = dynamic_cast<TObjString*>(iter.Next()))) { const Char_t* filename = GetFile(kDAQ, "pedestals", fileSource->GetName()); std::ifstream in(filename); if(!in) { Log(Form("File %s not found!", filename)); continue; } // Get header (how long is it ?) TString header; header.ReadLine(in); header.ToLower(); if(!header.Contains("pedestal")) { Log("File header is not from pedestal!"); continue; } Log("File contains data from pedestals"); // Read columns line int lineno = 2; header.ReadLine(in); // Loop until EOF while(in.peek()!=EOF) { if(in.bad()) { Log(Form("Bad read at line %d in %s", lineno, filename)); break; } UInt_t ddl=2, board, chip, channel, strip, sample, tb; Float_t ped, noise, mu, sigma, chi2ndf; Char_t c[11]; in >> ddl >> c[0] >> board >> c[1] >> chip >> c[2] >> channel >> c[3] >> strip >> c[4] >> sample >> c[5] >> tb >> c[6] >> ped >> c[7] >> noise >> c[8] >> mu >> c[9] >> sigma >> c[10] >> chi2ndf; lineno++; // Ignore trailing garbage if (strip > 127) continue; //Setting DDL to comply with the FMD in DAQ UInt_t FmdDDLBase = 3072; ddl = ddl - FmdDDLBase; //Setting the pedestals via the hardware address UShort_t det, sec, str; Char_t ring; pars->Hardware2Detector(ddl,board,chip,channel,det,ring,sec,str); strip += str; calibPed->Set(det,ring,sec,strip,ped,noise); } } return calibPed; } //____________________________________________________________________ AliFMDCalibGain* AliFMDPreprocessor::GetGainCalibration(TList* gainFiles) { // Read DAQ DA produced CSV files of pedestals, and return a // calibration object. // Parameters: // pedFiles List of pedestal files // Return // A pointer to a newly allocated AliFMDCalibPedestal object, or // null in case of errors. if(!gainFiles) return 0; AliFMDCalibGain* calibGain = new AliFMDCalibGain(); AliFMDParameters* pars = AliFMDParameters::Instance(); TIter iter(gainFiles); TObjString* fileSource; while((fileSource = dynamic_cast<TObjString *>(iter.Next()))) { const Char_t* filename = GetFile(kDAQ, "gains", fileSource->GetName()); std::ifstream in(filename); if(!in) { Log(Form("File %s not found!", filename)); continue; } //Get header (how long is it ?) TString header; header.ReadLine(in); header.ToLower(); if(!header.Contains("gain")) { Log("File header is not from gain!"); continue; } Log("File contains data from pulse gain"); // Read column headers header.ReadLine(in); int lineno = 2; // Read until EOF while(in.peek()!=EOF) { if(in.bad()) { Log(Form("Bad read at line %d in %s", lineno, filename)); break; } UInt_t ddl=2, board, chip, channel, strip; Float_t gain,error, chi2ndf; Char_t c[7]; in >> ddl >> c[0] >> board >> c[1] >> chip >> c[2] >> channel >> c[3] >> strip >> c[4] >> gain >> c[5] >> error >> c[6] >> chi2ndf; lineno++; // Ignore trailing garbage if(strip > 127) continue; //Setting DDL to comply with the FMD in DAQ UInt_t FmdDDLBase = 3072; ddl = ddl - FmdDDLBase; //Setting the pedestals via the hardware address UShort_t det, sec, str; Char_t ring; pars->Hardware2Detector(ddl,board,chip,channel,det,ring,sec,str); strip += str; calibGain->Set(det,ring,sec,strip,gain); } } return calibGain; } //____________________________________________________________________ // // EOF // <|endoftext|>
<commit_before>/* * This file is part of meego-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation ([email protected]) * * If you have questions regarding the use of this file, please contact * Nokia at [email protected]. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "bm_painting.h" #include "paintrunner.h" #include "loggingwindow.h" #include "mimkeyarea.h" #include "keyboarddata.h" #include "utils.h" // this test could not be compiled for Windows #include <time.h> #include <sys/time.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <MApplication> #include <MTheme> #include <MSceneWindow> #include <MScene> #include <MSceneManager> #include <QDir> namespace { int gArgc = 2; char *gArgv[2] = { (char *) "bm_painting", (char *) "-software" }; const char *const MImUserDirectory = ".meego-im"; } void Bm_Painting::initTestCase() { disableQtPlugins(); QDir dir; dir.mkpath(QString("%1/%2").arg(QDir::homePath()).arg(MImUserDirectory)); } void Bm_Painting::cleanupTestCase() { } void Bm_Painting::init() { keyboard = 0; subject = 0; } void Bm_Painting::cleanup() { delete subject; subject = 0; delete keyboard; keyboard = 0; delete sceneWindow; sceneWindow = 0; delete window; window = 0; delete widget; widget = 0; delete app; app = 0; } void Bm_Painting::benchmarkPaint_data() { QDir dir("/usr/share/meegotouch/virtual-keyboard/layouts/"); QStringList filters; QFileInfoList files; QFileInfo info; QStringList resultFilenames; QString fileNameTemplate(QString("%1/%2/%3-%4").arg(QDir::homePath()) .arg(MImUserDirectory) .arg(QCoreApplication::applicationPid())); QTest::addColumn<QString>("filename"); QTest::addColumn<bool>("hardwareRendering"); QTest::addColumn<bool>("compositing"); QTest::addColumn<QString>("resultFilename"); resultFilenames << fileNameTemplate.arg("sw_opaque.csv") << fileNameTemplate.arg("hw_opaque.csv") << fileNameTemplate.arg("sw_composite.csv") << fileNameTemplate.arg("hw_composite.csv"); filters << "en_gb.xml"; files = dir.entryInfoList(filters); int x = 0; for (int composite = 0; composite <= 1; ++composite) { for (int hw = 0; hw <= 1; ++hw) { for (int n = files.count() - 1; n >= 0; --n) { info = files.at(n); QString caseName = QString("file=%1 composite=%2 hw=%3 results=%4").arg(info.fileName()).arg(composite).arg(hw).arg(resultFilenames.at(x)); QTest::newRow(caseName.toLatin1().constData()) << info.fileName() << bool(hw) << bool(composite) << resultFilenames.at(x); ++x; } } } } void Bm_Painting::benchmarkPaint() { QFETCH(QString, filename); QFETCH(bool, hardwareRendering); QFETCH(bool, compositing); QFETCH(QString, resultFilename); gArgc = hardwareRendering ? 1 : 2; app = new MApplication(gArgc, gArgv); widget = new QWidget; if (compositing) { widget->setAttribute(Qt::WA_TranslucentBackground); } Qt::WindowFlags windowFlags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint; widget->setWindowFlags(windowFlags); widget->show(); window = new LoggingWindow(widget); window->setTranslucentBackground(!MApplication::softwareRendering()); if (MApplication::softwareRendering()) window->viewport()->setAutoFillBackground(false); sceneWindow = createMSceneWindow(window); window->show(); QTest::qWaitForWindowShown(window); QSize sceneSize = window->visibleSceneSize(M::Landscape); int w = sceneSize.width(); int h = sceneSize.height(); window->setSceneRect(0, 0, w, h); widget->resize(sceneSize); keyboard = new KeyboardData; QVERIFY(keyboard->loadNokiaKeyboard(filename)); subject = new MImKeyArea(keyboard->layout(LayoutData::General, M::Landscape)->section(LayoutData::mainSection)); subject->resize(defaultLayoutSize()); PaintRunner runner; window->scene()->addItem(&runner); runner.update(); subject->setParentItem(&runner); MImKey *key0 = dynamic_cast<MImKey *>(keyAt(0, 0)); MImKey *key1 = dynamic_cast<MImKey *>(keyAt(1, 3)); MImKey *key2 = dynamic_cast<MImKey *>(keyAt(2, 6)); QVERIFY(key0); QVERIFY(key1); const QPoint point0 = key0->buttonBoundingRect().center().toPoint(); const QPoint point1 = key1->buttonBoundingRect().center().toPoint(); const QPoint point2 = key2->buttonBoundingRect().center().toPoint(); QTouchEvent::TouchPoint press0(MImAbstractKeyArea::createTouchPoint(0, Qt::TouchPointPressed, subject->mapToScene(point0), QPointF())); QTouchEvent::TouchPoint release0(MImAbstractKeyArea::createTouchPoint(0, Qt::TouchPointReleased, subject->mapToScene(point0), QPointF())); QTouchEvent::TouchPoint press1(MImAbstractKeyArea::createTouchPoint(1, Qt::TouchPointPressed, subject->mapToScene(point1), QPointF())); QTouchEvent::TouchPoint release1(MImAbstractKeyArea::createTouchPoint(1, Qt::TouchPointReleased, subject->mapToScene(point1), QPointF())); QTouchEvent::TouchPoint press2(MImAbstractKeyArea::createTouchPoint(2, Qt::TouchPointPressed, subject->mapToScene(point2), QPointF())); QTouchEvent::TouchPoint release2(MImAbstractKeyArea::createTouchPoint(2, Qt::TouchPointReleased, subject->mapToScene(point2), QPointF())); QList< QList<QTouchEvent::TouchPoint> > plannedEvents; QList<QTouchEvent::TouchPoint> eventList; plannedEvents << eventList; eventList << press0; plannedEvents << eventList; eventList.clear(); eventList << release0; plannedEvents << eventList; eventList.clear(); eventList << press0 << press1; plannedEvents << eventList; eventList.clear(); eventList << release0 << release1; plannedEvents << eventList; eventList.clear(); eventList << press0 << press1 << press2; plannedEvents << eventList; eventList.clear(); eventList << release0 << release1 << release2; plannedEvents << eventList; eventList.clear(); window->loggingEnabled = true; foreach (eventList, plannedEvents) { foreach (const QTouchEvent::TouchPoint &event, eventList) { if (event.state() == Qt::TouchPointPressed) { qDebug() << "press " << event.scenePos(); subject->touchPointPressed(event); } else if (event.state() == Qt::TouchPointReleased) { qDebug() << "release " << event.scenePos(); subject->touchPointReleased(event); } } qDebug() << "***"; window->logMark(); QTest::qWait(1000); } window->loggingEnabled = false; window->writeResults(resultFilename); subject->setParentItem(0); } QSize Bm_Painting::defaultLayoutSize() { // Take visible scene size as layout size, but reduce keyboard's paddings first from its width. // The height value is ignored since MImAbstractKeyAreas determine their own height. return window->visibleSceneSize() - QSize(subject->style()->paddingLeft() + subject->style()->paddingRight(), 0); } MImAbstractKey *Bm_Painting::keyAt(unsigned int row, unsigned int column) const { // If this fails there is something wrong with the test. Q_ASSERT(subject && (row < static_cast<unsigned int>(subject->rowCount())) && (column < static_cast<unsigned int>(subject->sectionModel()->columnsAt(row)))); MImAbstractKey *key = 0; MImKeyArea *buttonArea = dynamic_cast<MImKeyArea *>(subject); if (buttonArea) { key = buttonArea->rowList[row].keys[column]; } return key; } QTEST_APPLESS_MAIN(Bm_Painting); <commit_msg>Changes: bm_painting uses environment variables to select test case<commit_after>/* * This file is part of meego-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation ([email protected]) * * If you have questions regarding the use of this file, please contact * Nokia at [email protected]. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "bm_painting.h" #include "paintrunner.h" #include "loggingwindow.h" #include "mimkeyarea.h" #include "keyboarddata.h" #include "utils.h" // this test could not be compiled for Windows #include <time.h> #include <sys/time.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <MApplication> #include <MTheme> #include <MSceneWindow> #include <MScene> #include <MSceneManager> #include <QDir> #include <QtGlobal> namespace { int gArgc = 2; char *gArgv[2] = { (char *) "bm_painting", (char *) "-software" }; const char *const MImUserDirectory = ".meego-im"; const int DefaultDelay = 1000; // milliseconds } void Bm_Painting::initTestCase() { disableQtPlugins(); QDir dir; dir.mkpath(QString("%1/%2").arg(QDir::homePath()).arg(MImUserDirectory)); } void Bm_Painting::cleanupTestCase() { } void Bm_Painting::init() { keyboard = 0; subject = 0; } void Bm_Painting::cleanup() { delete subject; subject = 0; delete keyboard; keyboard = 0; delete sceneWindow; sceneWindow = 0; delete window; window = 0; delete widget; widget = 0; delete app; app = 0; } /* * COMPOSITE variable defines whether main window should be * composited or not. Possible values (case sensitive): * * <unset> - perform tests for both opaque and tranclucent windows * * true - perform tests for tranclucent (composited) window * * any other - perform tests for opaque window * HARDWARE variable defines whether hardware acceleration should be used or * not. Possible values: * * <unset> - perform tests with and without hardware acceleration * * true - perform tests with hardware acceleration * * any other - perform tests without hardware acceleration * DELAY defines duration of one step in test case. Default value is 750 * milliseconds. */ void Bm_Painting::benchmarkPaint_data() { QDir dir("/usr/share/meegotouch/virtual-keyboard/layouts/"); QStringList filters; QFileInfoList files; QFileInfo info; QString resultFilenames[2][2]; QString fileNameTemplate(QString("%1/%2/%3-%4").arg(QDir::homePath()) .arg(MImUserDirectory) .arg(QCoreApplication::applicationPid())); int hwMin = 0; int hwMax = 1; int compositeMin = 0; int compositeMax = 1; int delay = DefaultDelay; QString env; env = qgetenv("COMPOSITE"); if (!env.isEmpty()) { compositeMin = compositeMax = ((env == "true") ? 1 : 0); } env = qgetenv("HARDWARE"); if (!env.isEmpty()) { hwMin = hwMax = ((env == "true") ? 1 : 0); } env = qgetenv("DELAY"); if (!env.isEmpty()) { delay = env.toInt(); } QTest::addColumn<QString>("filename"); QTest::addColumn<bool>("hardwareRendering"); QTest::addColumn<bool>("compositing"); QTest::addColumn<QString>("resultFilename"); QTest::addColumn<int>("delay"); resultFilenames[0][0] = fileNameTemplate.arg("sw_opaque.csv"); resultFilenames[1][0] = fileNameTemplate.arg("hw_opaque.csv"); resultFilenames[0][1] = fileNameTemplate.arg("sw_composite.csv"); resultFilenames[1][1] = fileNameTemplate.arg("hw_composite.csv"); filters << "en_gb.xml"; files = dir.entryInfoList(filters); for (int composite = compositeMin; composite <= compositeMax; ++composite) { for (int hw = hwMin; hw <= hwMax; ++hw) { for (int n = files.count() - 1; n >= 0; --n) { info = files.at(n); QString caseName = QString("file=%1 composite=%2 hw=%3 results=%4").arg(info.fileName()).arg(composite).arg(hw). arg(resultFilenames[hw][composite]); QTest::newRow(caseName.toLatin1().constData()) << info.fileName() << bool(hw) << bool(composite) << resultFilenames[hw][composite] << delay; } } } } void Bm_Painting::benchmarkPaint() { QFETCH(QString, filename); QFETCH(bool, hardwareRendering); QFETCH(bool, compositing); QFETCH(QString, resultFilename); QFETCH(int, delay); gArgc = hardwareRendering ? 1 : 2; app = new MApplication(gArgc, gArgv); widget = new QWidget; if (compositing) { widget->setAttribute(Qt::WA_TranslucentBackground); } Qt::WindowFlags windowFlags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint; widget->setWindowFlags(windowFlags); widget->show(); window = new LoggingWindow(widget); window->setTranslucentBackground(!MApplication::softwareRendering()); if (MApplication::softwareRendering()) window->viewport()->setAutoFillBackground(false); sceneWindow = createMSceneWindow(window); window->show(); QTest::qWaitForWindowShown(window); QSize sceneSize = window->visibleSceneSize(M::Landscape); int w = sceneSize.width(); int h = sceneSize.height(); window->setSceneRect(0, 0, w, h); widget->resize(sceneSize); keyboard = new KeyboardData; QVERIFY(keyboard->loadNokiaKeyboard(filename)); subject = new MImKeyArea(keyboard->layout(LayoutData::General, M::Landscape)->section(LayoutData::mainSection)); subject->resize(defaultLayoutSize()); PaintRunner runner; window->scene()->addItem(&runner); runner.update(); subject->setParentItem(&runner); MImKey *key0 = dynamic_cast<MImKey *>(keyAt(0, 0)); MImKey *key1 = dynamic_cast<MImKey *>(keyAt(1, 3)); MImKey *key2 = dynamic_cast<MImKey *>(keyAt(2, 6)); QVERIFY(key0); QVERIFY(key1); const QPoint point0 = key0->buttonBoundingRect().center().toPoint(); const QPoint point1 = key1->buttonBoundingRect().center().toPoint(); const QPoint point2 = key2->buttonBoundingRect().center().toPoint(); QTouchEvent::TouchPoint press0(MImAbstractKeyArea::createTouchPoint(0, Qt::TouchPointPressed, subject->mapToScene(point0), QPointF())); QTouchEvent::TouchPoint release0(MImAbstractKeyArea::createTouchPoint(0, Qt::TouchPointReleased, subject->mapToScene(point0), QPointF())); QTouchEvent::TouchPoint press1(MImAbstractKeyArea::createTouchPoint(1, Qt::TouchPointPressed, subject->mapToScene(point1), QPointF())); QTouchEvent::TouchPoint release1(MImAbstractKeyArea::createTouchPoint(1, Qt::TouchPointReleased, subject->mapToScene(point1), QPointF())); QTouchEvent::TouchPoint press2(MImAbstractKeyArea::createTouchPoint(2, Qt::TouchPointPressed, subject->mapToScene(point2), QPointF())); QTouchEvent::TouchPoint release2(MImAbstractKeyArea::createTouchPoint(2, Qt::TouchPointReleased, subject->mapToScene(point2), QPointF())); QList< QList<QTouchEvent::TouchPoint> > plannedEvents; QList<QTouchEvent::TouchPoint> eventList; plannedEvents << eventList; eventList << press0; plannedEvents << eventList; eventList.clear(); eventList << release0; plannedEvents << eventList; eventList.clear(); eventList << press0 << press1; plannedEvents << eventList; eventList.clear(); eventList << release0 << release1; plannedEvents << eventList; eventList.clear(); eventList << press0 << press1 << press2; plannedEvents << eventList; eventList.clear(); eventList << release0 << release1 << release2; plannedEvents << eventList; eventList.clear(); window->loggingEnabled = true; foreach (eventList, plannedEvents) { foreach (const QTouchEvent::TouchPoint &event, eventList) { if (event.state() == Qt::TouchPointPressed) { qDebug() << "press " << event.scenePos(); subject->touchPointPressed(event); } else if (event.state() == Qt::TouchPointReleased) { qDebug() << "release " << event.scenePos(); subject->touchPointReleased(event); } } qDebug() << "***"; window->logMark(); QTest::qWait(delay); } window->loggingEnabled = false; window->writeResults(resultFilename); subject->setParentItem(0); } QSize Bm_Painting::defaultLayoutSize() { // Take visible scene size as layout size, but reduce keyboard's paddings first from its width. // The height value is ignored since MImAbstractKeyAreas determine their own height. return window->visibleSceneSize() - QSize(subject->style()->paddingLeft() + subject->style()->paddingRight(), 0); } MImAbstractKey *Bm_Painting::keyAt(unsigned int row, unsigned int column) const { // If this fails there is something wrong with the test. Q_ASSERT(subject && (row < static_cast<unsigned int>(subject->rowCount())) && (column < static_cast<unsigned int>(subject->sectionModel()->columnsAt(row)))); MImAbstractKey *key = 0; MImKeyArea *buttonArea = dynamic_cast<MImKeyArea *>(subject); if (buttonArea) { key = buttonArea->rowList[row].keys[column]; } return key; } QTEST_APPLESS_MAIN(Bm_Painting); <|endoftext|>
<commit_before><commit_msg>TODO-593: bug fix<commit_after><|endoftext|>
<commit_before>// This file is part of gltfpack; see gltfpack.h for version/license details #include "gltfpack.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif struct BasisSettings { int etc1s_l; int etc1s_q; int uastc_l; float uastc_q; }; static const char* kMimeTypes[][2] = { {"image/jpeg", ".jpg"}, {"image/jpeg", ".jpeg"}, {"image/png", ".png"}, }; static const BasisSettings kBasisSettings[10] = { {0, 1, 0, 1.5f}, {0, 6, 0, 1.f}, {1, 20, 1, 1.0f}, {1, 50, 1, 0.75f}, {1, 90, 1, 0.5f}, {1, 128, 1, 0.4f}, {1, 160, 1, 0.34f}, {1, 192, 1, 0.29f}, // default {1, 224, 2, 0.26f}, {1, 255, 2, 0.f}, }; void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images) { for (size_t i = 0; i < data->materials_count; ++i) { const cgltf_material& material = data->materials[i]; if (material.has_pbr_metallic_roughness) { const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness; if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image) images[pbr.base_color_texture.texture->image - data->images].srgb = true; } if (material.has_pbr_specular_glossiness) { const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness; if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image) images[pbr.diffuse_texture.texture->image - data->images].srgb = true; } if (material.emissive_texture.texture && material.emissive_texture.texture->image) images[material.emissive_texture.texture->image - data->images].srgb = true; if (material.normal_texture.texture && material.normal_texture.texture->image) images[material.normal_texture.texture->image - data->images].normal_map = true; } } const char* inferMimeType(const char* path) { const char* ext = strrchr(path, '.'); if (!ext) return ""; std::string extl = ext; for (size_t i = 0; i < extl.length(); ++i) extl[i] = char(tolower(extl[i])); for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (extl == kMimeTypes[i][1]) return kMimeTypes[i][0]; return ""; } static const char* mimeExtension(const char* mime_type) { for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (strcmp(kMimeTypes[i][0], mime_type) == 0) return kMimeTypes[i][1]; return ".raw"; } #ifdef __EMSCRIPTEN__ EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), { var cp = require('child_process'); var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ]; var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio }); return ret.status == null ? 256 : ret.status; }); EM_JS(const char*, readenv, (const char* name), { var val = process.env[UTF8ToString(name)]; if (!val) return 0; var ret = _malloc(lengthBytesUTF8(val) + 1); stringToUTF8(val, ret, lengthBytesUTF8(val) + 1); return ret; }); #else static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr) { #ifdef _WIN32 std::string ignore = "nul"; #else std::string ignore = "/dev/null"; #endif std::string cmd = cmd_; if (ignore_stdout) (cmd += " >") += ignore; if (ignore_stderr) (cmd += " 2>") += ignore; return system(cmd.c_str()); } static const char* readenv(const char* name) { return getenv(name); } #endif bool checkBasis(bool verbose) { const char* basisu_path = readenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; cmd += " -version"; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0; } bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose) { (void)scale; TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".basis"); if (!writeFile(temp_input.path.c_str(), data)) return false; const char* basisu_path = readenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; const BasisSettings& bs = kBasisSettings[std::max(0, std::min(9, quality - 1))]; cmd += " -mipmap"; if (normal_map) { cmd += " -normal_map"; // for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness } else if (!srgb) { cmd += " -linear"; } if (uastc) { char settings[128]; sprintf(settings, " -uastc_level %d -uastc_rdo_q %.2f", bs.uastc_l, bs.uastc_q); cmd += " -uastc"; cmd += settings; cmd += " -uastc_rdo_d 1024"; } else { char settings[128]; sprintf(settings, " -comp_level %d -q %d", bs.etc1s_l, bs.etc1s_q); cmd += settings; } cmd += " -file "; cmd += temp_input.path; cmd += " -output_file "; cmd += temp_output.path; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0 && readFile(temp_output.path.c_str(), result); } bool checkKtx(bool verbose) { const char* toktx_path = readenv("TOKTX_PATH"); std::string cmd = toktx_path ? toktx_path : "toktx"; cmd += " --version"; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0; } bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose) { TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".ktx2"); if (!writeFile(temp_input.path.c_str(), data)) return false; const char* toktx_path = readenv("TOKTX_PATH"); std::string cmd = toktx_path ? toktx_path : "toktx"; const BasisSettings& bs = kBasisSettings[std::max(0, std::min(9, quality - 1))]; cmd += " --t2"; cmd += " --2d"; cmd += " --genmipmap"; cmd += " --nowarn"; if (scale < 1) { char sl[128]; sprintf(sl, "%g", scale); cmd += " --scale "; cmd += sl; } if (uastc) { char settings[128]; sprintf(settings, " %d --uastc_rdo_q %.2f", bs.uastc_l, bs.uastc_q); cmd += " --uastc"; cmd += settings; cmd += " --uastc_rdo_d 1024"; cmd += " --zcmp 9"; } else { char settings[128]; sprintf(settings, " --clevel %d --qlevel %d", bs.etc1s_l, bs.etc1s_q); cmd += " --bcmp"; cmd += settings; // for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness if (normal_map) cmd += " --normal_map"; } if (srgb) cmd += " --srgb"; else cmd += " --linear"; cmd += " -- "; cmd += temp_output.path; cmd += " "; cmd += temp_input.path; int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0 && readFile(temp_output.path.c_str(), result); } <commit_msg>gltfpack: Fix Windows build<commit_after>// This file is part of gltfpack; see gltfpack.h for version/license details #include "gltfpack.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif struct BasisSettings { int etc1s_l; int etc1s_q; int uastc_l; float uastc_q; }; static const char* kMimeTypes[][2] = { {"image/jpeg", ".jpg"}, {"image/jpeg", ".jpeg"}, {"image/png", ".png"}, }; static const BasisSettings kBasisSettings[10] = { {0, 1, 0, 1.5f}, {0, 6, 0, 1.f}, {1, 20, 1, 1.0f}, {1, 50, 1, 0.75f}, {1, 90, 1, 0.5f}, {1, 128, 1, 0.4f}, {1, 160, 1, 0.34f}, {1, 192, 1, 0.29f}, // default {1, 224, 2, 0.26f}, {1, 255, 2, 0.f}, }; void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images) { for (size_t i = 0; i < data->materials_count; ++i) { const cgltf_material& material = data->materials[i]; if (material.has_pbr_metallic_roughness) { const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness; if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image) images[pbr.base_color_texture.texture->image - data->images].srgb = true; } if (material.has_pbr_specular_glossiness) { const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness; if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image) images[pbr.diffuse_texture.texture->image - data->images].srgb = true; } if (material.emissive_texture.texture && material.emissive_texture.texture->image) images[material.emissive_texture.texture->image - data->images].srgb = true; if (material.normal_texture.texture && material.normal_texture.texture->image) images[material.normal_texture.texture->image - data->images].normal_map = true; } } const char* inferMimeType(const char* path) { const char* ext = strrchr(path, '.'); if (!ext) return ""; std::string extl = ext; for (size_t i = 0; i < extl.length(); ++i) extl[i] = char(tolower(extl[i])); for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (extl == kMimeTypes[i][1]) return kMimeTypes[i][0]; return ""; } static const char* mimeExtension(const char* mime_type) { for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (strcmp(kMimeTypes[i][0], mime_type) == 0) return kMimeTypes[i][1]; return ".raw"; } #ifdef __EMSCRIPTEN__ EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), { var cp = require('child_process'); var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ]; var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio }); return ret.status == null ? 256 : ret.status; }); EM_JS(const char*, readenv, (const char* name), { var val = process.env[UTF8ToString(name)]; if (!val) return 0; var ret = _malloc(lengthBytesUTF8(val) + 1); stringToUTF8(val, ret, lengthBytesUTF8(val) + 1); return ret; }); #else static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr) { #ifdef _WIN32 std::string ignore = "nul"; #else std::string ignore = "/dev/null"; #endif std::string cmd = cmd_; if (ignore_stdout) (cmd += " >") += ignore; if (ignore_stderr) (cmd += " 2>") += ignore; return system(cmd.c_str()); } static const char* readenv(const char* name) { return getenv(name); } #endif bool checkBasis(bool verbose) { const char* basisu_path = readenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; cmd += " -version"; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0; } bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose) { (void)scale; TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".basis"); if (!writeFile(temp_input.path.c_str(), data)) return false; const char* basisu_path = readenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; const BasisSettings& bs = kBasisSettings[quality <= 0 ? 0 : quality > 9 ? 9 : quality - 1]; cmd += " -mipmap"; if (normal_map) { cmd += " -normal_map"; // for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness } else if (!srgb) { cmd += " -linear"; } if (uastc) { char settings[128]; sprintf(settings, " -uastc_level %d -uastc_rdo_q %.2f", bs.uastc_l, bs.uastc_q); cmd += " -uastc"; cmd += settings; cmd += " -uastc_rdo_d 1024"; } else { char settings[128]; sprintf(settings, " -comp_level %d -q %d", bs.etc1s_l, bs.etc1s_q); cmd += settings; } cmd += " -file "; cmd += temp_input.path; cmd += " -output_file "; cmd += temp_output.path; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0 && readFile(temp_output.path.c_str(), result); } bool checkKtx(bool verbose) { const char* toktx_path = readenv("TOKTX_PATH"); std::string cmd = toktx_path ? toktx_path : "toktx"; cmd += " --version"; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0; } bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose) { TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".ktx2"); if (!writeFile(temp_input.path.c_str(), data)) return false; const char* toktx_path = readenv("TOKTX_PATH"); std::string cmd = toktx_path ? toktx_path : "toktx"; const BasisSettings& bs = kBasisSettings[quality <= 0 ? 0 : quality > 9 ? 9 : quality - 1]; cmd += " --t2"; cmd += " --2d"; cmd += " --genmipmap"; cmd += " --nowarn"; if (scale < 1) { char sl[128]; sprintf(sl, "%g", scale); cmd += " --scale "; cmd += sl; } if (uastc) { char settings[128]; sprintf(settings, " %d --uastc_rdo_q %.2f", bs.uastc_l, bs.uastc_q); cmd += " --uastc"; cmd += settings; cmd += " --uastc_rdo_d 1024"; cmd += " --zcmp 9"; } else { char settings[128]; sprintf(settings, " --clevel %d --qlevel %d", bs.etc1s_l, bs.etc1s_q); cmd += " --bcmp"; cmd += settings; // for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness if (normal_map) cmd += " --normal_map"; } if (srgb) cmd += " --srgb"; else cmd += " --linear"; cmd += " -- "; cmd += temp_output.path; cmd += " "; cmd += temp_input.path; int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false); if (verbose) printf("%s => %d\n", cmd.c_str(), rc); return rc == 0 && readFile(temp_output.path.c_str(), result); } <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "GrClip.h" #include "GrContext.h" #include "GrRenderTargetContext.h" #include "SkGradientShader.h" #include "SkImage_Base.h" #include "SkSurface.h" namespace skiagm { class AAFlagsGM : public GM { private: SkString onShortName() final { return SkString("aaflags"); } SkISize onISize() override { return SkISize::Make(1000, 1450); } void onOnceBeforeDraw() override { static constexpr SkScalar kW = SkIntToScalar(kTileW * kM); static constexpr SkScalar kH = SkIntToScalar(kTileH * kN); auto surf = SkSurface::MakeRaster( SkImageInfo::Make(kW, kH, kRGBA_8888_SkColorType, kPremul_SkAlphaType)); surf->getCanvas()->clear(SK_ColorLTGRAY); static constexpr SkScalar kStripeW = 10; static constexpr SkScalar kStripeSpacing = 30; SkPaint paint; static constexpr SkPoint pts1[] = {{0.f, 0.f}, {kW, kH}}; static constexpr SkColor kColors1[] = {SK_ColorCYAN, SK_ColorBLACK}; auto grad = SkGradientShader::MakeLinear(pts1, kColors1, nullptr, 2, SkShader::kClamp_TileMode); paint.setShader(std::move(grad)); paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(kStripeW); SkPoint stripePts[] = {{-kW - kStripeW, -kStripeW}, {kStripeW, kH + kStripeW}}; while (stripePts[0].fX <= kW) { surf->getCanvas()->drawPoints(SkCanvas::kLines_PointMode, 2, stripePts, paint); stripePts[0].fX += kStripeSpacing; stripePts[1].fX += kStripeSpacing; } static constexpr SkPoint pts2[] = {{0.f, kH}, {kW, 0.f}}; static constexpr SkColor kColors2[] = {SK_ColorMAGENTA, SK_ColorBLACK}; grad = SkGradientShader::MakeLinear(pts2, kColors2, nullptr, 2, SkShader::kClamp_TileMode); paint.setShader(std::move(grad)); paint.setBlendMode(SkBlendMode::kMultiply); stripePts[0] = {-kW - kStripeW, kH + kStripeW}; stripePts[1] = {kStripeW, -kStripeW}; while (stripePts[0].fX <= kW) { surf->getCanvas()->drawPoints(SkCanvas::kLines_PointMode, 2, stripePts, paint); stripePts[0].fX += kStripeSpacing; stripePts[1].fX += kStripeSpacing; } auto img = surf->makeImageSnapshot(); for (int y = 0; y < kN; ++y) { for (int x = 0; x < kM; ++x) { fImage[x][y] = img->makeSubset(SkIRect::MakeXYWH(x * kTileW, y * kTileH, kTileW, kTileH)); } } } void onDraw(SkCanvas* canvas) override { GrContext* ctx = canvas->getGrContext(); if (!ctx) { DrawGpuOnlyMessage(canvas); return; } GrRenderTargetContext* rtc = canvas->internal_private_accessTopLayerRenderTargetContext(); SkASSERT(rtc); SkScalar d = SkVector{kM * kTileW, kN * kTileH}.length(); SkMatrix matrices[4]; // rotation matrices[0].setRotate(30); matrices[0].postTranslate(d / 3, 0); // perespective SkPoint src[4]; SkRect::MakeWH(kM * kTileW, kN * kTileH).toQuad(src); SkPoint dst[4] = {{0, 0}, {kM * kTileW + 10.f, -5.f}, {kM * kTileW - 28.f, kN * kTileH + 40.f}, {45.f, kN * kTileH - 25.f}}; matrices[1].setPolyToPoly(src, dst, 4); matrices[1].postTranslate(d, 50.f); // skew matrices[2].setRotate(-60.f); matrices[2].postSkew(0.5f, -1.35f); matrices[2].postScale(0.6f, 1.05f); matrices[2].postTranslate(d, 2.5f * d); // perspective + mirror in x. dst[1] = {0, 0}; dst[0] = {3.f / 4.f * kM * kTileW, 0}; dst[3] = {2.f / 3.f * kM * kTileW, 1 / 4.f * kN * kTileH}; dst[2] = {1.f / 3.f * kM * kTileW, 1 / 4.f * kN * kTileH - 25.f}; matrices[3].setPolyToPoly(src, dst, 4); matrices[3].postTranslate(100.f, d); for (size_t m = 0; m < SK_ARRAY_COUNT(matrices); ++m) { // Draw grid of green "lines" at interior tile boundaries. static constexpr SkScalar kLineOutset = 10.f; static constexpr SkScalar kLineHalfW = 4.f; auto color = GrColor4f(0.f, 1.f, 0.f, 1.f); for (int x = 1; x < kM; ++x) { GrPaint paint; paint.setColor4f(color); SkRect lineRect = SkRect::MakeLTRB(x * kTileW - kLineHalfW, -kLineOutset, x * kTileW + kLineHalfW, kN * kTileH + kLineOutset); rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kYes, matrices[m], lineRect); } for (int y = 1; y < kN; ++y) { GrPaint paint; paint.setColor4f(color); SkRect lineRect = SkRect::MakeLTRB(-kLineOutset, y * kTileH - kLineHalfW, kTileW * kM + kLineOutset, y * kTileH + kLineHalfW); rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kYes, matrices[m], lineRect); } static constexpr GrColor kColor = GrColor_WHITE; for (int x = 0; x < kM; ++x) { for (int y = 0; y < kN; ++y) { auto proxy = as_IB(fImage[x][y]) ->asTextureProxyRef(ctx, GrSamplerState::ClampBilerp(), nullptr, nullptr, nullptr); auto srcR = proxy->getBoundsRect(); auto dstR = SkRect::MakeXYWH(x * kTileW, y * kTileH, kTileW, kTileH); GrQuadAAFlags aaFlags = GrQuadAAFlags::kNone; if (x == 0) { aaFlags |= GrQuadAAFlags::kLeft; } if (x == kM - 1) { aaFlags |= GrQuadAAFlags::kRight; } if (y == 0) { aaFlags |= GrQuadAAFlags::kTop; } if (y == kN - 1) { aaFlags |= GrQuadAAFlags::kBottom; } rtc->drawTexture(GrNoClip(), proxy, GrSamplerState::Filter::kBilerp, kColor, srcR, dstR, aaFlags, SkCanvas::kFast_SrcRectConstraint, matrices[m], nullptr, nullptr); } } } } static constexpr int kM = 4; static constexpr int kN = 4; static constexpr SkScalar kTileW = 100; static constexpr SkScalar kTileH = 100; sk_sp<SkImage> fImage[kM][kN]; }; DEF_GM(return new AAFlagsGM();) } // namespace skiagm <commit_msg>Don't crash in aaflags GM if context is abandoned<commit_after>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "GrClip.h" #include "GrContext.h" #include "GrRenderTargetContext.h" #include "SkGradientShader.h" #include "SkImage_Base.h" #include "SkSurface.h" namespace skiagm { class AAFlagsGM : public GM { private: SkString onShortName() final { return SkString("aaflags"); } SkISize onISize() override { return SkISize::Make(1000, 1450); } void onOnceBeforeDraw() override { static constexpr SkScalar kW = SkIntToScalar(kTileW * kM); static constexpr SkScalar kH = SkIntToScalar(kTileH * kN); auto surf = SkSurface::MakeRaster( SkImageInfo::Make(kW, kH, kRGBA_8888_SkColorType, kPremul_SkAlphaType)); surf->getCanvas()->clear(SK_ColorLTGRAY); static constexpr SkScalar kStripeW = 10; static constexpr SkScalar kStripeSpacing = 30; SkPaint paint; static constexpr SkPoint pts1[] = {{0.f, 0.f}, {kW, kH}}; static constexpr SkColor kColors1[] = {SK_ColorCYAN, SK_ColorBLACK}; auto grad = SkGradientShader::MakeLinear(pts1, kColors1, nullptr, 2, SkShader::kClamp_TileMode); paint.setShader(std::move(grad)); paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(kStripeW); SkPoint stripePts[] = {{-kW - kStripeW, -kStripeW}, {kStripeW, kH + kStripeW}}; while (stripePts[0].fX <= kW) { surf->getCanvas()->drawPoints(SkCanvas::kLines_PointMode, 2, stripePts, paint); stripePts[0].fX += kStripeSpacing; stripePts[1].fX += kStripeSpacing; } static constexpr SkPoint pts2[] = {{0.f, kH}, {kW, 0.f}}; static constexpr SkColor kColors2[] = {SK_ColorMAGENTA, SK_ColorBLACK}; grad = SkGradientShader::MakeLinear(pts2, kColors2, nullptr, 2, SkShader::kClamp_TileMode); paint.setShader(std::move(grad)); paint.setBlendMode(SkBlendMode::kMultiply); stripePts[0] = {-kW - kStripeW, kH + kStripeW}; stripePts[1] = {kStripeW, -kStripeW}; while (stripePts[0].fX <= kW) { surf->getCanvas()->drawPoints(SkCanvas::kLines_PointMode, 2, stripePts, paint); stripePts[0].fX += kStripeSpacing; stripePts[1].fX += kStripeSpacing; } auto img = surf->makeImageSnapshot(); for (int y = 0; y < kN; ++y) { for (int x = 0; x < kM; ++x) { fImage[x][y] = img->makeSubset(SkIRect::MakeXYWH(x * kTileW, y * kTileH, kTileW, kTileH)); } } } void onDraw(SkCanvas* canvas) override { GrContext* ctx = canvas->getGrContext(); if (!ctx) { DrawGpuOnlyMessage(canvas); return; } GrRenderTargetContext* rtc = canvas->internal_private_accessTopLayerRenderTargetContext(); SkASSERT(rtc); SkScalar d = SkVector{kM * kTileW, kN * kTileH}.length(); SkMatrix matrices[4]; // rotation matrices[0].setRotate(30); matrices[0].postTranslate(d / 3, 0); // perespective SkPoint src[4]; SkRect::MakeWH(kM * kTileW, kN * kTileH).toQuad(src); SkPoint dst[4] = {{0, 0}, {kM * kTileW + 10.f, -5.f}, {kM * kTileW - 28.f, kN * kTileH + 40.f}, {45.f, kN * kTileH - 25.f}}; matrices[1].setPolyToPoly(src, dst, 4); matrices[1].postTranslate(d, 50.f); // skew matrices[2].setRotate(-60.f); matrices[2].postSkew(0.5f, -1.35f); matrices[2].postScale(0.6f, 1.05f); matrices[2].postTranslate(d, 2.5f * d); // perspective + mirror in x. dst[1] = {0, 0}; dst[0] = {3.f / 4.f * kM * kTileW, 0}; dst[3] = {2.f / 3.f * kM * kTileW, 1 / 4.f * kN * kTileH}; dst[2] = {1.f / 3.f * kM * kTileW, 1 / 4.f * kN * kTileH - 25.f}; matrices[3].setPolyToPoly(src, dst, 4); matrices[3].postTranslate(100.f, d); for (size_t m = 0; m < SK_ARRAY_COUNT(matrices); ++m) { // Draw grid of green "lines" at interior tile boundaries. static constexpr SkScalar kLineOutset = 10.f; static constexpr SkScalar kLineHalfW = 4.f; auto color = GrColor4f(0.f, 1.f, 0.f, 1.f); for (int x = 1; x < kM; ++x) { GrPaint paint; paint.setColor4f(color); SkRect lineRect = SkRect::MakeLTRB(x * kTileW - kLineHalfW, -kLineOutset, x * kTileW + kLineHalfW, kN * kTileH + kLineOutset); rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kYes, matrices[m], lineRect); } for (int y = 1; y < kN; ++y) { GrPaint paint; paint.setColor4f(color); SkRect lineRect = SkRect::MakeLTRB(-kLineOutset, y * kTileH - kLineHalfW, kTileW * kM + kLineOutset, y * kTileH + kLineHalfW); rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kYes, matrices[m], lineRect); } static constexpr GrColor kColor = GrColor_WHITE; for (int x = 0; x < kM; ++x) { for (int y = 0; y < kN; ++y) { auto proxy = as_IB(fImage[x][y]) ->asTextureProxyRef(ctx, GrSamplerState::ClampBilerp(), nullptr, nullptr, nullptr); if (!proxy) { continue; } auto srcR = proxy->getBoundsRect(); auto dstR = SkRect::MakeXYWH(x * kTileW, y * kTileH, kTileW, kTileH); GrQuadAAFlags aaFlags = GrQuadAAFlags::kNone; if (x == 0) { aaFlags |= GrQuadAAFlags::kLeft; } if (x == kM - 1) { aaFlags |= GrQuadAAFlags::kRight; } if (y == 0) { aaFlags |= GrQuadAAFlags::kTop; } if (y == kN - 1) { aaFlags |= GrQuadAAFlags::kBottom; } rtc->drawTexture(GrNoClip(), proxy, GrSamplerState::Filter::kBilerp, kColor, srcR, dstR, aaFlags, SkCanvas::kFast_SrcRectConstraint, matrices[m], nullptr, nullptr); } } } } static constexpr int kM = 4; static constexpr int kN = 4; static constexpr SkScalar kTileW = 100; static constexpr SkScalar kTileH = 100; sk_sp<SkImage> fImage[kM][kN]; }; DEF_GM(return new AAFlagsGM();) } // namespace skiagm <|endoftext|>
<commit_before>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <TelepathyQt4/Connection> #include <TelepathyQt4/Contact> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Debug> #include <telepathy-glib/debug.h> #include <tests/lib/contactlist/conn.h> #include <tests/lib/test.h> using namespace Tp; class TestConnRosterGroups : public Test { Q_OBJECT public: TestConnRosterGroups(QObject *parent = 0) : Test(parent), mConnService(0) { } protected Q_SLOTS: void onGroupAdded(const QString &group); void expectConnInvalidated(); private Q_SLOTS: void initTestCase(); void init(); void testRosterGroups(); void cleanup(); void cleanupTestCase(); private: QString mConnName, mConnPath; ExampleContactListConnection *mConnService; ConnectionPtr mConn; QString mGroupAdded; }; void TestConnRosterGroups::onGroupAdded(const QString &group) { mGroupAdded = group; mLoop->exit(0); } void TestConnRosterGroups::expectConnInvalidated() { mLoop->exit(0); } void TestConnRosterGroups::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("conn-basics"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); gchar *name; gchar *connPath; GError *error = 0; mConnService = EXAMPLE_CONTACT_LIST_CONNECTION(g_object_new( EXAMPLE_TYPE_CONTACT_LIST_CONNECTION, "account", "[email protected]", "protocol", "contactlist", 0)); QVERIFY(mConnService != 0); QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService), "contacts", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName = name; mConnPath = connPath; g_free(name); g_free(connPath); } void TestConnRosterGroups::init() { initImpl(); mConn = Connection::create(mConnName, mConnPath); QVERIFY(connect(mConn->requestConnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(), true); QCOMPARE(mConn->status(), static_cast<uint>(Connection::StatusConnected)); } void TestConnRosterGroups::testRosterGroups() { Features features = Features() << Connection::FeatureRoster << Connection::FeatureRosterGroups; QVERIFY(connect(mConn->becomeReady(features), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(features), true); ContactManager *contactManager = mConn->contactManager(); QStringList expectedGroups; expectedGroups << "Cambridge" << "Francophones" << "Montreal"; expectedGroups.sort(); QStringList groups = contactManager->allKnownGroups(); groups.sort(); QCOMPARE(groups, expectedGroups); // Cambridge { QStringList expectedContacts; expectedContacts << "[email protected]" << "[email protected]" << "[email protected]" << "[email protected]"; expectedContacts.sort(); QStringList contacts; foreach (const ContactPtr &contact, contactManager->groupContacts("Cambridge")) { contacts << contact->id(); } contacts.sort(); QCOMPARE(contacts, expectedContacts); } // Francophones { QStringList expectedContacts; expectedContacts << "[email protected]" << "[email protected]" << "[email protected]"; expectedContacts.sort(); QStringList contacts; foreach (const ContactPtr &contact, contactManager->groupContacts("Francophones")) { contacts << contact->id(); } contacts.sort(); QCOMPARE(contacts, expectedContacts); } // Montreal { QStringList expectedContacts; expectedContacts << "[email protected]"; expectedContacts.sort(); QStringList contacts; foreach (const ContactPtr &contact, contactManager->groupContacts("Montreal")) { contacts << contact->id(); } contacts.sort(); QCOMPARE(contacts, expectedContacts); } QVERIFY(contactManager->groupContacts("foo").isEmpty()); } void TestConnRosterGroups::cleanup() { if (mConn) { // Disconnect and wait for the readiness change QVERIFY(connect(mConn->requestDisconnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); if (mConn->isValid()) { QVERIFY(connect(mConn.data(), SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)), SLOT(expectConnInvalidated()))); QCOMPARE(mLoop->exec(), 0); } } cleanupImpl(); } void TestConnRosterGroups::cleanupTestCase() { if (mConnService != 0) { g_object_unref(mConnService); mConnService = 0; } cleanupTestCaseImpl(); } QTEST_MAIN(TestConnRosterGroups) #include "_gen/conn-roster-groups.cpp.moc.hpp" <commit_msg>roster-groups example: Added tests for contact list group creation.<commit_after>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <TelepathyQt4/Connection> #include <TelepathyQt4/Contact> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Debug> #include <telepathy-glib/debug.h> #include <tests/lib/contactlist/conn.h> #include <tests/lib/test.h> using namespace Tp; class TestConnRosterGroups : public Test { Q_OBJECT public: TestConnRosterGroups(QObject *parent = 0) : Test(parent), mConnService(0) { } protected Q_SLOTS: void onGroupAdded(const QString &group); void expectConnInvalidated(); private Q_SLOTS: void initTestCase(); void init(); void testRosterGroups(); void cleanup(); void cleanupTestCase(); private: QString mConnName, mConnPath; ExampleContactListConnection *mConnService; ConnectionPtr mConn; QString mGroupAdded; }; void TestConnRosterGroups::onGroupAdded(const QString &group) { mGroupAdded = group; mLoop->exit(0); } void TestConnRosterGroups::expectConnInvalidated() { mLoop->exit(0); } void TestConnRosterGroups::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("conn-basics"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); gchar *name; gchar *connPath; GError *error = 0; mConnService = EXAMPLE_CONTACT_LIST_CONNECTION(g_object_new( EXAMPLE_TYPE_CONTACT_LIST_CONNECTION, "account", "[email protected]", "protocol", "contactlist", 0)); QVERIFY(mConnService != 0); QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService), "contacts", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName = name; mConnPath = connPath; g_free(name); g_free(connPath); } void TestConnRosterGroups::init() { initImpl(); mConn = Connection::create(mConnName, mConnPath); QVERIFY(connect(mConn->requestConnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(), true); QCOMPARE(mConn->status(), static_cast<uint>(Connection::StatusConnected)); } void TestConnRosterGroups::testRosterGroups() { Features features = Features() << Connection::FeatureRoster << Connection::FeatureRosterGroups; QVERIFY(connect(mConn->becomeReady(features), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(features), true); ContactManager *contactManager = mConn->contactManager(); QStringList expectedGroups; expectedGroups << "Cambridge" << "Francophones" << "Montreal"; expectedGroups.sort(); QStringList groups = contactManager->allKnownGroups(); groups.sort(); QCOMPARE(groups, expectedGroups); // Cambridge { QStringList expectedContacts; expectedContacts << "[email protected]" << "[email protected]" << "[email protected]" << "[email protected]"; expectedContacts.sort(); QStringList contacts; foreach (const ContactPtr &contact, contactManager->groupContacts("Cambridge")) { contacts << contact->id(); } contacts.sort(); QCOMPARE(contacts, expectedContacts); } // Francophones { QStringList expectedContacts; expectedContacts << "[email protected]" << "[email protected]" << "[email protected]"; expectedContacts.sort(); QStringList contacts; foreach (const ContactPtr &contact, contactManager->groupContacts("Francophones")) { contacts << contact->id(); } contacts.sort(); QCOMPARE(contacts, expectedContacts); } // Montreal { QStringList expectedContacts; expectedContacts << "[email protected]"; expectedContacts.sort(); QStringList contacts; foreach (const ContactPtr &contact, contactManager->groupContacts("Montreal")) { contacts << contact->id(); } contacts.sort(); QCOMPARE(contacts, expectedContacts); } QString group("foo"); QVERIFY(contactManager->groupContacts(group).isEmpty()); // add group foo QVERIFY(connect(contactManager, SIGNAL(groupAdded(const QString&)), SLOT(onGroupAdded(const QString&)))); QVERIFY(connect(contactManager->addGroup(group), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); while (mGroupAdded.isEmpty()) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mGroupAdded, group); expectedGroups << group; expectedGroups.sort(); groups = contactManager->allKnownGroups(); groups.sort(); QCOMPARE(groups, expectedGroups); } void TestConnRosterGroups::cleanup() { if (mConn) { // Disconnect and wait for the readiness change QVERIFY(connect(mConn->requestDisconnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); if (mConn->isValid()) { QVERIFY(connect(mConn.data(), SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)), SLOT(expectConnInvalidated()))); QCOMPARE(mLoop->exec(), 0); } } cleanupImpl(); } void TestConnRosterGroups::cleanupTestCase() { if (mConnService != 0) { g_object_unref(mConnService); mConnService = 0; } cleanupTestCaseImpl(); } QTEST_MAIN(TestConnRosterGroups) #include "_gen/conn-roster-groups.cpp.moc.hpp" <|endoftext|>
<commit_before>//include <tclap/CmdLine.h> #include <boost/program_options/errors.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/positional_options.hpp> #include <boost/program_options/value_semantic.hpp> #include <boost/program_options/variables_map.hpp> #include <ctype.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <algorithm> #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include "bin_file.hpp" #include "prenexusrenderer.hpp" #include "renderer.hpp" #include "version.hpp" using std::cerr; using std::cout; using std::endl; using std::invalid_argument; using std::string; using std::stringstream; using std::vector; namespace po = boost::program_options; typedef uint32_t event_t; struct Config{ bool byte_swap; bool show_data; bool show_line_num; bool multi_file; bool sum_data; bool sum_block; bool is_event; bool get_pix_range; vector<size_t> integrate; }; static const size_t BLOCK_SIZE=1024; static const event_t ERROR=0x80000000; static const string DEFAULT_TYPE="char"; static string::size_type count_occur(const string &str, const string &ch){ string::size_type count = 0; string::size_type index = 0; // infinite loop to make sure that the entire string is parsed. #pragma warning(disable: 4127) while(true) { #pragma warning(default: 4127) index = str.find(ch,index+1); if(index==string::npos) { break; } count++; } return count; } static bool my_isnotdigit(char c){ return !isdigit(c); } static int str_to_int(const string &str){ if(str.substr(0,1)=="-") return -1*str_to_int(str.substr(1,str.size())); string::const_iterator it = str.begin(); it = std::find_if(it,str.end(),my_isnotdigit); if(it!=str.end()) throw invalid_argument("str_to_int(string) argument is not an integer"); return atol(str.c_str()); } extern vector<string> split(const string &source,const string &split) { string::size_type number=count_occur(source,split); if(number==0) { vector<string> result; result.push_back(source); return result; } vector<string> result; string::size_type start=0; string::size_type stop=0; string inner; #pragma warning(disable: 4127) while(true) { #pragma warning(default: 4127) stop=source.find(split,start); if(stop==string::npos) { result.push_back(source.substr(start)); break; } else { result.push_back(source.substr(start,stop-start)); start=stop+split.size(); } } return result; } template <typename NumT> string thing_to_str(const NumT thing) { std::stringstream s; s << thing; return s.str(); } template <typename NumT> string thing_to_str(const vector<NumT> &thing) { std::stringstream s; size_t length = thing.size(); for ( size_t i = 0 ; i < length ; ++i ){ s << thing[i] << " "; } return s.str(); } string pixid_str(const size_t pixid, const vector<size_t> &bounds) { size_t rank = bounds.size(); if (rank<=0) { return ""; } size_t max_index=1; for (size_t i = 0 ; i<rank ; ++i ){ max_index*=bounds[i]; } if(pixid>max_index) { std::stringstream s; s << "Pixel id outside of known bounds: " << pixid << ">" << max_index; throw std::runtime_error(s.str()); } size_t my_id = pixid; vector<size_t> indices(bounds.size()); for (size_t i = 0 ; i < rank-1 ; ++i ) { indices[i] = my_id / bounds[i+1]; my_id = my_id - indices[i] * bounds[i+1]; } indices[rank-1] = my_id; return thing_to_str(indices); } /** * The main entry point for the program. */ int main(int argc, char** argv) { // ---------- Declare the supported options. po::options_description generic_options("Generic options"); generic_options.add_options() ("help,h", "Produce this help message.") ("version,v", "Print version string.") ; stringstream typesHelp; typesHelp << "Set the type of the data. Allowed values are: " << render::getKnownDataDescr() << ", " << prenexus::getKnownDataDescr(); po::options_description config_options("Configuration"); config_options.add_options() ("type,t", po::value<string>()->default_value(DEFAULT_TYPE), typesHelp.str().c_str()) ("offset", po::value<size_t>()->default_value(0), "Skip to this position (in bytes) in the file.") ("length", po::value<size_t>()->default_value(0), "Number of items to read (NOT in bytes). Zero means read to end of file.") ("records", po::value<size_t>()->default_value(1), "Number of items to print per line") ("byteswap", "Perform byte swapping on the data") ("quiet,q", "Do not print out values") ("lines", "show line numbers") ; po::options_description hidden_options; hidden_options.add_options() ("filename", po::value< vector<string> >(), "input files") ; // all options available on the command line po::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); // all options visible to the user po::options_description visible_options("Allowed options"); visible_options.add(generic_options).add(config_options); // ---------- parse the command line po::positional_options_description p; p.add("filename", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(cmdline_options) .positional(p).run(), vm); po::notify(vm); // ---------- get everything out of the options // work with generic options if (vm.count("help")) { cout << "Usage: " << argv[0] << " [options] <filenames>" << endl; cout << endl; cout << "Source code located at http://github.com/peterfpeterson/morebin" << endl; cout << endl; cout << visible_options << endl; cout << endl; cout << "Notes on complex types:" << endl; cout << " The following types are printed in colums (in order)" << endl; cout << endl; cout << " event" << endl; cout << "\ttof(uint32_t) Time of flight." << endl; cout << "\tpid(uint32_t) Pixel identifier as published by the DAS/DAE/DAQ." << endl; cout << " oldpulseid" << endl; cout << "\ttime(uint32_t,uint32_t) Time of the pulse" << endl; cout << "\tevent_index(uint64_t) The index of the first event for this pulse." << endl; cout << " pulseid" << endl; cout << "\ttime(uint32_t,uint32_t) Time of the pulse" << endl; cout << "\tevent_index(uint64_t) The index of the first event for this pulse." << endl; cout << "\tpCurrent(double) The proton charge for the pulse." << endl; cout << " rtdl" << endl; cout << "\ttime(uint32_t,uint32_t) Time of the pulse" << endl; cout << "\tpulseType(uint32_t)" << endl; cout << "\tvetoStatus(uint32_t)" << endl; cout << "\tpCurrent(uint32_t) The proton charge for the pulse." << endl; cout << "\tspare(uint32_t)" << endl; return 0; } if (vm.count("version")) { cout << "morebin version " << VERSION << " built " << DATE << endl; cout << endl; cout << "http://github.com/peterfpeterson/morebin/"; if (VERSION.find("SNAPSHOT") == string::npos) cout << "tree/v" << VERSION; cout << endl; return 0; } // config options size_t offset = 0; if (vm.count("offset")) offset = vm["offset"].as<size_t>(); size_t length = 0; if (vm.count("length")) length = vm["length"].as<size_t>(); size_t numItemsPerLine = 1; if (vm.count("records")) numItemsPerLine = vm["records"].as<size_t>(); bool byteswap = (vm.count("byteswap") > 0); bool quiet = (vm.count("quiet") > 0); string dataType = DEFAULT_TYPE; if (vm.count("type")) dataType = vm["type"].as<string>(); bool showLines = (vm.count("lines") > 0); // hidden options vector<string> files; if (vm.count("filename")) { files = vm["filename"].as< vector<string> >(); } else { cerr << "ERROR: failed to supply <filename>" << endl; //cmd.getOutput()->usage(cmd); return -1; } // ---------- push through the list of files try { bool multiFile = (files.size() > 1); render::Renderer * renderer = NULL; try { renderer = new render::Renderer(); renderer->setDataDescr(dataType); } catch (std::runtime_error &e) { std::cerr << "RUNTIME ERROR:" << e.what() << "\n"; renderer = new prenexus::PrenexusRenderer(); renderer->setDataDescr(dataType); } renderer->quiet(quiet); renderer->showLines(showLines); renderer->numItemsPerLine(numItemsPerLine); for (std::size_t i = 0; i < files.size(); i++) { BinFile file(files[i]); file.setByteSwap(byteswap); if (multiFile) { cout << "******************************" << endl; cout << "* " << files[i] << " size:" << file.size_in_bytes() << endl; cout << "******************************" << endl; } renderer->showData(file, offset, length); } delete renderer; } catch(std::runtime_error &e) { cerr << "RUNTIME ERROR:" << e.what() << endl; return -1; } return 0; } <commit_msg>Changing from pragma to ifdef to get rid of windoze warnings<commit_after>//include <tclap/CmdLine.h> #include <boost/program_options/errors.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/positional_options.hpp> #include <boost/program_options/value_semantic.hpp> #include <boost/program_options/variables_map.hpp> #include <ctype.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <algorithm> #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include "bin_file.hpp" #include "prenexusrenderer.hpp" #include "renderer.hpp" #include "version.hpp" using std::cerr; using std::cout; using std::endl; using std::invalid_argument; using std::string; using std::stringstream; using std::vector; namespace po = boost::program_options; typedef uint32_t event_t; struct Config{ bool byte_swap; bool show_data; bool show_line_num; bool multi_file; bool sum_data; bool sum_block; bool is_event; bool get_pix_range; vector<size_t> integrate; }; static const size_t BLOCK_SIZE=1024; static const event_t ERROR=0x80000000; static const string DEFAULT_TYPE="char"; static string::size_type count_occur(const string &str, const string &ch){ string::size_type count = 0; string::size_type index = 0; // infinite loop to make sure that the entire string is parsed. #ifdef _MSC_VER for(;;) { #else while(true) { #endif index = str.find(ch,index+1); if(index==string::npos) { break; } count++; } return count; } static bool my_isnotdigit(char c){ return !isdigit(c); } static int str_to_int(const string &str){ if(str.substr(0,1)=="-") return -1*str_to_int(str.substr(1,str.size())); string::const_iterator it = str.begin(); it = std::find_if(it,str.end(),my_isnotdigit); if(it!=str.end()) throw invalid_argument("str_to_int(string) argument is not an integer"); return atol(str.c_str()); } extern vector<string> split(const string &source,const string &split) { string::size_type number=count_occur(source,split); if(number==0) { vector<string> result; result.push_back(source); return result; } vector<string> result; string::size_type start=0; string::size_type stop=0; string inner; #ifdef _MSC_VER for(;;) { #else while(true) { #endif stop=source.find(split,start); if(stop==string::npos) { result.push_back(source.substr(start)); break; } else { result.push_back(source.substr(start,stop-start)); start=stop+split.size(); } } return result; } template <typename NumT> string thing_to_str(const NumT thing) { std::stringstream s; s << thing; return s.str(); } template <typename NumT> string thing_to_str(const vector<NumT> &thing) { std::stringstream s; size_t length = thing.size(); for ( size_t i = 0 ; i < length ; ++i ){ s << thing[i] << " "; } return s.str(); } string pixid_str(const size_t pixid, const vector<size_t> &bounds) { size_t rank = bounds.size(); if (rank<=0) { return ""; } size_t max_index=1; for (size_t i = 0 ; i<rank ; ++i ){ max_index*=bounds[i]; } if(pixid>max_index) { std::stringstream s; s << "Pixel id outside of known bounds: " << pixid << ">" << max_index; throw std::runtime_error(s.str()); } size_t my_id = pixid; vector<size_t> indices(bounds.size()); for (size_t i = 0 ; i < rank-1 ; ++i ) { indices[i] = my_id / bounds[i+1]; my_id = my_id - indices[i] * bounds[i+1]; } indices[rank-1] = my_id; return thing_to_str(indices); } /** * The main entry point for the program. */ int main(int argc, char** argv) { // ---------- Declare the supported options. po::options_description generic_options("Generic options"); generic_options.add_options() ("help,h", "Produce this help message.") ("version,v", "Print version string.") ; stringstream typesHelp; typesHelp << "Set the type of the data. Allowed values are: " << render::getKnownDataDescr() << ", " << prenexus::getKnownDataDescr(); po::options_description config_options("Configuration"); config_options.add_options() ("type,t", po::value<string>()->default_value(DEFAULT_TYPE), typesHelp.str().c_str()) ("offset", po::value<size_t>()->default_value(0), "Skip to this position (in bytes) in the file.") ("length", po::value<size_t>()->default_value(0), "Number of items to read (NOT in bytes). Zero means read to end of file.") ("records", po::value<size_t>()->default_value(1), "Number of items to print per line") ("byteswap", "Perform byte swapping on the data") ("quiet,q", "Do not print out values") ("lines", "show line numbers") ; po::options_description hidden_options; hidden_options.add_options() ("filename", po::value< vector<string> >(), "input files") ; // all options available on the command line po::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); // all options visible to the user po::options_description visible_options("Allowed options"); visible_options.add(generic_options).add(config_options); // ---------- parse the command line po::positional_options_description p; p.add("filename", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(cmdline_options) .positional(p).run(), vm); po::notify(vm); // ---------- get everything out of the options // work with generic options if (vm.count("help")) { cout << "Usage: " << argv[0] << " [options] <filenames>" << endl; cout << endl; cout << "Source code located at http://github.com/peterfpeterson/morebin" << endl; cout << endl; cout << visible_options << endl; cout << endl; cout << "Notes on complex types:" << endl; cout << " The following types are printed in colums (in order)" << endl; cout << endl; cout << " event" << endl; cout << "\ttof(uint32_t) Time of flight." << endl; cout << "\tpid(uint32_t) Pixel identifier as published by the DAS/DAE/DAQ." << endl; cout << " oldpulseid" << endl; cout << "\ttime(uint32_t,uint32_t) Time of the pulse" << endl; cout << "\tevent_index(uint64_t) The index of the first event for this pulse." << endl; cout << " pulseid" << endl; cout << "\ttime(uint32_t,uint32_t) Time of the pulse" << endl; cout << "\tevent_index(uint64_t) The index of the first event for this pulse." << endl; cout << "\tpCurrent(double) The proton charge for the pulse." << endl; cout << " rtdl" << endl; cout << "\ttime(uint32_t,uint32_t) Time of the pulse" << endl; cout << "\tpulseType(uint32_t)" << endl; cout << "\tvetoStatus(uint32_t)" << endl; cout << "\tpCurrent(uint32_t) The proton charge for the pulse." << endl; cout << "\tspare(uint32_t)" << endl; return 0; } if (vm.count("version")) { cout << "morebin version " << VERSION << " built " << DATE << endl; cout << endl; cout << "http://github.com/peterfpeterson/morebin/"; if (VERSION.find("SNAPSHOT") == string::npos) cout << "tree/v" << VERSION; cout << endl; return 0; } // config options size_t offset = 0; if (vm.count("offset")) offset = vm["offset"].as<size_t>(); size_t length = 0; if (vm.count("length")) length = vm["length"].as<size_t>(); size_t numItemsPerLine = 1; if (vm.count("records")) numItemsPerLine = vm["records"].as<size_t>(); bool byteswap = (vm.count("byteswap") > 0); bool quiet = (vm.count("quiet") > 0); string dataType = DEFAULT_TYPE; if (vm.count("type")) dataType = vm["type"].as<string>(); bool showLines = (vm.count("lines") > 0); // hidden options vector<string> files; if (vm.count("filename")) { files = vm["filename"].as< vector<string> >(); } else { cerr << "ERROR: failed to supply <filename>" << endl; //cmd.getOutput()->usage(cmd); return -1; } // ---------- push through the list of files try { bool multiFile = (files.size() > 1); render::Renderer * renderer = NULL; try { renderer = new render::Renderer(); renderer->setDataDescr(dataType); } catch (std::runtime_error &e) { std::cerr << "RUNTIME ERROR:" << e.what() << "\n"; renderer = new prenexus::PrenexusRenderer(); renderer->setDataDescr(dataType); } renderer->quiet(quiet); renderer->showLines(showLines); renderer->numItemsPerLine(numItemsPerLine); for (std::size_t i = 0; i < files.size(); i++) { BinFile file(files[i]); file.setByteSwap(byteswap); if (multiFile) { cout << "******************************" << endl; cout << "* " << files[i] << " size:" << file.size_in_bytes() << endl; cout << "******************************" << endl; } renderer->showData(file, offset, length); } delete renderer; } catch(std::runtime_error &e) { cerr << "RUNTIME ERROR:" << e.what() << endl; return -1; } return 0; } <|endoftext|>
<commit_before>#include "enrichment_tests.h" #include <cmath> #include <gtest/gtest.h> #include "composition.h" #include "context.h" #include "cyc_limits.h" #include "env.h" #include "error.h" #include "material.h" #include "recorder.h" #include "timer.h" namespace cyclus { namespace toolkit { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void EnrichmentTests::SetUp() { Env::SetNucDataPath(); feed_ = 0.0072; product_ = 0.05; tails_ = 0.002; assay_u_ = product_; mass_u_ = 10; Timer ti; Recorder rec; Context ctx(&ti, &rec); CompMap v; v[922350000] = assay_u_; v[922380000] = 1 - assay_u_; Composition::Ptr comp = Composition::CreateFromAtom(v); mat_ = Material::CreateUntracked(mass_u_, comp); SetEnrichmentParameters(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void EnrichmentTests::TearDown() {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void EnrichmentTests::SetEnrichmentParameters() { double feed_val = (1 - 2 * feed_) * std::log(1 / feed_ - 1); double tails_val = (1 - 2 * tails_) * std::log(1 / tails_ - 1); double product_val = (1 - 2 * product_) * std::log(1 / product_ - 1); feed_qty_ = mass_u_ * (product_ - tails_) / (feed_ - tails_); tails_qty_ = mass_u_ * (product_ - feed_) / (feed_ - tails_); swu_ = mass_u_ * product_val + tails_qty_ * tails_val - feed_qty_ * feed_val; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, assays) { Assays a(feed_, product_, tails_); EXPECT_DOUBLE_EQ(feed_, a.Feed()); EXPECT_DOUBLE_EQ(product_, a.Product()); EXPECT_DOUBLE_EQ(tails_, a.Tails()); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, valuefunction) { EXPECT_THROW(ValueFunc(0 - eps()), ValueError); EXPECT_THROW(ValueFunc(1), ValueError); double step = 0.001; double test_value = 0; while (test_value < 1) { double expected = (1 - 2 * test_value) * std::log(1 / test_value - 1); EXPECT_DOUBLE_EQ(expected, ValueFunc(test_value)); test_value += step; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, material) { EXPECT_DOUBLE_EQ(assay_u_, UraniumAssay(mat_)); EXPECT_DOUBLE_EQ(mass_u_, UraniumQty(mat_)); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, enrichmentcalcs) { Assays assays(feed_, UraniumAssay(mat_), tails_); double product_qty = UraniumQty(mat_); EXPECT_DOUBLE_EQ(feed_qty_, FeedQty(product_qty, assays)); EXPECT_DOUBLE_EQ(tails_qty_, TailsQty(product_qty, assays)); EXPECT_NEAR(swu_, SwuRequired(product_qty, assays), 1e-8); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, nonfissilematl) { // for testing material containing non-fissile components double extra_ = 0.05; double fissile_frac = (1-extra_); CompMap v_extra; v_extra[922350000] = assay_u_; v_extra[922390000] = extra_ ; v_extra[922380000] = 1 - assay_u_ - extra_; Composition::Ptr comp_extra = Composition::CreateFromAtom(v_extra); cyclus::Material::Ptr mat_extra_ = Material::CreateUntracked(mass_u_, comp_extra); Assays assays(feed_, UraniumAssay(mat_), tails_); double product_qty = UraniumQty(mat_); EXPECT_DOUBLE_EQ(feed_qty_ ,NonFissileMultiplier(mat_) * FeedQty(product_qty, assays)); EXPECT_NEAR(feed_qty_ / fissile_frac, NonFissileMultiplier(mat_extra_) * FeedQty(product_qty, assays), 0.05); } } // namespace toolkit } // namespace cyclus <commit_msg>xml annotation fix<commit_after>#include "enrichment_tests.h" #include <cmath> #include <gtest/gtest.h> #include "composition.h" #include "context.h" #include "cyc_limits.h" #include "env.h" #include "error.h" #include "material.h" #include "recorder.h" #include "timer.h" namespace cyclus { namespace toolkit { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void EnrichmentTests::SetUp() { Env::SetNucDataPath(); feed_ = 0.0072; product_ = 0.05; tails_ = 0.002; assay_u_ = product_; mass_u_ = 10; Timer ti; Recorder rec; Context ctx(&ti, &rec); CompMap v; v[922350000] = assay_u_; v[922380000] = 1 - assay_u_; Composition::Ptr comp = Composition::CreateFromAtom(v); mat_ = Material::CreateUntracked(mass_u_, comp); SetEnrichmentParameters(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void EnrichmentTests::TearDown() {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void EnrichmentTests::SetEnrichmentParameters() { double feed_val = (1 - 2 * feed_) * std::log(1 / feed_ - 1); double tails_val = (1 - 2 * tails_) * std::log(1 / tails_ - 1); double product_val = (1 - 2 * product_) * std::log(1 / product_ - 1); feed_qty_ = mass_u_ * (product_ - tails_) / (feed_ - tails_); tails_qty_ = mass_u_ * (product_ - feed_) / (feed_ - tails_); swu_ = mass_u_ * product_val + tails_qty_ * tails_val - feed_qty_ * feed_val; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, assays) { Assays a(feed_, product_, tails_); EXPECT_DOUBLE_EQ(feed_, a.Feed()); EXPECT_DOUBLE_EQ(product_, a.Product()); EXPECT_DOUBLE_EQ(tails_, a.Tails()); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, valuefunction) { EXPECT_THROW(ValueFunc(0 - eps()), ValueError); EXPECT_THROW(ValueFunc(1), ValueError); double step = 0.001; double test_value = 0; while (test_value < 1) { double expected = (1 - 2 * test_value) * std::log(1 / test_value - 1); EXPECT_DOUBLE_EQ(expected, ValueFunc(test_value)); test_value += step; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, material) { EXPECT_DOUBLE_EQ(assay_u_, UraniumAssay(mat_)); EXPECT_DOUBLE_EQ(mass_u_, UraniumQty(mat_)); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(EnrichmentTests, enrichmentcalcs) { Assays assays(feed_, UraniumAssay(mat_), tails_); double product_qty = UraniumQty(mat_); EXPECT_DOUBLE_EQ(feed_qty_, FeedQty(product_qty, assays)); EXPECT_DOUBLE_EQ(tails_qty_, TailsQty(product_qty, assays)); EXPECT_NEAR(swu_, SwuRequired(product_qty, assays), 1e-8); } } // namespace toolkit } // namespace cyclus <|endoftext|>
<commit_before>//===- Support/FileUtilities.cpp - File System Utilities ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a family of utility functions which are useful for doing // various things with files. // //===----------------------------------------------------------------------===// #include "llvm/Support/FileUtilities.h" #include "llvm/System/Path.h" #include "llvm/System/MappedFile.h" #include "llvm/ADT/StringExtras.h" #include <cmath> #include <cstring> #include <cctype> using namespace llvm; static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'D': // Strange exponential notation. case 'd': // Strange exponential notation. case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { // If we didn't stop in the middle of a number, don't backup. if (!isNumberChar(*Pos)) return Pos; // Otherwise, return to the start of the number. while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } /// CompareNumbers - compare two numbers, returning true if they are different. static bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End, double AbsTolerance, double RelTolerance, std::string *ErrorMsg) { char *F1NumEnd, *F2NumEnd; double V1 = 0.0, V2 = 0.0; // If one of the positions is at a space and the other isn't, chomp up 'til // the end of the space. while (isspace(*F1P) && F1P != F1End) ++F1P; while (isspace(*F2P) && F2P != F2End) ++F2P; // If we stop on numbers, compare their difference. Note that some ugliness // is built into this to permit support for numbers that use "D" or "d" as // their exponential marker, e.g. "1.234D45". This occurs in 200.sixtrack in // spec2k. if (isNumberChar(*F1P) && isNumberChar(*F2P)) { bool isDNotation; do { isDNotation = false; V1 = strtod(F1P, &F1NumEnd); V2 = strtod(F2P, &F2NumEnd); if (*F1NumEnd == 'D' || *F1NumEnd == 'd') { *F1NumEnd = 'e'; // Strange exponential notation! isDNotation = true; } if (*F2NumEnd == 'D' || *F2NumEnd == 'd') { *F2NumEnd = 'e'; // Strange exponential notation! isDNotation = true; } } while (isDNotation); } else { // Otherwise, the diff failed. F1NumEnd = F1P; F2NumEnd = F2P; } if (F1NumEnd == F1P || F2NumEnd == F2P) { if (ErrorMsg) *ErrorMsg = "Comparison failed, not a numeric difference."; return true; } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { if (ErrorMsg) { *ErrorMsg = "Compared: " + ftostr(V1) + " and " + ftostr(V2) + ": diff = " + ftostr(Diff) + "\n"; *ErrorMsg += "Out of tolerance: rel/abs: " + ftostr(RelTolerance) + "/" + ftostr(AbsTolerance); } return true; } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; return false; } // PadFileIfNeeded - If the files are not identical, we will have to be doing // numeric comparisons in here. There are bad cases involved where we (i.e., // strtod) might run off the beginning or end of the file if it starts or ends // with a number. Because of this, if needed, we pad the file so that it starts // and ends with a null character. static void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) { if (FileStart-FileEnd < 2 || isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) { unsigned FileLen = FileEnd-FileStart; char *NewFile = new char[FileLen+2]; NewFile[0] = 0; // Add null padding NewFile[FileLen+1] = 0; // Add null padding memcpy(NewFile+1, FileStart, FileLen); FP = NewFile+(FP-FileStart)+1; FileStart = NewFile+1; FileEnd = FileStart+FileLen; } } /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the /// files match, 1 if they are different, and 2 if there is a file error. This /// function differs from DiffFiles in that you can specify an absolete and /// relative FP error that is allowed to exist. If you specify a string to fill /// in for the error option, it will set the string to an error message if an /// error occurs, allowing the caller to distinguish between a failed diff and a /// file system error. /// int llvm::DiffFilesWithTolerance(const sys::Path &FileA, const sys::Path &FileB, double AbsTol, double RelTol, std::string *Error) { try { // Check for zero length files because some systems croak when you try to // mmap an empty file. size_t A_size = FileA.getSize(); size_t B_size = FileB.getSize(); // If they are both zero sized then they're the same if (A_size == 0 && B_size == 0) return 0; // If only one of them is zero sized then they can't be the same if ((A_size == 0 || B_size == 0)) return 1; // Now its safe to mmap the files into memory becasue both files // have a non-zero size. sys::MappedFile F1(FileA); sys::MappedFile F2(FileB); F1.map(); F2.map(); // Okay, now that we opened the files, scan them for the first difference. char *File1Start = F1.charBase(); char *File2Start = F2.charBase(); char *File1End = File1Start+A_size; char *File2End = File2Start+B_size; char *F1P = File1Start; char *F2P = File2Start; if (A_size == B_size) { // Are the buffers identical? if (std::memcmp(File1Start, File2Start, A_size) == 0) return 0; if (AbsTol == 0 && RelTol == 0) return 1; // Files different! } char *OrigFile1Start = File1Start; char *OrigFile2Start = File2Start; // If the files need padding, do so now. PadFileIfNeeded(File1Start, File1End, F1P); PadFileIfNeeded(File2Start, File2End, F2P); bool CompareFailed = false; while (1) { // Scan for the end of file or next difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) { CompareFailed = true; break; } } // Okay, we reached the end of file. If both files are at the end, we // succeeded. bool F1AtEnd = F1P >= File1End; bool F2AtEnd = F2P >= File2End; if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) { // Else, we might have run off the end due to a number: backup and retry. if (F1AtEnd && isNumberChar(F1P[-1])) --F1P; if (F2AtEnd && isNumberChar(F2P[-1])) --F2P; F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) CompareFailed = true; // If we found the end, we succeeded. if (F1P < File1End || F2P < File2End) CompareFailed = true; } if (OrigFile1Start != File1Start) delete[] (File1Start-1); // Back up past null byte if (OrigFile2Start != File2Start) delete[] (File2Start-1); // Back up past null byte return CompareFailed; } catch (const std::string &Msg) { if (Error) *Error = Msg; return 2; } } <commit_msg>For PR777: Add an additional catch block to ensure that this function can't throw any exceptions, even one's we're not expecting.<commit_after>//===- Support/FileUtilities.cpp - File System Utilities ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a family of utility functions which are useful for doing // various things with files. // //===----------------------------------------------------------------------===// #include "llvm/Support/FileUtilities.h" #include "llvm/System/Path.h" #include "llvm/System/MappedFile.h" #include "llvm/ADT/StringExtras.h" #include <cmath> #include <cstring> #include <cctype> using namespace llvm; static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'D': // Strange exponential notation. case 'd': // Strange exponential notation. case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { // If we didn't stop in the middle of a number, don't backup. if (!isNumberChar(*Pos)) return Pos; // Otherwise, return to the start of the number. while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } /// CompareNumbers - compare two numbers, returning true if they are different. static bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End, double AbsTolerance, double RelTolerance, std::string *ErrorMsg) { char *F1NumEnd, *F2NumEnd; double V1 = 0.0, V2 = 0.0; // If one of the positions is at a space and the other isn't, chomp up 'til // the end of the space. while (isspace(*F1P) && F1P != F1End) ++F1P; while (isspace(*F2P) && F2P != F2End) ++F2P; // If we stop on numbers, compare their difference. Note that some ugliness // is built into this to permit support for numbers that use "D" or "d" as // their exponential marker, e.g. "1.234D45". This occurs in 200.sixtrack in // spec2k. if (isNumberChar(*F1P) && isNumberChar(*F2P)) { bool isDNotation; do { isDNotation = false; V1 = strtod(F1P, &F1NumEnd); V2 = strtod(F2P, &F2NumEnd); if (*F1NumEnd == 'D' || *F1NumEnd == 'd') { *F1NumEnd = 'e'; // Strange exponential notation! isDNotation = true; } if (*F2NumEnd == 'D' || *F2NumEnd == 'd') { *F2NumEnd = 'e'; // Strange exponential notation! isDNotation = true; } } while (isDNotation); } else { // Otherwise, the diff failed. F1NumEnd = F1P; F2NumEnd = F2P; } if (F1NumEnd == F1P || F2NumEnd == F2P) { if (ErrorMsg) *ErrorMsg = "Comparison failed, not a numeric difference."; return true; } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { if (ErrorMsg) { *ErrorMsg = "Compared: " + ftostr(V1) + " and " + ftostr(V2) + ": diff = " + ftostr(Diff) + "\n"; *ErrorMsg += "Out of tolerance: rel/abs: " + ftostr(RelTolerance) + "/" + ftostr(AbsTolerance); } return true; } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; return false; } // PadFileIfNeeded - If the files are not identical, we will have to be doing // numeric comparisons in here. There are bad cases involved where we (i.e., // strtod) might run off the beginning or end of the file if it starts or ends // with a number. Because of this, if needed, we pad the file so that it starts // and ends with a null character. static void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) { if (FileStart-FileEnd < 2 || isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) { unsigned FileLen = FileEnd-FileStart; char *NewFile = new char[FileLen+2]; NewFile[0] = 0; // Add null padding NewFile[FileLen+1] = 0; // Add null padding memcpy(NewFile+1, FileStart, FileLen); FP = NewFile+(FP-FileStart)+1; FileStart = NewFile+1; FileEnd = FileStart+FileLen; } } /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the /// files match, 1 if they are different, and 2 if there is a file error. This /// function differs from DiffFiles in that you can specify an absolete and /// relative FP error that is allowed to exist. If you specify a string to fill /// in for the error option, it will set the string to an error message if an /// error occurs, allowing the caller to distinguish between a failed diff and a /// file system error. /// int llvm::DiffFilesWithTolerance(const sys::Path &FileA, const sys::Path &FileB, double AbsTol, double RelTol, std::string *Error) { try { // Check for zero length files because some systems croak when you try to // mmap an empty file. size_t A_size = FileA.getSize(); size_t B_size = FileB.getSize(); // If they are both zero sized then they're the same if (A_size == 0 && B_size == 0) return 0; // If only one of them is zero sized then they can't be the same if ((A_size == 0 || B_size == 0)) return 1; // Now its safe to mmap the files into memory becasue both files // have a non-zero size. sys::MappedFile F1(FileA); sys::MappedFile F2(FileB); F1.map(); F2.map(); // Okay, now that we opened the files, scan them for the first difference. char *File1Start = F1.charBase(); char *File2Start = F2.charBase(); char *File1End = File1Start+A_size; char *File2End = File2Start+B_size; char *F1P = File1Start; char *F2P = File2Start; if (A_size == B_size) { // Are the buffers identical? if (std::memcmp(File1Start, File2Start, A_size) == 0) return 0; if (AbsTol == 0 && RelTol == 0) return 1; // Files different! } char *OrigFile1Start = File1Start; char *OrigFile2Start = File2Start; // If the files need padding, do so now. PadFileIfNeeded(File1Start, File1End, F1P); PadFileIfNeeded(File2Start, File2End, F2P); bool CompareFailed = false; while (1) { // Scan for the end of file or next difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) { CompareFailed = true; break; } } // Okay, we reached the end of file. If both files are at the end, we // succeeded. bool F1AtEnd = F1P >= File1End; bool F2AtEnd = F2P >= File2End; if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) { // Else, we might have run off the end due to a number: backup and retry. if (F1AtEnd && isNumberChar(F1P[-1])) --F1P; if (F2AtEnd && isNumberChar(F2P[-1])) --F2P; F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) CompareFailed = true; // If we found the end, we succeeded. if (F1P < File1End || F2P < File2End) CompareFailed = true; } if (OrigFile1Start != File1Start) delete[] (File1Start-1); // Back up past null byte if (OrigFile2Start != File2Start) delete[] (File2Start-1); // Back up past null byte return CompareFailed; } catch (const std::string &Msg) { if (Error) *Error = Msg; return 2; } catch (...) { *Error = "Unknown Exception Occurred"; return 2; } } <|endoftext|>
<commit_before>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define __STDC_FORMAT_MACROS #include <thrift/perf/cpp/ClientWorker2.h> #include <thrift/lib/cpp/ClientUtil.h> #include <thrift/lib/cpp/async/TAsyncSSLSocket.h> #include <thrift/lib/cpp/async/TAsyncSocket.h> #include <thrift/lib/cpp/test/loadgen/RNG.h> #include <thrift/lib/cpp/util/kerberos/Krb5CredentialsCacheManager.h> #include <thrift/lib/cpp/util/kerberos/Krb5CredentialsCacheManagerLogger.h> #include <thrift/lib/cpp2/async/GssSaslClient.h> #include <thrift/lib/cpp2/async/HeaderClientChannel.h> #include <thrift/lib/cpp2/security/KerberosSASLThreadManager.h> #include <thrift/perf/cpp/ClientLoadConfig.h> using namespace boost; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::async; using namespace apache::thrift; namespace apache { namespace thrift { namespace test { const int kTimeout = 60000; std::shared_ptr<ClientWorker2::Client> ClientWorker2::createConnection() { const std::shared_ptr<ClientLoadConfig>& config = getConfig(); std::shared_ptr<TAsyncSocket> socket; std::unique_ptr< RequestChannel, folly::DelayedDestruction::Destructor> channel; if (config->useSR()) { facebook::servicerouter::ConnConfigs configs; facebook::servicerouter::ServiceOptions options; configs["sock_sendtimeout"] = folly::to<std::string>(kTimeout); configs["sock_recvtimeout"] = folly::to<std::string>(kTimeout); if (config->SASLPolicy() == "required" || config->SASLPolicy() == "permitted") { configs["thrift_security"] = config->SASLPolicy(); if (!config->SASLServiceTier().empty()) { configs["thrift_security_service_tier"] = config->SASLServiceTier(); } } if (config->useSSLTFO()) { configs["tls_tcp_fastopen"] = "true"; } channel = facebook::servicerouter::cpp2::getClientFactory() .getChannel(config->srTier(), ebm_.getEventBase(), options, configs); } else { if (config->useSSL()) { std::shared_ptr<SSLContext> context = std::make_shared<SSLContext>(); if (!config->trustedCAList().empty()) { context->loadTrustedCertificates(config->trustedCAList().c_str()); context->setVerificationOption( SSLContext::SSLVerifyPeerEnum::VERIFY); } if (!config->ciphers().empty()) { context->ciphers(config->ciphers()); } if (!config->key().empty() && !config->cert().empty()) { context->loadCertificate(config->cert().c_str()); context->loadPrivateKey(config->key().c_str()); } socket = TAsyncSSLSocket::newSocket(context, ebm_.getEventBase()); socket->connect(nullptr, *config->getAddress()); // Loop once to connect ebm_.getEventBase()->loop(); } else { socket = TAsyncSocket::newSocket(ebm_.getEventBase(), *config->getAddress()); } std::unique_ptr< HeaderClientChannel, folly::DelayedDestruction::Destructor> headerChannel( HeaderClientChannel::newChannel(socket)); // Always use binary in loadtesting to get apples to apples comparison headerChannel->setProtocolId(apache::thrift::protocol::T_BINARY_PROTOCOL); if (config->zlib()) { headerChannel->setTransform(THeader::ZLIB_TRANSFORM); } if (!config->useHeaderProtocol()) { headerChannel->setClientType(THRIFT_FRAMED_DEPRECATED); } headerChannel->setTimeout(kTimeout); if (config->SASLPolicy() == "permitted") { headerChannel->setSecurityPolicy(THRIFT_SECURITY_PERMITTED); } else if (config->SASLPolicy() == "required") { headerChannel->setSecurityPolicy(THRIFT_SECURITY_REQUIRED); } if (config->SASLPolicy() == "required" || config->SASLPolicy() == "permitted") { static auto krb5CredentialsCacheManagerLogger = std::make_shared<krb5::Krb5CredentialsCacheManagerLogger>(); static auto saslThreadManager = std::make_shared<SaslThreadManager>( krb5CredentialsCacheManagerLogger); static auto credentialsCacheManager = std::make_shared<krb5::Krb5CredentialsCacheManager>( krb5CredentialsCacheManagerLogger); headerChannel->setSaslClient(std::unique_ptr<apache::thrift::SaslClient>( new apache::thrift::GssSaslClient(socket->getEventBase()) )); headerChannel->getSaslClient()->setSaslThreadManager(saslThreadManager); headerChannel->getSaslClient()->setCredentialsCacheManager( credentialsCacheManager); headerChannel->getSaslClient()->setServiceIdentity( folly::format( "{}@{}", config->SASLServiceTier(), config->getAddressHostname()).str()); } channel = std::move(headerChannel); } return std::shared_ptr<ClientWorker2::Client>( new ClientWorker2::Client(std::move(channel))); } void ClientWorker2::performOperation(const std::shared_ptr<Client>& client, uint32_t opType) { switch (static_cast<ClientLoadConfig::OperationEnum>(opType)) { case ClientLoadConfig::OP_NOOP: return performNoop(client); case ClientLoadConfig::OP_ONEWAY_NOOP: return performOnewayNoop(client); case ClientLoadConfig::OP_ASYNC_NOOP: return performAsyncNoop(client); case ClientLoadConfig::OP_SLEEP: return performSleep(client); case ClientLoadConfig::OP_ONEWAY_SLEEP: return performOnewaySleep(client); case ClientLoadConfig::OP_BURN: return performBurn(client); case ClientLoadConfig::OP_ONEWAY_BURN: return performOnewayBurn(client); case ClientLoadConfig::OP_BAD_SLEEP: return performBadSleep(client); case ClientLoadConfig::OP_BAD_BURN: return performBadBurn(client); case ClientLoadConfig::OP_THROW_ERROR: return performThrowError(client); case ClientLoadConfig::OP_THROW_UNEXPECTED: return performThrowUnexpected(client); case ClientLoadConfig::OP_ONEWAY_THROW: return performOnewayThrow(client); case ClientLoadConfig::OP_SEND: return performSend(client); case ClientLoadConfig::OP_ONEWAY_SEND: return performOnewaySend(client); case ClientLoadConfig::OP_RECV: return performRecv(client); case ClientLoadConfig::OP_SENDRECV: return performSendrecv(client); case ClientLoadConfig::OP_ECHO: return performEcho(client); case ClientLoadConfig::OP_ADD: return performAdd(client); case ClientLoadConfig::OP_LARGE_CONTAINER: return performLargeContainer(client); case ClientLoadConfig::OP_ITER_ALL_FIELDS: return performIterAllFields(client); case ClientLoadConfig::NUM_OPS: // fall through break; // no default case, so gcc will warn us if a new op is added // and this switch statement is not updated } T_ERROR("ClientWorker2::performOperation() got unknown operation %" PRIu32, opType); assert(false); } void ClientWorker2::performNoop(const std::shared_ptr<Client>& client) { client->sync_noop(); } void ClientWorker2::performOnewayNoop(const std::shared_ptr<Client>& client) { client->sync_onewayNoop(); } void ClientWorker2::performAsyncNoop(const std::shared_ptr<Client>& client) { client->sync_asyncNoop(); } void ClientWorker2::performSleep(const std::shared_ptr<Client>& client) { client->sync_sleep(getConfig()->pickSleepUsec()); } void ClientWorker2::performOnewaySleep(const std::shared_ptr<Client>& client) { client->sync_onewaySleep(getConfig()->pickSleepUsec()); } void ClientWorker2::performBurn(const std::shared_ptr<Client>& client) { client->sync_burn(getConfig()->pickBurnUsec()); } void ClientWorker2::performOnewayBurn(const std::shared_ptr<Client>& client) { client->sync_onewayBurn(getConfig()->pickBurnUsec()); } void ClientWorker2::performBadSleep(const std::shared_ptr<Client>& client) { client->sync_badSleep(getConfig()->pickSleepUsec()); } void ClientWorker2::performBadBurn(const std::shared_ptr<Client>& client) { client->sync_badBurn(getConfig()->pickBurnUsec()); } void ClientWorker2::performThrowError(const std::shared_ptr<Client>& client) { uint32_t code = loadgen::RNG::getU32(); try { client->sync_throwError(code); T_ERROR("throwError() didn't throw any exception"); } catch (const LoadError& error) { assert(error.code == code); } } void ClientWorker2::performThrowUnexpected(const std::shared_ptr<Client>& client) { try { client->sync_throwUnexpected(loadgen::RNG::getU32()); T_ERROR("throwUnexpected() didn't throw any exception"); } catch (const TApplicationException& error) { // expected; do nothing } } void ClientWorker2::performOnewayThrow(const std::shared_ptr<Client>& client) { client->sync_onewayThrow(loadgen::RNG::getU32()); } void ClientWorker2::performSend(const std::shared_ptr<Client>& client) { std::string str(getConfig()->pickSendSize(), 'a'); client->sync_send(str); } void ClientWorker2::performOnewaySend(const std::shared_ptr<Client>& client) { std::string str(getConfig()->pickSendSize(), 'a'); client->sync_onewaySend(str); } void ClientWorker2::performRecv(const std::shared_ptr<Client>& client) { std::string str; client->sync_recv(str, getConfig()->pickRecvSize()); } void ClientWorker2::performSendrecv(const std::shared_ptr<Client>& client) { std::string sendStr(getConfig()->pickSendSize(), 'a'); std::string recvStr; client->sync_sendrecv(recvStr, sendStr, getConfig()->pickRecvSize()); } void ClientWorker2::performEcho(const std::shared_ptr<Client>& client) { std::string sendStr(getConfig()->pickSendSize(), 'a'); std::string recvStr; client->sync_echo(recvStr, sendStr); } void ClientWorker2::performAdd(const std::shared_ptr<Client>& client) { boost::uniform_int<int64_t> distribution; int64_t a = distribution(loadgen::RNG::getRNG()); int64_t b = distribution(loadgen::RNG::getRNG()); int64_t result = client->sync_add(a, b); if (result != a + b) { T_ERROR("add(%" PRId64 ", %" PRId64 " gave wrong result %" PRId64 "(expected %" PRId64 ")", a, b, result, a + b); } } void ClientWorker2::performLargeContainer( const std::shared_ptr<Client>& client) { std::vector<BigStruct> items; getConfig()->makeBigContainer<BigStruct>(items); client->sync_largeContainer(items); } void ClientWorker2::performIterAllFields( const std::shared_ptr<Client>& client) { std::vector<BigStruct> items; std::vector<BigStruct> out; getConfig()->makeBigContainer<BigStruct>(items); client->sync_iterAllFields(out, items); if (items != out) { T_ERROR("iterAllFields gave wrong result"); } } }}} // apache::thrift::test <commit_msg>(easy) Fix build<commit_after>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define __STDC_FORMAT_MACROS #include <thrift/perf/cpp/ClientWorker2.h> #include <thrift/lib/cpp/ClientUtil.h> #include <thrift/lib/cpp/async/TAsyncSSLSocket.h> #include <thrift/lib/cpp/async/TAsyncSocket.h> #include <thrift/lib/cpp/test/loadgen/RNG.h> #include <thrift/lib/cpp/util/kerberos/Krb5CredentialsCacheManager.h> #include <thrift/lib/cpp/util/kerberos/Krb5CredentialsCacheManagerLogger.h> #include <thrift/lib/cpp2/async/GssSaslClient.h> #include <thrift/lib/cpp2/async/HeaderClientChannel.h> #include <thrift/lib/cpp2/security/KerberosSASLThreadManager.h> #include <thrift/perf/cpp/ClientLoadConfig.h> using namespace boost; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::async; using namespace apache::thrift; namespace apache { namespace thrift { namespace test { const int kTimeout = 60000; std::shared_ptr<ClientWorker2::Client> ClientWorker2::createConnection() { const std::shared_ptr<ClientLoadConfig>& config = getConfig(); std::shared_ptr<TAsyncSocket> socket; std::unique_ptr< RequestChannel, folly::DelayedDestruction::Destructor> channel; if (config->useSR()) { facebook::servicerouter::ConnConfigs configs; facebook::servicerouter::ServiceOptions options; configs["sock_sendtimeout"] = folly::to<std::string>(kTimeout); configs["sock_recvtimeout"] = folly::to<std::string>(kTimeout); if (config->SASLPolicy() == "required" || config->SASLPolicy() == "permitted") { configs["thrift_security"] = config->SASLPolicy(); if (!config->SASLServiceTier().empty()) { configs["thrift_security_service_tier"] = config->SASLServiceTier(); } } if (config->useSSLTFO()) { configs["tls_tcp_fastopen"] = "true"; } channel = facebook::servicerouter::cpp2::getClientFactory() .getChannel(config->srTier(), ebm_.getEventBase(), options, configs); } else { if (config->useSSL()) { std::shared_ptr<SSLContext> context = std::make_shared<SSLContext>(); if (!config->trustedCAList().empty()) { context->loadTrustedCertificates(config->trustedCAList().c_str()); context->setVerificationOption( SSLContext::SSLVerifyPeerEnum::VERIFY); } if (!config->ciphers().empty()) { context->ciphers(config->ciphers()); } if (!config->key().empty() && !config->cert().empty()) { context->loadCertificate(config->cert().c_str()); context->loadPrivateKey(config->key().c_str()); } socket = TAsyncSSLSocket::newSocket(context, ebm_.getEventBase()); socket->connect(nullptr, *config->getAddress()); // Loop once to connect ebm_.getEventBase()->loop(); } else { socket = TAsyncSocket::newSocket(ebm_.getEventBase(), *config->getAddress()); } std::unique_ptr< HeaderClientChannel, folly::DelayedDestruction::Destructor> headerChannel( HeaderClientChannel::newChannel(socket)); // Always use binary in loadtesting to get apples to apples comparison headerChannel->setProtocolId(apache::thrift::protocol::T_BINARY_PROTOCOL); if (config->zlib()) { headerChannel->setTransform(THeader::ZLIB_TRANSFORM); } if (!config->useHeaderProtocol()) { headerChannel->setClientType(THRIFT_FRAMED_DEPRECATED); } headerChannel->setTimeout(kTimeout); if (config->SASLPolicy() == "permitted") { headerChannel->setSecurityPolicy(THRIFT_SECURITY_PERMITTED); } else if (config->SASLPolicy() == "required") { headerChannel->setSecurityPolicy(THRIFT_SECURITY_REQUIRED); } if (config->SASLPolicy() == "required" || config->SASLPolicy() == "permitted") { static auto krb5CredentialsCacheManagerLogger = std::make_shared<krb5::Krb5CredentialsCacheManagerLogger>(); static auto saslThreadManager = std::make_shared<SaslThreadManager>( krb5CredentialsCacheManagerLogger); static auto credentialsCacheManager = std::make_shared<krb5::Krb5CredentialsCacheManager>( krb5CredentialsCacheManagerLogger); headerChannel->setSaslClient(std::unique_ptr<apache::thrift::SaslClient>( new apache::thrift::GssSaslClient(socket->getEventBase()) )); headerChannel->getSaslClient()->setSaslThreadManager(saslThreadManager); headerChannel->getSaslClient()->setCredentialsCacheManager( credentialsCacheManager); headerChannel->getSaslClient()->setServiceIdentity( folly::format( "{}@{}", config->SASLServiceTier(), config->getAddressHostname()).str()); } channel = std::move(headerChannel); } return std::shared_ptr<ClientWorker2::Client>( new ClientWorker2::Client(std::move(channel))); } void ClientWorker2::performOperation(const std::shared_ptr<Client>& client, uint32_t opType) { switch (static_cast<ClientLoadConfig::OperationEnum>(opType)) { case ClientLoadConfig::OP_NOOP: return performNoop(client); case ClientLoadConfig::OP_ONEWAY_NOOP: return performOnewayNoop(client); case ClientLoadConfig::OP_ASYNC_NOOP: return performAsyncNoop(client); case ClientLoadConfig::OP_SLEEP: return performSleep(client); case ClientLoadConfig::OP_ONEWAY_SLEEP: return performOnewaySleep(client); case ClientLoadConfig::OP_BURN: return performBurn(client); case ClientLoadConfig::OP_ONEWAY_BURN: return performOnewayBurn(client); case ClientLoadConfig::OP_BAD_SLEEP: return performBadSleep(client); case ClientLoadConfig::OP_BAD_BURN: return performBadBurn(client); case ClientLoadConfig::OP_THROW_ERROR: return performThrowError(client); case ClientLoadConfig::OP_THROW_UNEXPECTED: return performThrowUnexpected(client); case ClientLoadConfig::OP_ONEWAY_THROW: return performOnewayThrow(client); case ClientLoadConfig::OP_SEND: return performSend(client); case ClientLoadConfig::OP_ONEWAY_SEND: return performOnewaySend(client); case ClientLoadConfig::OP_RECV: return performRecv(client); case ClientLoadConfig::OP_SENDRECV: return performSendrecv(client); case ClientLoadConfig::OP_ECHO: return performEcho(client); case ClientLoadConfig::OP_ADD: return performAdd(client); case ClientLoadConfig::OP_LARGE_CONTAINER: return performLargeContainer(client); case ClientLoadConfig::OP_ITER_ALL_FIELDS: return performIterAllFields(client); case ClientLoadConfig::NUM_OPS: // fall through break; // no default case, so gcc will warn us if a new op is added // and this switch statement is not updated } T_ERROR("ClientWorker2::performOperation() got unknown operation %" PRIu32, opType); assert(false); } void ClientWorker2::performNoop(const std::shared_ptr<Client>& client) { client->sync_noop(); } void ClientWorker2::performOnewayNoop(const std::shared_ptr<Client>& client) { client->sync_onewayNoop(); } void ClientWorker2::performAsyncNoop(const std::shared_ptr<Client>& client) { client->sync_asyncNoop(); } void ClientWorker2::performSleep(const std::shared_ptr<Client>& client) { client->sync_sleep(getConfig()->pickSleepUsec()); } void ClientWorker2::performOnewaySleep(const std::shared_ptr<Client>& client) { client->sync_onewaySleep(getConfig()->pickSleepUsec()); } void ClientWorker2::performBurn(const std::shared_ptr<Client>& client) { client->sync_burn(getConfig()->pickBurnUsec()); } void ClientWorker2::performOnewayBurn(const std::shared_ptr<Client>& client) { client->sync_onewayBurn(getConfig()->pickBurnUsec()); } void ClientWorker2::performBadSleep(const std::shared_ptr<Client>& client) { client->sync_badSleep(getConfig()->pickSleepUsec()); } void ClientWorker2::performBadBurn(const std::shared_ptr<Client>& client) { client->sync_badBurn(getConfig()->pickBurnUsec()); } void ClientWorker2::performThrowError(const std::shared_ptr<Client>& client) { uint32_t code = loadgen::RNG::getU32(); try { client->sync_throwError(code); T_ERROR("throwError() didn't throw any exception"); } catch (const LoadError& error) { assert(static_cast<uint32_t>(error.code) == code); } } void ClientWorker2::performThrowUnexpected(const std::shared_ptr<Client>& client) { try { client->sync_throwUnexpected(loadgen::RNG::getU32()); T_ERROR("throwUnexpected() didn't throw any exception"); } catch (const TApplicationException& error) { // expected; do nothing } } void ClientWorker2::performOnewayThrow(const std::shared_ptr<Client>& client) { client->sync_onewayThrow(loadgen::RNG::getU32()); } void ClientWorker2::performSend(const std::shared_ptr<Client>& client) { std::string str(getConfig()->pickSendSize(), 'a'); client->sync_send(str); } void ClientWorker2::performOnewaySend(const std::shared_ptr<Client>& client) { std::string str(getConfig()->pickSendSize(), 'a'); client->sync_onewaySend(str); } void ClientWorker2::performRecv(const std::shared_ptr<Client>& client) { std::string str; client->sync_recv(str, getConfig()->pickRecvSize()); } void ClientWorker2::performSendrecv(const std::shared_ptr<Client>& client) { std::string sendStr(getConfig()->pickSendSize(), 'a'); std::string recvStr; client->sync_sendrecv(recvStr, sendStr, getConfig()->pickRecvSize()); } void ClientWorker2::performEcho(const std::shared_ptr<Client>& client) { std::string sendStr(getConfig()->pickSendSize(), 'a'); std::string recvStr; client->sync_echo(recvStr, sendStr); } void ClientWorker2::performAdd(const std::shared_ptr<Client>& client) { boost::uniform_int<int64_t> distribution; int64_t a = distribution(loadgen::RNG::getRNG()); int64_t b = distribution(loadgen::RNG::getRNG()); int64_t result = client->sync_add(a, b); if (result != a + b) { T_ERROR("add(%" PRId64 ", %" PRId64 " gave wrong result %" PRId64 "(expected %" PRId64 ")", a, b, result, a + b); } } void ClientWorker2::performLargeContainer( const std::shared_ptr<Client>& client) { std::vector<BigStruct> items; getConfig()->makeBigContainer<BigStruct>(items); client->sync_largeContainer(items); } void ClientWorker2::performIterAllFields( const std::shared_ptr<Client>& client) { std::vector<BigStruct> items; std::vector<BigStruct> out; getConfig()->makeBigContainer<BigStruct>(items); client->sync_iterAllFields(out, items); if (items != out) { T_ERROR("iterAllFields gave wrong result"); } } }}} // apache::thrift::test <|endoftext|>
<commit_before>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "ExternalPythonExecutor.h" #include "DataSource.h" #include "EmdFormat.h" #include "Operator.h" #include "OperatorPython.h" #include "Pipeline.h" #include "PipelineWorker.h" namespace tomviz { ExternalPythonExecutor::ExternalPythonExecutor(Pipeline* pipeline) : ExternalPipelineExecutor(pipeline) { } ExternalPythonExecutor::~ExternalPythonExecutor() = default; Pipeline::Future* ExternalPythonExecutor::execute(vtkDataObject* data, QList<Operator*> operators, int start, int end) { auto future = ExternalPipelineExecutor::execute(data, operators, start, end); // We are now ready to run the pipeline QStringList args = executorArgs(start); PipelineSettings settings; auto pythonExecutable = settings.externalPythonExecutablePath(); // Find the tomviz-pipeline executable auto pythonExecutableFile = QFileInfo(pythonExecutable); if (!pythonExecutableFile.exists()) { displayError("External Python Error", QString("The external python executable doesn't exist: %1\n") .arg(pythonExecutable)); return Pipeline::emptyFuture(); } auto baseDir = pythonExecutableFile.dir(); auto tomvizPipelineExecutable = QFileInfo(baseDir.filePath("tomviz-pipeline")); if (!tomvizPipelineExecutable.exists()) { displayError( "External Python Error", QString("Unable to find tomviz-pipeline executable, please ensure " "tomviz package has been installed in python environment." "Click the Help button for more details on setting up your " "Python environment.")); return Pipeline::emptyFuture(); } m_process.reset(new QProcess(this)); connect(m_process.data(), &QProcess::errorOccurred, this, &ExternalPythonExecutor::error); connect( m_process.data(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [this](int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::CrashExit) { displayError("External Python Error", QString("The external python process crash: %1\n\n " "stderr:\n%2 \n\n stdout:\n%3 \n") .arg(commandLine(this->m_process.data())) .arg(QString(this->m_process->readAllStandardError())) .arg(QString(this->m_process->readAllStandardOutput()))); } else if (exitCode != 0) { displayError( "External Python Error", QString("The external python return a non-zero exist code: %1\n\n " "command: %2 \n\n stderr:\n%3 \n\n stdout:\n%4 \n") .arg(exitCode) .arg(commandLine(this->m_process.data())) .arg(QString(this->m_process->readAllStandardError())) .arg(QString(this->m_process->readAllStandardOutput()))); } }); // We have to get the process environment and unset TOMVIZ_APPLICATION and // set that as the process environment for the process, otherwise the // python package will think its running in the applicaton. auto processEnv = QProcessEnvironment::systemEnvironment(); processEnv.remove("TOMVIZ_APPLICATION"); m_process->setProcessEnvironment(processEnv); m_process->start(tomvizPipelineExecutable.filePath(), args); return future; } void ExternalPythonExecutor::cancel(std::function<void()> canceled) { reset(); m_process->kill(); canceled(); } bool ExternalPythonExecutor::cancel(Operator* op) { Q_UNUSED(op); // Stop the progress reader m_progressReader->stop(); m_process->kill(); // Clean update state. reset(); // We can't cancel an individual operator so we return false, so the caller // knows return false; } bool ExternalPythonExecutor::isRunning() { return !m_process.isNull() && m_process->state() != QProcess::NotRunning; } void ExternalPythonExecutor::error(QProcess::ProcessError error) { auto process = qobject_cast<QProcess*>(sender()); auto invocation = commandLine(process); displayError("Execution Error", QString("An error occurred executing '%1', '%2'") .arg(invocation) .arg(error)); } void ExternalPythonExecutor::pipelineStarted() { qDebug("Pipeline started in external python!"); } void ExternalPythonExecutor::reset() { ExternalPipelineExecutor::reset(); m_process->waitForFinished(); m_process.reset(); } QString ExternalPythonExecutor::executorWorkingDir() { return workingDir(); } QString ExternalPythonExecutor::commandLine(QProcess* process) { return QString("%1 %2") .arg(process->program()) .arg(process->arguments().join(" ")); } } // namespace tomviz <commit_msg>Send stdout and stderr to the message console<commit_after>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "ExternalPythonExecutor.h" #include "DataSource.h" #include "EmdFormat.h" #include "Operator.h" #include "OperatorPython.h" #include "Pipeline.h" #include "PipelineWorker.h" namespace tomviz { ExternalPythonExecutor::ExternalPythonExecutor(Pipeline* pipeline) : ExternalPipelineExecutor(pipeline) { } ExternalPythonExecutor::~ExternalPythonExecutor() = default; Pipeline::Future* ExternalPythonExecutor::execute(vtkDataObject* data, QList<Operator*> operators, int start, int end) { auto future = ExternalPipelineExecutor::execute(data, operators, start, end); // We are now ready to run the pipeline QStringList args = executorArgs(start); PipelineSettings settings; auto pythonExecutable = settings.externalPythonExecutablePath(); // Find the tomviz-pipeline executable auto pythonExecutableFile = QFileInfo(pythonExecutable); if (!pythonExecutableFile.exists()) { displayError("External Python Error", QString("The external python executable doesn't exist: %1\n") .arg(pythonExecutable)); return Pipeline::emptyFuture(); } auto baseDir = pythonExecutableFile.dir(); auto tomvizPipelineExecutable = QFileInfo(baseDir.filePath("tomviz-pipeline")); if (!tomvizPipelineExecutable.exists()) { displayError( "External Python Error", QString("Unable to find tomviz-pipeline executable, please ensure " "tomviz package has been installed in python environment." "Click the Help button for more details on setting up your " "Python environment.")); return Pipeline::emptyFuture(); } m_process.reset(new QProcess(this)); connect(m_process.data(), &QProcess::errorOccurred, this, &ExternalPythonExecutor::error); connect( m_process.data(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [this](int exitCode, QProcess::ExitStatus exitStatus) { QString standardOut(this->m_process->readAllStandardOutput()); QString standardErr(this->m_process->readAllStandardError()); if (exitStatus == QProcess::CrashExit) { displayError("External Python Error", QString("The external python process crash: %1\n\n " "stderr:\n%2 \n\n stdout:\n%3 \n") .arg(commandLine(this->m_process.data())) .arg(standardErr) .arg(standardOut)); } else if (exitCode != 0) { displayError( "External Python Error", QString("The external python return a non-zero exist code: %1\n\n " "command: %2 \n\n stderr:\n%3 \n\n stdout:\n%4 \n") .arg(exitCode) .arg(commandLine(this->m_process.data())) .arg(standardErr) .arg(standardOut)); } qDebug().noquote() << standardErr; qDebug().noquote() << standardOut; }); // We have to get the process environment and unset TOMVIZ_APPLICATION and // set that as the process environment for the process, otherwise the // python package will think its running in the applicaton. auto processEnv = QProcessEnvironment::systemEnvironment(); processEnv.remove("TOMVIZ_APPLICATION"); m_process->setProcessEnvironment(processEnv); m_process->start(tomvizPipelineExecutable.filePath(), args); return future; } void ExternalPythonExecutor::cancel(std::function<void()> canceled) { reset(); m_process->kill(); canceled(); } bool ExternalPythonExecutor::cancel(Operator* op) { Q_UNUSED(op); // Stop the progress reader m_progressReader->stop(); m_process->kill(); // Clean update state. reset(); // We can't cancel an individual operator so we return false, so the caller // knows return false; } bool ExternalPythonExecutor::isRunning() { return !m_process.isNull() && m_process->state() != QProcess::NotRunning; } void ExternalPythonExecutor::error(QProcess::ProcessError error) { auto process = qobject_cast<QProcess*>(sender()); auto invocation = commandLine(process); displayError("Execution Error", QString("An error occurred executing '%1', '%2'") .arg(invocation) .arg(error)); } void ExternalPythonExecutor::pipelineStarted() { qDebug("Pipeline started in external python!"); } void ExternalPythonExecutor::reset() { ExternalPipelineExecutor::reset(); m_process->waitForFinished(); m_process.reset(); } QString ExternalPythonExecutor::executorWorkingDir() { return workingDir(); } QString ExternalPythonExecutor::commandLine(QProcess* process) { return QString("%1 %2") .arg(process->program()) .arg(process->arguments().join(" ")); } } // namespace tomviz <|endoftext|>
<commit_before>#include "hphp/runtime/base/base-includes.h" #include "hphp/runtime/ext/std/ext_std_errorfunc.h" #include "hphp/runtime/base/php-globals.h" #include "hphp/runtime/base/hphp-system.h" #include "hphp/runtime/ext/ext_hotprofiler.h" #include "newrelic_transaction.h" #include "newrelic_collector_client.h" #include "newrelic_common.h" #include "newrelic_profiler.h" #include <string> #include <iostream> #include <fstream> #include <stdlib.h> #include <thread> #include <unistd.h> using namespace std; namespace HPHP { bool keep_running = true; class ScopedGenericSegment : public SweepableResourceData { public: DECLARE_RESOURCE_ALLOCATION(ScopedGenericSegment) CLASSNAME_IS("scoped_generic_segment") virtual const String& o_getClassNameHook() const { return classnameof(); } explicit ScopedGenericSegment(string name) : name(name) { segment_id = newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str()); } virtual ~ScopedGenericSegment() { if (segment_id < 0) return; newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id); } private: int64_t segment_id; string name; }; void ScopedGenericSegment::sweep() { } class ScopedDatastoreSegment : public SweepableResourceData { public: DECLARE_RESOURCE_ALLOCATION(ScopedDatastoreSegment) CLASSNAME_IS("scoped_database_segment") virtual const String& o_getClassNameHook() const { return classnameof(); } explicit ScopedDatastoreSegment(string table, string operation) : table(table), operation(operation) { // TODO segment_id = newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str()); } virtual ~ScopedDatastoreSegment() { if (segment_id < 0) return; newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id); } private: int64_t segment_id; string table; string operation; }; void ScopedDatastoreSegment::sweep() { } class ScopedExternalSegment : public SweepableResourceData { public: DECLARE_RESOURCE_ALLOCATION(ScopedExternalSegment) CLASSNAME_IS("scoped_external_segment") virtual const String& o_getClassNameHook() const { return classnameof(); } explicit ScopedExternalSegment(string host, string name) : host(host), name(name) { segment_id = newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str()); } virtual ~ScopedExternalSegment() { if (segment_id < 0) return; newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id); } private: int64_t segment_id; string host; string name; }; void ScopedExternalSegment::sweep() { } // Profiler factory- for starting and stopping the profiler DECLARE_EXTERN_REQUEST_LOCAL(ProfilerFactory, s_profiler_factory); static int64_t HHVM_FUNCTION(newrelic_start_transaction_intern) { int64_t transaction_id = newrelic_transaction_begin(); return transaction_id; } static int64_t HHVM_FUNCTION(newrelic_name_transaction_intern, const String & name) { return newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, name.c_str()); } static int64_t HHVM_FUNCTION(newrelic_transaction_set_request_url, const String & request_url) { return newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str()); } static int64_t HHVM_FUNCTION(newrelic_transaction_set_max_trace_segments, int threshold) { return newrelic_transaction_set_max_trace_segments(NEWRELIC_AUTOSCOPE, threshold); } static int64_t HHVM_FUNCTION(newrelic_transaction_set_threshold, int threshold) { //deprecated return false; } static int64_t HHVM_FUNCTION(newrelic_end_transaction) { return newrelic_transaction_end(NEWRELIC_AUTOSCOPE); } static int64_t HHVM_FUNCTION(newrelic_segment_generic_begin, const String & name) { return newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str()); } static int64_t HHVM_FUNCTION(newrelic_segment_datastore_begin, const String & table, const String & operation, const String & sql, const String & sql_trace_rollup_name, String & sql_obfuscator) { // TODO return newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str(), sql.c_str(), sql_trace_rollup_name.c_str(), sql_obfuscator.c_str()); return false; } static int64_t HHVM_FUNCTION(newrelic_segment_external_begin, const String & host, const String & name) { return newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str()); } static int64_t HHVM_FUNCTION(newrelic_segment_end, int64_t id) { return newrelic_segment_end(NEWRELIC_AUTOSCOPE, id); } static int64_t HHVM_FUNCTION(newrelic_notice_error_intern, const String & exception_type, const String & error_message, const String & stack_trace, const String & stack_frame_delimiter) { return newrelic_transaction_notice_error(NEWRELIC_AUTOSCOPE, exception_type.c_str(), error_message.c_str(), stack_trace.c_str(), stack_frame_delimiter.c_str()); } static int64_t HHVM_FUNCTION(newrelic_add_attribute_intern, const String & name, const String & value) { return newrelic_transaction_add_attribute(NEWRELIC_AUTOSCOPE, name.c_str(), value.c_str()); } static void HHVM_FUNCTION(newrelic_set_external_profiler, int64_t maxdepth ) { Profiler *pr = new NewRelicProfiler(maxdepth); s_profiler_factory->setExternalProfiler(pr); } static Variant HHVM_FUNCTION(newrelic_get_scoped_generic_segment, const String & name) { ScopedGenericSegment * segment = nullptr; segment = newres<ScopedGenericSegment>(name.c_str()); return Resource(segment); } static Variant HHVM_FUNCTION(newrelic_get_scoped_database_segment, const String & table, const String & operation) { ScopedDatastoreSegment * segment = nullptr; segment = newres<ScopedDatastoreSegment>(table.c_str(), operation.c_str()); return Resource(segment); } static Variant HHVM_FUNCTION(newrelic_get_scoped_external_segment, const String & host, const String & name) { ScopedExternalSegment * segment = nullptr; segment = newres<ScopedExternalSegment>(host.c_str(), name.c_str()); return Resource(segment); } const StaticString s__NR_ERROR_CALLBACK("NewRelicExtensionHelper::errorCallback"), s__NR_EXCEPTION_CALLBACK("NewRelicExtensionHelper::exceptionCallback"); static class NewRelicExtension : public Extension { public: NewRelicExtension () : Extension("newrelic") { config_loaded = false; } virtual void init_newrelic() { newrelic_register_message_handler(newrelic_message_handler); newrelic_init(license_key.c_str(), app_name.c_str(), app_language.c_str(), app_language_version.c_str()); } virtual void moduleLoad(const IniSetting::Map& ini, Hdf config) { license_key = RuntimeOption::EnvVariables["NEWRELIC_LICENSE_KEY"]; app_name = RuntimeOption::EnvVariables["NEWRELIC_APP_NAME"]; app_language = RuntimeOption::EnvVariables["NEWRELIC_APP_LANGUAGE"]; app_language_version = RuntimeOption::EnvVariables["NEWRELIC_APP_LANGUAGE_VERSION"]; if (app_language.empty()) { app_language = "php-hhvm"; } if (app_language_version.empty()) { app_language_version = HPHP::getHphpCompilerVersion(); } setenv("NEWRELIC_LICENSE_KEY", license_key.c_str(), 1); setenv("NEWRELIC_APP_NAME", app_name.c_str(), 1); setenv("NEWRELIC_APP_LANGUAGE", app_language.c_str(), 1); setenv("NEWRELIC_APP_LANGUAGE_VERSION", app_language_version.c_str(), 1); if (!license_key.empty() && !app_name.empty() && !app_language.empty() && !app_language_version.empty()) config_loaded = true; } virtual void moduleInit () { if (config_loaded) init_newrelic(); HHVM_FE(newrelic_start_transaction_intern); HHVM_FE(newrelic_name_transaction_intern); HHVM_FE(newrelic_transaction_set_request_url); HHVM_FE(newrelic_transaction_set_max_trace_segments); HHVM_FE(newrelic_transaction_set_threshold); HHVM_FE(newrelic_end_transaction); HHVM_FE(newrelic_segment_generic_begin); HHVM_FE(newrelic_segment_datastore_begin); HHVM_FE(newrelic_segment_external_begin); HHVM_FE(newrelic_segment_end); HHVM_FE(newrelic_get_scoped_generic_segment); HHVM_FE(newrelic_get_scoped_database_segment); HHVM_FE(newrelic_get_scoped_external_segment); HHVM_FE(newrelic_notice_error_intern); HHVM_FE(newrelic_add_attribute_intern); HHVM_FE(newrelic_set_external_profiler); loadSystemlib(); } virtual void requestShutdown() { newrelic_transaction_end(NEWRELIC_AUTOSCOPE); } virtual void requestInit() { f_set_error_handler(s__NR_ERROR_CALLBACK); f_set_exception_handler(s__NR_EXCEPTION_CALLBACK); //TODO: make it possible to disable that via ini newrelic_transaction_begin(); String request_url = php_global(s__SERVER).toArray()[s__REQUEST_URI].toString(); newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str()); String script_name = php_global(s__SERVER).toArray()[s__SCRIPT_NAME].toString(); newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, script_name.c_str()); } private: std::string license_key; std::string app_name; std::string app_language; std::string app_language_version; int64_t global_transaction_id = 0; bool config_loaded; } s_newrelic_extension; HHVM_GET_MODULE(newrelic) } // namespace HPHP <commit_msg>Add NO_EXTENSION_VERSION_YET<commit_after>#include "hphp/runtime/base/base-includes.h" #include "hphp/runtime/ext/std/ext_std_errorfunc.h" #include "hphp/runtime/base/php-globals.h" #include "hphp/runtime/base/hphp-system.h" #include "hphp/runtime/ext/ext_hotprofiler.h" #include "newrelic_transaction.h" #include "newrelic_collector_client.h" #include "newrelic_common.h" #include "newrelic_profiler.h" #include <string> #include <iostream> #include <fstream> #include <stdlib.h> #include <thread> #include <unistd.h> using namespace std; namespace HPHP { bool keep_running = true; class ScopedGenericSegment : public SweepableResourceData { public: DECLARE_RESOURCE_ALLOCATION(ScopedGenericSegment) CLASSNAME_IS("scoped_generic_segment") virtual const String& o_getClassNameHook() const { return classnameof(); } explicit ScopedGenericSegment(string name) : name(name) { segment_id = newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str()); } virtual ~ScopedGenericSegment() { if (segment_id < 0) return; newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id); } private: int64_t segment_id; string name; }; void ScopedGenericSegment::sweep() { } class ScopedDatastoreSegment : public SweepableResourceData { public: DECLARE_RESOURCE_ALLOCATION(ScopedDatastoreSegment) CLASSNAME_IS("scoped_database_segment") virtual const String& o_getClassNameHook() const { return classnameof(); } explicit ScopedDatastoreSegment(string table, string operation) : table(table), operation(operation) { // TODO segment_id = newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str()); } virtual ~ScopedDatastoreSegment() { if (segment_id < 0) return; newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id); } private: int64_t segment_id; string table; string operation; }; void ScopedDatastoreSegment::sweep() { } class ScopedExternalSegment : public SweepableResourceData { public: DECLARE_RESOURCE_ALLOCATION(ScopedExternalSegment) CLASSNAME_IS("scoped_external_segment") virtual const String& o_getClassNameHook() const { return classnameof(); } explicit ScopedExternalSegment(string host, string name) : host(host), name(name) { segment_id = newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str()); } virtual ~ScopedExternalSegment() { if (segment_id < 0) return; newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id); } private: int64_t segment_id; string host; string name; }; void ScopedExternalSegment::sweep() { } // Profiler factory- for starting and stopping the profiler DECLARE_EXTERN_REQUEST_LOCAL(ProfilerFactory, s_profiler_factory); static int64_t HHVM_FUNCTION(newrelic_start_transaction_intern) { int64_t transaction_id = newrelic_transaction_begin(); return transaction_id; } static int64_t HHVM_FUNCTION(newrelic_name_transaction_intern, const String & name) { return newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, name.c_str()); } static int64_t HHVM_FUNCTION(newrelic_transaction_set_request_url, const String & request_url) { return newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str()); } static int64_t HHVM_FUNCTION(newrelic_transaction_set_max_trace_segments, int threshold) { return newrelic_transaction_set_max_trace_segments(NEWRELIC_AUTOSCOPE, threshold); } static int64_t HHVM_FUNCTION(newrelic_transaction_set_threshold, int threshold) { //deprecated return false; } static int64_t HHVM_FUNCTION(newrelic_end_transaction) { return newrelic_transaction_end(NEWRELIC_AUTOSCOPE); } static int64_t HHVM_FUNCTION(newrelic_segment_generic_begin, const String & name) { return newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str()); } static int64_t HHVM_FUNCTION(newrelic_segment_datastore_begin, const String & table, const String & operation, const String & sql, const String & sql_trace_rollup_name, String & sql_obfuscator) { // TODO return newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str(), sql.c_str(), sql_trace_rollup_name.c_str(), sql_obfuscator.c_str()); return false; } static int64_t HHVM_FUNCTION(newrelic_segment_external_begin, const String & host, const String & name) { return newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str()); } static int64_t HHVM_FUNCTION(newrelic_segment_end, int64_t id) { return newrelic_segment_end(NEWRELIC_AUTOSCOPE, id); } static int64_t HHVM_FUNCTION(newrelic_notice_error_intern, const String & exception_type, const String & error_message, const String & stack_trace, const String & stack_frame_delimiter) { return newrelic_transaction_notice_error(NEWRELIC_AUTOSCOPE, exception_type.c_str(), error_message.c_str(), stack_trace.c_str(), stack_frame_delimiter.c_str()); } static int64_t HHVM_FUNCTION(newrelic_add_attribute_intern, const String & name, const String & value) { return newrelic_transaction_add_attribute(NEWRELIC_AUTOSCOPE, name.c_str(), value.c_str()); } static void HHVM_FUNCTION(newrelic_set_external_profiler, int64_t maxdepth ) { Profiler *pr = new NewRelicProfiler(maxdepth); s_profiler_factory->setExternalProfiler(pr); } static Variant HHVM_FUNCTION(newrelic_get_scoped_generic_segment, const String & name) { ScopedGenericSegment * segment = nullptr; segment = newres<ScopedGenericSegment>(name.c_str()); return Resource(segment); } static Variant HHVM_FUNCTION(newrelic_get_scoped_database_segment, const String & table, const String & operation) { ScopedDatastoreSegment * segment = nullptr; segment = newres<ScopedDatastoreSegment>(table.c_str(), operation.c_str()); return Resource(segment); } static Variant HHVM_FUNCTION(newrelic_get_scoped_external_segment, const String & host, const String & name) { ScopedExternalSegment * segment = nullptr; segment = newres<ScopedExternalSegment>(host.c_str(), name.c_str()); return Resource(segment); } const StaticString s__NR_ERROR_CALLBACK("NewRelicExtensionHelper::errorCallback"), s__NR_EXCEPTION_CALLBACK("NewRelicExtensionHelper::exceptionCallback"); static class NewRelicExtension : public Extension { public: NewRelicExtension () : Extension("newrelic", NO_EXTENSION_VERSION_YET) { config_loaded = false; } virtual void init_newrelic() { newrelic_register_message_handler(newrelic_message_handler); newrelic_init(license_key.c_str(), app_name.c_str(), app_language.c_str(), app_language_version.c_str()); } virtual void moduleLoad(const IniSetting::Map& ini, Hdf config) { license_key = RuntimeOption::EnvVariables["NEWRELIC_LICENSE_KEY"]; app_name = RuntimeOption::EnvVariables["NEWRELIC_APP_NAME"]; app_language = RuntimeOption::EnvVariables["NEWRELIC_APP_LANGUAGE"]; app_language_version = RuntimeOption::EnvVariables["NEWRELIC_APP_LANGUAGE_VERSION"]; if (app_language.empty()) { app_language = "php-hhvm"; } if (app_language_version.empty()) { app_language_version = HPHP::getHphpCompilerVersion(); } setenv("NEWRELIC_LICENSE_KEY", license_key.c_str(), 1); setenv("NEWRELIC_APP_NAME", app_name.c_str(), 1); setenv("NEWRELIC_APP_LANGUAGE", app_language.c_str(), 1); setenv("NEWRELIC_APP_LANGUAGE_VERSION", app_language_version.c_str(), 1); if (!license_key.empty() && !app_name.empty() && !app_language.empty() && !app_language_version.empty()) config_loaded = true; } virtual void moduleInit () { if (config_loaded) init_newrelic(); HHVM_FE(newrelic_start_transaction_intern); HHVM_FE(newrelic_name_transaction_intern); HHVM_FE(newrelic_transaction_set_request_url); HHVM_FE(newrelic_transaction_set_max_trace_segments); HHVM_FE(newrelic_transaction_set_threshold); HHVM_FE(newrelic_end_transaction); HHVM_FE(newrelic_segment_generic_begin); HHVM_FE(newrelic_segment_datastore_begin); HHVM_FE(newrelic_segment_external_begin); HHVM_FE(newrelic_segment_end); HHVM_FE(newrelic_get_scoped_generic_segment); HHVM_FE(newrelic_get_scoped_database_segment); HHVM_FE(newrelic_get_scoped_external_segment); HHVM_FE(newrelic_notice_error_intern); HHVM_FE(newrelic_add_attribute_intern); HHVM_FE(newrelic_set_external_profiler); loadSystemlib(); } virtual void requestShutdown() { newrelic_transaction_end(NEWRELIC_AUTOSCOPE); } virtual void requestInit() { f_set_error_handler(s__NR_ERROR_CALLBACK); f_set_exception_handler(s__NR_EXCEPTION_CALLBACK); //TODO: make it possible to disable that via ini newrelic_transaction_begin(); String request_url = php_global(s__SERVER).toArray()[s__REQUEST_URI].toString(); newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str()); String script_name = php_global(s__SERVER).toArray()[s__SCRIPT_NAME].toString(); newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, script_name.c_str()); } private: std::string license_key; std::string app_name; std::string app_language; std::string app_language_version; int64_t global_transaction_id = 0; bool config_loaded; } s_newrelic_extension; HHVM_GET_MODULE(newrelic) } // namespace HPHP <|endoftext|>
<commit_before>/* Copyright (c) 2011, Wesley Moore http://www.wezm.net/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the node-genx Project, Wesley Moore, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <node.h> #include <node_events.h> #include <iostream> extern "C" { #include "genx.h" } using namespace v8; using namespace node; using namespace std; static Persistent<String> sym_data; class Writer: public EventEmitter { private: genxWriter writer; genxSender sender; Persistent<Object> stream; public: static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->Inherit(EventEmitter::constructor_template); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(String::NewSymbol("Writer")); NODE_SET_PROTOTYPE_METHOD(t, "startDocument", StartDoc); NODE_SET_PROTOTYPE_METHOD(t, "endDocument", EndDocument); NODE_SET_PROTOTYPE_METHOD(t, "startElementLiteral", StartElementLiteral); NODE_SET_PROTOTYPE_METHOD(t, "addText", AddText); NODE_SET_PROTOTYPE_METHOD(t, "addComment", AddComment); NODE_SET_PROTOTYPE_METHOD(t, "addAttributeLiteral", AddAttributeLiteral); NODE_SET_PROTOTYPE_METHOD(t, "endElement", EndElement); target->Set(String::NewSymbol("Writer"), t->GetFunction()); sym_data = NODE_PSYMBOL("data"); } Writer() { // alloc, free, userData writer = genxNew(NULL, NULL, this); sender.send = sender_send; sender.sendBounded = sender_sendBounded; sender.flush = sender_flush; stream = Persistent<Object>::Persistent(); } ~Writer() { if(!stream.IsEmpty()) stream.Dispose(); // or Clear? genxDispose(writer); } protected: static Handle<Value> New(const Arguments& args) { HandleScope scope; Writer* writer = new Writer(); writer->Wrap(args.This()); return args.This(); } static Handle<Value> StartDoc(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); w->startDoc(); return args.This(); } genxStatus startDoc() { return genxStartDocSender(writer, &sender); } static Handle<Value> EndDocument(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); w->endDocument(); return args.This(); } genxStatus endDocument() { return genxEndDocument(writer); } static Handle<Value> StartElementLiteral(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 type = NULL; if (args.Length() <1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "First argument must be a String"))); } Local<String> Type = args[0]->ToString(); // Get the raw UTF-8 element type int length = Type->Utf8Length(); type = new unsigned char[length]; Type->WriteUtf8((char *)type, length); w->startElementLiteral(type); delete[] type; return args.This(); } genxStatus startElementLiteral(constUtf8 type) { return genxStartElementLiteral(writer, NULL, type); } static Handle<Value> AddText(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 text = NULL; genxStatus status; if (args.Length() <1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "First argument must be a String"))); } // Get the raw UTF-8 text Local<String> Text = args[0]->ToString(); int length = Text->Utf8Length(); text = new unsigned char[length]; Text->WriteUtf8((char *)text, length); status = w->addText(text); delete[] text; return args.This(); } genxStatus addText(constUtf8 text) { // TODO handle the return value from genx here? return genxAddText(writer, text); } static Handle<Value> AddComment(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 text = NULL; genxStatus status; if (args.Length() <1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "First argument must be a String"))); } Local<String> Text = args[0]->ToString(); text = createUtf8FromString(Text); status = w->addComment(text); delete[] text; return args.This(); } genxStatus addComment(constUtf8 comment) { // TODO handle the return value from genx here? return genxComment(writer, comment); } static Handle<Value> AddAttributeLiteral(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 name = NULL; utf8 value = NULL; if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsString()) { return ThrowException(Exception::Error(String::New( "Must supply two string arguments"))); } Local<String> Name = args[0]->ToString(); Local<String> Value = args[1]->ToString(); // Get the raw UTF-8 strings name = createUtf8FromString(Name); value = createUtf8FromString(Value); w->addAttributeLiteral(name, value); delete[] name; delete[] value; return args.This(); } genxStatus addAttributeLiteral(constUtf8 name, constUtf8 value) { constUtf8 xmlns = NULL; return genxAddAttributeLiteral(writer, xmlns, name, value); } static Handle<Value> EndElement(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); w->endElement(); return args.This(); } genxStatus endElement() { return genxEndElement(writer); } private: static utf8 createUtf8FromString(Handle<String> String) { utf8 string = NULL; int length = String->Utf8Length(); string = new unsigned char[length]; String->WriteUtf8((char *)string, length); return string; } static genxStatus sender_send(void *userData, constUtf8 s) { HandleScope scope; Writer *w = reinterpret_cast<Writer *>(userData); // Deliver the data event Local<String> dataString = String::New((const char *)s); Handle<Value> argv[1] = { dataString }; w->Emit(sym_data, 1, argv); return GENX_SUCCESS; } static genxStatus sender_sendBounded(void *userData, constUtf8 start, constUtf8 end) { HandleScope scope; Writer *w = reinterpret_cast<Writer *>(userData); // Deliver the data event Local<String> dataString = String::New((const char *)start, end - start); Handle<Value> argv[1] = { dataString }; w->Emit(sym_data, 1, argv); return GENX_SUCCESS; } static genxStatus sender_flush(void * userData) { return GENX_SUCCESS; } }; extern "C" { static void init (Handle<Object> target) { Writer::Initialize(target); } NODE_MODULE(genx, init); } <commit_msg>Simplify addText<commit_after>/* Copyright (c) 2011, Wesley Moore http://www.wezm.net/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the node-genx Project, Wesley Moore, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <node.h> #include <node_events.h> #include <iostream> extern "C" { #include "genx.h" } using namespace v8; using namespace node; using namespace std; static Persistent<String> sym_data; class Writer: public EventEmitter { private: genxWriter writer; genxSender sender; Persistent<Object> stream; public: static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->Inherit(EventEmitter::constructor_template); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(String::NewSymbol("Writer")); NODE_SET_PROTOTYPE_METHOD(t, "startDocument", StartDoc); NODE_SET_PROTOTYPE_METHOD(t, "endDocument", EndDocument); NODE_SET_PROTOTYPE_METHOD(t, "startElementLiteral", StartElementLiteral); NODE_SET_PROTOTYPE_METHOD(t, "addText", AddText); NODE_SET_PROTOTYPE_METHOD(t, "addComment", AddComment); NODE_SET_PROTOTYPE_METHOD(t, "addAttributeLiteral", AddAttributeLiteral); NODE_SET_PROTOTYPE_METHOD(t, "endElement", EndElement); target->Set(String::NewSymbol("Writer"), t->GetFunction()); sym_data = NODE_PSYMBOL("data"); } Writer() { // alloc, free, userData writer = genxNew(NULL, NULL, this); sender.send = sender_send; sender.sendBounded = sender_sendBounded; sender.flush = sender_flush; stream = Persistent<Object>::Persistent(); } ~Writer() { if(!stream.IsEmpty()) stream.Dispose(); // or Clear? genxDispose(writer); } protected: static Handle<Value> New(const Arguments& args) { HandleScope scope; Writer* writer = new Writer(); writer->Wrap(args.This()); return args.This(); } static Handle<Value> StartDoc(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); w->startDoc(); return args.This(); } genxStatus startDoc() { return genxStartDocSender(writer, &sender); } static Handle<Value> EndDocument(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); w->endDocument(); return args.This(); } genxStatus endDocument() { return genxEndDocument(writer); } static Handle<Value> StartElementLiteral(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 type = NULL; if (args.Length() <1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "First argument must be a String"))); } Local<String> Type = args[0]->ToString(); // Get the raw UTF-8 element type int length = Type->Utf8Length(); type = new unsigned char[length]; Type->WriteUtf8((char *)type, length); w->startElementLiteral(type); delete[] type; return args.This(); } genxStatus startElementLiteral(constUtf8 type) { return genxStartElementLiteral(writer, NULL, type); } static Handle<Value> AddText(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 text = NULL; genxStatus status; if (args.Length() <1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "First argument must be a String"))); } Local<String> Text = args[0]->ToString(); text = createUtf8FromString(Text); status = w->addText(text); delete[] text; return args.This(); } genxStatus addText(constUtf8 text) { // TODO handle the return value from genx here? return genxAddText(writer, text); } static Handle<Value> AddComment(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 text = NULL; genxStatus status; if (args.Length() <1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "First argument must be a String"))); } Local<String> Text = args[0]->ToString(); text = createUtf8FromString(Text); status = w->addComment(text); delete[] text; return args.This(); } genxStatus addComment(constUtf8 comment) { // TODO handle the return value from genx here? return genxComment(writer, comment); } static Handle<Value> AddAttributeLiteral(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); utf8 name = NULL; utf8 value = NULL; if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsString()) { return ThrowException(Exception::Error(String::New( "Must supply two string arguments"))); } Local<String> Name = args[0]->ToString(); Local<String> Value = args[1]->ToString(); // Get the raw UTF-8 strings name = createUtf8FromString(Name); value = createUtf8FromString(Value); w->addAttributeLiteral(name, value); delete[] name; delete[] value; return args.This(); } genxStatus addAttributeLiteral(constUtf8 name, constUtf8 value) { constUtf8 xmlns = NULL; return genxAddAttributeLiteral(writer, xmlns, name, value); } static Handle<Value> EndElement(const Arguments& args) { HandleScope scope; Writer* w = ObjectWrap::Unwrap<Writer>(args.This()); w->endElement(); return args.This(); } genxStatus endElement() { return genxEndElement(writer); } private: static utf8 createUtf8FromString(Handle<String> String) { utf8 string = NULL; int length = String->Utf8Length(); string = new unsigned char[length]; String->WriteUtf8((char *)string, length); return string; } static genxStatus sender_send(void *userData, constUtf8 s) { HandleScope scope; Writer *w = reinterpret_cast<Writer *>(userData); // Deliver the data event Local<String> dataString = String::New((const char *)s); Handle<Value> argv[1] = { dataString }; w->Emit(sym_data, 1, argv); return GENX_SUCCESS; } static genxStatus sender_sendBounded(void *userData, constUtf8 start, constUtf8 end) { HandleScope scope; Writer *w = reinterpret_cast<Writer *>(userData); // Deliver the data event Local<String> dataString = String::New((const char *)start, end - start); Handle<Value> argv[1] = { dataString }; w->Emit(sym_data, 1, argv); return GENX_SUCCESS; } static genxStatus sender_flush(void * userData) { return GENX_SUCCESS; } }; extern "C" { static void init (Handle<Object> target) { Writer::Initialize(target); } NODE_MODULE(genx, init); } <|endoftext|>
<commit_before>/* * observer.hpp * Base classes for observer pattern of GoF design patterns * * written by janus_wel<[email protected]> * This source code is in public domain, and has NO WARRANTY. * */ #ifndef OBSERBER_HPP #define OBSERBER_HPP #include <list> namespace pattern { namespace observer { // forward declarations template<typename T> class basic_subject; template<typename T> class basic_observer; /* * The class to change states * To use, you must define the class or struct that is derived from this class. * */ template<typename T> class basic_subject { public: // typedefs typedef T state_t; typedef basic_observer<state_t> observer_t; /* I think that std::list is best container to contain observers, because: * * - The order of items that are added is kept, so the user of this class * can handle the order of notifications. * - For now, I exclude a sort of the list and sorted addition of a * new items for simplicity. * - There is a need for successive accesses to all items from start to * end once, so it isn't the disadvantage that randome access is slow. * - Adding and removing items are fast. * * */ typedef std::list<observer_t*> observer_list_t; typedef typename observer_list_t::iterator observer_it; protected: // the list of observers observer_list_t observers; protected: // the member function to get current (latest) states virtual const state_t& state(void) const = 0; public: // register an observer inline basic_subject& attach(observer_t& o) { observers.push_back(&o); return *this; } inline basic_subject& attach(observer_t* o) { observers.push_back(o); return *this; } // release an observer inline basic_subject& detach(observer_t& o) { observers.remove(&o); return *this; } inline basic_subject& detach(observer_t* o) { observers.remove(o); return *this; } // notice the current states to all of observers // Should we use std::for_each(3) ? void notify(void) { state_t s = state(); for (observer_it it = observers.begin(); it != observers.end(); ++it) { (*it)->update(s); } } // typical destructor virtual ~basic_subject(void) {} }; /* * The class to observe children of basic_subject class * To use, you must define the class or struct that is derived from this class. * */ template<typename T> class basic_observer { public: // typedefs typedef T state_t; public: // Objects of this class are identified by the memory address of its instance. inline bool operator==(const basic_observer& rhs) const { return this == &rhs; } inline bool operator!=(const basic_observer& rhs) const { return !(*this == rhs); } // typical destructor virtual ~basic_observer(void) {} public: // virtual functions virtual void update(const state_t& s) = 0; }; } } #endif // OBSERBER_HPP <commit_msg>Add and fix some comments and fairing<commit_after>/* * observer.hpp * Base classes for observer pattern of GoF design patterns * * written by janus_wel<[email protected]> * This source code is in public domain, and has NO WARRANTY. * */ #ifndef OBSERBER_HPP #define OBSERBER_HPP #include <list> namespace pattern { namespace observer { // forward declarations template<typename T> class basic_subject; template<typename T> class basic_observer; /* * a base class to change states * To use: * * 1. Define the class or struct that is derived from this class. * 2. Define new member variables to indicates the state of the * object and new member functions to change states if those * variables aren't public. * 3. Implement the member function state(0). This function must * return the value that is contained in the derived class as * member variables. * */ template<typename T> class basic_subject { public: // typedefs typedef T state_t; typedef basic_subject<state_t> this_t; typedef basic_observer<state_t> observer_t; /* * I think that std::list is best container to contain * observers, because: * * - The order of items that are added is kept, so the * user of this class can handle the order of * notifications. * - For now, I exclude a sort of the list and sorted * addition of a new items for simplicity. * - There is a need for successive accesses to all items * from start to end once, so it isn't the disadvantage * that randome access is slow. * - Adding and removing items are fast. * */ typedef std::list<observer_t*> observer_array_t; typedef typename observer_array_t::iterator observer_array_it_t; protected: // a list of observers observer_array_t observers; public: // typical destructor virtual ~basic_subject(void) {} // register an observer inline this_t& attach(observer_t& o) { observers.push_back(&o); return *this; } inline this_t& attach(observer_t* o) { observers.push_back(o); return *this; } // release an observer inline this_t& detach(observer_t& o) { observers.remove(&o); return *this; } inline this_t& detach(observer_t* o) { observers.remove(o); return *this; } // notice the current states to all of observers // Should we use std::for_each(3) ? void notify(void) { state_t s = state(); for (observer_array_it_t it = observers.begin(); it != observers.end(); ++it) { (*it)->update(s); } } protected: // the member function to get current (latest) states virtual const state_t& state(void) const = 0; }; /* * a base class to observe children of basic_subject class * To use: * * 1. Define the class or struct that is derived from this class. * 2. Implement the member function handle(1). * */ template<typename T> class basic_observer { public: // typedefs typedef T state_t; typedef basic_observer<state_t> this_t; public: // typical destructor virtual ~basic_observer(void) {} // Objects of this class are identified by the memory // address of its instance. inline bool operator==(const this_t& rhs) const { return this == &rhs; } inline bool operator!=(const this_t& rhs) const { return !(*this == rhs); } public: // a virtual function which should be implemented by // derived classes virtual void update(const state_t& s) = 0; }; } } #endif // OBSERBER_HPP <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { ll N, A, B, C, D; cin >> N >> A >> B >> C >> D; ll T = B + D * N - A; ll delta = D - C; ll wari = 2 * D - delta; cerr << T << " " << delta << " " << wari << endl; assert(wari >= 0); ll sup = T / wari; ll inf = (T - N * delta + wari - 1) / wari; for (auto i = inf; i <= sup; ++i) { cerr << i << endl; cout << "YES" << endl; return 0; } cout << "NO" << endl; } <commit_msg>submit B.cpp to 'B - Moderate Differences' (agc017) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { ll N, A, B, C, D; cin >> N >> A >> B >> C >> D; --N; ll T = B + D * N - A; ll delta = D - C; ll wari = 2 * D - delta; cerr << T << " " << delta << " " << wari << endl; assert(wari >= 0); ll sup = T / wari; ll inf = (T - N * delta + wari - 1) / wari; for (auto i = inf; i <= sup; ++i) { cerr << i << endl; cout << "YES" << endl; return 0; } cout << "NO" << endl; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; vector<int> V[100010]; bool visited[100010]; typedef tuple<int, int> state; int main () { int N; cin >> N; for (auto i = 0; i < N-1; ++i) { int a, b; a--; b--; cin >> a >> b; V[a].push_back(b); V[b].push_back(a); } stack<state> S; S.push(state(0, 0)); int parent; int D; fill(visited, visited+N, false); while (!S.empty()) { int now = get<0>(S.top()); int d = get<1>(S.top()); S.pop(); if (!visited[now]) { visited[now] = true; if (now == N-1) { D = d; parent = now; break; } for (auto x : V[now]) { if (!visited[x]) { S.push(state(x, d+1)); } } } } stack<state> SS; SS.push(state(N-1, 0)); int cnt = 0; fill(visited, visited+N, false); while (!SS.empty()) { int now = get<0>(SS.top()); int d = get<1>(SS.top()); SS.pop(); if (!visited[now]) { visited[now] = true; cnt++; for (auto x : V[now]) { if (!visited[x] && x != parent) { SS.push(state(x, d+1)); } } } } int su = (D-1)/2 + cnt - 1; int fa = N - 2 - fa; if (fa > su) { cout << "Fennec" << endl; } else { cout << "Snuke" << endl; } } <commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; vector<int> V[100010]; bool visited[100010]; typedef tuple<int, int> state; int main () { int N; cin >> N; for (auto i = 0; i < N-1; ++i) { int a, b; a--; b--; cin >> a >> b; V[a].push_back(b); V[b].push_back(a); } stack<state> S; S.push(state(N-1, 0)); int parent; int D; fill(visited, visited+N, false); while (!S.empty()) { int now = get<0>(S.top()); int d = get<1>(S.top()); S.pop(); if (!visited[now]) { visited[now] = true; if (now == 0) { D = d; parent = now; break; } for (auto x : V[now]) { if (!visited[x]) { S.push(state(x, d+1)); } } } } stack<state> SS; SS.push(state(0, 0)); int cnt = 0; fill(visited, visited+N, false); while (!SS.empty()) { int now = get<0>(SS.top()); int d = get<1>(SS.top()); SS.pop(); if (!visited[now]) { visited[now] = true; cnt++; for (auto x : V[now]) { if (!visited[x] && x != parent) { SS.push(state(x, d+1)); } } } } int su = (D-1)/2 + cnt - 1; int fa = N - 2 - fa; if (fa > su) { cout << "Fennec" << endl; } else { cout << "Snuke" << endl; } } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { string S; cin >> S; int x[2]; cin >> x[0] >> x[1]; vector<int> V[2]; bool isx = 0; int cnt = 0; for (auto e : S) { if (e == 'F') cnt++; else { if (cnt > 0) { V[isx].push_back(cnt); } cnt = 0; isx = !isx; } } if (cnt > 0) { V[isx].push_back(cnt); } for (auto k = 0; k < 2; ++k) { int sum = 0; for (auto e : V[k]) { sum += e; } if ((x[k] + sum) %2 != 0) { cout << "No" << endl; return 0; } int mokuhyo = (x[k] + sum)/2; bool dp[10000]; fill(dp, dp+10000, false); dp[0] = true; for (auto e : V[k]) { for (auto i = 9999; i >= 0; --i) { if (dp[i] && i + e < 10000) { dp[i+e] = true; } } } if (!dp[mokuhyo]) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; } <commit_msg>submit D.cpp to 'D - FT Robot' (arc087) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { string S; cin >> S; int x[2]; cin >> x[0] >> x[1]; vector<int> V[2]; bool isx = 0; int cnt = 0; for (auto e : S) { if (e == 'F') cnt++; else { if (cnt > 0) { V[isx].push_back(cnt); } cnt = 0; isx = !isx; } } if (cnt > 0) { V[isx].push_back(cnt); } for (auto k = 0; k < 2; ++k) { int sum = 0; for (auto e : V[k]) { sum += e; } if ((x[k] + sum) %2 != 0) { cout << "No" << endl; return 0; } int mokuhyo = (x[k] + sum)/2; if (mokuhyo < 0 || mokuhyo > sum) { cout << "No" << endl; return 0; } bool dp[10000]; fill(dp, dp+10000, false); dp[0] = true; for (auto e : V[k]) { for (auto i = 9999; i >= 0; --i) { if (dp[i] && i + e < 10000) { dp[i+e] = true; } } } if (!dp[mokuhyo]) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { string S; cin >> S; int x[2]; cin >> x[0] >> x[1]; vector<int> V[2]; bool isx = 0; int cnt = 0; bool isfirst = true; for (auto e : S) { if (e == 'F') cnt++; else { if (isfirst) { x[0] -= cnt; isfirst = false; } else if (cnt > 0) { V[isx].push_back(cnt); } cnt = 0; isx = !isx; } } if (cnt > 0) { V[isx].push_back(cnt); } for (auto k = 0; k < 2; ++k) { int sum = 0; for (auto e : V[k]) { sum += e; } if ((x[k] + sum) %2 != 0) { cout << "No" << endl; return 0; } int mokuhyo = (x[k] + sum)/2; if (mokuhyo < 0 || mokuhyo > sum) { cout << "No" << endl; return 0; } bool dp[10000]; fill(dp, dp+10000, false); dp[0] = true; for (auto e : V[k]) { for (auto i = 9999; i >= 0; --i) { if (dp[i] && i + e < 10000) { dp[i+e] = true; } } } if (!dp[mokuhyo]) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; } <commit_msg>submit D.cpp to 'D - FT Robot' (arc087) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { string S; cin >> S; int x[2]; cin >> x[0] >> x[1]; vector<int> V[2]; bool isx = 0; int cnt = 0; bool isfirst = true; for (auto e : S) { if (e == 'F') cnt++; else { if (isfirst) { x[0] -= cnt; isfirst = false; } else if (cnt > 0) { V[isx].push_back(cnt); } cnt = 0; isx = !isx; } } if (isfirst) { x[0] -= cnt; isfirst = false; } else if (cnt > 0) { V[isx].push_back(cnt); } for (auto k = 0; k < 2; ++k) { int sum = 0; for (auto e : V[k]) { sum += e; } if ((x[k] + sum) %2 != 0) { cout << "No" << endl; return 0; } int mokuhyo = (x[k] + sum)/2; if (mokuhyo < 0 || mokuhyo > sum) { cout << "No" << endl; return 0; } bool dp[10000]; fill(dp, dp+10000, false); dp[0] = true; for (auto e : V[k]) { for (auto i = 9999; i >= 0; --i) { if (dp[i] && i + e < 10000) { dp[i+e] = true; } } } if (!dp[mokuhyo]) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; } <|endoftext|>
<commit_before>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-4-15 21:25:15 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; string S; int N; bool par[20010]; bool used[20010]; bool solve() { N = S.size(); int cnt = 0; for (auto i = 0; i < N; i++) { par[i] = (S[i] == '('); if (par[i]) { ++cnt; } } if (cnt != N/2) { return false; } fill(used, used + N, false); int c[2] = {0, 0}; int now = 0; while (now < N && (c[0] < N / 4 || c[1] < N / 4)) { assert(c[0] >= c[1]); if (c[0] == N/4) { if (!par[now]) { used[now] = true; c[1]++; } } else if (c[0] == c[1]) { if (par[now]) { used[now] = true; c[0]++; } } else { used[now] = true; c[par[now]]++; } now++; } if (c[0] < N/4 || c[1] < N/4) { return false; } c[0] = c[1] = 0; now = 0; #if DEBUG == 1 cerr << "S = " << S << endl; cerr << "S1 = "; for (auto i = 0; i < N; i++) { if (used[i]) { cerr << S[i]; } cerr << endl; } cerr << "S2 = "; for (auto i = 0; i < N; i++) { if (!used[i]) { cerr << S[i]; } cerr << endl; } #endif while (now < N && (c[0] < N / 4 || c[1] < N / 4)) { if (used[now]) { now++; continue; } assert(c[0] >= c[1]); if (c[0] == N/4) { if (par[now]) { used[now] = true; c[1]++; } } else if (c[0] == c[1]) { if (!par[now]) { used[now] = true; c[0]++; } } else { used[now] = true; c[1 - (int)par[now]]++; } now++; } if (c[0] < N/4 || c[1] < N/4) { return false; } return true; } int main() { int Q; cin >> Q; for (auto i = 0; i < Q; i++) { cin >> S; cout << (solve() ? "Yes" : "No") << endl; } }<commit_msg>tried C.cpp to 'C'<commit_after>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-4-15 21:25:15 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; string S; int N; bool par[20010]; bool used[20010]; bool solve() { N = S.size(); int cnt = 0; for (auto i = 0; i < N; i++) { par[i] = (S[i] == '('); if (par[i]) { ++cnt; } } if (cnt != N/2) { return false; } fill(used, used + N, false); int c[2] = {0, 0}; int now = 0; while (now < N && (c[0] < N / 4 || c[1] < N / 4)) { assert(c[0] >= c[1]); if (c[0] == N/4) { if (!par[now]) { used[now] = true; c[1]++; } } else if (c[0] == c[1]) { if (par[now]) { used[now] = true; c[0]++; } } else { used[now] = true; c[par[now]]++; } now++; } if (c[0] < N/4 || c[1] < N/4) { return false; } c[0] = c[1] = 0; now = 0; #if DEBUG == 1 cerr << "S = " << S << endl; cerr << "S1 = "; for (auto i = 0; i < N; i++) { if (used[i]) { cerr << S[i]; } } cerr << endl; cerr << "S2 = "; for (auto i = 0; i < N; i++) { if (!used[i]) { cerr << S[i]; } } cerr << endl; #endif while (now < N && (c[0] < N / 4 || c[1] < N / 4)) { if (used[now]) { now++; continue; } assert(c[0] >= c[1]); if (c[0] == N/4) { if (par[now]) { used[now] = true; c[1]++; } } else if (c[0] == c[1]) { if (!par[now]) { used[now] = true; c[0]++; } } else { used[now] = true; c[1 - (int)par[now]]++; } now++; } if (c[0] < N/4 || c[1] < N/4) { return false; } return true; } int main() { int Q; cin >> Q; for (auto i = 0; i < Q; i++) { cin >> S; cout << (solve() ? "Yes" : "No") << endl; } }<|endoftext|>
<commit_before>/** * File : B.cpp * Author : Kazune Takahashi * Created : 2018-5-20 21:05:39 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; int P[200010]; int solve() { int now = 0; for (auto i = 0; i < N; i++) { if (P[i] == now + 1) { now++; } } return N - now; } int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> P[i]; } int ans = solve(); reverse(P, P + N); for (auto i = 0; i < N; i++) { P[i] = N - P[i] + 1; // cerr << "P[" << i << "] = " << P[i] << endl; } ans = min(ans, solve()); cout << ans << endl; }<commit_msg>tried B.cpp to 'B'<commit_after>/** * File : B.cpp * Author : Kazune Takahashi * Created : 2018-5-20 21:05:39 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const int infty = 1000000007; int N; int P[200010]; int dp[200010]; int solve() { fill(dp, dp + 200010, infty); for (auto i = 0; i < N; i++) { *lower_bound(dp, dp + N, P[i]) = P[i]; } return N - (lower_bound(dp, dp + N, infty) - dp); } int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> P[i]; } int ans = solve(); reverse(P, P + N); for (auto i = 0; i < N; i++) { P[i] = N - P[i] + 1; // cerr << "P[" << i << "] = " << P[i] << endl; } ans = min(ans, solve()); cout << ans << endl; }<|endoftext|>
<commit_before>/** * File : E.cpp * Author : Kazune Takahashi * Created : 2018-7-1 22:00:11 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> D; int N; int A[100010]; int DP[100010]; int DP2[100010]; set<D> S[100010]; void make_S(int i) { if (!S[i].empty()) { return; } S[i].insert(D(-A[0], 0)); S[i].insert(D(-A[i], i)); for (auto j = 0; j < N; j++) { int mask = (1 << N) - 1 - (1 << j); int new_i = mask & i; if (new_i == i || new_i == 0) { continue; } make_S(new_i); auto it = S[new_i].begin(); S[i].insert(*it); it++; S[i].insert(*it); } } int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < (1 << N); i++) { make_S(i); auto it = S[i].begin(); cerr << "i = " << i << endl; cerr << "(" << -get<0>(*it) << ", " << get<1>(*it) << ")" << endl; DP2[i] = -(get<0>(*it)); it++; cerr << "(" << -get<0>(*it) << ", " << get<1>(*it) << ")" << endl; DP2[i] += -(get<0>(*it)); } // flush DP[0] = 0; for (auto i = 1; i < (1 << N); i++) { DP[i] = max(DP[i - 1], DP2[i]); cout << DP[i] << endl; } }<commit_msg>submit E.cpp to 'E - Or Plus Max' (arc100) [C++14 (GCC 5.4.1)]<commit_after>/** * File : E.cpp * Author : Kazune Takahashi * Created : 2018-7-1 22:00:11 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> D; int N; int A[100010]; int DP[100010]; int DP2[100010]; set<D> S[100010]; void make_S(int i) { if (!S[i].empty()) { return; } S[i].insert(D(-A[0], 0)); S[i].insert(D(-A[i], i)); for (auto j = 0; j < N; j++) { int mask = (1 << N) - 1 - (1 << j); int new_i = mask & i; if (new_i == i || new_i == 0) { continue; } make_S(new_i); auto it = S[new_i].begin(); S[i].insert(*it); it++; S[i].insert(*it); } } int main() { cin >> N; for (auto i = 0; i < (1 << N); i++) { cin >> A[i]; } for (auto i = 0; i < (1 << N); i++) { make_S(i); auto it = S[i].begin(); // cerr << "i = " << i << endl; // cerr << "(" << -get<0>(*it) << ", " << get<1>(*it) << ")" << endl; DP2[i] = -(get<0>(*it)); it++; // cerr << "(" << -get<0>(*it) << ", " << get<1>(*it) << ")" << endl; DP2[i] += -(get<0>(*it)); } // flush DP[0] = 0; for (auto i = 1; i < (1 << N); i++) { DP[i] = max(DP[i - 1], DP2[i]); cout << DP[i] << endl; } }<|endoftext|>
<commit_before>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-12-15 21:49:53 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; int A[200010]; int K[100]; int S; bool solve(int X) { fill(K, K + A[0], 0); for (auto i = 0; i < N - 1; i++) { if (A[i] > A[i + 1]) { S = A[i + 1]; } else { bool ok = false; for (auto j = A[i] - 1; j >= 0; j--) { K[j]++; if (K[j] == X) { K[j] = 0; } else { ok = true; break; } } if (!ok) { return false; } for (auto j = A[i]; j < A[i + 1]; j++) { K[j] = 0; } } } return true; } int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; A[i] = min(100, A[i]); } reverse(A, A + N); int ub = N; int lb = 0; while (ub - lb > 1) { int t = (ub + lb) / 2; if (solve(t)) { ub = t; } else { lb = t; } } cout << ub << endl; }<commit_msg>submit C.cpp to 'C - Lexicographic constraints' (agc029) [C++14 (GCC 5.4.1)]<commit_after>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-12-15 21:49:53 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; int A[200010]; int K[1000]; bool solve(int X) { fill(K, K + A[0], 0); for (auto i = 0; i < N - 1; i++) { if (A[i] > A[i + 1]) { continue; } else { bool ok = false; for (auto j = A[i] - 1; j >= 0; j--) { K[j]++; if (K[j] == X) { K[j] = 0; } else { ok = true; break; } } if (!ok) { return false; } for (auto j = A[i]; j < A[i + 1]; j++) { K[j] = 0; } } } return true; } int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; A[i] = min(1000, A[i]); } reverse(A, A + N); int ub = N; int lb = 0; while (ub - lb > 1) { int t = (ub + lb) / 2; if (solve(t)) { ub = t; } else { lb = t; } } cout << ub << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : C.cpp * Author : Kazune Takahashi * Created : 2019-6-2 21:52:44 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; /* void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } */ /* const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; */ // const ll MOD = 1000000007; int N; ll X; ll b[100010]; ll l[100010]; ll u[100010]; ll maxi = 0; ll now = 0; ll ans = 0; typedef tuple<ll, ll, ll, ll> card; // maxi, b, l, u; typedef tuple<ll, ll, ll, ll> card2; // u, l, b, cost; vector<card> V; vector<card2> W; int main() { cin >> N >> X; for (auto i = 0; i < N; i++) { cin >> b[i] >> l[i] >> u[i]; } for (auto i = 0; i < N; i++) { maxi += b[i] * l[i]; } for (auto i = 0; i < N; i++) { ll t = (l[i] * b[i] + u[i] * (X - b[i])); V.emplace_back(t, b[i], l[i], u[i]); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); int ind = 0; while (maxi >= now) { ll t, b, l, u; tie(t, b, l, u) = V[ind++]; now += t; ans += X; W.emplace_back(u, l, b, X); #if DEBUG == 1 cerr << "(" << t << ", " << b << ", " << l << ", " << u << ")" << endl; #endif } sort(W.begin(), W.end()); ind = 0; #if DEBUG == 1 ll u, l, b, x; tie(u, l, b, x) = W[0]; cerr << "W[0]: "; cerr << "(" << u << ", " << l << ", " << b << ", " << x << ")" << endl; #endif while (now >= maxi) { if (get<3>(W[0]) > get<2>(W[0])) { now -= get<0>(W[0]); } else { now -= get<1>(W[0]); } get<3>(W[0])--; ans--; } cout << ans + 1 << endl; }<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1 /** * File : C.cpp * Author : Kazune Takahashi * Created : 2019-6-2 21:52:44 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; /* void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } */ /* const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; */ // const ll MOD = 1000000007; int N; ll X; ll b[100010]; ll l[100010]; ll u[100010]; ll maxi = 0; ll now = 0; ll ans = 0; typedef tuple<ll, ll, ll, ll> card; // maxi, b, l, u; typedef tuple<ll, ll, ll> card2; // b, l, u; vector<card> V; int main() { cin >> N >> X; for (auto i = 0; i < N; i++) { cin >> b[i] >> l[i] >> u[i]; } for (auto i = 0; i < N; i++) { maxi += b[i] * l[i]; } for (auto i = 0; i < N; i++) { ll t = (l[i] * b[i] + u[i] * (X - b[i])); V.emplace_back(t, b[i], l[i], u[i]); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); int ind = 0; while (true) { ll t, b, l, u; tie(t, b, l, u) = V[ind++]; if (now + t >= maxi) { break; } } ans = X; ll dx = maxi - now; for (auto i = ind; i < N; i++) { ll t, b, l, u; tie(t, b, l, u) = V[i]; ll tmp = 0; if (dx >= l * b) { tmp = b + (dx - l * b + u - 1) / u; } else { tmp = (dx + b - 1) / b; } ans = min(tmp, ans); } cout << ans + X * ind << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/9/2019, 9:32:28 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; #define mattype long long #include <valarray> #include <random> using namespace std; // 行列 struct matrix { int row, col; valarray<mattype> a; matrix(int N, int M) { // matrix A(N, M); で初期化できる。 a = valarray<mattype>(N * M); row = N; col = M; } bool operator<(const matrix &right) const { // 使わないけどtupleに必要 if (row != right.row) { return row < right.row; } if (col != right.col) { return col < right.col; } for (auto i = 0; i < row * col; i++) { if (a[i] != right.a[i]) { return a[i] < right.a[i]; } } return false; } bool operator>(const matrix &right) const { // 使わないけどtupleに必要 if (row != right.row) { return row > right.row; } if (col != right.col) { return col > right.col; } for (auto i = 0; i < row * col; i++) { if (a[i] != right.a[i]) { return a[i] > right.a[i]; } } return false; } bool operator==(const matrix &right) const { if (row != right.row) return false; if (col != right.col) return false; for (auto i = 0; i < row * col; i++) { if (a[i] != right.a[i]) { return false; } } return true; } string to_s() const { string res = ""; for (auto i = 0; i < row; i++) { for (auto j = 0; j < col; j++) { res += to_string(a[i * col + j]); if (j != col - 1) res += " "; } if (i != row - 1) res += "\n"; } return res; } void input() { // 大抵行列表示で入力されるからこれで事足りるでしょう。 for (auto i = 0; i < row * col; i++) { cin >> a[i]; } } }; ostream &operator<<(ostream &s, const matrix A) { // cout << A << endl; で苦もなく表示。 return s << A.to_s(); } matrix multiply(matrix A, matrix B) { // AB を出力 assert(A.col == B.row); int N = A.col; matrix C(A.row, B.col); for (auto i = 0; i < C.row; i++) { for (auto j = 0; j < C.col; j++) { C.a[i * C.col + j] = ((valarray<mattype>)A.a[slice(i * A.col, N, 1)] * (valarray<mattype>)B.a[slice(j, N, B.col)]) .sum(); } } return C; } matrix inverse(matrix A, matrix B) { // A^{-1} B を出力 assert(A.row == A.col); assert(A.col == B.row); int N = A.row; int M = B.col; for (auto i = 0; i < N; i++) { mattype taikaku = A.a[i * N + i]; for (auto k = 0; k < N; k++) { if (i == k) continue; mattype keisu = A.a[k * N + i] / taikaku; // A.a[k*N+i] = 0; for (auto j = i + 1; j < N; j++) { A.a[k * N + j] = A.a[k * N + j] - keisu * A.a[i * N + j]; } for (auto j = 0; j < M; j++) { B.a[k * M + j] = B.a[k * M + j] - keisu * B.a[i * M + j]; } } } for (auto i = 0; i < N; i++) { mattype taikaku = A.a[i * N + i]; for (auto j = 0; j < M; j++) { B.a[i * M + j] = B.a[i * M + j] / taikaku; } } return B; } matrix transposed(matrix A) { // 転置 matrix B = matrix(A.col, A.row); for (auto i = 0; i < B.row; i++) { for (auto j = 0; j < B.col; j++) { B.a[i * B.col + j] = A.a[j * A.col + i]; } } return B; } bool AB_is_equal_to_C(matrix A, matrix B, matrix C, int times) { // AB = C かどうかを判定。timesには回数を指定。 // N * M が 10^6 くらいなら、times = 10 で 1秒単位がかかるようになるから要注意。 // でも 10 はほしいところである。 assert(A.col == B.row); assert(A.row == C.row); assert(B.col == C.col); random_device rd; mt19937 mt(rd()); matrix p = matrix(B.col, 1); for (auto i = 0; i < times; i++) { for (auto j = 0; j < B.col; j++) { p.a[j] = mt() % 10000; } if (multiply(A, multiply(B, p)) == multiply(C, p)) { /* cerr << "ABp is following:" << endl; cerr << multiply(A, multiply(B, p)) << endl; cerr << "Cp is following:" << endl; cerr << multiply(C, p) << endl; */ continue; } else { return false; } } return true; } // 此処から先は、modを取るパターン。 mattype MOD = 1000; matrix mod_multiply(matrix A, matrix B) { assert(A.col == B.row); int N = A.col; matrix C(A.row, B.col); for (auto i = 0; i < C.row; i++) { for (auto j = 0; j < C.col; j++) { C.a[i * C.col + j] = ((valarray<mattype>)A.a[slice(i * A.col, N, 1)] * (valarray<mattype>)B.a[slice(j, N, B.col)]) .sum() % MOD; } } return C; } matrix mod_pow(matrix A, mattype n) { // n \geq 1 if (n % 2 == 0) { matrix B = mod_pow(A, n / 2); return mod_multiply(B, B); } else if (n == 1) { return A; } else { return mod_multiply(A, mod_pow(A, n - 1)); } } // 此処から先 main ll L, A, B; ll upper[100]; matrix choose(ll k, ll n) { matrix K(3, 3); ll p = 1; for (auto i = 0; i < k; i++) { p *= 10LL; } K.a = {p % MOD, 1, 0, 0, 1, B, 0, 0, 1}; return mod_pow(K, n); } ll f(ll i) { return A + B * i; } int main() { cin >> L >> A >> B >> MOD; for (auto i = 1; i <= 18; i++) { ll ok = upper[i - 1]; ll ng = L; if ((int)to_string(f(ok)).size() != i) { upper[i] = ok; continue; } while (abs(ok - ng) > 1) { ll t = (ok + ng) / 2; if ((int)to_string(f(t)).size() == i) { ok = t; } else { ng = t; } } upper[i] = ng; } matrix v(3, 1); v.a = {0, A, 1}; for (auto i = 1; i <= 18; i++) { ll x = upper[i] - upper[i - 1]; if (x == 0) { continue; } #if DEBUG == 1 cerr << "i = " << i << ", upper[" << i << "] = " << upper[i] << endl; cerr << "f(" << upper[i] - 1 << ") = " << f(upper[i] - 1) << endl; cerr << "f(" << upper[i] << ") = " << f(upper[i]) << endl; #endif v = mod_multiply(choose(i, x), v); } cout << v.a[0] << endl; }<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/9/2019, 9:32:28 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; template <class T> class Matrix { public: static T MOD; private: int H, W; T **a; public: Matrix() {} Matrix(int h, int w) : H(h), W(w) { a = new T *[H]; for (auto i = 0; i < H; i++) { a[i] = new T[W]; } } Matrix &operator=(const Matrix A) { H = A.H; W = A.W; for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { a[i][j] = A.a[i][j]; } } return *this; } Matrix &operator=(const vector<T> v) { assert((int)v.size() == H * W); for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { a[i][j] = v[i * W + j]; } } return *this; } const Matrix operator-() const { Matrix X(H, W); for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { X.a[i][j] = MOD - a[i][j]; if (MOD > 0) { X.a[i][j] %= MOD; } } } } const Matrix operator+(const Matrix &A) const { assert(A.H == H); assert(A.W == W); Matrix X(H, W); for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { X.a[i][j] = a[i][j] + A.a[i][j]; if (MOD > 0) { X.a[i][j] %= MOD; } } } } const Matrix operator-(const Matrix &A) const { return this + (-A); } const Matrix operator*(const Matrix &A) const { assert(W == A.H); Matrix X(H, A.W); for (auto i = 0; i < X.H; i++) { for (auto j = 0; j < X.W; j++) { X.a[i][j] = 0; for (auto k = 0; k < W; k++) { X.a[i][j] += a[i][k] * A.a[k][j]; if (MOD > 0) { X.a[i][j] %= MOD; } } } } } Matrix &operator+=(const Matrix &A) { Matrix X = this + A; this = X; return this; } Matrix &operator-=(const Matrix &A) { return this += (-A); } Matrix &operator*=(const Matrix &A) { Matrix X = this * A; this = X; return this; } bool operator==(const Matrix &A) const { assert(H == A.H); assert(W == A.W); for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { if (a[i][j] != A.a[i][j]) { return false; } } } return true; } bool operator!=(const Matrix &A) const { return !(this == A); } const T *&operator[](const size_t i) const { return a[i]; } T *&operator[](const size_t i) { return a[i]; } Matrix power(T N) { assert(H == W); // N > 0 if (N == 1) { return *this; } if (N % 2 == 1) { return power(N - 1) * (*this); } Matrix X = power(N / 2); return X * X; } }; template <class T> T Matrix<T>::MOD = 0; ll L, A, B, M; ll upper[100]; Matrix<ll> choose(ll k, ll n) { Matrix<ll> K(3, 3); ll p = 1; for (auto i = 0; i < k; i++) { p *= 10LL; } K = {p % M, 1, 0, 0, 1, B, 0, 0, 1}; return K.power(n); } ll f(ll i) { return A + B * i; } int main() { cin >> L >> A >> B >> M; Matrix<ll>::MOD = M; for (auto i = 1; i <= 18; i++) { ll ok = upper[i - 1]; ll ng = L; if ((int)to_string(f(ok)).size() != i) { upper[i] = ok; continue; } while (abs(ok - ng) > 1) { ll t = (ok + ng) / 2; if ((int)to_string(f(t)).size() == i) { ok = t; } else { ng = t; } } upper[i] = ng; } Matrix<ll> v(3, 1); v = {0, A, 1}; for (auto i = 1; i <= 18; i++) { ll x = upper[i] - upper[i - 1]; if (x == 0) { continue; } #if DEBUG == 1 cerr << "i = " << i << ", upper[" << i << "] = " << upper[i] << endl; cerr << "f(" << upper[i] - 1 << ") = " << f(upper[i] - 1) << endl; cerr << "f(" << upper[i] << ") = " << f(upper[i]) << endl; #endif v = choose(i, x) * v; } cout << v[0][0] << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 12/11/2019, 4:20:39 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> #include <boost/optional.hpp> // for C++14 // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- struct Element { ll left, right; boost::optional<ll> value; // for C++14 }; class Solve { ll N; ll L; vector<Element> A; public: Solve(ll N, ll L, vector<ll> input) : N{N}, L{L}, A(N) { for (auto i = 0; i < N; i++) { A[i].value = input[i]; A[i].left = 1; A[i].right = 1; } } ll count() { ll ans{N}; while (true) { #if DEBUG == 1 cerr << "A = {"; for (auto const &e : A) { if (e.value) { cerr << *e.value << ", "; } else { cerr << "n, "; } } cerr << "}" << endl; cerr << "L = {"; for (auto const &e : A) { cerr << e.left << ", "; } cerr << "}" << endl; cerr << "R = {"; for (auto const &e : A) { cerr << e.right << ", "; } cerr << "}" << endl; #endif boost::optional<ll> M{min_value()}; if (!M) { break; } vector<Element> T; vector<Element> tmp; for (auto const &e : A) { if (e.value == M) { tmp.push_back(e); } else if (!tmp.empty()) { update(ans, T, tmp); T.push_back(e); } else { T.push_back(e); } } if (!tmp.empty()) { update(ans, T, tmp); } swap(A, T); // delete_none(); } return ans; } private: boost::optional<ll> min_value() { boost::optional<ll> ans; for (auto const &e : A) { if (e.value) { if (ans) { ch_min(*ans, *e.value); } else { ans = e.value; } } } return ans; } void update(ll &ans, vector<Element> &T, vector<Element> &tmp) { ans += calc(tmp); tmp = press(tmp); ans -= calc(tmp); copy(tmp.begin(), tmp.end(), back_inserter(T)); tmp.clear(); } ll calc(vector<Element> const &X) { ll ans{0}; ll sum_right{0}; int S{static_cast<int>(X.size())}; for (auto i = L - 1; i < S; i++) { sum_right += X[i].right; } for (auto i = 0; i < S - L + 1; i++) { ans += X[i].left * sum_right; sum_right -= X[i + L - 1].right; } assert(sum_right == 0); return ans; } vector<Element> press(vector<Element> &V) { ll S{static_cast<ll>(V.size())}; if (S < L) { return {{0, 0, boost::none}}; } ll K{*V[0].value + 1}; vector<Element> ans(S / L); for (auto &e : ans) { e.value = K; } for (auto i = L - 1; i < S; i++) { ans[(i - L + 1) / L].right += V[i].right; } reverse(V.begin(), V.end()); reverse(ans.begin(), ans.end()); for (auto i = L - 1; i < S; i++) { ans[(i - L + 1) / L].left += V[i].left; } reverse(ans.begin(), ans.end()); return ans; } void delete_none() { vector<Element> T; int S{static_cast<int>(A.size())}; for (auto i = 0; i < S; i++) { if (i < S - 1 && !A[i].value && !A[i + 1].value) { continue; } T.push_back(move(A[i])); } swap(A, T); } }; int main() { ll N, L; cin >> N >> L; vector<ll> A(N); for (auto i = 0; i < N; i++) { cin >> A[i]; } Solve solve(N, L, move(A)); cout << solve.count() << endl; } <commit_msg>submit F.cpp to 'F - Counting of Subarrays' (agc037) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 12/11/2019, 4:20:39 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> #include <boost/optional.hpp> // for C++14 // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- struct Element { ll left, right; boost::optional<ll> value; // for C++14 }; class Solve { ll N; ll L; vector<Element> A; public: Solve(ll N, ll L, vector<ll> input) : N{N}, L{L}, A(N) { for (auto i = 0; i < N; i++) { A[i].value = input[i]; A[i].left = 1; A[i].right = 1; } } ll count() { ll ans{N}; while (true) { boost::optional<ll> M{min_value()}; if (!M) { break; } vector<Element> T; vector<Element> tmp; for (auto &&e : A) { if (e.value == M) { tmp.push_back(move(e)); } else if (!tmp.empty()) { update(ans, T, move(tmp)); T.push_back(move(e)); } else { T.push_back(move(e)); } } if (!tmp.empty()) { update(ans, T, move(tmp)); } swap(A, T); } return ans; } private: boost::optional<ll> min_value() { boost::optional<ll> ans; for (auto const &e : A) { if (e.value) { if (ans) { ch_min(*ans, *e.value); } else { ans = e.value; } } } return ans; } void update(ll &ans, vector<Element> &T, vector<Element> &&tmp) { ans += calc(tmp); tmp = press(move(tmp)); ans -= calc(tmp); copy(move(tmp).begin(), move(tmp).end(), back_inserter(T)); tmp.clear(); } ll calc(vector<Element> const &X) { ll ans{0}; ll sum_right{0}; int S{static_cast<int>(X.size())}; for (auto i = L - 1; i < S; i++) { sum_right += X[i].right; } for (auto i = 0; i < S - L + 1; i++) { ans += X[i].left * sum_right; sum_right -= X[i + L - 1].right; } assert(sum_right == 0); return ans; } vector<Element> press(vector<Element> &&V) { ll S{static_cast<ll>(V.size())}; if (S < L) { return {{0, 0, boost::none}}; } ll K{*V[0].value + 1}; vector<Element> ans(S / L); for (auto &e : ans) { e.value = K; } for (auto i = L - 1; i < S; i++) { ans[(i - L + 1) / L].right += V[i].right; } reverse(V.begin(), V.end()); reverse(ans.begin(), ans.end()); for (auto i = L - 1; i < S; i++) { ans[(i - L + 1) / L].left += V[i].left; } reverse(ans.begin(), ans.end()); return ans; } void delete_none() { vector<Element> T; int S{static_cast<int>(A.size())}; for (auto i = 0; i < S; i++) { if (i < S - 1 && !A[i].value && !A[i + 1].value) { continue; } T.push_back(move(A[i])); } swap(A, T); } }; int main() { ll N, L; cin >> N >> L; vector<ll> A(N); for (auto i = 0; i < N; i++) { cin >> A[i]; } Solve solve(N, L, move(A)); cout << solve.count() << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2019/8/18 21:17:08 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } string S, T; int N; ll X[100010][26]; int main() { cin >> S >> T; N = S.size(); fill(&X[0][0], &X[0][0] + 26 * 100010, infty); vector<ll> T(26, infty); for (auto t = 0; t < 2; t++) { for (auto i = N - 1; i >= 0; i--) { for (auto k = 0; k < 26; k++) { T[k]++; } for (auto k = 0; k < 26; k++) { X[i][k] = min(T[k], X[i][k]); } T[S[i] - 'a'] = 0; } } #if DEBUG == 1 cerr << "aaaa" << endl; #endif ll ans{0}; int M = T.size(); int now{N - 1}; for (auto i = 0; i < M; i++) { int n = T[i] - 'a'; if (X[now][n] >= infty) { No(); } ans += X[now][n]; now += X[now][n]; now %= N; } cout << ans << endl; }<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2019/8/18 21:17:08 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } string S, T; int N; ll X[100010][26]; int main() { cin >> S >> T; N = S.size(); fill(&X[0][0], &X[0][0] + 26 * 100010, infty); vector<ll> T(26, infty); for (auto t = 0; t < 2; t++) { for (auto i = N - 1; i >= 0; i--) { for (auto k = 0; k < 26; k++) { T[k]++; } for (auto k = 0; k < 26; k++) { X[i][k] = min(T[k], X[i][k]); } T[S[i] - 'a'] = 0; } } ll ans{0}; int M = T.size(); int now{N - 1}; for (auto i = 0; i < M; i++) { int n = T[i] - 'a'; #if DEBUG == 1 cerr << "T[" << i << "] = " << T[i] << endl; #endif if (X[now][n] >= infty) { No(); } ans += X[now][n]; now += X[now][n]; now %= N; } cout << ans << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2019/9/1 21:13:18 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } int N; vector<queue<int>> V; int main() { cin >> N; V.resize(N); for (auto i = 0; i < N; i++) { for (auto j = 0; j < N - 1; j++) { int a; cin >> a; --a; V[i].push(a); } } vector<bool> used(N, false); int ans{0}; while (true) { fill(used.begin(), used.end(), false); for (auto i = 0; i < N; i++) { if (V[i].empty()) { No(); } int j = V[i].front(); if (V[j].empty()) { No(); } if (V[j].front() == i) { used[i] = used[j] = true; } } int cnt{0}; for (auto i = 0; i < N; i++) { if (used[i]) { V[i].pop(); } ++cnt; } int emp{0}; for (auto i = 0; i < N; i++) { if (V[i].empty()) { ++emp; } } if (emp == N) { cout << ans << endl; return 0; } if (cnt == 0) { No(); } } }<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2019/9/1 21:13:18 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } int N; vector<queue<int>> V; int main() { cin >> N; V.resize(N); for (auto i = 0; i < N; i++) { for (auto j = 0; j < N - 1; j++) { int a; cin >> a; --a; V[i].push(a); } } vector<bool> used(N, false); int ans{0}; while (true) { fill(used.begin(), used.end(), false); for (auto i = 0; i < N; i++) { if (V[i].empty()) { continue; } int j = V[i].front(); if (V[j].empty()) { No(); } if (V[j].front() == i) { used[i] = used[j] = true; } } int cnt{0}; for (auto i = 0; i < N; i++) { if (used[i]) { V[i].pop(); } ++cnt; } int emp{0}; for (auto i = 0; i < N; i++) { if (V[i].empty()) { ++emp; } } if (emp == N) { cout << ans << endl; return 0; } if (cnt == 0) { No(); } } }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 2/10/2020, 11:07:01 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Sieve ----- class Sieve { static constexpr ll MAX_SIZE{1000010LL}; ll N; vector<ll> f; vector<ll> prime_nums; public: Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{} { f[0] = f[1] = -1; for (auto i = 2; i < N; i++) { if (f[i]) { continue; } prime_nums.push_back(i); f[i] = i; for (auto j = 2 * i; j < N; j += i) { if (!f[j]) { f[j] = i; } } } } bool is_prime(ll x) const { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return f[x]; } for (auto e : prime_nums) { if (x % e == 0) { return false; } } return true; } vector<ll> const &primes() const { return prime_nums; } vector<ll> factor_list(ll x) const { if (x < 2) { return {}; } vector<ll> res; auto it{prime_nums.begin()}; if (x < N) { while (x != 1) { res.push_back(f[x]); x /= f[x]; } } else { while (x != 1 && it != prime_nums.end()) { if (x % *it == 0) { res.push_back(*it); x /= *it; } else { ++it; } } if (x != 1) { res.push_back(x); } } return res; } vector<tuple<ll, ll>> factor(ll x) const { if (x < 2) { return {}; } auto factors{factor_list(x)}; vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)}; for (auto x : factors) { if (x == get<0>(res.back())) { get<1>(res.back())++; } else { res.emplace_back(x, 1); } } return res; } }; // ----- main() ----- int main() { Sieve sieve; ll A, B; cin >> A >> B; ll M{gcd(A, B)}; auto V{sieve.factor(M)}; cout << V.size() << endl; } <commit_msg>submit D.cpp to 'D - Disjoint Set of Common Divisors' (abc142) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 2/10/2020, 11:07:01 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Sieve ----- class Sieve { static constexpr ll MAX_SIZE{1000010LL}; ll N; vector<ll> f; vector<ll> prime_nums; public: Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{} { f[0] = f[1] = -1; for (auto i = 2; i < N; i++) { if (f[i]) { continue; } prime_nums.push_back(i); f[i] = i; for (auto j = 2 * i; j < N; j += i) { if (!f[j]) { f[j] = i; } } } } bool is_prime(ll x) const { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return f[x]; } for (auto e : prime_nums) { if (x % e == 0) { return false; } } return true; } vector<ll> const &primes() const { return prime_nums; } vector<ll> factor_list(ll x) const { if (x < 2) { return {}; } vector<ll> res; auto it{prime_nums.begin()}; if (x < N) { while (x != 1) { res.push_back(f[x]); x /= f[x]; } } else { while (x != 1 && it != prime_nums.end()) { if (x % *it == 0) { res.push_back(*it); x /= *it; } else { ++it; } } if (x != 1) { res.push_back(x); } } return res; } vector<tuple<ll, ll>> factor(ll x) const { if (x < 2) { return {}; } auto factors{factor_list(x)}; vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)}; for (auto x : factors) { if (x == get<0>(res.back())) { get<1>(res.back())++; } else { res.emplace_back(x, 1); } } return res; } }; // ----- main() ----- int main() { Sieve sieve; ll A, B; cin >> A >> B; ll M{gcd(A, B)}; auto V{sieve.factor(M)}; cout << V.size() + 1 << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/1/11 1:58:48 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using boost::rational; using boost::multiprecision::cpp_int; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll lcm(ll x, ll y) { return x * y / gcd(x, y); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- MP algorithm ----- template <typename Type> class MP { int N; Type S; vector<int> A; public: MP() {} MP(Type const &S) : N(S.size()), S{S}, A(N + 1, -1) { int j{-1}; for (auto i = 0; i < N; i++) { while (j != -1 && S[j] != S[i]) { j = A[j]; } ++j; A[i + 1] = j; } } int operator[](int i) { return A[i]; } vector<int> find_all(Type const &T) { vector<int> res; int j{0}; for (auto i = 0; i < static_cast<int>(T.size()); i++) { while (j != -1 && S[j] != T[i]) { j = A[j]; } ++j; if (j == N) { res.push_back(i - j + 1); } } return res; } }; // ----- main() ----- vector<int> f(vector<int> const &A) { int N(A.size()); vector<int> res(N); for (auto i = 0; i < N; i++) { res[i] = A[i] ^ A[(i + 1) % N]; } return res; } int main() { int N; cin >> N; vector<int> A(N), B(N); for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < N; i++) { cin >> B[i]; } vector<int> xa{f(A)}, xb{f(B)}; MP<vector<int>> mp(xa); xb.insert(xb.end(), xb.begin(), xb.end()); auto res{mp.find_all(xb)}; vector<int> ks; for (int p : res) { ks.push_back(N - p); } sort(ks.begin(), ks.end()); for (int k : ks) { if (k >= N) { continue; } int x = A[k] ^ B[0]; cout << k << " " << x << endl; } } <commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/1/11 1:58:48 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using boost::rational; using boost::multiprecision::cpp_int; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll lcm(ll x, ll y) { return x * y / gcd(x, y); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- MP algorithm ----- template <typename Type> class MP { int N; Type S; vector<int> A; public: MP() {} MP(Type const &S) : N(S.size()), S{S}, A(N + 1, -1) { int j{-1}; for (auto i = 0; i < N; i++) { while (j != -1 && S[j] != S[i]) { j = A[j]; } ++j; A[i + 1] = j; } } int operator[](int i) { return A[i]; } vector<int> find_all(Type const &T) { vector<int> res; int j{0}; for (auto i = 0; i < static_cast<int>(T.size()); i++) { while (j != -1 && S[j] != T[i]) { j = A[j]; } ++j; if (j == N) { res.push_back(i - j + 1); } } return res; } }; // ----- main() ----- vector<int> f(vector<int> const &A) { int N(A.size()); vector<int> res(N); for (auto i = 0; i < N; i++) { res[i] = A[i] ^ A[(i + 1) % N]; } return res; } int main() { int N; cin >> N; vector<int> A(N), B(N); for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < N; i++) { cin >> B[i]; } vector<int> xa{f(A)}, xb{f(B)}; MP<vector<int>> mp(xa); xb.insert(xb.end(), xb.begin(), xb.end()); for (auto i = 0; i < N; i++) { cerr << "xa[" << i << "] = " << xa[i] << endl; } for (auto i = 0; i < 2 * N; i++) { cerr << "xb[" << i << "] = " << xb[i] << endl; } auto res{mp.find_all(xb)}; vector<int> ks; for (int p : res) { ks.push_back(N - p); } sort(ks.begin(), ks.end()); for (int k : ks) { if (k >= N) { continue; } int x = A[k] ^ B[0]; cout << k << " " << x << endl; } } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/1/19 21:18:43 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll lcm(ll x, ll y) { return x / gcd(x, y) * y; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- struct C { int u, w; }; struct Edge { int to, num; }; int N; vector<vector<Edge>> V; ll power(ll x) { if (x == 0) { return 1; } if (x % 2 == 0) { ll h{power(x / 2)}; return h * h; } return 2 * power(x - 1); } vector<int> count(C c) { int u{c.u}; int w{c.w}; vector<int> parent(N, -1); stack<int> S; S.push(u); while (!S.empty()) { int now{S.top()}; S.pop(); for (auto x : V[now]) { if (x.to != parent[now]) { parent[x.to] = now; S.push(x.to); } } } vector<int> res; int temp{w}; while (temp != -1) { for (auto x : V[temp]) { if (x.to == parent[temp]) { res.push_back(x.num); break; } } temp = parent[temp]; } return res; } int main() { cin >> N; V.resize(N); for (auto i = 0; i < N - 1; ++i) { int a, b; cin >> a >> b; --a; --b; V[a].push_back((Edge){b, i}); V[b].push_back((Edge){a, i}); } int M; cin >> M; vector<C> W(M); for (auto i = 0; i < M; ++i) { cin >> W[i].u >> W[i].w; W[i].u--; W[i].w--; } vector<vector<int>> visited(M); for (auto i = 0; i < M; ++i) { visited[i] = count(W[i]); #if DEBUG == 1 cerr << "visited[" << i << "] = "; for (auto x : visited[i]) { cerr << x << ", "; } cerr << endl; #endif } ll ans{power(N - 1)}; for (auto k = 0; k < (1 << M); ++k) { int cnt{0}; for (auto i = 0; i < M; ++i) { cnt += (k >> i) & 1; } ll K{cnt % 2 ? 1 : -1}; vector<bool> white(N - 1, false); for (auto i = 0; i < M; ++i) { if ((k >> i) & 1) { for (auto x : visited[i]) { white[x] = true; } } } int free{0}; for (auto i = 0; i < N - 1; ++i) { if (!white[i]) { ++free; } } ans += K * power(free); } cout << ans << endl; } <commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/1/19 21:18:43 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll lcm(ll x, ll y) { return x / gcd(x, y) * y; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- struct C { int u, w; }; struct Edge { int to, num; }; int N; vector<vector<Edge>> V; ll power(ll x) { if (x == 0) { return 1; } if (x % 2 == 0) { ll h{power(x / 2)}; return h * h; } return 2 * power(x - 1); } vector<int> count(C c) { int u{c.u}; int w{c.w}; vector<int> parent(N, -1); stack<int> S; S.push(u); while (!S.empty()) { int now{S.top()}; S.pop(); for (auto x : V[now]) { if (x.to != parent[now]) { parent[x.to] = now; S.push(x.to); } } } vector<int> res; int temp{w}; while (temp != -1) { for (auto x : V[temp]) { if (x.to == parent[temp]) { res.push_back(x.num); break; } } temp = parent[temp]; } return res; } int main() { cin >> N; V.resize(N); for (auto i = 0; i < N - 1; ++i) { int a, b; cin >> a >> b; --a; --b; V[a].push_back((Edge){b, i}); V[b].push_back((Edge){a, i}); } int M; cin >> M; vector<C> W(M); for (auto i = 0; i < M; ++i) { cin >> W[i].u >> W[i].w; W[i].u--; W[i].w--; } vector<vector<int>> visited(M); for (auto i = 0; i < M; ++i) { visited[i] = count(W[i]); #if DEBUG == 1 cerr << "visited[" << i << "] = "; for (auto x : visited[i]) { cerr << x << ", "; } cerr << endl; #endif } ll ans{power(N - 1)}; for (auto k = 0; k < (1 << M); ++k) { int cnt{0}; for (auto i = 0; i < M; ++i) { cnt += (k >> i) & 1; } ll K{cnt % 2 ? 1 : -1}; vector<bool> white(N - 1, false); for (auto i = 0; i < M; ++i) { if ((k >> i) & 1) { for (auto x : visited[i]) { white[x] = true; } } } int free{0}; for (auto i = 0; i < N - 1; ++i) { if (!white[i]) { ++free; } } #if DEBUG == 1 cerr << "k = " << k << ", free = " << free << endl; #endif ans += K * power(free); } cout << ans << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 1/31/2020, 3:04:12 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- class Solve { int N, u, v; vector<vector<int>> V; public: Solve(int N, int u, int v, vector<vector<int>> const &V) : N{N}, u{u}, v{v}, V(V) {} void flush() { if (u == v) { cout << 0 << endl; return; } vector<int> from_u(N, -1); from_u[u] = 0; dfs(from_u, u); vector<int> from_v(N, -1); from_v[v] = 0; dfs(from_v, v); int ans{0}; for (auto i = 0; i < N; ++i) { #if DEBUG == 1 cerr << "from_u[" << i << "] = " << from_u[i] << endl; cerr << "from_v[" << i << "] = " << from_v[i] << endl; #endif if (from_u[i] > from_v[i]) { ch_max(ans, from_u[i]); } } cout << ans << endl; } private: void dfs(vector<int> &dist, int x, int p = -1) { if (dist[x] == -1) { for (auto y : V[x]) { if (y != -1) { dist[y] = dist[x] + 1; dfs(dist, y, x); } } } } }; int main() { int N, u, v; cin >> N >> u >> v; --u; --v; vector<vector<int>> V(N); for (auto i = 0; i < N - 1; ++i) { int A, B; cin >> A >> B; --A; --B; V[A].push_back(B); V[B].push_back(A); } Solve solve(N, u, v, V); solve.flush(); } <commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 1/31/2020, 3:04:12 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- class Solve { int N, u, v; vector<vector<int>> V; public: Solve(int N, int u, int v, vector<vector<int>> const &V) : N{N}, u{u}, v{v}, V(V) {} void flush() { if (u == v) { cout << 0 << endl; return; } vector<int> from_u(N, -1); from_u[u] = 0; dfs(from_u, u); vector<int> from_v(N, -1); from_v[v] = 0; dfs(from_v, v); int ans{0}; for (auto i = 0; i < N; ++i) { #if DEBUG == 1 cerr << "from_u[" << i << "] = " << from_u[i] << endl; cerr << "from_v[" << i << "] = " << from_v[i] << endl; #endif if (from_u[i] > from_v[i]) { ch_max(ans, from_u[i]); } } cout << ans << endl; } private: void dfs(vector<int> &dist, int x, int p = -1) { if (dist[x] == -1) { for (auto y : V[x]) { if (y != p) { dist[y] = dist[x] + 1; dfs(dist, y, x); } } } } }; int main() { int N, u, v; cin >> N >> u >> v; --u; --v; vector<vector<int>> V(N); for (auto i = 0; i < N - 1; ++i) { int A, B; cin >> A >> B; --A; --B; V[A].push_back(B); V[B].push_back(A); } Solve solve(N, u, v, V); solve.flush(); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2/3/2020, 3:34:32 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N; ll K; cin >> N >> K; vector<ll> A(N); for (auto i = 0; i < N; ++i) { cin >> A[i]; --A[i]; } vector<ll> imos(N + 1, 0); map<ll, ll> M; partial_sum(A.begin(), A.end(), imos.begin() + 1); for_each(imos.begin(), imos.end(), [&](auto &x) { x %= K; M[x]; M[x]++; }); #if DEBUG == 1 for (auto i = 0; i < N + 1; ++i) { cerr << "imos[" << i << "] = " << imos[i] << endl; } #endif #if DEBUG == 1 for (auto x : M) { cerr << "M[" << x.first << "] = " << x.second << endl; } #endif ll ans{0}; for_each(M.begin(), M.end(), [&](auto x) { auto y{x.second}; ans += y * (y - 1) / 2; }); cout << ans << endl; } <commit_msg>submit E.cpp to 'E - Rem of Sum is Num' (abc146) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2/3/2020, 3:34:32 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N; ll K; cin >> N >> K; vector<ll> A(N); for (auto i = 0; i < N; ++i) { cin >> A[i]; --A[i]; } vector<ll> imos(N + 1, 0); partial_sum(A.begin(), A.end(), imos.begin() + 1); for_each(imos.begin(), imos.end(), [&](auto &x) { x %= K; }); ll ans{0}; map<ll, ll> M; for (auto i = 0; i < N + 1; ++i) { auto c{M[imos[i]]}; ans += c; M[imos[i]]++; if (i - K + 1 >= 0) { M[imos[i - K + 1]]--; } } cout << ans << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/6/8 0:52:25 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N, K; cin >> N >> K; vector<ll> H(N + 2, 0); for (auto i{1}; i <= N; ++i) { cin >> H[i]; } vector<vector<ll>> dp(N + 1, vector<ll>(N - K + 1, Infty<ll>())); dp[0][0] = 0; for (auto i{1}; i <= N; ++i) { for (auto j{1}; j <= N - K; ++j) { for (auto k{0}; k < i; ++k) { ch_min(dp[i][j], dp[k][j - 1] + max(0LL, H[i] - H[k])); } } } ll ans{Infty<ll>()}; for (auto i{0}; i < N; ++i) { ch_min(ans, dp[i][N - K]); } cout << ans << endl; } <commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/6/8 0:52:25 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N, K; cin >> N >> K; vector<ll> H(N + 2, 0); for (auto i{1}; i <= N; ++i) { cin >> H[i]; } vector<vector<ll>> dp(N + 1, vector<ll>(N - K + 1, Infty<ll>())); dp[0][0] = 0; for (auto i{1}; i <= N; ++i) { for (auto j{1}; j <= N - K; ++j) { for (auto k{0}; k < i; ++k) { if (dp[k][j - 1] == Infty<ll>()) { continue; } ch_min(dp[i][j], dp[k][j - 1] + max(0LL, H[i] - H[k])); } } } ll ans{Infty<ll>()}; for (auto i{0}; i < N; ++i) { ch_min(ans, dp[i][N - K]); } cout << ans << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/17/2020, 10:21:45 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll k; vector<ll> d; ll n, x, m; ll L, R; public: Solve(ll k, vector<ll> const &d) : k{k}, d{d} { cin >> n >> x >> m; x %= m; for (auto &e : Solve::d) { e %= m; } L = (n - 1) / k; R = (n - 1) % k; } void flush() { cout << n - 1 - calc_Y() - calc_Z() << endl; } private: ll calc_Z() { ll S{0}; for (auto i{0}; i < k; ++i) { S += d[i]; } ll res{x + L * S}; for (auto i{0}; i <= R; ++i) { res += d[i]; } return res / m; } ll calc_Y() { ll C{0}; for (auto i{0}; i < k; ++i) { if (d[i] == 0) { ++C; } } ll res{L * C}; for (auto i{0}; i <= R; ++i) { if (d[i] == 0) { ++res; } } return res; } }; // ----- main() ----- /* int main() { Solve solve; solve.flush(); } */ int main() { ll k, q; cin >> k >> q; vector<ll> d(k); for (auto i{0}; i < k; ++i) { cin >> d[i]; } for (auto t{0}; t < q; ++t) { Solve solve(k, d); solve.flush(); } } <commit_msg>submit F.cpp to 'F - Modularness' (abc156) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/17/2020, 10:21:45 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll k; vector<ll> d; ll n, x, m; ll L, R; public: Solve(ll k, vector<ll> const &d) : k{k}, d{d} { cin >> n >> x >> m; x %= m; for (auto &e : Solve::d) { e %= m; } L = (n - 1) / k; R = (n - 1) % k; } void flush() { cout << n - 1 - calc_Y() - calc_Z() << endl; } private: ll calc_Z() { ll S{0}; for (auto i{0}; i < k; ++i) { S += d[i]; } ll res{x + L * S}; for (auto i{0}; i < R; ++i) { res += d[i]; } return res / m; } ll calc_Y() { ll C{0}; for (auto i{0}; i < k; ++i) { if (d[i] == 0) { ++C; } } ll res{L * C}; for (auto i{0}; i < R; ++i) { if (d[i] == 0) { ++res; } } return res; } }; // ----- main() ----- /* int main() { Solve solve; solve.flush(); } */ int main() { ll k, q; cin >> k >> q; vector<ll> d(k); for (auto i{0}; i < k; ++i) { cin >> d[i]; } for (auto t{0}; t < q; ++t) { Solve solve(k, d); solve.flush(); } } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/17/2020, 1:01:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } // ----- Solve ----- using Bomb = tuple<int, bool>; struct Edge { int src, dst, id, on; // ll cost; Edge() {} Edge(int src, int dst, int id, int on = false) : src{src}, dst{dst}, id{id}, on{on} {} // Edge(int src, int dst, ll cost) : src{src}, dst{dst}, cost{cost} {} void added_edge(vector<vector<Edge>> &V) { V[src].push_back(*this); } void added_rev(vector<vector<Edge>> &V) { V[dst].push_back(rev()); } Edge rev() { Edge edge{*this}; swap(edge.src, edge.dst); return edge; } }; class Solve { int N, M; vector<Bomb> bombs; vector<bool> B; vector<vector<Edge>> V; vector<bool> table; vector<int> parents; public: Solve(int N, int M) : N{N}, M{M}, bombs(N), B(N + 1), V(N + 1), table(M, false), parents(N + 1, -1) { // bombs for (auto i{0}; i < N; ++i) { int a, b; cin >> a >> b; bombs[i] = Bomb{a, b == 1}; } sort(bombs.begin(), bombs.end()); // B B[0] = get<1>(bombs[0]); for (auto i{1}; i < N; ++i) { B[i] = get<1>(bombs[i]) ^ get<1>(bombs[i - 1]); } B[N] = get<1>(bombs[N - 1]); // V for (auto i{0}; i < M; ++i) { int l, r; cin >> l >> r; // The following two lines are referring to https://atcoder.jp/contests/abc155/submissions/10163379 auto v{static_cast<int>(distance(bombs.begin(), lower_bound(bombs.begin(), bombs.end(), Bomb{l, -1})))}; auto w{static_cast<int>(distance(bombs.begin(), lower_bound(bombs.begin(), bombs.end(), Bomb{r, 2})))}; #if DEBUG == 1 cerr << "l = " << l << ", r = " << r << ", v = " << v << ", w = " << w << endl; #endif if (v == w) { continue; } Edge edge{v, w, i}; edge.added_edge(V); edge.added_rev(V); } } void flush() { make_table(); int cnt{0}; for (auto i{0}; i < M; ++i) { if (table[i]) { ++cnt; } } cout << cnt << endl; for (auto i{0}; i < M; ++i) { if (table[i]) { cout << i + 1; } --cnt; if (cnt > 0) { cout << " "; } else { cout << endl; } } } private: void make_table() { for (auto i{0}; i < N + 1; ++i) { if (parents[i] == -1) { if (dfs(i) == 1) { No(); } } } for (auto i{0}; i < N + 1; ++i) { for (auto const &e : V[i]) { if (e.on) { table[e.id] = true; } } } } int dfs(int src) { int sum{B[src] ? 1 : 0}; for (auto &e : V[src]) { if (parents[e.dst] != -1) { continue; } parents[e.dst] = e.src; int tmp{dfs(e.dst)}; sum += tmp; e.on = (tmp == 1); } return sum & 1; } }; // ----- main() ----- int main() { int N, M; cin >> N >> M; Solve solve(N, M); solve.flush(); } <commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/17/2020, 1:01:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } // ----- Solve ----- using Bomb = tuple<int, bool>; struct Edge { int src, dst, id, on; // ll cost; Edge() {} Edge(int src, int dst, int id, int on = false) : src{src}, dst{dst}, id{id}, on{on} {} // Edge(int src, int dst, ll cost) : src{src}, dst{dst}, cost{cost} {} void added_edge(vector<vector<Edge>> &V) { V[src].push_back(*this); } void added_rev(vector<vector<Edge>> &V) { V[dst].push_back(rev()); } Edge rev() { Edge edge{*this}; swap(edge.src, edge.dst); return edge; } }; class Solve { int N, M; vector<Bomb> bombs; vector<bool> B; vector<vector<Edge>> V; vector<bool> table; vector<int> parents; public: Solve(int N, int M) : N{N}, M{M}, bombs(N), B(N + 1), V(N + 1), table(M, false), parents(N + 1, -1) { // bombs for (auto i{0}; i < N; ++i) { int a, b; cin >> a >> b; bombs[i] = Bomb{a, b == 1}; } sort(bombs.begin(), bombs.end()); #if DEBUG == 1 for (auto i{0}; i < N; ++i) { cerr << "bombs[" << i << "] = (" << get<0>(bombs[i]) << ", " << get<1>(bombs[i]) << ")" << endl; } #endif // B B[0] = get<1>(bombs[0]); for (auto i{1}; i < N; ++i) { B[i] = get<1>(bombs[i]) ^ get<1>(bombs[i - 1]); } B[N] = get<1>(bombs[N - 1]); // V for (auto i{0}; i < M; ++i) { int l, r; cin >> l >> r; // The following two lines are referring to https://atcoder.jp/contests/abc155/submissions/10163379 auto v{static_cast<int>(distance(bombs.begin(), lower_bound(bombs.begin(), bombs.end(), Bomb{l, -1})))}; auto w{static_cast<int>(distance(bombs.begin(), lower_bound(bombs.begin(), bombs.end(), Bomb{r, 2})))}; #if DEBUG == 1 cerr << "l = " << l << ", r = " << r << ", v = " << v << ", w = " << w << endl; #endif if (v == w) { continue; } Edge edge{v, w, i}; edge.added_edge(V); edge.added_rev(V); } } void flush() { make_table(); int cnt{0}; for (auto i{0}; i < M; ++i) { if (table[i]) { ++cnt; } } cout << cnt << endl; for (auto i{0}; i < M; ++i) { if (table[i]) { cout << i + 1; } --cnt; if (cnt > 0) { cout << " "; } else { cout << endl; } } } private: void make_table() { for (auto i{0}; i < N + 1; ++i) { if (parents[i] == -1) { if (dfs(i) == 1) { No(); } } } for (auto i{0}; i < N + 1; ++i) { for (auto const &e : V[i]) { if (e.on) { table[e.id] = true; } } } } int dfs(int src) { int sum{B[src] ? 1 : 0}; for (auto &e : V[src]) { if (parents[e.dst] != -1) { continue; } parents[e.dst] = e.src; int tmp{dfs(e.dst)}; sum += tmp; e.on = (tmp == 1); } return sum & 1; } }; // ----- main() ----- int main() { int N, M; cin >> N >> M; Solve solve(N, M); solve.flush(); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/6/27 20:59:09 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } // ----- Solve ----- class Solve { public: Solve() { } void flush() { } private: }; // ----- main() ----- /* int main() { Solve solve; solve.flush(); } */ int main() { int N; cin >> N; ll K, L, C; cin >> K >> L; C = 0; for (auto i{0}; i < N - 2; ++i) { ll x; cin >> x; C ^= x; } ll X{K + L}; #if DEBUG == 1 cerr << "X = " << X << ", C = " << C << endl; #endif if ((X - C) & 1) { No(); } ll D{(X - C) >> 1}; #if DEBUG == 1 cerr << "D = " << D << endl; #endif ll A{0}; ll T{0}; for (auto i{60}; i >= 0; --i) { bool bit{false}; if (D >> i & 1) { if (X >> i & 1) { No(); } else { bit = true; } } else { if (X >> i & 1) { T |= 1LL << 1; } else { } } if (bit) { A |= 1LL << i; } else { } } if (K < A) { No(); } #if DEBUG == 1 cerr << "K = " << K << endl; cerr << "A = " << A << endl; cerr << "T = " << T << endl; #endif for (auto i{60}; i >= 0; --i) { if (T >> i & 1) { #if DEBUG == 1 cerr << "i = " << i << endl; #endif if (K < A + (1LL << i)) { continue; } else { A |= 1LL << i; } } } #if DEBUG == 1 cerr << "A = " << A << endl; #endif auto B{X - A}; if ((A ^ B) != C) { sleep(10); } if (0 < A && A <= K) { cout << K - A << endl; } else { No(); } } <commit_msg>submit F.cpp to 'F - Unfair Nim' (abc172) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2020/6/27 20:59:09 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } // ----- Solve ----- class Solve { public: Solve() { } void flush() { } private: }; // ----- main() ----- /* int main() { Solve solve; solve.flush(); } */ int main() { int N; cin >> N; ll K, L, C; cin >> K >> L; C = 0; for (auto i{0}; i < N - 2; ++i) { ll x; cin >> x; C ^= x; } ll X{K + L}; #if DEBUG == 1 cerr << "X = " << X << ", C = " << C << endl; #endif if ((X - C) & 1) { No(); } ll D{(X - C) >> 1}; #if DEBUG == 1 cerr << "D = " << D << endl; #endif ll A{0}; ll T{0}; for (auto i{60}; i >= 0; --i) { bool bit{false}; if (D >> i & 1) { if (X >> i & 1) { No(); } else { bit = true; } } else { if (X >> i & 1) { T |= 1LL << i; } else { } } if (bit) { A |= 1LL << i; } else { } } if (K < A) { No(); } #if DEBUG == 1 cerr << "K = " << K << endl; cerr << "A = " << A << endl; cerr << "T = " << T << endl; #endif for (auto i{60}; i >= 0; --i) { if (T >> i & 1) { #if DEBUG == 1 cerr << "i = " << i << endl; #endif if (K < A + (1LL << i)) { continue; } else { A |= 1LL << i; } } } #if DEBUG == 1 cerr << "A = " << A << endl; #endif auto B{X - A}; if ((A ^ B) != C) { sleep(10); } if (0 < A && A <= K) { cout << K - A << endl; } else { No(); } } <|endoftext|>
<commit_before>#include "alfe/main.h" #include "alfe/cga.h" class GameWindow : public RootWindow { public: GameWindow() : _wisdom(File("wisdom")), _output(&_data, &_sequencer, &_bitmap) { _output.setConnector(1); // old composite _output.setScanlineProfile(0); // rectangle _output.setHorizontalProfile(0); // rectangle _output.setScanlineWidth(1); _output.setScanlineBleeding(2); // symmetrical _output.setHorizontalBleeding(2); // symmetrical _output.setZoom(2); _output.setHorizontalRollOff(0); _output.setHorizontalLobes(4); _output.setVerticalRollOff(0); _output.setVerticalLobes(4); _output.setSubPixelSeparation(1); _output.setPhosphor(0); // colour _output.setMask(0); _output.setMaskSize(0); _output.setAspectRatio(5.0/6.0); _output.setOverscan(0); _output.setCombFilter(0); // no filter _output.setHue(0); _output.setSaturation(100); _output.setContrast(100); _output.setBrightness(0); _output.setShowClipping(false); _output.setChromaBandwidth(1); _output.setLumaBandwidth(1); _output.setRollOff(0); _output.setLobes(1.5); _output.setPhase(1); static const int regs = -CGAData::registerLogCharactersPerBank; Byte cgaRegistersData[regs] = { 0 }; Byte* cgaRegisters = &cgaRegistersData[regs]; cgaRegisters[CGAData::registerLogCharactersPerBank] = 12; cgaRegisters[CGAData::registerScanlinesRepeat] = 1; cgaRegisters[CGAData::registerHorizontalTotalHigh] = 0; cgaRegisters[CGAData::registerHorizontalDisplayedHigh] = 0; cgaRegisters[CGAData::registerHorizontalSyncPositionHigh] = 0; cgaRegisters[CGAData::registerVerticalTotalHigh] = 0; cgaRegisters[CGAData::registerVerticalDisplayedHigh] = 0; cgaRegisters[CGAData::registerVerticalSyncPositionHigh] = 0; cgaRegisters[CGAData::registerMode] = 9; cgaRegisters[CGAData::registerPalette] = 0; cgaRegisters[CGAData::registerHorizontalTotal] = 114 - 1; cgaRegisters[CGAData::registerHorizontalDisplayed] = 80; cgaRegisters[CGAData::registerHorizontalSyncPosition] = 90; cgaRegisters[CGAData::registerHorizontalSyncWidth] = 16; cgaRegisters[CGAData::registerVerticalTotal] = 128 - 1; cgaRegisters[CGAData::registerVerticalTotalAdjust] = 6; cgaRegisters[CGAData::registerVerticalDisplayed] = 100; cgaRegisters[CGAData::registerVerticalSyncPosition] = 112; cgaRegisters[CGAData::registerInterlaceMode] = 2; cgaRegisters[CGAData::registerMaximumScanline] = 1; cgaRegisters[CGAData::registerCursorStart] = 6; cgaRegisters[CGAData::registerCursorEnd] = 7; cgaRegisters[CGAData::registerStartAddressHigh] = 0; cgaRegisters[CGAData::registerStartAddressLow] = 0; cgaRegisters[CGAData::registerCursorAddressHigh] = 0; cgaRegisters[CGAData::registerCursorAddressLow] = 0; _data.change(0, -regs, regs, &cgaRegistersData[0]); _data.setTotals(238944, 910, 238875); _data.change(0, 0, 0x4000, &_vram[0]); _outputSize = _output.requiredSize(); add(&_bitmap); add(&_animated); _animated.setDrawWindow(this); _animated.setRate(60); _buffer = 0; _buffers[0].clear(); _buffers[1].clear(); } private: FFTWWisdom<float> _wisdom; CGAData _data; CGASequencer _sequencer; CGAOutput _output; AnimatedWindow _animated; BitmapWindow _bitmap; }; class Program : public WindowProgram<GameWindow> { }; <commit_msg>More CGA game<commit_after>#include "alfe/main.h" #include "alfe/cga.h" class GameWindow : public RootWindow { public: GameWindow() : _wisdom(File("wisdom")), _output(&_data, &_sequencer, &_bitmap) { _output.setConnector(1); // old composite _output.setScanlineProfile(0); // rectangle _output.setHorizontalProfile(0); // rectangle _output.setScanlineWidth(1); _output.setScanlineBleeding(2); // symmetrical _output.setHorizontalBleeding(2); // symmetrical _output.setZoom(2); _output.setHorizontalRollOff(0); _output.setHorizontalLobes(4); _output.setVerticalRollOff(0); _output.setVerticalLobes(4); _output.setSubPixelSeparation(1); _output.setPhosphor(0); // colour _output.setMask(0); _output.setMaskSize(0); _output.setAspectRatio(5.0/6.0); _output.setOverscan(0); _output.setCombFilter(0); // no filter _output.setHue(0); _output.setSaturation(100); _output.setContrast(100); _output.setBrightness(0); _output.setShowClipping(false); _output.setChromaBandwidth(1); _output.setLumaBandwidth(1); _output.setRollOff(0); _output.setLobes(1.5); _output.setPhase(1); static const int regs = -CGAData::registerLogCharactersPerBank; Byte cgaRegistersData[regs] = { 0 }; Byte* cgaRegisters = &cgaRegistersData[regs]; cgaRegisters[CGAData::registerLogCharactersPerBank] = 12; cgaRegisters[CGAData::registerScanlinesRepeat] = 1; cgaRegisters[CGAData::registerHorizontalTotalHigh] = 0; cgaRegisters[CGAData::registerHorizontalDisplayedHigh] = 0; cgaRegisters[CGAData::registerHorizontalSyncPositionHigh] = 0; cgaRegisters[CGAData::registerVerticalTotalHigh] = 0; cgaRegisters[CGAData::registerVerticalDisplayedHigh] = 0; cgaRegisters[CGAData::registerVerticalSyncPositionHigh] = 0; cgaRegisters[CGAData::registerMode] = 9; cgaRegisters[CGAData::registerPalette] = 0; cgaRegisters[CGAData::registerHorizontalTotal] = 114 - 1; cgaRegisters[CGAData::registerHorizontalDisplayed] = 80; cgaRegisters[CGAData::registerHorizontalSyncPosition] = 90; cgaRegisters[CGAData::registerHorizontalSyncWidth] = 16; cgaRegisters[CGAData::registerVerticalTotal] = 128 - 1; cgaRegisters[CGAData::registerVerticalTotalAdjust] = 6; cgaRegisters[CGAData::registerVerticalDisplayed] = 100; cgaRegisters[CGAData::registerVerticalSyncPosition] = 112; cgaRegisters[CGAData::registerInterlaceMode] = 2; cgaRegisters[CGAData::registerMaximumScanline] = 1; cgaRegisters[CGAData::registerCursorStart] = 6; cgaRegisters[CGAData::registerCursorEnd] = 7; cgaRegisters[CGAData::registerStartAddressHigh] = 0; cgaRegisters[CGAData::registerStartAddressLow] = 0; cgaRegisters[CGAData::registerCursorAddressHigh] = 0; cgaRegisters[CGAData::registerCursorAddressLow] = 0; _data.change(0, -regs, regs, &cgaRegistersData[0]); _data.setTotals(238944, 910, 238875); _data.change(0, 0, 0x4000, &_vram[0]); _outputSize = _output.requiredSize(); add(&_bitmap); add(&_animated); _animated.setDrawWindow(this); _animated.setRate(60); _buffer = 0; _buffers[0].clear(); _buffers[1].clear(); } void create() { setText("CGA game"); setInnerSize(_outputSize); _bitmap.setTopLeft(Vector(0, 0)); _bitmap.setInnerSize(_outputSize); RootWindow::create(); _animated.start(); } virtual void draw() { _data.change(0, 0, 0x4000, &_vram[0]); _output.restart(); _animated.restart(); } bool keyboardEvent(int key, bool up) { if (up) return false; switch (key) { case VK_RIGHT: if (_autoRotate) _dTheta += 1; else _theta += 1; return true; case VK_LEFT: if (_autoRotate) _dTheta -= 1; else _theta -= 1; return true; case VK_UP: if (_autoRotate) _dPhi -= 1; else _phi -= 1; return true; case VK_DOWN: if (_autoRotate) _dPhi += 1; else _phi += 1; return true; case 'N': _shape = (_shape + 1) % (sizeof(shapes)/sizeof(shapes[0])); return true; case VK_SPACE: _autoRotate = !_autoRotate; if (!_autoRotate) { _dTheta = 0; _dPhi = 0; } return true; } return false; } private: FFTWWisdom<float> _wisdom; CGAData _data; CGASequencer _sequencer; CGAOutput _output; AnimatedWindow _animated; BitmapWindow _bitmap; Array<Byte> _background; Array<Byte> _foreground; Array<Byte> _buffer; Array<Byte> _tiles; }; class Program : public WindowProgram<GameWindow> { }; <|endoftext|>
<commit_before>#include "llvm/ADT/APInt.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/NoFolder.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <iostream> #include <fstream> using namespace llvm; using namespace std; static LLVMContext C; static IRBuilder<NoFolder> Builder(C); static std::unique_ptr<Module> M = llvm::make_unique<Module>("calc", C); static ifstream gInFile; char gCurValue = -1; int gArgsLen = 6; int gLineNo = 1; enum oper {ADD = 0, SUB, MUL, DIV, MOD}; bool debug = true; void parseExpression(); void skipSpaces(); void usage(void) { printf("executable <input file.calc>\r\n"); return; } bool openFile(int argc, char **argv) { if (argc < 2) { usage(); return false; } gInFile.open (argv[1], ifstream::in); return true; } char getChar() { return gCurValue; } void nextChar(void) { if (!gInFile.eof()) { gCurValue = gInFile.get(); } else { gCurValue = EOF; } } char getnextChar() { nextChar(); return gCurValue; } bool accept(char c) { if (getChar() == c) { nextChar(); return true; } return false; } bool check(char c) { if (getChar() == c) { return true; } return false; } string getContext() { string context; getline(gInFile, context); return context; } void printError() { printf ("Invalid statement at LineNo:%d:%d - %s", gLineNo, (int)gInFile.tellg(), getContext().c_str()); exit(0); } void printError(const char *c) { printf("Unable to compile due to error %s at Line: %d FilePosition:%d \r\n", c, gLineNo, (int)gInFile.tellg()); printf("Remaining Code: %s", getContext().c_str()); exit(0); } void parseComment() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } while (getnextChar() != '\n'); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseArgs() { char errmsg[50]; if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } int i; //Move the pointer next to a getnextChar(); for (i = 0; i < gArgsLen; i++) { if (accept('0' + (i - 0))) { //Change from int to char break; } } if (i == gArgsLen) { sprintf(errmsg, "Invalid argument (a%c) used in the program", getChar()); printError(errmsg); } getnextChar(); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } //Guess this should return an LLVM object void parseArithmeticOperation() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } char oper = getChar(); parseExpression(); parseExpression(); //Get Oper1 //Oper1 = parseExpression(); //Oper2 = parseExpression(); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseNumber() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } int num = 0, count = 0; char ch = getChar(); while ((ch >= 0) && (ch <= 9)) { num = (num * 10 * count++) + (0 + (ch - '0')); } //changed the int to number; if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseRelationalOperation() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } if (accept('>')) { //This is greater than if (accept('=')) { //This is greater than equals } } else if (accept('<')) { //This is less than if (accept('=')) { //This is less than equals } } else if (accept('!') && accept('=')) { //This is not equal to } else if (accept('=') && accept('=')) { //This is double equals } parseExpression(); parseExpression(); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseBoolExpression() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } skipSpaces(); char ch = getnextChar(); if (accept('t') && accept('r') && accept('u') && accept('e')) { //Its a true condition } else if (accept('f') && accept('a') && accept('l') && accept('s') && accept('e')) { //Its a false condition } else if ((ch == '>') || (ch == '<') || (ch == '=') || (ch == '!')) { parseRelationalOperation(); } else if (ch == ('(')) { parseBoolExpression(); if (accept(')') == false) { printError("Missing ) Paranthesis in boolean exp"); } } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseIf() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } if (accept('i') && accept('f')) { //Move till you find the ( of the bool expression parseBoolExpression(); parseExpression(); parseExpression(); } else { printError(); } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void skipSpaces() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } while (true) { if (accept(' ')) { continue; } else if (accept('\n')) { gLineNo++; continue; } break; } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } /* This function is called with the current pointer * at ( */ void parseExpression() { char errmsg[75]; if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } skipSpaces(); char ch = getChar(); while (ch != EOF) { if (ch == '#') { parseComment(); getnextChar(); } else if (ch == 'a') { parseArgs(); break; } else if (ch == '\n') { //Increment the line number, so that we can give a //meaningful error message gLineNo++; } else if (ch == ' ') { //Ignore White space } else if ((ch == '+') || (ch == '-') || (ch == '*') || (ch == '/') || (ch == '%')) { parseArithmeticOperation(); break; } else if ((ch >= 0) && (ch <= 9)) { return parseNumber(); } else if (ch == '(') { getnextChar(); return parseExpression(); if (check(')') == false) { printError("Missing Matching paranthesis"); } } else if (ch == 'i') { parseIf(); break; } else if (ch == ')') { getnextChar(); break; } else { printError(); } ch = getnextChar(); } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parser() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } char ch = getnextChar(); while(ch != EOF) { if (ch == '#') { parseComment(); } else { parseExpression(); skipSpaces(); if (getChar() == EOF) { break; } else { printError(); } } ch = getnextChar(); } printf("Parsed successfully\r\n"); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } static int compile() { M->setTargetTriple(llvm::sys::getProcessTriple()); std::vector<Type *> SixInts(6, Type::getInt64Ty(C)); FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false); Function *F = Function::Create(FT, Function::ExternalLinkage, "f", &*M); BasicBlock *BB = BasicBlock::Create(C, "entry", F); Builder.SetInsertPoint(BB); // TODO: parse the source program // TODO: generate correct LLVM instead of just an empty function Value *RetVal = ConstantInt::get(C, APInt(64, 0)); Builder.CreateRet(RetVal); assert(!verifyModule(*M, &outs())); M->dump(); return 0; } int main(int argc, char **argv) { if (openFile(argc, argv) == true) { parser(); //return compile(); } return -1; } <commit_msg>parser mostly working<commit_after>#include "llvm/ADT/APInt.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/NoFolder.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <iostream> #include <fstream> using namespace llvm; using namespace std; static LLVMContext C; static IRBuilder<NoFolder> Builder(C); static std::unique_ptr<Module> M = llvm::make_unique<Module>("calc", C); static ifstream gInFile; char gCurValue = -1; int gArgsLen = 6; int gLineNo = 1; enum oper {ADD = 0, SUB, MUL, DIV, MOD}; bool debug = true; void parseExpression(); void skipSpaces(); void usage(void) { printf("executable <input file.calc>\r\n"); return; } bool openFile(int argc, char **argv) { if (argc < 2) { usage(); return false; } gInFile.open (argv[1], ifstream::in); return true; } char getChar() { return gCurValue; } void nextChar(void) { if (!gInFile.eof()) { gCurValue = gInFile.get(); } else { gCurValue = EOF; } } char getnextChar() { nextChar(); return gCurValue; } bool accept(char c) { if (getChar() == c) { nextChar(); return true; } return false; } bool check(char c) { if (getChar() == c) { return true; } return false; } string getContext() { string context; getline(gInFile, context); return context; } void printError(int lineno) { printf ("%d:Invalid statement at LineNo:%d:%d - %c%s", lineno, gLineNo, (int)gInFile.tellg(), getChar(), getContext().c_str()); exit(0); } void printError(int lineno, const char *c) { printf("%d:Unable to compile due to error %s at Line: %d FilePosition:%d \r\n", lineno, c, gLineNo, (int)gInFile.tellg()); printf("Remaining Code: %c%s", getChar(), getContext().c_str()); exit(0); } void parseComment() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } while (getnextChar() != '\n'); //Skip \n getnextChar(); gLineNo++; if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseArgs() { char errmsg[50]; if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } int i; //Move the pointer next to a getnextChar(); for (i = 0; i < gArgsLen; i++) { if (accept('0' + (i - 0))) { //Change from int to char break; } } if (i == gArgsLen) { sprintf(errmsg, "Invalid argument (a%c) used in the program", getChar()); printError(__LINE__, errmsg); } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } //Guess this should return an LLVM object void parseArithmeticOperation(char oper) { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } parseExpression(); parseExpression(); //Get Oper1 //Oper1 = parseExpression(); //Oper2 = parseExpression(); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseNumber() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } int num = 0, count = 0; char ch = getChar(); while ((ch >= '0') && (ch <= '9')) { num = (num * 10 * count++) + (0 + (ch - '0')); ch = getnextChar(); } //changed the int to number; if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseRelationalOperation() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } if (accept('>')) { //This is greater than if (accept('=')) { //This is greater than equals } } else if (accept('<')) { //This is less than if (accept('=')) { //This is less than equals } } else if (accept('!') && accept('=')) { //This is not equal to } else if (accept('=') && accept('=')) { //This is double equals } parseExpression(); parseExpression(); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseBoolExpression() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } skipSpaces(); char ch = getChar(); if (accept('t') && accept('r') && accept('u') && accept('e')) { //Its a true condition } else if (accept('f') && accept('a') && accept('l') && accept('s') && accept('e')) { //Its a false condition } else if ((ch == '>') || (ch == '<') || (ch == '=') || (ch == '!')) { parseRelationalOperation(); } else if (ch == ('(')) { getnextChar(); parseBoolExpression(); if (accept(')') == false) { printError(__LINE__, "Missing ) Paranthesis in boolean exp"); } } else { printError(__LINE__, "Boolean expression Missing"); } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parseIf() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } if (accept('i') && accept('f')) { //Move till you find the ( of the bool expression parseBoolExpression(); parseExpression(); parseExpression(); } else { printError(__LINE__); } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void skipSpaces() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } while (getChar() != EOF) { if (accept(' ')) { continue; } else if (accept('\n')) { gLineNo++; continue; } break; } if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } /* This function is called with the current pointer * at ( */ void parseExpression() { char errmsg[75]; if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } skipSpaces(); char ch = getChar(); do{ if (ch == '#') { parseComment(); } else if (ch == 'a') { parseArgs(); break; } else if (ch == '\n') { //Increment the line number, so that we can give a //meaningful error message gLineNo++; } else if (ch == ' ') { //Ignore White space } else if ((ch == '+') || (ch == '-') || (ch == '*') || (ch == '/') || (ch == '%')) { getnextChar(); parseArithmeticOperation(ch); break; } else if ((ch >= '0') && (ch <= '9')) { parseNumber(); break; } else if (ch == '(') { getnextChar(); parseExpression(); if (accept(')') == false) { printError(__LINE__, "Missing Matching paranthesis"); } break; } else if (ch == 'i') { parseIf(); break; } else if (ch == ')') { getnextChar(); break; } else { printError(__LINE__); } ch = getChar(); }while (ch != EOF); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } void parser() { if (debug) { printf("Enter %s\r\n", __PRETTY_FUNCTION__); } char ch = getnextChar(); while(ch != EOF) { if (ch == '#') { parseComment(); } else { parseExpression(); skipSpaces(); if (getChar() == EOF) { break; } else { printError(__LINE__); } } ch = getChar(); } printf("Parsed successfully\r\n"); if (debug) { printf("Exit %s\r\n", __PRETTY_FUNCTION__); } } static int compile() { M->setTargetTriple(llvm::sys::getProcessTriple()); std::vector<Type *> SixInts(6, Type::getInt64Ty(C)); FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false); Function *F = Function::Create(FT, Function::ExternalLinkage, "f", &*M); BasicBlock *BB = BasicBlock::Create(C, "entry", F); Builder.SetInsertPoint(BB); // TODO: parse the source program // TODO: generate correct LLVM instead of just an empty function Value *RetVal = ConstantInt::get(C, APInt(64, 0)); Builder.CreateRet(RetVal); assert(!verifyModule(*M, &outs())); M->dump(); return 0; } int main(int argc, char **argv) { if (openFile(argc, argv) == true) { parser(); //return compile(); } return -1; } <|endoftext|>
<commit_before>/***************************************************** * THIS IS A GENERATED FILE. DO NOT EDIT. * Implementation for Application /*NAME*/ * Generated from ThingML (http://www.thingml.org) *****************************************************/ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #include <signal.h> #include <pthread.h> #include "thingml_typedefs.h" #include "runtime.h" #include "ros/ros.h" /*INCLUDES*/ // From annotation C_HEADERS: /*C_HEADERS*/ /*ROS_HEADERS*/ /*CONFIGURATION*/ /*ROS_HANDLERS*/ void initialize_ROS_connectors() { /*ROS_CONNECTORS*/ } /*C_GLOBALS*/ int main(int argc, char *argv[]) { init_runtime(); /*C_MAIN*/ initialize_ROS_connectors(); /*INIT_CODE*/ /*ROS_INIT*/ while (ros::ok()) { /*POLL_CODE*/ processMessageQueue(); ros::spinOnce(); } exit(0); }<commit_msg>Fixed ROS initialization order<commit_after>/***************************************************** * THIS IS A GENERATED FILE. DO NOT EDIT. * Implementation for Application /*NAME*/ * Generated from ThingML (http://www.thingml.org) *****************************************************/ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #include <signal.h> #include <pthread.h> #include "thingml_typedefs.h" #include "runtime.h" #include "ros/ros.h" /*INCLUDES*/ // From annotation C_HEADERS: /*C_HEADERS*/ /*ROS_HEADERS*/ /*CONFIGURATION*/ /*ROS_HANDLERS*/ void initialize_ROS_connectors() { /*ROS_CONNECTORS*/ } /*C_GLOBALS*/ int main(int argc, char *argv[]) { init_runtime(); /*C_MAIN*/ initialize_ROS_connectors(); /*ROS_INIT*/ /*INIT_CODE*/ while (ros::ok()) { /*POLL_CODE*/ processMessageQueue(); ros::spinOnce(); } exit(0); }<|endoftext|>
<commit_before>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2018, Marcus Rowe <[email protected]>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "animationframesmanager.h" #include "animationframecommands.h" #include "gui-qt/common/abstractidmaplistmodel.h" #include "gui-qt/metasprite/abstractmsdocument.h" #include "gui-qt/metasprite/abstractselection.h" using namespace UnTech::GuiQt::MetaSprite::Animation; const QStringList AnimationFramesManager::FLIP_STRINGS({ QString(), QString::fromUtf8("hFlip"), QString::fromUtf8("vFlip"), QString::fromUtf8("hvFlip") }); AnimationFramesManager::AnimationFramesManager(QObject* parent) : PropertyTableManager(parent) , _document(nullptr) , _animation(nullptr) { using Type = PropertyType; setItemsMovable(true); addProperty(tr("Frame"), PropertyId::FRAME, Type::IDSTRING); addProperty(tr("Flip"), PropertyId::FLIP, Type::COMBO, FLIP_STRINGS, QVariantList{ 0, 1, 2, 3 }); addProperty(tr("Dur"), PropertyId::DURATION, Type::UNSIGNED); addProperty(tr("Duration"), PropertyId::DURATION_STRING, Type::STRING); } void AnimationFramesManager::setDocument(AbstractMsDocument* document) { Q_ASSERT(document != nullptr); if (_document) { _document->disconnect(this); _document->selection()->disconnect(this); } _document = document; onSelectedAnimationChanged(); connect(_document->selection(), &AbstractSelection::selectedAnimationChanged, this, &AnimationFramesManager::onSelectedAnimationChanged); connect(_document, &AbstractMsDocument::animationDataChanged, this, &AnimationFramesManager::onAnimationDataChanged); connect(_document, &AbstractMsDocument::animationFrameChanged, this, &AnimationFramesManager::onAnimationFrameChanged); connect(_document, &AbstractMsDocument::animationFrameAdded, this, &AnimationFramesManager::onAnimationFrameAdded); connect(_document, &AbstractMsDocument::animationFrameAboutToBeRemoved, this, &AnimationFramesManager::onAnimationFrameAboutToBeRemoved); connect(_document, &AbstractMsDocument::animationFrameMoved, this, &AnimationFramesManager::onAnimationFrameMoved); } void AnimationFramesManager::updateParameters(int index, int id, QVariant& param1, QVariant& param2) const { Q_UNUSED(param2); if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return; } switch ((PropertyId)id) { case PropertyId::FRAME: param1 = _document->frameListModel()->displayList(); break; case PropertyId::FLIP: case PropertyId::DURATION: case PropertyId::DURATION_STRING: break; }; } void AnimationFramesManager::onSelectedAnimationChanged() { MSA::Animation* animation = _document->selection()->selectedAnimation(); if (_animation != animation) { _animation = animation; emit dataReset(); } } void AnimationFramesManager::onAnimationDataChanged(const void* animation) { if (animation == _animation) { emit dataChanged(); } } void AnimationFramesManager::onAnimationFrameChanged(const void* animation, unsigned index) { if (animation == _animation) { emit itemChanged(index); } } void AnimationFramesManager::onAnimationFrameAdded(const void* animation, unsigned index) { if (animation == _animation) { emit itemAdded(index); } } void AnimationFramesManager::onAnimationFrameAboutToBeRemoved(const void* animation, unsigned index) { if (animation == _animation) { emit itemRemoved(index); } } void AnimationFramesManager::onAnimationFrameMoved(const void* animation, unsigned oldPos, unsigned newPos) { if (animation == _animation) { emit itemMoved(oldPos, newPos); } } int AnimationFramesManager::rowCount() const { if (_animation) { return _animation->frames.size(); } else { return 0; } } QVariant AnimationFramesManager::data(int index, int id) const { if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return QVariant(); } const MSA::AnimationFrame& aFrame = _animation->frames.at(index); unsigned flipIndex = (aFrame.frame.vFlip << 1) | aFrame.frame.hFlip; switch ((PropertyId)id) { case PropertyId::FRAME: return QString::fromStdString(aFrame.frame.name); case PropertyId::FLIP: return flipIndex; case PropertyId::DURATION: return aFrame.duration; case PropertyId::DURATION_STRING: { return QString::fromStdString(_animation->durationFormat.durationToString(aFrame.duration)); } }; return QVariant(); } bool AnimationFramesManager::setData(int index, int id, const QVariant& value) { if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return false; } const auto& oldFrame = _animation->frames.at(index); MSA::AnimationFrame aFrame = oldFrame; switch ((PropertyId)id) { case PropertyId::FRAME: aFrame.frame.name = value.toString().toStdString(); break; case PropertyId::FLIP: aFrame.frame.hFlip = value.toUInt() & 1; aFrame.frame.vFlip = value.toUInt() & 2; break; case PropertyId::DURATION: aFrame.duration = value.toUInt(); break; case PropertyId::DURATION_STRING: return false; }; if (aFrame != oldFrame) { _document->undoStack()->push( new ChangeAnimationFrame(_document, _animation, index, aFrame)); return true; } return false; } bool AnimationFramesManager::canInsertItem() { return _animation != nullptr && _animation->frames.can_insert(); } bool AnimationFramesManager::canCloneItem(int index) { return _animation != nullptr && _animation->frames.can_insert() && index >= 0 && (unsigned)index < _animation->frames.size(); } bool AnimationFramesManager::insertItem(int index) { if (_animation == nullptr || _animation->frames.can_insert() == false || index < 0 || (unsigned)index > _animation->frames.size()) { return false; } _document->undoStack()->push( new AddAnimationFrame(_document, _animation, index)); return true; } bool AnimationFramesManager::cloneItem(int index) { if (_animation == nullptr || _animation->frames.can_insert() == false || index < 0 || (unsigned)index > _animation->frames.size()) { return false; } _document->undoStack()->push( new CloneAnimationFrame(_document, _animation, index)); return true; } bool AnimationFramesManager::removeItem(int index) { if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return false; } _document->undoStack()->push( new RemoveAnimationFrame(_document, _animation, index)); return true; } bool AnimationFramesManager::moveItem(int from, int to) { if (_animation == nullptr || from == to || from < 0 || (unsigned)from >= _animation->frames.size() || to < 0 || (unsigned)to >= _animation->frames.size()) { return false; } _document->undoStack()->push( new MoveAnimationFrame(_document, _animation, from, to)); return true; } <commit_msg>Fix nullptr segfault in AnimationFramesManager<commit_after>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2018, Marcus Rowe <[email protected]>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "animationframesmanager.h" #include "animationframecommands.h" #include "gui-qt/common/abstractidmaplistmodel.h" #include "gui-qt/metasprite/abstractmsdocument.h" #include "gui-qt/metasprite/abstractselection.h" using namespace UnTech::GuiQt::MetaSprite::Animation; const QStringList AnimationFramesManager::FLIP_STRINGS({ QString(), QString::fromUtf8("hFlip"), QString::fromUtf8("vFlip"), QString::fromUtf8("hvFlip") }); AnimationFramesManager::AnimationFramesManager(QObject* parent) : PropertyTableManager(parent) , _document(nullptr) , _animation(nullptr) { using Type = PropertyType; setItemsMovable(true); addProperty(tr("Frame"), PropertyId::FRAME, Type::IDSTRING); addProperty(tr("Flip"), PropertyId::FLIP, Type::COMBO, FLIP_STRINGS, QVariantList{ 0, 1, 2, 3 }); addProperty(tr("Dur"), PropertyId::DURATION, Type::UNSIGNED); addProperty(tr("Duration"), PropertyId::DURATION_STRING, Type::STRING); } void AnimationFramesManager::setDocument(AbstractMsDocument* document) { if (_document) { _document->disconnect(this); _document->selection()->disconnect(this); } _document = document; _animation = nullptr; emit dataReset(); if (_document) { onSelectedAnimationChanged(); connect(_document->selection(), &AbstractSelection::selectedAnimationChanged, this, &AnimationFramesManager::onSelectedAnimationChanged); connect(_document, &AbstractMsDocument::animationDataChanged, this, &AnimationFramesManager::onAnimationDataChanged); connect(_document, &AbstractMsDocument::animationFrameChanged, this, &AnimationFramesManager::onAnimationFrameChanged); connect(_document, &AbstractMsDocument::animationFrameAdded, this, &AnimationFramesManager::onAnimationFrameAdded); connect(_document, &AbstractMsDocument::animationFrameAboutToBeRemoved, this, &AnimationFramesManager::onAnimationFrameAboutToBeRemoved); connect(_document, &AbstractMsDocument::animationFrameMoved, this, &AnimationFramesManager::onAnimationFrameMoved); } } void AnimationFramesManager::updateParameters(int index, int id, QVariant& param1, QVariant& param2) const { Q_UNUSED(param2); if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return; } switch ((PropertyId)id) { case PropertyId::FRAME: param1 = _document->frameListModel()->displayList(); break; case PropertyId::FLIP: case PropertyId::DURATION: case PropertyId::DURATION_STRING: break; }; } void AnimationFramesManager::onSelectedAnimationChanged() { MSA::Animation* animation = _document->selection()->selectedAnimation(); if (_animation != animation) { _animation = animation; emit dataReset(); } } void AnimationFramesManager::onAnimationDataChanged(const void* animation) { if (animation == _animation) { emit dataChanged(); } } void AnimationFramesManager::onAnimationFrameChanged(const void* animation, unsigned index) { if (animation == _animation) { emit itemChanged(index); } } void AnimationFramesManager::onAnimationFrameAdded(const void* animation, unsigned index) { if (animation == _animation) { emit itemAdded(index); } } void AnimationFramesManager::onAnimationFrameAboutToBeRemoved(const void* animation, unsigned index) { if (animation == _animation) { emit itemRemoved(index); } } void AnimationFramesManager::onAnimationFrameMoved(const void* animation, unsigned oldPos, unsigned newPos) { if (animation == _animation) { emit itemMoved(oldPos, newPos); } } int AnimationFramesManager::rowCount() const { if (_animation) { return _animation->frames.size(); } else { return 0; } } QVariant AnimationFramesManager::data(int index, int id) const { if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return QVariant(); } const MSA::AnimationFrame& aFrame = _animation->frames.at(index); unsigned flipIndex = (aFrame.frame.vFlip << 1) | aFrame.frame.hFlip; switch ((PropertyId)id) { case PropertyId::FRAME: return QString::fromStdString(aFrame.frame.name); case PropertyId::FLIP: return flipIndex; case PropertyId::DURATION: return aFrame.duration; case PropertyId::DURATION_STRING: { return QString::fromStdString(_animation->durationFormat.durationToString(aFrame.duration)); } }; return QVariant(); } bool AnimationFramesManager::setData(int index, int id, const QVariant& value) { if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return false; } const auto& oldFrame = _animation->frames.at(index); MSA::AnimationFrame aFrame = oldFrame; switch ((PropertyId)id) { case PropertyId::FRAME: aFrame.frame.name = value.toString().toStdString(); break; case PropertyId::FLIP: aFrame.frame.hFlip = value.toUInt() & 1; aFrame.frame.vFlip = value.toUInt() & 2; break; case PropertyId::DURATION: aFrame.duration = value.toUInt(); break; case PropertyId::DURATION_STRING: return false; }; if (aFrame != oldFrame) { _document->undoStack()->push( new ChangeAnimationFrame(_document, _animation, index, aFrame)); return true; } return false; } bool AnimationFramesManager::canInsertItem() { return _animation != nullptr && _animation->frames.can_insert(); } bool AnimationFramesManager::canCloneItem(int index) { return _animation != nullptr && _animation->frames.can_insert() && index >= 0 && (unsigned)index < _animation->frames.size(); } bool AnimationFramesManager::insertItem(int index) { if (_animation == nullptr || _animation->frames.can_insert() == false || index < 0 || (unsigned)index > _animation->frames.size()) { return false; } _document->undoStack()->push( new AddAnimationFrame(_document, _animation, index)); return true; } bool AnimationFramesManager::cloneItem(int index) { if (_animation == nullptr || _animation->frames.can_insert() == false || index < 0 || (unsigned)index > _animation->frames.size()) { return false; } _document->undoStack()->push( new CloneAnimationFrame(_document, _animation, index)); return true; } bool AnimationFramesManager::removeItem(int index) { if (_animation == nullptr || index < 0 || (unsigned)index >= _animation->frames.size()) { return false; } _document->undoStack()->push( new RemoveAnimationFrame(_document, _animation, index)); return true; } bool AnimationFramesManager::moveItem(int from, int to) { if (_animation == nullptr || from == to || from < 0 || (unsigned)from >= _animation->frames.size() || to < 0 || (unsigned)to >= _animation->frames.size()) { return false; } _document->undoStack()->push( new MoveAnimationFrame(_document, _animation, from, to)); return true; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_psi_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_psi_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000; constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000; constexpr uint64_t literal_0b00111001000000101111111111111 = 0b00111001000000101111111111111; constexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000; constexpr uint64_t literal_0b11000110001010010000000000000 = 0b11000110001010010000000000000; constexpr uint64_t literal_0x000 = 0x000; constexpr uint64_t literal_0b00000 = 0b00000; fapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer )); l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer )); l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer )); l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer )); l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111001000000101111111111111 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer )); l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer )); l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000110001010010000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer )); l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 ); l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>PSI FIR updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_psi_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_psi_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000; constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000; constexpr uint64_t literal_0b00111111000000100000011011111 = 0b00111111000000100000011011111; constexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000; constexpr uint64_t literal_0b11000000001010011111100100000 = 0b11000000001010011111100100000; constexpr uint64_t literal_0x000 = 0x000; constexpr uint64_t literal_0b00000 = 0b00000; fapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer )); l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer )); l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer )); l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer )); l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111111000000100000011011111 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer )); l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer )); l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000000001010011111100100000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer )); l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 ); l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Modules/Legacy/Fields/GetFieldBoundary.h> #include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundary.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Modules::Fields; GetFieldBoundary::GetFieldBoundary() : Module(ModuleLookupInfo("GetFieldBoundary", "NewField", "SCIRun"), false) { algo_ = algoFactory_->create(get_module_name(), getLogger()); } void GetFieldBoundary::execute() { FieldHandle field; get_input_handle("Field",field,true); // If parameters changed, do algorithm if (inputs_changed_ || !oport_cached("BoundaryField") || !oport_cached("Mapping")) { update_state(Executing); FieldHandle ofield; MatrixHandle mapping; if (!(algo_.run(field,ofield,mapping))) return; send_output_handle("BoundaryField", ofield); send_output_handle("Mapping", mapping); } } <commit_msg>Change input function call<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Modules/Legacy/Fields/GetFieldBoundary.h> #include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundary.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Modules::Fields; GetFieldBoundary::GetFieldBoundary() : Module(ModuleLookupInfo("GetFieldBoundary", "NewField", "SCIRun"), false) { algo_ = algoFactory_->create(get_module_name(), getLogger()); } void GetFieldBoundary::execute() { FieldHandle field = getRequiredInput(Field); // If parameters changed, do algorithm if (inputs_changed_ || !oport_cached("BoundaryField") || !oport_cached("Mapping")) { update_state(Executing); FieldHandle ofield; MatrixHandle mapping; if (!(algo_.run(field,ofield,mapping))) return; send_output_handle("BoundaryField", ofield); send_output_handle("Mapping", mapping); } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <string.h> #if defined(_WIN32) # define _WIN32_LEAN_AND_MEAN # define NOMINMAX # include <windows.h> #else # include <sys/stat.h> // S_ISREG, stat # include <dirent.h> // opendir, readir, DIR # include <unistd.h> // rmdir, mkdir #endif #include "u_file.h" #include "u_algorithm.h" #include "u_misc.h" namespace u { file::file() : m_handle(nullptr) { } file::file(FILE *fp) : m_handle(fp) { } file::file(file &&other) : m_handle(other.m_handle) { other.m_handle = nullptr; } file::~file() { if (m_handle) fclose(m_handle); } file &file::operator=(file &&other) { m_handle = other.m_handle; other.m_handle = nullptr; return *this; } file::operator FILE*() { return m_handle; } FILE *file::get() const { return m_handle; } void file::close() { fclose(m_handle); m_handle = nullptr; } u::string fixPath(const u::string &path) { u::string fix = path; for (char *it = &fix[0]; (it = strpbrk(it, "/\\")); *it++ = u::kPathSep) ; return fix; } // file system stuff bool exists(const u::string &inputPath, pathType type) { u::string &&path = u::move(u::fixPath(inputPath)); if (type == kFile) return dir::isFile(path); // type == kDirectory #if defined(_WIN32) const DWORD attribs = GetFileAttributesA(inputPath.c_str()); if (attribs == INVALID_FILE_ATTRIBUTES) return false; if (!(attribs & FILE_ATTRIBUTE_DIRECTORY)) return false; #else struct stat info; if (stat(path.c_str(), &info) != 0) return false; // Couldn't stat directory if (!(info.st_mode & S_IFDIR)) return false; // Not a directory #endif return true; } bool remove(const u::string &path, pathType type) { u::string &&fix = u::move(fixPath(path)); if (type == kFile) { #if defined(_WIN32) return DeleteFileA(&fix[0]) != 0; #else return ::remove(&fix[0]) == 0; #endif } // type == kDirectory #if defined(_WIN32) return RemoveDirectoryA(&fix[0]) != 0; #else return ::rmdir(&fix[0]) == 0; #endif } bool mkdir(const u::string &dir) { u::string &&fix = u::move(u::fixPath(dir)); #if defined(_WIN32) return CreateDirectoryA(&fix[0], nullptr) != 0; #else return ::mkdir(&fix[0], 0775); #endif } u::file fopen(const u::string& infile, const char *type) { return ::fopen(fixPath(infile).c_str(), type); } bool getline(u::file &fp, u::string &line) { line.clear(); for (;;) { char buf[256]; if (!fgets(buf, sizeof buf, fp.get())) { if (feof(fp.get())) return !line.empty(); abort(); } size_t n = strlen(buf); if (n && buf[n - 1] == '\n') --n; if (n && buf[n - 1] == '\r') --n; line.append(buf, n); if (n < sizeof buf - 1) return true; } return false; } u::optional<u::string> getline(u::file &fp) { u::string s; if (!getline(fp, s)) return u::none; return u::move(s); } u::optional<u::vector<unsigned char>> read(const u::string &file, const char *mode) { auto fp = u::fopen(file, mode); if (!fp) return u::none; u::vector<unsigned char> data; if (fseek(fp.get(), 0, SEEK_END) != 0) return u::none; const auto size = ftell(fp.get()); if (size <= 0) return u::none; data.resize(size); if (fseek(fp.get(), 0, SEEK_SET) != 0) return u::none; if (fread(&data[0], data.size(), 1, fp.get()) != 1) return u::none; return data; } bool write(const u::vector<unsigned char> &data, const u::string &file, const char *mode) { auto fp = u::fopen(file, mode); if (!fp) return false; if (fwrite(&data[0], data.size(), 1, fp.get()) != 1) return false; return true; } ///! dir #if !defined(_WIN32) #include <unistd.h> #include <dirent.h> #define IS_IGNORE(X) ((X)->d_name[0] == '.' && !(X)->d_name[1+((X)->d_name[1]=='.')]) ///! dir::const_iterator dir::const_iterator::const_iterator(void *handle) : m_handle(handle) , m_name(nullptr) { if (!m_handle) return; // Ignore "." and ".." struct dirent *next = readdir((DIR *)m_handle); while (next && IS_IGNORE(next)) next = readdir((DIR *)m_handle); m_name = next ? next->d_name : nullptr; } dir::const_iterator &dir::const_iterator::operator++() { struct dirent *next = readdir((DIR *)m_handle); while (next && IS_IGNORE(next)) next = readdir((DIR *)m_handle); m_name = next ? next->d_name : nullptr; return *this; } ///! dir dir::dir(const char *where) : m_handle((void *)opendir(where)) { } dir::~dir() { if (m_handle) closedir((DIR *)m_handle); } bool dir::isFile(const char *fileName) { struct stat buff; if (stat(fileName, &buff) != 0) return false; return S_ISREG(buff.st_mode); } #else #define IS_IGNORE(X) ((X).cFileName[0] == '.' && !(X).cFileName[1+((X).cFileName[1]=='.')]) struct findContext { findContext(const char *where); ~findContext(); HANDLE handle; WIN32_FIND_DATA findData; }; inline findContext::findContext(const char *where) : handle(INVALID_HANDLE_VALUE) { static constexpr const char kPathExtra[] = "\\*"; const size_t length = strlen(where); U_ASSERT(length + sizeof kPathExtra < MAX_PATH); char path[MAX_PATH]; memcpy((void *)path, (const void *)where, length); memcpy((void *)&path[length], (const void *)kPathExtra, sizeof kPathExtra); if (!(handle = FindFirstFileA(path, &findData))) return; // Ignore "." and ".." if (IS_IGNORE(findData)) { BOOL next = FindNextFileA(handle, &findData); while (next && IS_IGNORE(findData)) next = FindNextFileA(handle, &findData); } } inline findContext::~findContext() { if (handle != INVALID_HANDLE_VALUE) FindClose(handle); } ///! dir::const_iterator dir::const_iterator::const_iterator(void *handle) : m_handle(handle) , m_name(((findContext*)m_handle)->findData.cFileName) { } dir::const_iterator &dir::const_iterator::operator++() { findContext *context = (findContext*)m_handle; BOOL next = FindNextFileA(context->handle, &context->findData); // Ignore "." and ".." while (next && IS_IGNORE(context->findData)) next = FindNextFileA(context->handle, &context->findData); m_name = next ? context->findData.cFileName : nullptr; return *this; } ///! dir dir::dir(const char *where) : m_handle(new findContext(where)) { } dir::~dir() { delete (findContext*)m_handle; } bool dir::isFile(const char *fileName) { const DWORD attribs = GetFileAttributesA(fileName); if (attribs == INVALID_FILE_ATTRIBUTES) return false; if (attribs & FILE_ATTRIBUTE_DIRECTORY) return false; return true; } #endif } <commit_msg>Apparently this is undefined<commit_after>#include <stdlib.h> #include <string.h> #if defined(_WIN32) # define _WIN32_LEAN_AND_MEAN # define NOMINMAX # include <windows.h> #else # include <sys/stat.h> // S_ISREG, stat # include <dirent.h> // opendir, readir, DIR # include <unistd.h> // rmdir, mkdir #endif #include "u_file.h" #include "u_algorithm.h" #include "u_misc.h" namespace u { file::file() : m_handle(nullptr) { } file::file(FILE *fp) : m_handle(fp) { } file::file(file &&other) : m_handle(other.m_handle) { other.m_handle = nullptr; } file::~file() { if (m_handle) fclose(m_handle); } file &file::operator=(file &&other) { m_handle = other.m_handle; other.m_handle = nullptr; return *this; } file::operator FILE*() { return m_handle; } FILE *file::get() const { return m_handle; } void file::close() { fclose(m_handle); m_handle = nullptr; } u::string fixPath(const u::string &path) { u::string fix = path; for (char *it = &fix[0]; (it = strpbrk(it, "/\\")); *it++ = u::kPathSep) ; return fix; } // file system stuff bool exists(const u::string &inputPath, pathType type) { u::string &&path = u::fixPath(inputPath); if (type == kFile) return dir::isFile(path); // type == kDirectory #if defined(_WIN32) const DWORD attribs = GetFileAttributesA(inputPath.c_str()); if (attribs == INVALID_FILE_ATTRIBUTES) return false; if (!(attribs & FILE_ATTRIBUTE_DIRECTORY)) return false; #else struct stat info; if (stat(path.c_str(), &info) != 0) return false; // Couldn't stat directory if (!(info.st_mode & S_IFDIR)) return false; // Not a directory #endif return true; } bool remove(const u::string &path, pathType type) { u::string &&fix = u::fixPath(path); if (type == kFile) { #if defined(_WIN32) return DeleteFileA(&fix[0]) != 0; #else return ::remove(&fix[0]) == 0; #endif } // type == kDirectory #if defined(_WIN32) return RemoveDirectoryA(&fix[0]) != 0; #else return ::rmdir(&fix[0]) == 0; #endif } bool mkdir(const u::string &dir) { u::string &&fix = u::fixPath(dir); #if defined(_WIN32) return CreateDirectoryA(&fix[0], nullptr) != 0; #else return ::mkdir(&fix[0], 0775); #endif } u::file fopen(const u::string& infile, const char *type) { return ::fopen(fixPath(infile).c_str(), type); } bool getline(u::file &fp, u::string &line) { line.clear(); for (;;) { char buf[256]; if (!fgets(buf, sizeof buf, fp.get())) { if (feof(fp.get())) return !line.empty(); abort(); } size_t n = strlen(buf); if (n && buf[n - 1] == '\n') --n; if (n && buf[n - 1] == '\r') --n; line.append(buf, n); if (n < sizeof buf - 1) return true; } return false; } u::optional<u::string> getline(u::file &fp) { u::string s; if (!getline(fp, s)) return u::none; return u::move(s); } u::optional<u::vector<unsigned char>> read(const u::string &file, const char *mode) { auto fp = u::fopen(file, mode); if (!fp) return u::none; u::vector<unsigned char> data; if (fseek(fp.get(), 0, SEEK_END) != 0) return u::none; const auto size = ftell(fp.get()); if (size <= 0) return u::none; data.resize(size); if (fseek(fp.get(), 0, SEEK_SET) != 0) return u::none; if (fread(&data[0], data.size(), 1, fp.get()) != 1) return u::none; return data; } bool write(const u::vector<unsigned char> &data, const u::string &file, const char *mode) { auto fp = u::fopen(file, mode); if (!fp) return false; if (fwrite(&data[0], data.size(), 1, fp.get()) != 1) return false; return true; } ///! dir #if !defined(_WIN32) #include <unistd.h> #include <dirent.h> #define IS_IGNORE(X) ((X)->d_name[0] == '.' && !(X)->d_name[1+((X)->d_name[1]=='.')]) ///! dir::const_iterator dir::const_iterator::const_iterator(void *handle) : m_handle(handle) , m_name(nullptr) { if (!m_handle) return; // Ignore "." and ".." struct dirent *next = readdir((DIR *)m_handle); while (next && IS_IGNORE(next)) next = readdir((DIR *)m_handle); m_name = next ? next->d_name : nullptr; } dir::const_iterator &dir::const_iterator::operator++() { struct dirent *next = readdir((DIR *)m_handle); while (next && IS_IGNORE(next)) next = readdir((DIR *)m_handle); m_name = next ? next->d_name : nullptr; return *this; } ///! dir dir::dir(const char *where) : m_handle((void *)opendir(where)) { } dir::~dir() { if (m_handle) closedir((DIR *)m_handle); } bool dir::isFile(const char *fileName) { struct stat buff; if (stat(fileName, &buff) != 0) return false; return S_ISREG(buff.st_mode); } #else #define IS_IGNORE(X) ((X).cFileName[0] == '.' && !(X).cFileName[1+((X).cFileName[1]=='.')]) struct findContext { findContext(const char *where); ~findContext(); HANDLE handle; WIN32_FIND_DATA findData; }; inline findContext::findContext(const char *where) : handle(INVALID_HANDLE_VALUE) { static constexpr const char kPathExtra[] = "\\*"; const size_t length = strlen(where); U_ASSERT(length + sizeof kPathExtra < MAX_PATH); char path[MAX_PATH]; memcpy((void *)path, (const void *)where, length); memcpy((void *)&path[length], (const void *)kPathExtra, sizeof kPathExtra); if (!(handle = FindFirstFileA(path, &findData))) return; // Ignore "." and ".." if (IS_IGNORE(findData)) { BOOL next = FindNextFileA(handle, &findData); while (next && IS_IGNORE(findData)) next = FindNextFileA(handle, &findData); } } inline findContext::~findContext() { if (handle != INVALID_HANDLE_VALUE) FindClose(handle); } ///! dir::const_iterator dir::const_iterator::const_iterator(void *handle) : m_handle(handle) , m_name(((findContext*)m_handle)->findData.cFileName) { } dir::const_iterator &dir::const_iterator::operator++() { findContext *context = (findContext*)m_handle; BOOL next = FindNextFileA(context->handle, &context->findData); // Ignore "." and ".." while (next && IS_IGNORE(context->findData)) next = FindNextFileA(context->handle, &context->findData); m_name = next ? context->findData.cFileName : nullptr; return *this; } ///! dir dir::dir(const char *where) : m_handle(new findContext(where)) { } dir::~dir() { delete (findContext*)m_handle; } bool dir::isFile(const char *fileName) { const DWORD attribs = GetFileAttributesA(fileName); if (attribs == INVALID_FILE_ATTRIBUTES) return false; if (attribs & FILE_ATTRIBUTE_DIRECTORY) return false; return true; } #endif } <|endoftext|>
<commit_before>/** * Copyright 2012 Thinkbox Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file contains definitions for working with prt data types at runtime and compile time. * See http://www.thinkboxsoftware.com/krak-prt-file-format/ for more details. */ #pragma once #include <string> #include <stdexcept> #include <string> #pragma warning( push, 3 ) #include <half.h> #pragma warning( pop ) #include <cctype> #include <string> #if defined(WIN32) || defined(_WIN64) #if _MSC_VER >= 1600 #define HAS_CSTDINT_TYPES #define STDNAMESPACE std #include <cstdint> #endif #else #define HAS_CSTDINT_TYPES #define STDNAMESPACE #include <stdint.h> #endif namespace prtio{ namespace data_types{ //This list contains all the types defined in the PRT file spec at //http://www.thinkboxsoftware.com/krak-prt-file-format/ enum enum_t{ type_int16, type_int32, type_int64, type_float16, type_float32, type_float64, type_uint16, type_uint32, type_uint64, type_int8, type_uint8, type_count //This must be the last entry. It's a marker for the number of possible inputs }; typedef half float16_t; typedef float float32_t; typedef double float64_t; //I foresee this changing depending on the platform & compiler. #ifndef HAS_CSTDINT_TYPES typedef char int8_t; typedef short int16_t; typedef int int32_t; typedef long long int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; #else using STDNAMESPACE::int8_t; using STDNAMESPACE::int16_t; using STDNAMESPACE::int32_t; using STDNAMESPACE::int64_t; using STDNAMESPACE::uint8_t; using STDNAMESPACE::uint16_t; using STDNAMESPACE::uint32_t; using STDNAMESPACE::uint64_t; #endif //This global array may be indexed using the corresponding type enumeration. For example, the size of //a float32 is sizes[type_float32]. const std::size_t sizes[] = { sizeof(int16_t), sizeof(int32_t), sizeof(int64_t), sizeof(float16_t), sizeof(float32_t), sizeof(float64_t), sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t), sizeof(int8_t), sizeof(uint8_t) }; //This global array maps from enum_t values to names. For example the name for type_float32 is names[type_float32]. const char* names[] = { "int16", "int32", "int64", "float16", "float32", "float64", "uint16", "uint32", "uint64", "int8", "uint8" }; /** * The traits template class and it specializations exist to provide compile time information about a mapping * from C++ types to PRT io types. * @tparam T The type we are mapping into the PRT file io enumeration types. * @note traits<T>::data_type() returns the enum_t value of the equivalent PRT io type for T. */ template <typename T> struct traits; #define PRT_TRAITS_IMPL( type, enumVal ) \ template <> \ struct traits< type >{ \ inline static enum_t data_type(){ \ return enumVal; \ } \ }; PRT_TRAITS_IMPL( int8_t , type_int8 ); PRT_TRAITS_IMPL( int16_t, type_int16 ); PRT_TRAITS_IMPL( int32_t, type_int32 ); PRT_TRAITS_IMPL( int64_t, type_int64 ); PRT_TRAITS_IMPL( uint8_t , type_uint8 ); PRT_TRAITS_IMPL( uint16_t, type_uint16 ); PRT_TRAITS_IMPL( uint32_t, type_uint32 ); PRT_TRAITS_IMPL( uint64_t, type_uint64 ); PRT_TRAITS_IMPL( float16_t, type_float16 ); PRT_TRAITS_IMPL( float32_t, type_float32 ); PRT_TRAITS_IMPL( float64_t, type_float64 ); #if defined(WIN32) || defined(_WIN64) //Windows treats long and int as separate types. PRT_TRAITS_IMPL( long, type_int32 ); PRT_TRAITS_IMPL( unsigned long, type_uint32 ); #endif #undef PRT_TRAITS_IMPL /** * Extracts a data_type::enum_t from a string representation. */ std::pair<enum_t,std::size_t> parse_data_type( const std::string& typeString ){ std::string::const_iterator it = typeString.begin(), itEnd = typeString.end(); //Skip beginning whitespace for( ; it != itEnd && std::isspace(*it); ++it ) ; //The type comes first, ending at whitespace or a [ bracket. std::string::const_iterator typeStart = it; for( ; it != itEnd && !std::isspace(*it) && (*it) != '['; ++it ) ; std::string::const_iterator typeEnd = it; if( it == itEnd ) throw std::runtime_error( "Invalid data type string: \"" + typeString + "\"" ); //Skip whitespace until an open bracket. for( ; it != itEnd && std::isspace(*it); ++it ) ; //Make sure we closed the arity in brackets correctly if( it == itEnd || (*it) != '[' ) throw std::runtime_error( "Invalid data type string: \"" + typeString + "\"" ); std::string::const_iterator arityStart = ++it; for( ; it != itEnd && std::isdigit(*it); ++it ) ; if( it == itEnd || (*it) != ']' || ++it != itEnd ) throw std::runtime_error( "Invalid data type string: \"" + typeString + "\"" ); enum_t resultType = type_count; std::size_t resultArity = 0; for( int i = 0, iEnd = type_count; i < iEnd && resultType == type_count; ++i ){ if( std::strncmp( names[i], &*typeStart, (typeEnd - typeStart) ) == 0 ) resultType = static_cast<enum_t>( i ); } resultArity = static_cast<std::size_t>( atoi( &*arityStart ) ); return std::make_pair( resultType, resultArity ); } }//namespace data_types }//namespace prtio <commit_msg>Add static to const char array so that it is defined only once Add inline into template function so that it is declared only once If the above is not done, multiple include of headers will result in compiler errors<commit_after>/** * Copyright 2012 Thinkbox Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file contains definitions for working with prt data types at runtime and compile time. * See http://www.thinkboxsoftware.com/krak-prt-file-format/ for more details. */ #pragma once #include <string> #include <stdexcept> #include <string> #pragma warning( push, 3 ) #include <half.h> #pragma warning( pop ) #include <cctype> #include <string> #if defined(WIN32) || defined(_WIN64) #if _MSC_VER >= 1600 #define HAS_CSTDINT_TYPES #define STDNAMESPACE std #include <cstdint> #endif #else #define HAS_CSTDINT_TYPES #define STDNAMESPACE #include <stdint.h> #endif namespace prtio{ namespace data_types{ //This list contains all the types defined in the PRT file spec at //http://www.thinkboxsoftware.com/krak-prt-file-format/ enum enum_t{ type_int16, type_int32, type_int64, type_float16, type_float32, type_float64, type_uint16, type_uint32, type_uint64, type_int8, type_uint8, type_count //This must be the last entry. It's a marker for the number of possible inputs }; typedef half float16_t; typedef float float32_t; typedef double float64_t; //I foresee this changing depending on the platform & compiler. #ifndef HAS_CSTDINT_TYPES typedef char int8_t; typedef short int16_t; typedef int int32_t; typedef long long int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; #else using STDNAMESPACE::int8_t; using STDNAMESPACE::int16_t; using STDNAMESPACE::int32_t; using STDNAMESPACE::int64_t; using STDNAMESPACE::uint8_t; using STDNAMESPACE::uint16_t; using STDNAMESPACE::uint32_t; using STDNAMESPACE::uint64_t; #endif //This global array may be indexed using the corresponding type enumeration. For example, the size of //a float32 is sizes[type_float32]. const std::size_t sizes[] = { sizeof(int16_t), sizeof(int32_t), sizeof(int64_t), sizeof(float16_t), sizeof(float32_t), sizeof(float64_t), sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t), sizeof(int8_t), sizeof(uint8_t) }; //This global array maps from enum_t values to names. For example the name for type_float32 is names[type_float32]. static const char* names[] = { "int16", "int32", "int64", "float16", "float32", "float64", "uint16", "uint32", "uint64", "int8", "uint8" }; /** * The traits template class and it specializations exist to provide compile time information about a mapping * from C++ types to PRT io types. * @tparam T The type we are mapping into the PRT file io enumeration types. * @note traits<T>::data_type() returns the enum_t value of the equivalent PRT io type for T. */ template <typename T> struct traits; #define PRT_TRAITS_IMPL( type, enumVal ) \ template <> \ struct traits< type >{ \ inline static enum_t data_type(){ \ return enumVal; \ } \ }; PRT_TRAITS_IMPL( int8_t , type_int8 ); PRT_TRAITS_IMPL( int16_t, type_int16 ); PRT_TRAITS_IMPL( int32_t, type_int32 ); PRT_TRAITS_IMPL( int64_t, type_int64 ); PRT_TRAITS_IMPL( uint8_t , type_uint8 ); PRT_TRAITS_IMPL( uint16_t, type_uint16 ); PRT_TRAITS_IMPL( uint32_t, type_uint32 ); PRT_TRAITS_IMPL( uint64_t, type_uint64 ); PRT_TRAITS_IMPL( float16_t, type_float16 ); PRT_TRAITS_IMPL( float32_t, type_float32 ); PRT_TRAITS_IMPL( float64_t, type_float64 ); #if defined(WIN32) || defined(_WIN64) //Windows treats long and int as separate types. PRT_TRAITS_IMPL( long, type_int32 ); PRT_TRAITS_IMPL( unsigned long, type_uint32 ); #endif #undef PRT_TRAITS_IMPL /** * Extracts a data_type::enum_t from a string representation. */ inline std::pair<enum_t,std::size_t> parse_data_type( const std::string& typeString ){ std::string::const_iterator it = typeString.begin(), itEnd = typeString.end(); //Skip beginning whitespace for( ; it != itEnd && std::isspace(*it); ++it ) ; //The type comes first, ending at whitespace or a [ bracket. std::string::const_iterator typeStart = it; for( ; it != itEnd && !std::isspace(*it) && (*it) != '['; ++it ) ; std::string::const_iterator typeEnd = it; if( it == itEnd ) throw std::runtime_error( "Invalid data type string: \"" + typeString + "\"" ); //Skip whitespace until an open bracket. for( ; it != itEnd && std::isspace(*it); ++it ) ; //Make sure we closed the arity in brackets correctly if( it == itEnd || (*it) != '[' ) throw std::runtime_error( "Invalid data type string: \"" + typeString + "\"" ); std::string::const_iterator arityStart = ++it; for( ; it != itEnd && std::isdigit(*it); ++it ) ; if( it == itEnd || (*it) != ']' || ++it != itEnd ) throw std::runtime_error( "Invalid data type string: \"" + typeString + "\"" ); enum_t resultType = type_count; std::size_t resultArity = 0; for( int i = 0, iEnd = type_count; i < iEnd && resultType == type_count; ++i ){ if( std::strncmp( names[i], &*typeStart, (typeEnd - typeStart) ) == 0 ) resultType = static_cast<enum_t>( i ); } resultArity = static_cast<std::size_t>( atoi( &*arityStart ) ); return std::make_pair( resultType, resultArity ); } }//namespace data_types }//namespace prtio <|endoftext|>
<commit_before>#include <ros/ros.h> #include <opencv/cv.h> #include <opencv/highgui.h> #include <opencv/cxcore.h> #include <std_msgs/Float64.h> #include <std_msgs/String.h> #include <scan2image/ScanImage.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <sensor_msgs/LaserScan.h> #include <algorithm> #include "scan2image.h" #include "calibration_camera_lidar/projection_matrix.h" #include <sensor_msgs/CameraInfo.h> #if 1 // AXE #define XSTR(x) #x #define STR(x) XSTR(x) #endif static cv::Mat cameraExtrinsicMat; static cv::Mat cameraMat; static cv::Mat distCoeff; static cv::Size imageSize; ros::Publisher transformed_point_data; static bool isProjection; static bool isIntrinsic; Scan_image scan_image; void trans_depth_points_to_image_points(Scan_points_dataset* scan_points_dataset, Image_points_dataset* image_points_dataset) { float camera_x; float camera_y; float camera_z; int i; for(i = 0; i < (int)scan_points_dataset->scan_points.x.size(); i++) { /* * Coordinate transformation. Change from laser range finder coordinate to camera coordinate */ camera_x = (cameraExtrinsicMat.at<double>(0,0) * scan_points_dataset->scan_points.x.at(i)*1000 + cameraExtrinsicMat.at<double>(0,1) * scan_points_dataset->scan_points.y.at(i)*1000 + cameraExtrinsicMat.at<double>(0,2) * scan_points_dataset->scan_points.z.at(i)*1000) + (cameraExtrinsicMat.at<double>(0,3)); camera_y = (cameraExtrinsicMat.at<double>(1,0) * scan_points_dataset->scan_points.x.at(i)*1000 + cameraExtrinsicMat.at<double>(1,1) * scan_points_dataset->scan_points.y.at(i)*1000 + cameraExtrinsicMat.at<double>(1,2) * scan_points_dataset->scan_points.z.at(i)*1000) + (cameraExtrinsicMat.at<double>(1,3)); camera_z = (cameraExtrinsicMat.at<double>(2,0) * scan_points_dataset->scan_points.x.at(i)*1000 + cameraExtrinsicMat.at<double>(2,1) * scan_points_dataset->scan_points.y.at(i)*1000 + cameraExtrinsicMat.at<double>(2,2) * scan_points_dataset->scan_points.z.at(i)*1000) + (cameraExtrinsicMat.at<double>(2,3)); if (camera_z >= 0.0) { /* * Projection transformation. Change from camera coordinate to image coordinate */ image_points_dataset->image_points.x.push_back((camera_x * cameraMat.at<double>(0,0) / camera_z) + cameraMat.at<double>(0,2)); image_points_dataset->image_points.y.push_back((camera_y * cameraMat.at<double>(1,1) / camera_z) + cameraMat.at<double>(1,2)); /* * Calculate euclidean distance from the camera to objects */ image_points_dataset->distance.push_back(sqrt(camera_x * camera_x + camera_y * camera_y + camera_z * camera_z) * 100); //unit of length is centimeter /* * Copy to intensity */ if(!(scan_points_dataset->intensity.empty())){ image_points_dataset->intensity.push_back(scan_points_dataset->intensity.at(i)); } } } } static void projection_callback(const calibration_camera_lidar::projection_matrix& msg) { printf("projection\n"); cameraExtrinsicMat = cv::Mat(4,4,CV_64F); for (int row=0; row<4; row++) { for (int col=0; col<4; col++) { cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col]; printf("%f\t", cameraExtrinsicMat.at<double>(row, col)); } printf("\n"); } isProjection = true; } static void intrinsic_callback(const sensor_msgs::CameraInfo& msg) { printf("intrinsic\n"); if (!isIntrinsic || imageSize.height != msg.height || imageSize.width != msg.width) { if (isIntrinsic) { free(scan_image.distance); free(scan_image.intensity); } scan_image.distance = (float *)calloc(msg.height * msg.width, sizeof(float)); scan_image.intensity = (float *)calloc(msg.height * msg.width, sizeof(float)); scan_image.max_y = NO_DATA; scan_image.min_y = NO_DATA; } imageSize.height = msg.height; imageSize.width = msg.width; cameraMat = cv::Mat(3,3, CV_64F); for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { cameraMat.at<double>(row, col) = msg.K[row * 3 + col]; printf("%f\t", cameraMat.at<double>(row, col)); } printf("\n"); } distCoeff = cv::Mat(1,5,CV_64F); for (int col=0; col<5; col++) { distCoeff.at<double>(col) = msg.D[col]; } isIntrinsic = true; } void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg) { if (!(isIntrinsic && isProjection)){ return; } static Scan_points_dataset scan_points_dataset; static Image_points_dataset image_points_dataset; static int i; static int count; static int stored_num[MAX_IMAGE_WIDTH * MAX_IMAGE_HEIGHT]; // ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max); /* * Initialize */ scan_points_dataset.scan_points.x.resize(msg->ranges.size()); scan_points_dataset.scan_points.y.resize(msg->ranges.size()); scan_points_dataset.scan_points.z.resize(msg->ranges.size()); scan_points_dataset.intensity.resize(msg->intensities.size()); image_points_dataset.image_points.x.clear(); image_points_dataset.image_points.y.clear(); image_points_dataset.distance.clear(); image_points_dataset.intensity.clear(); count = 0; /* * Change to three dimentional coordinate. And copy intensity */ for(i = 0; i < (int)msg->ranges.size(); i++) { scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter if(!(msg->intensities.empty())){ scan_points_dataset.intensity.at(i) = msg->intensities.at(i); } } /* * Change from laser range finder coordinate to image coordinate */ trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset); /* * Judge out of image frame. And Determine max_y and min_y */ for (i = 0, count = 0; i < (int)image_points_dataset.image_points.x.size(); i++) { /* Judge NaN */ if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) { std::cout <<"Not a Number is i:" << i << std::endl; continue; } /* Judge out of X-axis image */ if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) { continue; } /* Judge out of Y-axis image */ if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) { continue; } scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i); if(!msg->intensities.empty()){ scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i); } if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) { scan_image.max_y = (int)image_points_dataset.image_points.y.at(i); } else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) { scan_image.min_y = (int)image_points_dataset.image_points.y.at(i); } /* for init zero */ stored_num[count] = (int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i); count++; } /* * Create message(Topic) */ scan2image::ScanImage scan_image_msg; scan_image_msg.header = msg->header; scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height); scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height); scan_image_msg.max_y = scan_image.max_y; scan_image_msg.min_y = scan_image.min_y; /* * Publish message(Topic) */ transformed_point_data.publish(scan_image_msg); /* * Init zero */ for (i = 0; i < count; ++i) { scan_image.distance[stored_num[i]] = 0; } scan_image.max_y = NO_DATA; scan_image.min_y = NO_DATA; } int main(int argc, char **argv) { isProjection = false; isIntrinsic = false; ros::init(argc, argv, "scan2image"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("scan", 1, scanCallback); ros::Subscriber projection_sub = n.subscribe("projection_matrix", 1, projection_callback); ros::Subscriber intrinsic_sub = n.subscribe("camera/camera_info", 1, intrinsic_callback); transformed_point_data = n.advertise<scan2image::ScanImage>("scan_image", 1); ros::spin(); free(scan_image.distance); free(scan_image.intensity); return 0; } <commit_msg>change from static variable to auto variable<commit_after>#include <ros/ros.h> #include <opencv/cv.h> #include <opencv/highgui.h> #include <opencv/cxcore.h> #include <std_msgs/Float64.h> #include <std_msgs/String.h> #include <scan2image/ScanImage.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <sensor_msgs/LaserScan.h> #include <algorithm> #include "scan2image.h" #include "calibration_camera_lidar/projection_matrix.h" #include <sensor_msgs/CameraInfo.h> #if 1 // AXE #define XSTR(x) #x #define STR(x) XSTR(x) #endif static cv::Mat cameraExtrinsicMat; static cv::Mat cameraMat; static cv::Mat distCoeff; static cv::Size imageSize; ros::Publisher transformed_point_data; static bool isProjection; static bool isIntrinsic; Scan_image scan_image; void trans_depth_points_to_image_points(Scan_points_dataset* scan_points_dataset, Image_points_dataset* image_points_dataset) { float camera_x; float camera_y; float camera_z; int i; for(i = 0; i < (int)scan_points_dataset->scan_points.x.size(); i++) { /* * Coordinate transformation. Change from laser range finder coordinate to camera coordinate */ camera_x = (cameraExtrinsicMat.at<double>(0,0) * scan_points_dataset->scan_points.x.at(i)*1000 + cameraExtrinsicMat.at<double>(0,1) * scan_points_dataset->scan_points.y.at(i)*1000 + cameraExtrinsicMat.at<double>(0,2) * scan_points_dataset->scan_points.z.at(i)*1000) + (cameraExtrinsicMat.at<double>(0,3)); camera_y = (cameraExtrinsicMat.at<double>(1,0) * scan_points_dataset->scan_points.x.at(i)*1000 + cameraExtrinsicMat.at<double>(1,1) * scan_points_dataset->scan_points.y.at(i)*1000 + cameraExtrinsicMat.at<double>(1,2) * scan_points_dataset->scan_points.z.at(i)*1000) + (cameraExtrinsicMat.at<double>(1,3)); camera_z = (cameraExtrinsicMat.at<double>(2,0) * scan_points_dataset->scan_points.x.at(i)*1000 + cameraExtrinsicMat.at<double>(2,1) * scan_points_dataset->scan_points.y.at(i)*1000 + cameraExtrinsicMat.at<double>(2,2) * scan_points_dataset->scan_points.z.at(i)*1000) + (cameraExtrinsicMat.at<double>(2,3)); if (camera_z >= 0.0) { /* * Projection transformation. Change from camera coordinate to image coordinate */ image_points_dataset->image_points.x.push_back((camera_x * cameraMat.at<double>(0,0) / camera_z) + cameraMat.at<double>(0,2)); image_points_dataset->image_points.y.push_back((camera_y * cameraMat.at<double>(1,1) / camera_z) + cameraMat.at<double>(1,2)); /* * Calculate euclidean distance from the camera to objects */ image_points_dataset->distance.push_back(sqrt(camera_x * camera_x + camera_y * camera_y + camera_z * camera_z) * 100); //unit of length is centimeter /* * Copy to intensity */ if(!(scan_points_dataset->intensity.empty())){ image_points_dataset->intensity.push_back(scan_points_dataset->intensity.at(i)); } } } } static void projection_callback(const calibration_camera_lidar::projection_matrix& msg) { printf("projection\n"); cameraExtrinsicMat = cv::Mat(4,4,CV_64F); for (int row=0; row<4; row++) { for (int col=0; col<4; col++) { cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col]; printf("%f\t", cameraExtrinsicMat.at<double>(row, col)); } printf("\n"); } isProjection = true; } static void intrinsic_callback(const sensor_msgs::CameraInfo& msg) { printf("intrinsic\n"); if (!isIntrinsic || imageSize.height != msg.height || imageSize.width != msg.width) { if (isIntrinsic) { free(scan_image.distance); free(scan_image.intensity); } scan_image.distance = (float *)calloc(msg.height * msg.width, sizeof(float)); scan_image.intensity = (float *)calloc(msg.height * msg.width, sizeof(float)); scan_image.max_y = NO_DATA; scan_image.min_y = NO_DATA; } imageSize.height = msg.height; imageSize.width = msg.width; cameraMat = cv::Mat(3,3, CV_64F); for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { cameraMat.at<double>(row, col) = msg.K[row * 3 + col]; printf("%f\t", cameraMat.at<double>(row, col)); } printf("\n"); } distCoeff = cv::Mat(1,5,CV_64F); for (int col=0; col<5; col++) { distCoeff.at<double>(col) = msg.D[col]; } isIntrinsic = true; } void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg) { if (!(isIntrinsic && isProjection)){ return; } static Scan_points_dataset scan_points_dataset; static Image_points_dataset image_points_dataset; static int stored_num[MAX_IMAGE_WIDTH * MAX_IMAGE_HEIGHT]; int i; int count; // ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max); /* * Initialize */ scan_points_dataset.scan_points.x.resize(msg->ranges.size()); scan_points_dataset.scan_points.y.resize(msg->ranges.size()); scan_points_dataset.scan_points.z.resize(msg->ranges.size()); scan_points_dataset.intensity.resize(msg->intensities.size()); image_points_dataset.image_points.x.clear(); image_points_dataset.image_points.y.clear(); image_points_dataset.distance.clear(); image_points_dataset.intensity.clear(); count = 0; /* * Change to three dimentional coordinate. And copy intensity */ for(i = 0; i < (int)msg->ranges.size(); i++) { scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter if(!(msg->intensities.empty())){ scan_points_dataset.intensity.at(i) = msg->intensities.at(i); } } /* * Change from laser range finder coordinate to image coordinate */ trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset); /* * Judge out of image frame. And Determine max_y and min_y */ for (i = 0, count = 0; i < (int)image_points_dataset.image_points.x.size(); i++) { /* Judge NaN */ if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) { std::cout <<"Not a Number is i:" << i << std::endl; continue; } /* Judge out of X-axis image */ if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) { continue; } /* Judge out of Y-axis image */ if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) { continue; } scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i); if(!msg->intensities.empty()){ scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i); } if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) { scan_image.max_y = (int)image_points_dataset.image_points.y.at(i); } else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) { scan_image.min_y = (int)image_points_dataset.image_points.y.at(i); } /* for init zero */ stored_num[count] = (int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i); count++; } /* * Create message(Topic) */ scan2image::ScanImage scan_image_msg; scan_image_msg.header = msg->header; scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height); scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height); scan_image_msg.max_y = scan_image.max_y; scan_image_msg.min_y = scan_image.min_y; /* * Publish message(Topic) */ transformed_point_data.publish(scan_image_msg); /* * Init zero */ for (i = 0; i < count; ++i) { scan_image.distance[stored_num[i]] = 0; } scan_image.max_y = NO_DATA; scan_image.min_y = NO_DATA; } int main(int argc, char **argv) { isProjection = false; isIntrinsic = false; ros::init(argc, argv, "scan2image"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("scan", 1, scanCallback); ros::Subscriber projection_sub = n.subscribe("projection_matrix", 1, projection_callback); ros::Subscriber intrinsic_sub = n.subscribe("camera/camera_info", 1, intrinsic_callback); transformed_point_data = n.advertise<scan2image::ScanImage>("scan_image", 1); ros::spin(); free(scan_image.distance); free(scan_image.intensity); return 0; } <|endoftext|>
<commit_before>//============================================================================== // Main source file //============================================================================== #include <QCoreApplication> #include <QMap> #include <QProcess> #include <QString> //============================================================================== #include <iostream> //============================================================================== typedef QMap<QString, QStringList> Tests; //============================================================================== int main(int pArgc, char *pArgv[]) { // Retrieve the different arguments that were passed QStringList args = QStringList(); for (int i = 1; i < pArgc; ++i) args << pArgv[i]; // The different tests that are to be run Tests tests; tests["CellMLSupport"] = QStringList() << "test"; // Run the different tests QString exePath = QCoreApplication(pArgc, pArgv).applicationDirPath(); QStringList failedTests = QStringList(); int res = 0; Tests::const_iterator iter = tests.constBegin(); while (iter != tests.constEnd()) { if (iter != tests.constBegin()) { std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; } std::cout << "********* " << qPrintable(iter.key()) << " *********" << std::endl; std::cout << std::endl; foreach (const QString &test, iter.value()) { QString testName = QString("%1_%2").arg(iter.key(), test); // On Linux and Mac OS X, if we want to load plugins, we must // execute the test from the directory where the test is, so... ::chdir(qPrintable(exePath)); // Execute the test itself int testRes = QProcess::execute(QString("%1/%2").arg(exePath, testName), args); if (testRes) failedTests << testName; res = res?res:testRes; std::cout << std::endl; } std::cout << qPrintable(QString("*").repeated(9+1+iter.key().count()+1+9)) << std::endl; ++iter; } // Reporting std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << "********* Reporting *********" << std::endl; std::cout << std::endl; if (failedTests.isEmpty()) { std::cout << "All the tests passed!" << std::endl; } else { if (failedTests.count() == 1) std::cout << "The following test failed:" << std::endl; else std::cout << "The following tests failed:" << std::endl; foreach (const QString &failedTest, failedTests) std::cout << " - " << qPrintable(failedTest) << std::endl; } std::cout << std::endl; std::cout << "*****************************" << std::endl; // Return the overall outcome of the tests return res; } //============================================================================== // End of file //============================================================================== <commit_msg>Fixed an issue (which I thought didn't exist) with regards to the running of tests.<commit_after>//============================================================================== // Main source file //============================================================================== #include <QCoreApplication> #include <QMap> #include <QProcess> #include <QString> //============================================================================== #include <iostream> //============================================================================== typedef QMap<QString, QStringList> Tests; //============================================================================== int main(int pArgc, char *pArgv[]) { // Retrieve the different arguments that were passed QStringList args = QStringList(); for (int i = 1; i < pArgc; ++i) args << pArgv[i]; // The different tests that are to be run Tests tests; tests["CellMLSupport"] = QStringList() << "test"; // Run the different tests QString exePath = QCoreApplication(pArgc, pArgv).applicationDirPath(); QStringList failedTests = QStringList(); int res = 0; Tests::const_iterator iter = tests.constBegin(); while (iter != tests.constEnd()) { if (iter != tests.constBegin()) { std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; } std::cout << "********* " << qPrintable(iter.key()) << " *********" << std::endl; std::cout << std::endl; foreach (const QString &test, iter.value()) { QString testName = QString("%1_%2").arg(iter.key(), test); // On Linux and Mac OS X, if we want to load plugins, we must // execute the test from the directory where the test is, so... #ifndef Q_WS_WIN ::chdir(qPrintable(exePath)); #endif // Execute the test itself int testRes = QProcess::execute(QString("%1/%2").arg(exePath, testName), args); if (testRes) failedTests << testName; res = res?res:testRes; std::cout << std::endl; } std::cout << qPrintable(QString("*").repeated(9+1+iter.key().count()+1+9)) << std::endl; ++iter; } // Reporting std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << "********* Reporting *********" << std::endl; std::cout << std::endl; if (failedTests.isEmpty()) { std::cout << "All the tests passed!" << std::endl; } else { if (failedTests.count() == 1) std::cout << "The following test failed:" << std::endl; else std::cout << "The following tests failed:" << std::endl; foreach (const QString &failedTest, failedTests) std::cout << " - " << qPrintable(failedTest) << std::endl; } std::cout << std::endl; std::cout << "*****************************" << std::endl; // Return the overall outcome of the tests return res; } //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <commit_msg>initialize random number generator for tests<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <|endoftext|>
<commit_before>#include "fly/logger/styler.hpp" #include "fly/types/string/string.hpp" // clang-format off // Due to a missing #include in catch_reporter_registrars.hpp, this must be included first. #include "catch2/interfaces/catch_interfaces_reporter.hpp" // clang-format on #include "catch2/catch_reporter_registrars.hpp" #include "catch2/catch_session.hpp" #include "catch2/catch_test_case_info.hpp" #include "catch2/reporters/catch_reporter_console.hpp" #include <chrono> #include <cstdint> #include <string> #include <vector> /** * A Catch2 test reporter for reporting colorful test and section names to console. */ class FlyReporter : public Catch::ConsoleReporter { public: explicit FlyReporter(const Catch::ReporterConfig &config) : Catch::ConsoleReporter(config) { } ~FlyReporter() override = default; static std::string getDescription() { return "Catch2 test reporter for libfly"; } void testRunStarting(const Catch::TestRunInfo &info) override { Catch::ConsoleReporter::testRunStarting(info); m_test_start = std::chrono::steady_clock::now(); } void testRunEnded(const Catch::TestRunStats &stats) override { Catch::ConsoleReporter::testRunEnded(stats); const auto end = std::chrono::steady_clock::now(); const auto duration = std::chrono::duration<double>(end - m_test_start); // ConsoleReporter prints a second newline above, so go up one line before logging the time. stream << fly::logger::Styler( fly::logger::Cursor::Up, fly::logger::Style::Bold, fly::logger::Color::Cyan) << "Total time "; stream << fly::String::format("{:.3f} seconds\n\n", duration.count()); } void testCaseStarting(const Catch::TestCaseInfo &info) override { Catch::ConsoleReporter::testCaseStarting(info); stream_header(fly::logger::Color::Green, fly::String::format("{} Test", info.name)); m_current_test_case_start = std::chrono::steady_clock::now(); } void sectionStarting(const Catch::SectionInfo &info) override { Catch::ConsoleReporter::sectionStarting(info); std::size_t level = m_section_level++; if (level == 0) { m_sections.push_back(info.name); return; } auto path = fly::String::join('/', m_sections.back(), info.name); if (auto it = std::find(m_sections.begin(), m_sections.end(), path); it != m_sections.end()) { std::swap(*it, *(m_sections.end() - 1)); return; } const fly::logger::Styler style(fly::logger::Color::Cyan, fly::logger::Style::Italic); stream << style << "[ "; if (level != 1) { stream << fly::String::format("{: >{}}└─➤ ", "", (level - 2) * 4); } stream << fly::String::format("{} ]\n", info.name); m_sections.push_back(std::move(path)); } void sectionEnded(const Catch::SectionStats &stats) override { Catch::ConsoleReporter::sectionEnded(stats); --m_section_level; } void testCaseEnded(const Catch::TestCaseStats &stats) override { Catch::ConsoleReporter::testCaseEnded(stats); const auto end = std::chrono::steady_clock::now(); const auto duration = std::chrono::duration<double>(end - m_current_test_case_start); const std::string &name = stats.testInfo->name; if (stats.totals.assertions.allOk()) { stream_header( fly::logger::Color::Green, fly::String::format("PASSED {} ({:.3f} seconds)", name, duration.count())); } else { stream_header( fly::logger::Color::Red, fly::String::format("FAILED {} ({:.3f} seconds)", name, duration.count())); } stream << '\n'; m_sections.clear(); } private: void stream_header(fly::logger::Color::StandardColor color, std::string message) { stream << fly::logger::Styler(fly::logger::Style::Bold, color) << fly::String::format("[==== {} ====]\n", message); } std::chrono::steady_clock::time_point m_test_start; std::chrono::steady_clock::time_point m_current_test_case_start; std::vector<std::string> m_sections; std::size_t m_section_level {0}; }; CATCH_REGISTER_REPORTER("libfly", FlyReporter) int main(int argc, char **argv) { return Catch::Session().run(argc, argv); } <commit_msg>Move libfly Catch2 reporter method definitions out-of-line<commit_after>#include "fly/logger/styler.hpp" #include "fly/types/string/string.hpp" // clang-format off // Due to a missing #include in catch_reporter_registrars.hpp, this must be included first. #include "catch2/interfaces/catch_interfaces_reporter.hpp" // clang-format on #include "catch2/catch_reporter_registrars.hpp" #include "catch2/catch_session.hpp" #include "catch2/catch_test_case_info.hpp" #include "catch2/reporters/catch_reporter_console.hpp" #include <chrono> #include <cstdint> #include <string> #include <vector> /** * A Catch2 test reporter for reporting colorful test and section names to console. */ class FlyReporter : public Catch::ConsoleReporter { public: explicit FlyReporter(const Catch::ReporterConfig &config); ~FlyReporter() override = default; static std::string getDescription(); void testRunStarting(const Catch::TestRunInfo &info) override; void testCaseStarting(const Catch::TestCaseInfo &info) override; void sectionStarting(const Catch::SectionInfo &info) override; void sectionEnded(const Catch::SectionStats &stats) override; void testCaseEnded(const Catch::TestCaseStats &stats) override; void testRunEnded(const Catch::TestRunStats &stats) override; private: void stream_header(fly::logger::Color::StandardColor color, std::string message); std::chrono::steady_clock::time_point m_test_start; std::chrono::steady_clock::time_point m_current_test_case_start; std::vector<std::string> m_sections; std::size_t m_section_level {0}; }; //================================================================================================== FlyReporter::FlyReporter(const Catch::ReporterConfig &config) : Catch::ConsoleReporter(config) { } //================================================================================================== std::string FlyReporter::getDescription() { return "Catch2 test reporter for libfly"; } //================================================================================================== void FlyReporter::testRunStarting(const Catch::TestRunInfo &info) { Catch::ConsoleReporter::testRunStarting(info); m_test_start = std::chrono::steady_clock::now(); } //================================================================================================== void FlyReporter::testCaseStarting(const Catch::TestCaseInfo &info) { Catch::ConsoleReporter::testCaseStarting(info); stream_header(fly::logger::Color::Green, fly::String::format("{} Test", info.name)); m_current_test_case_start = std::chrono::steady_clock::now(); } //================================================================================================== void FlyReporter::sectionStarting(const Catch::SectionInfo &info) { Catch::ConsoleReporter::sectionStarting(info); std::size_t level = m_section_level++; if (level == 0) { m_sections.push_back(info.name); return; } auto section = fly::String::join('/', m_sections.back(), info.name); if (auto it = std::find(m_sections.begin(), m_sections.end(), section); it != m_sections.end()) { std::swap(*it, *(m_sections.end() - 1)); return; } const fly::logger::Styler style(fly::logger::Color::Cyan, fly::logger::Style::Italic); stream << style << "[ "; if (level != 1) { stream << fly::String::format("{: >{}}└─➤ ", "", (level - 2) * 4); } stream << fly::String::format("{} ]\n", info.name); m_sections.push_back(std::move(section)); } //================================================================================================== void FlyReporter::sectionEnded(const Catch::SectionStats &stats) { Catch::ConsoleReporter::sectionEnded(stats); --m_section_level; } //================================================================================================== void FlyReporter::testCaseEnded(const Catch::TestCaseStats &stats) { Catch::ConsoleReporter::testCaseEnded(stats); const auto end = std::chrono::steady_clock::now(); const auto duration = std::chrono::duration<double>(end - m_current_test_case_start); const std::string &name = stats.testInfo->name; if (stats.totals.assertions.allOk()) { stream_header( fly::logger::Color::Green, fly::String::format("PASSED {} ({:.3f} seconds)", name, duration.count())); } else { stream_header( fly::logger::Color::Red, fly::String::format("FAILED {} ({:.3f} seconds)", name, duration.count())); } stream << '\n'; m_sections.clear(); } //================================================================================================== void FlyReporter::testRunEnded(const Catch::TestRunStats &stats) { Catch::ConsoleReporter::testRunEnded(stats); const auto end = std::chrono::steady_clock::now(); const auto duration = std::chrono::duration<double>(end - m_test_start); // ConsoleReporter prints a second newline above, so go up one line before logging the time. stream << fly::logger::Styler(fly::logger::Cursor::Up); stream << fly::logger::Styler(fly::logger::Style::Bold, fly::logger::Color::Cyan) << "Total time "; stream << fly::String::format("{:.3f} seconds\n\n", duration.count()); } //================================================================================================== void FlyReporter::stream_header(fly::logger::Color::StandardColor color, std::string message) { stream << fly::logger::Styler(fly::logger::Style::Bold, color) << fly::String::format("[==== {} ====]\n", message); } //================================================================================================== CATCH_REGISTER_REPORTER("libfly", FlyReporter) int main(int argc, char **argv) { return Catch::Session().run(argc, argv); } <|endoftext|>
<commit_before>#include <cassert> #include <cstring> #include <pprintpp.hpp> #define TEST(correct_str, ...) \ assert(!strcmp(AUTOFORMAT(__VA_ARGS__), correct_str)) int main() { TEST("", ""); TEST(" { ", " \\{ "); TEST("{}", "\\{}"); TEST(" { %d } ", " \\{ {} } ", 123); TEST("%p", "{}", nullptr); TEST("%p", "{}", reinterpret_cast<void*>(0)); // For safety reasons: // Only print strings as strings, if the user also writes {s} TEST("%p", "{}", "str"); TEST("%s", "{s}", "str"); TEST("%c", "{}", static_cast<char>(123)); TEST("%d", "{}", static_cast<short>(123)); TEST("%d", "{}", 123); TEST("%ld", "{}", 123l); TEST("%lld", "{}", 123ll); TEST("%u", "{}", 123u); TEST("%lu", "{}", 123ul); TEST("%llu", "{}", 123ull); TEST("%x", "{x}", 123u); TEST("%lx", "{x}", 123ul); TEST("%llx", "{x}", 123ull); TEST("%f", "{}", 1.0f); TEST("%lf", "{}", 1.0); TEST("%10d", "{10}", 123); TEST("%10x", "{10x}", 123u); TEST("%#10x", "{#10x}", 123u); pprintf("Green, green, green! All tests passed.\n"); pprintf("{s} {} {1} {} {} {} {} {} {} {} {} {} {} {} {} {#x}\n", "1",2u,3.0,4.0f,5ull,'6',7ul,8,9,10,11,12,13,14,15,16u); return 0; } <commit_msg>Add <cstdio> to unit test<commit_after>#include <cassert> #include <cstring> #include <cstdio> #include <pprintpp.hpp> #define TEST(correct_str, ...) \ assert(!strcmp(AUTOFORMAT(__VA_ARGS__), correct_str)) int main() { TEST("", ""); TEST(" { ", " \\{ "); TEST("{}", "\\{}"); TEST(" { %d } ", " \\{ {} } ", 123); TEST("%p", "{}", nullptr); TEST("%p", "{}", reinterpret_cast<void*>(0)); // For safety reasons: // Only print strings as strings, if the user also writes {s} TEST("%p", "{}", "str"); TEST("%s", "{s}", "str"); TEST("%c", "{}", static_cast<char>(123)); TEST("%d", "{}", static_cast<short>(123)); TEST("%d", "{}", 123); TEST("%ld", "{}", 123l); TEST("%lld", "{}", 123ll); TEST("%u", "{}", 123u); TEST("%lu", "{}", 123ul); TEST("%llu", "{}", 123ull); TEST("%x", "{x}", 123u); TEST("%lx", "{x}", 123ul); TEST("%llx", "{x}", 123ull); TEST("%f", "{}", 1.0f); TEST("%lf", "{}", 1.0); TEST("%10d", "{10}", 123); TEST("%10x", "{10x}", 123u); TEST("%#10x", "{#10x}", 123u); pprintf("Green, green, green! All tests passed.\n"); pprintf("{s} {} {1} {} {} {} {} {} {} {} {} {} {} {} {} {#x}\n", "1",2u,3.0,4.0f,5ull,'6',7ul,8,9,10,11,12,13,14,15,16u); return 0; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include "./catch.hpp" #include "./ReQL.hpp" int main(int argc, char **argv) { int result = Catch::Session().run(argc, argv); try { ReQL::Connection conn; ReQL::db_list({}).filter({ ReQL::func({ 1.0, ReQL::var({1.0}).ne({std::string("rethinkdb")}) }) }).for_each({ ReQL::func({ 2.0, ReQL::var({2.0}).db({}).wait({}) .funcall({ ReQL::func({ 3.0, ReQL::var({2.0}).db_drop({}) }) }) }) }) .run(conn).toVector().clear(); conn.close(); } catch (ReQL::ReQLError &e) { (void)e; } return result; } <commit_msg>Make query explicit.<commit_after>#define CATCH_CONFIG_RUNNER #include "./catch.hpp" #include "./ReQL.hpp" int main(int argc, char **argv) { int result = Catch::Session().run(argc, argv); try { ReQL::Connection conn; ReQL::db_list(std::vector<ReQL::Query>()) .filter(std::vector<ReQL::Query>({ ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>({ReQL::Query(1.0)})), ReQL::var(std::vector<ReQL::Query>({ReQL::Query(1.0)})) .ne(std::vector<ReQL::Query>({ ReQL::Query(std::string("rethinkdb")) })) })) })) .for_each(std::vector<ReQL::Query>({ ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>({ReQL::Query(2.0)})), ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>()), ReQL::db_drop(std::vector<ReQL::Query>({ ReQL::var(std::vector<ReQL::Query>({ReQL::Query(2.0)})) })) })) .funcall(std::vector<ReQL::Query>({ ReQL::db(std::vector<ReQL::Query>({ ReQL::var(std::vector<ReQL::Query>({ReQL::Query(2.0)})) })) .wait(std::vector<ReQL::Query>()) })) })) })) .run(conn).toVector().clear(); conn.close(); } catch (ReQL::ReQLError &e) { (void)e; } return result; } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "lid_allocator.h" #include <vespa/searchlib/common/bitvectoriterator.h> #include <vespa/searchlib/fef/termfieldmatchdataarray.h> #include <vespa/searchlib/fef/matchdata.h> #include <mutex> #include <vespa/log/log.h> LOG_SETUP(".proton.documentmetastore.lid_allocator"); using search::fef::TermFieldMatchDataArray; using search::queryeval::Blueprint; using search::queryeval::FieldSpecBaseList; using search::queryeval::SearchIterator; using search::queryeval::SimpleLeafBlueprint; using vespalib::GenerationHolder; namespace proton::documentmetastore { LidAllocator::LidAllocator(uint32_t size, uint32_t capacity, GenerationHolder &genHolder) : _holdLids(), _freeLids(size, capacity, genHolder, true, false), _usedLids(size, capacity, genHolder, false, true), _pendingHoldLids(size, capacity, genHolder, false, false), _lidFreeListConstructed(false), _activeLids(size, capacity, genHolder, false, false), _numActiveLids(0u) { } LidAllocator::~LidAllocator() = default; LidAllocator::DocId LidAllocator::getFreeLid(DocId lidLimit) { DocId lid = _freeLids.getLowest(); if (lid >= lidLimit) { lid = lidLimit; } else { _freeLids.clearBit(lid); } return lid; } LidAllocator::DocId LidAllocator::peekFreeLid(DocId lidLimit) { DocId lid = _freeLids.getLowest(); if (lid >= lidLimit) { lid = lidLimit; } return lid; } void LidAllocator::ensureSpace(uint32_t newSize, uint32_t newCapacity) { _freeLids.resizeVector(newSize, newCapacity); _usedLids.resizeVector(newSize, newCapacity); _pendingHoldLids.resizeVector(newSize, newCapacity); _activeLids.resizeVector(newSize, newCapacity); } void LidAllocator::unregisterLid(DocId lid) { assert(!_pendingHoldLids.testBit(lid)); if (isFreeListConstructed()) { _pendingHoldLids.setBit(lid); } _usedLids.clearBit(lid); if (_activeLids.testBit(lid)) { _activeLids.clearBit(lid); _numActiveLids.store(_activeLids.count(), std::memory_order_relaxed); } } void LidAllocator::unregister_lids(const std::vector<DocId>& lids) { if (lids.empty()) { return; } auto high = isFreeListConstructed() ? _pendingHoldLids.set_bits(lids) : _pendingHoldLids.assert_not_set_bits(lids); assert(high < _usedLids.size()); _usedLids.clear_bits(lids); assert(high < _activeLids.size()); _activeLids.consider_clear_bits(lids); _numActiveLids.store(_activeLids.count(), std::memory_order_relaxed); } void LidAllocator::moveLidBegin(DocId fromLid, DocId toLid) { (void) fromLid; assert(!_pendingHoldLids.testBit(fromLid)); assert(!_pendingHoldLids.testBit(toLid)); if (isFreeListConstructed()) { assert(!_freeLids.testBit(fromLid)); assert(_freeLids.testBit(toLid)); _freeLids.clearBit(toLid); } } void LidAllocator::moveLidEnd(DocId fromLid, DocId toLid) { if (isFreeListConstructed()) { // old lid must be scheduled for hold by caller _pendingHoldLids.setBit(fromLid); } _usedLids.setBit(toLid); _usedLids.clearBit(fromLid); if (_activeLids.testBit(fromLid)) { _activeLids.setBit(toLid); _activeLids.clearBit(fromLid); } } void LidAllocator::holdLids(const std::vector<DocId> &lids, DocId lidLimit, generation_t currentGeneration) { (void) lidLimit; for (const auto &lid : lids) { assert(lid > 0); assert(holdLidOK(lid, lidLimit)); _pendingHoldLids.clearBit(lid); _holdLids.add(lid, currentGeneration); } } bool LidAllocator::holdLidOK(DocId lid, DocId lidLimit) const { if (_lidFreeListConstructed && lid != 0 && lid < lidLimit && lid < _usedLids.size() && lid < _pendingHoldLids.size() && _pendingHoldLids.testBit(lid)) { return true; } LOG(error, "LidAllocator::holdLidOK(%u, %u): " "_lidFreeListConstructed=%s, " "_usedLids.size()=%d, " "_pendingHoldLids.size()=%d, " "_pendingHoldLids bit=%s", lid, lidLimit, _lidFreeListConstructed ? "true" : "false", (int) _usedLids.size(), (int) _pendingHoldLids.size(), lid < _pendingHoldLids.size() ? (_pendingHoldLids.testBit(lid) ? "true" : "false" ) : "invalid" ); return false; } void LidAllocator::constructFreeList(DocId lidLimit) { assert(!isFreeListConstructed()); _holdLids.clear(); for (uint32_t lid = 1; lid < lidLimit; ++lid) { if (!validLid(lid)) { _freeLids.setBit(lid); } } } namespace { class WhiteListBlueprint : public SimpleLeafBlueprint { private: const search::BitVector &_activeLids; mutable std::mutex _lock; mutable std::vector<search::fef::TermFieldMatchData *> _matchDataVector; SearchIterator::UP createLeafSearch(const TermFieldMatchDataArray &tfmda, bool strict) const override { assert(tfmda.size() == 0); (void) tfmda; return createFilterSearch(strict, FilterConstraint::UPPER_BOUND); } public: WhiteListBlueprint(const search::BitVector &activeLids) : SimpleLeafBlueprint(FieldSpecBaseList()), _activeLids(activeLids), _matchDataVector() { size_t numHits = _activeLids.countTrueBits(); setEstimate(HitEstimate(numHits, (numHits == 0))); } bool isWhiteList() const override { return true; } SearchIterator::UP createFilterSearch(bool strict, FilterConstraint) const override { auto tfmd = new search::fef::TermFieldMatchData; { std::lock_guard<std::mutex> lock(_lock); _matchDataVector.push_back(tfmd); } return search::BitVectorIterator::create(&_activeLids, get_docid_limit(), *tfmd, strict); } ~WhiteListBlueprint() { for (auto matchData : _matchDataVector) { delete matchData; } } }; } Blueprint::UP LidAllocator::createWhiteListBlueprint() const { return std::make_unique<WhiteListBlueprint>(_activeLids.getBitVector()); } void LidAllocator::updateActiveLids(DocId lid, bool active) { bool oldActive = _activeLids.testBit(lid); if (oldActive != active) { if (active) { _activeLids.setBit(lid); } else { _activeLids.clearBit(lid); } _numActiveLids.store(_activeLids.count(), std::memory_order_relaxed); } } void LidAllocator::clearDocs(DocId lidLow, DocId lidLimit) { (void) lidLow; (void) lidLimit; assert(_usedLids.getNextTrueBit(lidLow) >= lidLimit); } void LidAllocator::shrinkLidSpace(DocId committedDocIdLimit) { ensureSpace(committedDocIdLimit, committedDocIdLimit); } } <commit_msg>Revert "Count number of bits to create a better estimate of number of hits it…"<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "lid_allocator.h" #include <vespa/searchlib/common/bitvectoriterator.h> #include <vespa/searchlib/fef/termfieldmatchdataarray.h> #include <vespa/searchlib/fef/matchdata.h> #include <mutex> #include <vespa/log/log.h> LOG_SETUP(".proton.documentmetastore.lid_allocator"); using search::fef::TermFieldMatchDataArray; using search::queryeval::Blueprint; using search::queryeval::FieldSpecBaseList; using search::queryeval::SearchIterator; using search::queryeval::SimpleLeafBlueprint; using vespalib::GenerationHolder; namespace proton::documentmetastore { LidAllocator::LidAllocator(uint32_t size, uint32_t capacity, GenerationHolder &genHolder) : _holdLids(), _freeLids(size, capacity, genHolder, true, false), _usedLids(size, capacity, genHolder, false, true), _pendingHoldLids(size, capacity, genHolder, false, false), _lidFreeListConstructed(false), _activeLids(size, capacity, genHolder, false, false), _numActiveLids(0u) { } LidAllocator::~LidAllocator() = default; LidAllocator::DocId LidAllocator::getFreeLid(DocId lidLimit) { DocId lid = _freeLids.getLowest(); if (lid >= lidLimit) { lid = lidLimit; } else { _freeLids.clearBit(lid); } return lid; } LidAllocator::DocId LidAllocator::peekFreeLid(DocId lidLimit) { DocId lid = _freeLids.getLowest(); if (lid >= lidLimit) { lid = lidLimit; } return lid; } void LidAllocator::ensureSpace(uint32_t newSize, uint32_t newCapacity) { _freeLids.resizeVector(newSize, newCapacity); _usedLids.resizeVector(newSize, newCapacity); _pendingHoldLids.resizeVector(newSize, newCapacity); _activeLids.resizeVector(newSize, newCapacity); } void LidAllocator::unregisterLid(DocId lid) { assert(!_pendingHoldLids.testBit(lid)); if (isFreeListConstructed()) { _pendingHoldLids.setBit(lid); } _usedLids.clearBit(lid); if (_activeLids.testBit(lid)) { _activeLids.clearBit(lid); _numActiveLids.store(_activeLids.count(), std::memory_order_relaxed); } } void LidAllocator::unregister_lids(const std::vector<DocId>& lids) { if (lids.empty()) { return; } auto high = isFreeListConstructed() ? _pendingHoldLids.set_bits(lids) : _pendingHoldLids.assert_not_set_bits(lids); assert(high < _usedLids.size()); _usedLids.clear_bits(lids); assert(high < _activeLids.size()); _activeLids.consider_clear_bits(lids); _numActiveLids.store(_activeLids.count(), std::memory_order_relaxed); } void LidAllocator::moveLidBegin(DocId fromLid, DocId toLid) { (void) fromLid; assert(!_pendingHoldLids.testBit(fromLid)); assert(!_pendingHoldLids.testBit(toLid)); if (isFreeListConstructed()) { assert(!_freeLids.testBit(fromLid)); assert(_freeLids.testBit(toLid)); _freeLids.clearBit(toLid); } } void LidAllocator::moveLidEnd(DocId fromLid, DocId toLid) { if (isFreeListConstructed()) { // old lid must be scheduled for hold by caller _pendingHoldLids.setBit(fromLid); } _usedLids.setBit(toLid); _usedLids.clearBit(fromLid); if (_activeLids.testBit(fromLid)) { _activeLids.setBit(toLid); _activeLids.clearBit(fromLid); } } void LidAllocator::holdLids(const std::vector<DocId> &lids, DocId lidLimit, generation_t currentGeneration) { (void) lidLimit; for (const auto &lid : lids) { assert(lid > 0); assert(holdLidOK(lid, lidLimit)); _pendingHoldLids.clearBit(lid); _holdLids.add(lid, currentGeneration); } } bool LidAllocator::holdLidOK(DocId lid, DocId lidLimit) const { if (_lidFreeListConstructed && lid != 0 && lid < lidLimit && lid < _usedLids.size() && lid < _pendingHoldLids.size() && _pendingHoldLids.testBit(lid)) { return true; } LOG(error, "LidAllocator::holdLidOK(%u, %u): " "_lidFreeListConstructed=%s, " "_usedLids.size()=%d, " "_pendingHoldLids.size()=%d, " "_pendingHoldLids bit=%s", lid, lidLimit, _lidFreeListConstructed ? "true" : "false", (int) _usedLids.size(), (int) _pendingHoldLids.size(), lid < _pendingHoldLids.size() ? (_pendingHoldLids.testBit(lid) ? "true" : "false" ) : "invalid" ); return false; } void LidAllocator::constructFreeList(DocId lidLimit) { assert(!isFreeListConstructed()); _holdLids.clear(); for (uint32_t lid = 1; lid < lidLimit; ++lid) { if (!validLid(lid)) { _freeLids.setBit(lid); } } } namespace { class WhiteListBlueprint : public SimpleLeafBlueprint { private: const search::BitVector &_activeLids; mutable std::mutex _lock; mutable std::vector<search::fef::TermFieldMatchData *> _matchDataVector; SearchIterator::UP createLeafSearch(const TermFieldMatchDataArray &tfmda, bool strict) const override { assert(tfmda.size() == 0); (void) tfmda; return createFilterSearch(strict, FilterConstraint::UPPER_BOUND); } public: WhiteListBlueprint(const search::BitVector &activeLids) : SimpleLeafBlueprint(FieldSpecBaseList()), _activeLids(activeLids), _matchDataVector() { setEstimate(HitEstimate(_activeLids.size(), false)); } bool isWhiteList() const override { return true; } SearchIterator::UP createFilterSearch(bool strict, FilterConstraint) const override { auto tfmd = new search::fef::TermFieldMatchData; { std::lock_guard<std::mutex> lock(_lock); _matchDataVector.push_back(tfmd); } return search::BitVectorIterator::create(&_activeLids, get_docid_limit(), *tfmd, strict); } ~WhiteListBlueprint() { for (auto matchData : _matchDataVector) { delete matchData; } } }; } Blueprint::UP LidAllocator::createWhiteListBlueprint() const { return std::make_unique<WhiteListBlueprint>(_activeLids.getBitVector()); } void LidAllocator::updateActiveLids(DocId lid, bool active) { bool oldActive = _activeLids.testBit(lid); if (oldActive != active) { if (active) { _activeLids.setBit(lid); } else { _activeLids.clearBit(lid); } _numActiveLids.store(_activeLids.count(), std::memory_order_relaxed); } } void LidAllocator::clearDocs(DocId lidLow, DocId lidLimit) { (void) lidLow; (void) lidLimit; assert(_usedLids.getNextTrueBit(lidLow) >= lidLimit); } void LidAllocator::shrinkLidSpace(DocId committedDocIdLimit) { ensureSpace(committedDocIdLimit, committedDocIdLimit); } } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * a simple version of meta state service for development * * Revision history: * 2015-11-04, @imzhenyu ([email protected]), setup the sketch * 2015-11-11, Tianyi WANG, first version done * xxxx-xx-xx, author, fix bug about xxx */ # include "meta_state_service_simple.h" # include <dsn/internal/task.h> # include <stack> # include <utility> namespace dsn { namespace dist { // path: /, /n1/n2, /n1/n2/, /n2/n2/n3 std::string meta_state_service_simple::normalize_path(const std::string& s) { if (s.empty() || s[0] != '/') return ""; if (s.length() > 1 && *s.rbegin() == '/') return s.substr(0, s.length() - 1); return s; } error_code meta_state_service_simple::extract_name_parent_from_path( const std::string& s, /*out*/ std::string& name, /*out*/ std::string& parent ) { auto pos = s.find_last_of('/'); if (pos == std::string::npos) return ERR_INVALID_PARAMETERS; name = s.substr(pos + 1); if (pos > 0) parent = s.substr(0, pos); else parent = "/"; return ERR_OK; } static void __err_cb_bind_and_enqueue( task_ptr lock_task, error_code err, int delay_milliseconds = 0 ) { auto t = dynamic_cast<safe_late_task<meta_state_service::err_callback>*>(lock_task.get()); t->bind_and_enqueue( [&](meta_state_service::err_callback& cb) { return bind(cb, err); }, delay_milliseconds ); } void meta_state_service_simple::write_log(blob&& log_blob, std::function<error_code()> internal_operation, task_ptr task) { _log_lock.lock(); uint64_t log_offset = _offset; _offset += log_blob.length(); auto continuation_task = std::unique_ptr<operation>(new operation(false, [=](bool log_succeed) { dassert(log_succeed, "we cannot handle logging failure now"); __err_cb_bind_and_enqueue(task, internal_operation(), 0); })); auto continuation_task_ptr = continuation_task.get(); _task_queue.emplace(move(continuation_task)); _log_lock.unlock(); file::write( _log, log_blob.buffer_ptr(), log_blob.length(), log_offset, LPC_META_STATE_SERVICE_SIMPLE_INTERNAL, this, [=](error_code err, size_t bytes) { dassert(err == ERR_OK && bytes == log_blob.length(), "we cannot handle logging failure now"); _log_lock.lock(); continuation_task_ptr->done = true; while (!_task_queue.empty()) { if (!_task_queue.front()->done) { break; } _task_queue.front()->cb(true); _task_queue.pop(); } _log_lock.unlock(); } ); } error_code meta_state_service_simple::create_node_internal(const std::string& node, const blob& value) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it != _quick_map.end()) return ERR_NODE_ALREADY_EXIST; std::string name, parent; auto err = extract_name_parent_from_path(path, name, parent); if (err != ERR_OK) { return err; } auto parent_it = _quick_map.find(parent); if (parent_it == _quick_map.end()) return ERR_OBJECT_NOT_FOUND; state_node* n = new state_node(name, parent_it->second, value); parent_it->second->children.insert(quick_map::value_type(name, n)); _quick_map.insert(quick_map::value_type(path, n)); return ERR_OK; } error_code meta_state_service_simple::delete_node_internal(const std::string& node, bool recursive) { auto path = normalize_path(node); if (path == "/") return ERR_INVALID_PARAMETERS; // cannot delete root zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it == _quick_map.end()) return ERR_OBJECT_NOT_FOUND; if (!recursive && !me_it->second->children.empty()) return ERR_INVALID_PARAMETERS; struct delete_state { std::string path; state_node *node; decltype(state_node::children)::iterator next_child_to_delete; }; std::stack<delete_state> delete_stack; delete_stack.push({ path, me_it->second, me_it->second->children.begin() }); for (; !delete_stack.empty();) { auto &node_pair = delete_stack.top(); if (node_pair.node->children.end() == node_pair.next_child_to_delete) { auto delnum = _quick_map.erase(node_pair.path); dassert(delnum == 1, "inconsistent state between quick map and tree"); delete node_pair.node; delete_stack.pop(); } else { auto child_it = node_pair.next_child_to_delete; delete_stack.push({ node_pair.path + "/" + child_it->second->name, child_it->second, child_it->second->children.begin() }); ++node_pair.next_child_to_delete; } } std::string name, parent; auto err = extract_name_parent_from_path(path, name, parent); if (err != ERR_OK) { return err; } auto parent_it = _quick_map.find(parent); dassert(parent_it != _quick_map.end(), "unable to find parent node"); //XXX we cannot delete root, right? auto erase_num = parent_it->second->children.erase(name); dassert(erase_num == 1, "inconsistent state between quick map and tree"); return ERR_OK; } error_code meta_state_service_simple::set_data_internal(const std::string& node, const blob& value) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto it = _quick_map.find(path); if (it == _quick_map.end()) return ERR_OBJECT_NOT_FOUND; it->second->data = value; return ERR_OK; } error_code meta_state_service_simple::initialize(const char* dir) { _offset = 0; std::string log_path = dsn::utils::filesystem::path_combine(dir, "meta_state_service.log"); if (utils::filesystem::file_exists(log_path)) { if (FILE* fd = fopen(log_path.c_str(), "rb")) { for (;;) { log_header header; if (fread(&header, sizeof(log_header), 1, fd) != 1) { break; } if (header.magic != log_header::default_magic) { break; } std::shared_ptr<char> buffer(new char[header.size]); if (fread(buffer.get(), header.size, 1, fd) != 1) { break; } _offset += sizeof(header) + header.size; blob blob_wrapper(buffer, (int)header.size); binary_reader reader(blob_wrapper); int op_type; unmarshall(reader, op_type); switch (static_cast<operation_type>(op_type)) { case operation_type::create_node: { std::string node; blob data; create_node_log::parse(reader, node, data); create_node_internal(node, data).end_tracking(); break; } case operation_type::delete_node: { std::string node; bool recursively_delete; delete_node_log::parse(reader, node, recursively_delete); delete_node_internal(node, recursively_delete).end_tracking(); break; } case operation_type::set_data: { std::string node; blob data; set_data_log::parse(reader, node, data); set_data_internal(node, data).end_tracking(); break; } default: //The log is complete but its content is modified by cosmic ray. This is unacceptable dassert(false, "meta state server log corrupted"); } } fclose(fd); } } _log = dsn_file_open(log_path.c_str(), O_RDWR | O_CREAT | O_BINARY, 0666); if (!_log) { derror("open file failed: %s", log_path.c_str()); return ERR_FILE_OPERATION_FAILED; } return ERR_OK; } task_ptr meta_state_service_simple::create_node( const std::string& node, task_code cb_code, const err_callback& cb_create, const blob& value, clientlet* tracker ) { auto task = tasking::create_late_task(cb_code, cb_create, 0, tracker); write_log( create_node_log::get_log(node, value), [=]{ return create_node_internal(node, value); }, task ); return task; } task_ptr meta_state_service_simple::delete_node( const std::string& node, bool recursively_delete, task_code cb_code, const err_callback& cb_delete, clientlet* tracker) { auto task = tasking::create_late_task(cb_code, cb_delete, 0, tracker); write_log( delete_node_log::get_log(node, recursively_delete), [=] { return delete_node_internal(node, recursively_delete); }, task ); return task; } task_ptr meta_state_service_simple::node_exist( const std::string& node, task_code cb_code, const err_callback& cb_exist, clientlet* tracker) { error_code err; { zauto_lock _(_state_lock); err = _quick_map.find(normalize_path(node)) != _quick_map.end() ? ERR_OK : ERR_PATH_NOT_FOUND; } return tasking::enqueue( cb_code, tracker, [=]() { cb_exist(err); } ); } task_ptr meta_state_service_simple::get_data( const std::string& node, task_code cb_code, const err_value_callback& cb_get_data, clientlet* tracker) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it == _quick_map.end()) { return tasking::enqueue( cb_code, tracker, [=]() { cb_get_data(ERR_OBJECT_NOT_FOUND, {}); } ); } else { auto data_copy = me_it->second->data; return tasking::enqueue( cb_code, tracker, [=]() mutable { cb_get_data(ERR_OK, std::move(data_copy)); } ); } } task_ptr meta_state_service_simple::set_data( const std::string& node, const blob& value, task_code cb_code, const err_callback& cb_set_data, clientlet* tracker) { auto task = tasking::create_late_task(cb_code, cb_set_data, 0, tracker); write_log( set_data_log::get_log(node, value), [=] { return set_data_internal(node, value); }, task ); return task; } task_ptr meta_state_service_simple::get_children( const std::string& node, task_code cb_code, const err_stringv_callback& cb_get_children, clientlet* tracker) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it == _quick_map.end()) { return tasking::enqueue( cb_code, tracker, [=]() { cb_get_children(ERR_OBJECT_NOT_FOUND, {}); } ); } else { std::vector<std::string> result; for (auto &child_pair : me_it->second->children) { result.push_back(child_pair.first); } return tasking::enqueue( cb_code, tracker, [=]() mutable { cb_get_children(ERR_OK, move(result)); } ); } } meta_state_service_simple::~meta_state_service_simple() { dsn_file_close(_log); } } } <commit_msg>using task_ptr instead of auto for return value from create_late_task to avoid non-referenced object<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * a simple version of meta state service for development * * Revision history: * 2015-11-04, @imzhenyu ([email protected]), setup the sketch * 2015-11-11, Tianyi WANG, first version done * xxxx-xx-xx, author, fix bug about xxx */ # include "meta_state_service_simple.h" # include <dsn/internal/task.h> # include <stack> # include <utility> namespace dsn { namespace dist { // path: /, /n1/n2, /n1/n2/, /n2/n2/n3 std::string meta_state_service_simple::normalize_path(const std::string& s) { if (s.empty() || s[0] != '/') return ""; if (s.length() > 1 && *s.rbegin() == '/') return s.substr(0, s.length() - 1); return s; } error_code meta_state_service_simple::extract_name_parent_from_path( const std::string& s, /*out*/ std::string& name, /*out*/ std::string& parent ) { auto pos = s.find_last_of('/'); if (pos == std::string::npos) return ERR_INVALID_PARAMETERS; name = s.substr(pos + 1); if (pos > 0) parent = s.substr(0, pos); else parent = "/"; return ERR_OK; } static void __err_cb_bind_and_enqueue( task_ptr lock_task, error_code err, int delay_milliseconds = 0 ) { auto t = dynamic_cast<safe_late_task<meta_state_service::err_callback>*>(lock_task.get()); t->bind_and_enqueue( [&](meta_state_service::err_callback& cb) { return bind(cb, err); }, delay_milliseconds ); } void meta_state_service_simple::write_log(blob&& log_blob, std::function<error_code()> internal_operation, task_ptr task) { _log_lock.lock(); uint64_t log_offset = _offset; _offset += log_blob.length(); auto continuation_task = std::unique_ptr<operation>(new operation(false, [=](bool log_succeed) { dassert(log_succeed, "we cannot handle logging failure now"); __err_cb_bind_and_enqueue(task, internal_operation(), 0); })); auto continuation_task_ptr = continuation_task.get(); _task_queue.emplace(move(continuation_task)); _log_lock.unlock(); file::write( _log, log_blob.buffer_ptr(), log_blob.length(), log_offset, LPC_META_STATE_SERVICE_SIMPLE_INTERNAL, this, [=](error_code err, size_t bytes) { dassert(err == ERR_OK && bytes == log_blob.length(), "we cannot handle logging failure now"); _log_lock.lock(); continuation_task_ptr->done = true; while (!_task_queue.empty()) { if (!_task_queue.front()->done) { break; } _task_queue.front()->cb(true); _task_queue.pop(); } _log_lock.unlock(); } ); } error_code meta_state_service_simple::create_node_internal(const std::string& node, const blob& value) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it != _quick_map.end()) return ERR_NODE_ALREADY_EXIST; std::string name, parent; auto err = extract_name_parent_from_path(path, name, parent); if (err != ERR_OK) { return err; } auto parent_it = _quick_map.find(parent); if (parent_it == _quick_map.end()) return ERR_OBJECT_NOT_FOUND; state_node* n = new state_node(name, parent_it->second, value); parent_it->second->children.insert(quick_map::value_type(name, n)); _quick_map.insert(quick_map::value_type(path, n)); return ERR_OK; } error_code meta_state_service_simple::delete_node_internal(const std::string& node, bool recursive) { auto path = normalize_path(node); if (path == "/") return ERR_INVALID_PARAMETERS; // cannot delete root zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it == _quick_map.end()) return ERR_OBJECT_NOT_FOUND; if (!recursive && !me_it->second->children.empty()) return ERR_INVALID_PARAMETERS; struct delete_state { std::string path; state_node *node; decltype(state_node::children)::iterator next_child_to_delete; }; std::stack<delete_state> delete_stack; delete_stack.push({ path, me_it->second, me_it->second->children.begin() }); for (; !delete_stack.empty();) { auto &node_pair = delete_stack.top(); if (node_pair.node->children.end() == node_pair.next_child_to_delete) { auto delnum = _quick_map.erase(node_pair.path); dassert(delnum == 1, "inconsistent state between quick map and tree"); delete node_pair.node; delete_stack.pop(); } else { auto child_it = node_pair.next_child_to_delete; delete_stack.push({ node_pair.path + "/" + child_it->second->name, child_it->second, child_it->second->children.begin() }); ++node_pair.next_child_to_delete; } } std::string name, parent; auto err = extract_name_parent_from_path(path, name, parent); if (err != ERR_OK) { return err; } auto parent_it = _quick_map.find(parent); dassert(parent_it != _quick_map.end(), "unable to find parent node"); //XXX we cannot delete root, right? auto erase_num = parent_it->second->children.erase(name); dassert(erase_num == 1, "inconsistent state between quick map and tree"); return ERR_OK; } error_code meta_state_service_simple::set_data_internal(const std::string& node, const blob& value) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto it = _quick_map.find(path); if (it == _quick_map.end()) return ERR_OBJECT_NOT_FOUND; it->second->data = value; return ERR_OK; } error_code meta_state_service_simple::initialize(const char* dir) { _offset = 0; std::string log_path = dsn::utils::filesystem::path_combine(dir, "meta_state_service.log"); if (utils::filesystem::file_exists(log_path)) { if (FILE* fd = fopen(log_path.c_str(), "rb")) { for (;;) { log_header header; if (fread(&header, sizeof(log_header), 1, fd) != 1) { break; } if (header.magic != log_header::default_magic) { break; } std::shared_ptr<char> buffer(new char[header.size]); if (fread(buffer.get(), header.size, 1, fd) != 1) { break; } _offset += sizeof(header) + header.size; blob blob_wrapper(buffer, (int)header.size); binary_reader reader(blob_wrapper); int op_type; unmarshall(reader, op_type); switch (static_cast<operation_type>(op_type)) { case operation_type::create_node: { std::string node; blob data; create_node_log::parse(reader, node, data); create_node_internal(node, data).end_tracking(); break; } case operation_type::delete_node: { std::string node; bool recursively_delete; delete_node_log::parse(reader, node, recursively_delete); delete_node_internal(node, recursively_delete).end_tracking(); break; } case operation_type::set_data: { std::string node; blob data; set_data_log::parse(reader, node, data); set_data_internal(node, data).end_tracking(); break; } default: //The log is complete but its content is modified by cosmic ray. This is unacceptable dassert(false, "meta state server log corrupted"); } } fclose(fd); } } _log = dsn_file_open(log_path.c_str(), O_RDWR | O_CREAT | O_BINARY, 0666); if (!_log) { derror("open file failed: %s", log_path.c_str()); return ERR_FILE_OPERATION_FAILED; } return ERR_OK; } task_ptr meta_state_service_simple::create_node( const std::string& node, task_code cb_code, const err_callback& cb_create, const blob& value, clientlet* tracker ) { task_ptr task = tasking::create_late_task(cb_code, cb_create, 0, tracker); write_log( create_node_log::get_log(node, value), [=]{ return create_node_internal(node, value); }, task ); return task; } task_ptr meta_state_service_simple::delete_node( const std::string& node, bool recursively_delete, task_code cb_code, const err_callback& cb_delete, clientlet* tracker) { task_ptr task = tasking::create_late_task(cb_code, cb_delete, 0, tracker); write_log( delete_node_log::get_log(node, recursively_delete), [=] { return delete_node_internal(node, recursively_delete); }, task ); return task; } task_ptr meta_state_service_simple::node_exist( const std::string& node, task_code cb_code, const err_callback& cb_exist, clientlet* tracker) { error_code err; { zauto_lock _(_state_lock); err = _quick_map.find(normalize_path(node)) != _quick_map.end() ? ERR_OK : ERR_PATH_NOT_FOUND; } return tasking::enqueue( cb_code, tracker, [=]() { cb_exist(err); } ); } task_ptr meta_state_service_simple::get_data( const std::string& node, task_code cb_code, const err_value_callback& cb_get_data, clientlet* tracker) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it == _quick_map.end()) { return tasking::enqueue( cb_code, tracker, [=]() { cb_get_data(ERR_OBJECT_NOT_FOUND, {}); } ); } else { auto data_copy = me_it->second->data; return tasking::enqueue( cb_code, tracker, [=]() mutable { cb_get_data(ERR_OK, std::move(data_copy)); } ); } } task_ptr meta_state_service_simple::set_data( const std::string& node, const blob& value, task_code cb_code, const err_callback& cb_set_data, clientlet* tracker) { task_ptr task = tasking::create_late_task(cb_code, cb_set_data, 0, tracker); write_log( set_data_log::get_log(node, value), [=] { return set_data_internal(node, value); }, task ); return task; } task_ptr meta_state_service_simple::get_children( const std::string& node, task_code cb_code, const err_stringv_callback& cb_get_children, clientlet* tracker) { auto path = normalize_path(node); zauto_lock _(_state_lock); auto me_it = _quick_map.find(path); if (me_it == _quick_map.end()) { return tasking::enqueue( cb_code, tracker, [=]() { cb_get_children(ERR_OBJECT_NOT_FOUND, {}); } ); } else { std::vector<std::string> result; for (auto &child_pair : me_it->second->children) { result.push_back(child_pair.first); } return tasking::enqueue( cb_code, tracker, [=]() mutable { cb_get_children(ERR_OK, move(result)); } ); } } meta_state_service_simple::~meta_state_service_simple() { dsn_file_close(_log); } } } <|endoftext|>
<commit_before>#include "profile.hpp" #include "../../rdb/rdb.hpp" #include "../../utils/utils.hpp" #include <cerrno> static unsigned long nsols; static void dfline(std::vector<std::string>&, void*); int main(int argc, const char *argv[]) { if (argc < 4) fatal("usage: mkprof: <rdb root> <cost bins> <time bins> [key=value*]"); const char *root = argv[1]; printf("root: %s\n", root); errno = 0; char *end; unsigned int ncost = strtol(argv[2], &end, 10); if (end == argv[2]) fatal("Invalid number of cost bins: %s", argv[2]); printf("%u cost bins\n", ncost); unsigned int ntime = strtol(argv[3], &end, 10); if (end == argv[3]) fatal("Invalid number of time bins: %s", argv[3]); printf("%u time bins\n", ntime); RdbAttrs attrs = attrargs(argc-4, argv+4); printf("attributes:\n"); for (auto k = attrs.getkeys().begin(); k != attrs.getkeys().end(); k++) printf("\t%s=%s\n", k->c_str(), attrs.lookup(*k).c_str()); if (!attrs.mem("alg")) fatal("alg attribute must be specified"); std::vector<std::string> paths = withattrs(root, attrs); printf("%lu data files\n", paths.size()); std::vector<AnytimeProfile::SolutionStream> stream; for (auto p = paths.begin(); p != paths.end(); p++) { FILE *f = fopen(p->c_str(), "r"); if (!f) { warnx(errno, "failed to open %s for reading", p->c_str()); continue; } AnytimeProfile::SolutionStream sols; dfread(f, dfline, &sols, NULL); stream.push_back(sols); fclose(f); } printf("%lu solutions\n", nsols); AnytimeProfile prof(ncost, ntime, stream); std::string alg = attrs.lookup("alg"); attrs.rm("alg"); attrs.push_back("alg", alg+".profile"); attrs.push_back("cost bins", argv[2]); attrs.push_back("time bins", argv[3]); std::string opath = pathfor(root, attrs); printf("saving profile to %s\n", opath.c_str()); FILE *f = fopen(opath.c_str(), "w"); if (!f) fatal("failed to open %s for writing", opath.c_str()); prof.save(f); fclose(f); return 0; } static void dfline(std::vector<std::string> &line, void *aux) { AnytimeProfile::SolutionStream *sols = static_cast<AnytimeProfile::SolutionStream*>(aux); // sol is the deprecated altrow name for ARA* // incumbent solutions, incumbent is the new // name. if (line[0] != "#altrow" || (line[1] != "sol" && line[1] != "incumbent")) return; AnytimeProfile::Solution sol; sol.cost = strtod(line[7].c_str(), NULL); sol.time = strtod(line[8].c_str(), NULL); sols->push_back(sol); nsols++; }<commit_msg>mkprof: exit gracefully if there are no solutions.<commit_after>#include "profile.hpp" #include "../../rdb/rdb.hpp" #include "../../utils/utils.hpp" #include <cerrno> static unsigned long nsols; static void dfline(std::vector<std::string>&, void*); int main(int argc, const char *argv[]) { if (argc < 4) fatal("usage: mkprof: <rdb root> <cost bins> <time bins> [key=value*]"); const char *root = argv[1]; printf("root: %s\n", root); errno = 0; char *end; unsigned int ncost = strtol(argv[2], &end, 10); if (end == argv[2]) fatal("Invalid number of cost bins: %s", argv[2]); printf("%u cost bins\n", ncost); unsigned int ntime = strtol(argv[3], &end, 10); if (end == argv[3]) fatal("Invalid number of time bins: %s", argv[3]); printf("%u time bins\n", ntime); RdbAttrs attrs = attrargs(argc-4, argv+4); printf("attributes:\n"); for (auto k = attrs.getkeys().begin(); k != attrs.getkeys().end(); k++) printf("\t%s=%s\n", k->c_str(), attrs.lookup(*k).c_str()); if (!attrs.mem("alg")) fatal("alg attribute must be specified"); std::vector<std::string> paths = withattrs(root, attrs); printf("%lu data files\n", paths.size()); std::vector<AnytimeProfile::SolutionStream> stream; for (auto p = paths.begin(); p != paths.end(); p++) { FILE *f = fopen(p->c_str(), "r"); if (!f) { warnx(errno, "failed to open %s for reading", p->c_str()); continue; } AnytimeProfile::SolutionStream sols; dfread(f, dfline, &sols, NULL); stream.push_back(sols); fclose(f); } printf("%lu solutions\n", nsols); if (nsols == 0) { puts("No solutions"); return 1; } AnytimeProfile prof(ncost, ntime, stream); std::string alg = attrs.lookup("alg"); attrs.rm("alg"); attrs.push_back("alg", alg+".profile"); attrs.push_back("cost bins", argv[2]); attrs.push_back("time bins", argv[3]); std::string opath = pathfor(root, attrs); printf("saving profile to %s\n", opath.c_str()); FILE *f = fopen(opath.c_str(), "w"); if (!f) fatal("failed to open %s for writing", opath.c_str()); prof.save(f); fclose(f); return 0; } static void dfline(std::vector<std::string> &line, void *aux) { AnytimeProfile::SolutionStream *sols = static_cast<AnytimeProfile::SolutionStream*>(aux); // sol is the deprecated altrow name for ARA* // incumbent solutions, incumbent is the new // name. if (line[0] != "#altrow" || (line[1] != "sol" && line[1] != "incumbent")) return; AnytimeProfile::Solution sol; sol.cost = strtod(line[7].c_str(), NULL); sol.time = strtod(line[8].c_str(), NULL); sols->push_back(sol); nsols++; }<|endoftext|>
<commit_before> #include "lest.hpp" #include "z85.h" #include "z85.hpp" using namespace std; void test_nopadding(const char* data, size_t dataSize, const char* text) { const size_t bufSize = 32 * 1024; if (dataSize > bufSize * 0.7) { EXPECT(false); return; } EXPECT(dataSize % 4 == 0); char encodedBuf[bufSize] = {0}; const size_t encodedBytes = Z85_encode(data, encodedBuf, dataSize); EXPECT(encodedBytes % 5 == 0); EXPECT(encodedBytes == (dataSize * 5 / 4)); EXPECT(!strcmp(text, encodedBuf)); char decodedBuf[bufSize] = {0}; const size_t decodedBytes = Z85_decode(encodedBuf, decodedBuf, encodedBytes); EXPECT(decodedBytes % 4 == 0); EXPECT(decodedBytes == dataSize); EXPECT(!memcmp(data, decodedBuf, dataSize)); char encodedBufWithPadding[bufSize] = {0}; const size_t encodedBytesWithPadding = Z85_encode_with_padding(data, encodedBufWithPadding, dataSize); EXPECT(encodedBytes + (encodedBytes ? 1 : 0) == encodedBytesWithPadding); // +one byte for padding count EXPECT(encodedBytesWithPadding == 0 || encodedBufWithPadding[0] == '4'); // nothing should be padded, so 4 count EXPECT(!memcmp(encodedBuf, encodedBufWithPadding + 1, encodedBytes)); char decodedBufWithPadding[bufSize] = {0}; const size_t decodedBytesWithPadding = Z85_decode_with_padding(encodedBufWithPadding, decodedBufWithPadding, encodedBytesWithPadding); EXPECT(decodedBytesWithPadding % 4 == 0); EXPECT(decodedBytesWithPadding == dataSize); EXPECT(!memcmp(data, decodedBufWithPadding, dataSize)); } const lest::test specification[] = { "Hello world!", [] { EXPECT(z85::encode(string("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B")) == "HelloWorld"); }, "Test unsafe", [] { test_nopadding("", 0, ""); test_nopadding("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", 8, "HelloWorld"); test_nopadding("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0" "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7", 32, "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"); }, }; int main() { return lest::run(specification); } <commit_msg>build fix for gcc<commit_after> #include <cstring> #include "lest.hpp" #include "z85.h" #include "z85.hpp" using namespace std; void test_nopadding(const char* data, size_t dataSize, const char* text) { const size_t bufSize = 32 * 1024; if (dataSize > bufSize * 0.7) { EXPECT(false); return; } EXPECT(dataSize % 4 == 0); char encodedBuf[bufSize] = {0}; const size_t encodedBytes = Z85_encode(data, encodedBuf, dataSize); EXPECT(encodedBytes % 5 == 0); EXPECT(encodedBytes == (dataSize * 5 / 4)); EXPECT(!strcmp(text, encodedBuf)); char decodedBuf[bufSize] = {0}; const size_t decodedBytes = Z85_decode(encodedBuf, decodedBuf, encodedBytes); EXPECT(decodedBytes % 4 == 0); EXPECT(decodedBytes == dataSize); EXPECT(!memcmp(data, decodedBuf, dataSize)); char encodedBufWithPadding[bufSize] = {0}; const size_t encodedBytesWithPadding = Z85_encode_with_padding(data, encodedBufWithPadding, dataSize); EXPECT(encodedBytes + (encodedBytes ? 1 : 0) == encodedBytesWithPadding); // +one byte for padding count EXPECT(encodedBytesWithPadding == 0 || encodedBufWithPadding[0] == '4'); // nothing should be padded, so 4 count EXPECT(!memcmp(encodedBuf, encodedBufWithPadding + 1, encodedBytes)); char decodedBufWithPadding[bufSize] = {0}; const size_t decodedBytesWithPadding = Z85_decode_with_padding(encodedBufWithPadding, decodedBufWithPadding, encodedBytesWithPadding); EXPECT(decodedBytesWithPadding % 4 == 0); EXPECT(decodedBytesWithPadding == dataSize); EXPECT(!memcmp(data, decodedBufWithPadding, dataSize)); } const lest::test specification[] = { "Hello world!", [] { EXPECT(z85::encode(string("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B")) == "HelloWorld"); }, "Test unsafe", [] { test_nopadding("", 0, ""); test_nopadding("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", 8, "HelloWorld"); test_nopadding("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0" "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7", 32, "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"); }, }; int main() { return lest::run(specification); } <|endoftext|>
<commit_before><commit_msg>added initial tests for convergence for FinalFluxOrN<commit_after><|endoftext|>
<commit_before>#include "nanovg_addon.h" #include <stb_image.h> #include <iostream> #include <cstring> NanoVGAddon::NanoVGAddon() { name_ = "nanovg"; version_ = "0.0.1"; // TODO: have bootstrap.t prepend the standard truss_message struct onto all addon headers? header_ = R"( /* NanoVG Addon Embedded Header */ typedef struct Addon Addon; typedef struct { unsigned int message_type; unsigned int data_length; unsigned char* data; unsigned int refcount; } truss_message; truss_message* truss_nanovg_load_image(Addon* addon, const char* filename, int* w, int* h, int* n); )"; } const std::string& NanoVGAddon::getName() { return name_; } const std::string& NanoVGAddon::getHeader() { return header_; } const std::string& NanoVGAddon::getVersion() { return version_; } void NanoVGAddon::init(truss::Interpreter* owner) { // nothing special to do } void NanoVGAddon::shutdown() { // nothing to do here either } void NanoVGAddon::update(double dt) { // no updates } // loads an image truss_message* NanoVGAddon::loadImage(const char* filename, int& width, int& height, int& numChannels) { std::cout << "Loading " << filename << std::endl; unsigned char* img; stbi_set_unpremultiply_on_load(1); stbi_convert_iphone_png_to_rgb(1); // always request 4 channels (rgba) from stbi // stbi will return 4 channels, but the number reported will be // the actual number of channels in the source image. Since we // don't care about that, load that into a dummy variable and // return 4 channels always. int dummy; numChannels = 4; img = stbi_load(filename, &width, &height, &dummy, 4); if (img == NULL) { std::cout << "Failed to load " << filename << ": " << stbi_failure_reason() << std::endl; return NULL; } std::cout << "w: " << width << ", h: " << height << ", n: " << numChannels << std::endl; unsigned int datalength = width * height * numChannels; truss_message* ret = truss_create_message(datalength); std::memcpy(ret->data, img, datalength); stbi_image_free(img); return ret; } NanoVGAddon::~NanoVGAddon() { // nothing to do here either really } TRUSS_C_API truss_message* truss_nanovg_load_image(NanoVGAddon* addon, const char* filename, int* w, int* h, int* n) { return addon->loadImage(filename, *w, *h, *n); }<commit_msg>have loadimage go through physfs<commit_after>#include "nanovg_addon.h" #include <stb_image.h> #include <iostream> #include <cstring> NanoVGAddon::NanoVGAddon() { name_ = "nanovg"; version_ = "0.0.1"; // TODO: have bootstrap.t prepend the standard truss_message struct onto all addon headers? header_ = R"( /* NanoVG Addon Embedded Header */ typedef struct Addon Addon; typedef struct { unsigned int message_type; unsigned int data_length; unsigned char* data; unsigned int refcount; } truss_message; truss_message* truss_nanovg_load_image(Addon* addon, const char* filename, int* w, int* h, int* n); )"; } const std::string& NanoVGAddon::getName() { return name_; } const std::string& NanoVGAddon::getHeader() { return header_; } const std::string& NanoVGAddon::getVersion() { return version_; } void NanoVGAddon::init(truss::Interpreter* owner) { // nothing special to do } void NanoVGAddon::shutdown() { // nothing to do here either } void NanoVGAddon::update(double dt) { // no updates } // loads an image truss_message* NanoVGAddon::loadImage(const char* filename, int& width, int& height, int& numChannels) { unsigned char* img; stbi_set_unpremultiply_on_load(1); stbi_convert_iphone_png_to_rgb(1); // always request 4 channels (rgba) from stbi // stbi will return 4 channels, but the number reported will be // the actual number of channels in the source image. Since we // don't care about that, load that into a dummy variable and // return 4 channels always. int dummy; truss_message* rawfile = truss_load_file(filename); if (rawfile == NULL) { return NULL; } numChannels = 4; img = stbi_load_from_memory(rawfile->data, rawfile->data_length, &width, &height, &dummy, 4); if (img == NULL) { truss_log(TRUSS_LOG_ERROR, "Image loading error."); truss_log(TRUSS_LOG_ERROR, stbi_failure_reason()); truss_release_message(rawfile); return NULL; } unsigned int datalength = width * height * numChannels; truss_message* ret = truss_create_message(datalength); std::memcpy(ret->data, img, datalength); stbi_image_free(img); truss_release_message(rawfile); return ret; } NanoVGAddon::~NanoVGAddon() { // nothing to do here either really } TRUSS_C_API truss_message* truss_nanovg_load_image(NanoVGAddon* addon, const char* filename, int* w, int* h, int* n) { return addon->loadImage(filename, *w, *h, *n); }<|endoftext|>
<commit_before><commit_msg>fix build on older compilers<commit_after><|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "gtplib/gtpfrontend.hpp" #include "dummyengine.hpp" #include <iostream> #include <sstream> #include <tuple> using namespace std; using namespace gtp; template<typename Command, typename ...Params> WhateverCommand Cmd(Params... params) { Command c; typedef decltype(c.params) Tuple; return WhateverCommand(Command{Tuple(params...)}); } std::map<string, WhateverCommand> buildPairs() { std::map<string, WhateverCommand> result; result["protocol_version"] = Cmd<CmdProtocolVersion>(); result["name"] = Cmd<CmdName>(); result["known_command"] = Cmd<CmdKnownCommand>(); result["list_commands"] = Cmd<CmdListCommands>(); result["boardsize 19"] = Cmd<CmdBoardSize>(19); result["clear_board"] = Cmd<CmdClearBoard>(); result["komi 0.5"] = Cmd<CmdKomi>(0.5); result["play b a12"] = Cmd<CmdPlay>(Move{Color::black, Vertex{0, 12}}); result["genmove w"] = Cmd<CmdGenmove>(Color::white); result["fixed_handicap 4"] = Cmd<CmdFixedHandicap>(4); result["version"] = Cmd<CmdVersion>(); return result; } TEST(DirectConversion, OneAfterAnother) { std::map<string, WhateverCommand> pairs = buildPairs(); std::vector<WhateverCommand> expected; std::stringstream inputBuffer; for (auto pair : pairs) { inputBuffer << pair.first << "\n"; expected.push_back (pair.second); } inputBuffer << "quit\n"; expected.push_back(CmdQuit{}); inputBuffer.flush(); std::stringstream outputDummyBuffer; DummyEngine engine; gtp::EngineFrontend<DummyEngine> frontend (inputBuffer, outputDummyBuffer, engine); frontend.start(); size_t expectedCommandCount = expected.size(); size_t parsedCommandCount = engine.commands_.size(); size_t min = std::min(expectedCommandCount, parsedCommandCount); for (size_t k = 0; k < min; ++k) { EXPECT_EQ(engine.commands_[k], expected[k]); } EXPECT_EQ(expectedCommandCount, parsedCommandCount); } TEST(ReverseConversion, OneAfterAnother) { std::map<string, WhateverCommand> pairs = buildPairs(); std::vector<WhateverCommand> expected; std::stringstream inputBuffer; for (auto pair : pairs) { inputBuffer << pair.first << "\n"; expected.push_back (pair.second); } inputBuffer << "quit\n"; expected.push_back(CmdQuit{}); inputBuffer.flush(); std::stringstream outputDummyBuffer; DummyEngine engine; gtp::EngineFrontend<DummyEngine> frontend (inputBuffer, outputDummyBuffer, engine); frontend.start(); size_t expectedCommandCount = expected.size(); size_t parsedCommandCount = engine.commands_.size(); size_t min = std::min(expectedCommandCount, parsedCommandCount); for (auto c : engine.commands_) { cout << "AGGG: " << c << endl; } for (size_t k = 0; k < min; ++k) { cout << "Testing " << expected[k] << "..." << endl; EXPECT_EQ(engine.commands_[k], expected[k]); } EXPECT_EQ(expectedCommandCount, parsedCommandCount); } <commit_msg>Remove dummy test<commit_after>#include <gtest/gtest.h> #include "gtplib/gtpfrontend.hpp" #include "dummyengine.hpp" #include <iostream> #include <sstream> #include <tuple> using namespace std; using namespace gtp; template<typename Command, typename ...Params> WhateverCommand Cmd(Params... params) { Command c; typedef decltype(c.params) Tuple; return WhateverCommand(Command{Tuple(params...)}); } std::map<string, WhateverCommand> buildPairs() { std::map<string, WhateverCommand> result; result["protocol_version"] = Cmd<CmdProtocolVersion>(); result["name"] = Cmd<CmdName>(); result["known_command"] = Cmd<CmdKnownCommand>(); result["list_commands"] = Cmd<CmdListCommands>(); result["boardsize 19"] = Cmd<CmdBoardSize>(19); result["clear_board"] = Cmd<CmdClearBoard>(); result["komi 0.5"] = Cmd<CmdKomi>(0.5); result["play b a12"] = Cmd<CmdPlay>(Move{Color::black, Vertex{0, 12}}); result["genmove w"] = Cmd<CmdGenmove>(Color::white); result["fixed_handicap 4"] = Cmd<CmdFixedHandicap>(4); result["version"] = Cmd<CmdVersion>(); return result; } TEST(DirectConversion, OneAfterAnother) { std::map<string, WhateverCommand> pairs = buildPairs(); std::vector<WhateverCommand> expected; std::stringstream inputBuffer; for (auto pair : pairs) { inputBuffer << pair.first << "\n"; expected.push_back (pair.second); } inputBuffer << "quit\n"; expected.push_back(CmdQuit{}); inputBuffer.flush(); std::stringstream outputDummyBuffer; DummyEngine engine; gtp::EngineFrontend<DummyEngine> frontend (inputBuffer, outputDummyBuffer, engine); frontend.start(); size_t expectedCommandCount = expected.size(); size_t parsedCommandCount = engine.commands_.size(); size_t min = std::min(expectedCommandCount, parsedCommandCount); for (size_t k = 0; k < min; ++k) { EXPECT_EQ(engine.commands_[k], expected[k]); } EXPECT_EQ(expectedCommandCount, parsedCommandCount); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_ #define _Stroika_Foundation_DataExchange_OptionsFile_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Characters/Format.h" #include "../Streams/BasicBinaryInputOutputStream.h" namespace Stroika { namespace Foundation { namespace DataExchange { /* ******************************************************************************** ************************** DataExchange::OptionsFile *************************** ******************************************************************************** */ template <typename T> Optional<T> OptionsFile::Read () { Optional<VariantValue> tmp = Read<VariantValue> (); if (tmp.IsMissing ()) { return Optional<T> (); } try { return fMapper_.ToObject<T> (*tmp); } catch (const BadFormatException& bf) { fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetFilePath_ ().c_str ())); return Optional<T> (); } catch (...) { // if this fails, its probably because somehow the data in the config file was bad. // So at least log that, and continue without reading anything (as if empty file) fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetFilePath_ ().c_str ())); return Optional<T> (); } } template <typename T> T OptionsFile::Read (const T& defaultObj, ReadFlags readFlags) { Optional<T> eltRead = Read<T> (); Optional<T> elt2Write; // only if needed String msgAugment; if (eltRead.IsMissing ()) { if (readFlags == ReadFlags::eWriteIfChanged) { elt2Write = defaultObj; msgAugment = L"default"; } } else { if (readFlags == ReadFlags::eWriteIfChanged) { try { // See if re-persisting the item would change it. // This is useful if your data model adds or removes fields. It updates the file contents written to the // upgraded/latest form Memory::BLOB oldData = ReadRaw (); // @todo could have saved from previous Read<T> Memory::BLOB newData; { Streams::BasicBinaryOutputStream outStream; WriteRaw (outStream, fMapper_.FromObject (*eltRead)); // not sure needed? outStream.Flush(); newData = outStream.As<Memory::BLOB> (); } if (oldData != newData) { elt2Write = eltRead; msgAugment = L"(because something changed)"; } } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetFilePath_ ().c_str ())); } } } if (elt2Write.IsPresent ()) { fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing %s '%s' configuration file.", msgAugment.c_str (), GetFilePath_ ().c_str ())); try { Write (*elt2Write); } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetFilePath_ ().c_str ())); } return *elt2Write; } else if (eltRead.IsPresent ()) { return *eltRead; } else { return defaultObj; } } template <typename T> void OptionsFile::Write (const T& optionsObject) { Write<VariantValue> (fMapper_.FromObject<T> (optionsObject)); } } } } #endif /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/ <commit_msg>minor fix to OptionsFile<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_ #define _Stroika_Foundation_DataExchange_OptionsFile_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Characters/Format.h" #include "../Streams/BasicBinaryOutputStream.h" namespace Stroika { namespace Foundation { namespace DataExchange { /* ******************************************************************************** ************************** DataExchange::OptionsFile *************************** ******************************************************************************** */ template <typename T> Optional<T> OptionsFile::Read () { Optional<VariantValue> tmp = Read<VariantValue> (); if (tmp.IsMissing ()) { return Optional<T> (); } try { return fMapper_.ToObject<T> (*tmp); } catch (const BadFormatException& bf) { fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetFilePath_ ().c_str ())); return Optional<T> (); } catch (...) { // if this fails, its probably because somehow the data in the config file was bad. // So at least log that, and continue without reading anything (as if empty file) fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetFilePath_ ().c_str ())); return Optional<T> (); } } template <typename T> T OptionsFile::Read (const T& defaultObj, ReadFlags readFlags) { Optional<T> eltRead = Read<T> (); Optional<T> elt2Write; // only if needed String msgAugment; if (eltRead.IsMissing ()) { if (readFlags == ReadFlags::eWriteIfChanged) { elt2Write = defaultObj; msgAugment = L"default"; } } else { if (readFlags == ReadFlags::eWriteIfChanged) { try { // See if re-persisting the item would change it. // This is useful if your data model adds or removes fields. It updates the file contents written to the // upgraded/latest form Memory::BLOB oldData = ReadRaw (); // @todo could have saved from previous Read<T> Memory::BLOB newData; { Streams::BasicBinaryOutputStream outStream; WriteRaw (outStream, fMapper_.FromObject (*eltRead)); // not sure needed? outStream.Flush(); newData = outStream.As<Memory::BLOB> (); } if (oldData != newData) { elt2Write = eltRead; msgAugment = L"(because something changed)"; } } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetFilePath_ ().c_str ())); } } } if (elt2Write.IsPresent ()) { fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing %s '%s' configuration file.", msgAugment.c_str (), GetFilePath_ ().c_str ())); try { Write (*elt2Write); } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetFilePath_ ().c_str ())); } return *elt2Write; } else if (eltRead.IsPresent ()) { return *eltRead; } else { return defaultObj; } } template <typename T> void OptionsFile::Write (const T& optionsObject) { Write<VariantValue> (fMapper_.FromObject<T> (optionsObject)); } } } } #endif /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/ <|endoftext|>
<commit_before>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #pragma once //#include "aliceVision/multiview/homographyKernelSolver.hpp" //#include "aliceVision/robustEstimation/ACRansac.hpp" //#include "aliceVision/robustEstimation/ACRansacKernelAdaptator.hpp" //#include "aliceVision/robustEstimation/guidedMatching.hpp" #include "aliceVision/matching/IndMatch.hpp" //#include "aliceVision/matching/IndMatchDecorator.hpp" #include "aliceVision/sfm/SfMData.hpp" #include "aliceVision/feature/RegionsPerView.hpp" #include "aliceVision/matchingImageCollection/GeometricFilterMatrix.hpp" namespace aliceVision { namespace matchingImageCollection { //-- Multiple homography matrices estimation template functor, based on homography growing, used for filter pair of putative correspondences struct GeometricFilterMatrix_HGrowing : public GeometricFilterMatrix { GeometricFilterMatrix_HGrowing( double dPrecision = std::numeric_limits<double>::infinity(), size_t iteration = 1024) : GeometricFilterMatrix(dPrecision, std::numeric_limits<double>::infinity(), iteration) , _maxNbHomographies(10) , _minRemainingMatches(20) , _similarityTolerance(10) , _affinityTolerance(10) , _homographyTolerance(5) , _minNbPlanarMatches(6) , _nbIterations(8) , _maxFractionPlanarMatches(0.7) { _Hs.push_back(Mat3::Identity()); } /** * @brief Given two sets of image points, it estimates the homography matrix * relating them using a robust method (like A Contrario Ransac). */ template<typename Regions_or_Features_ProviderT> EstimationStatus geometricEstimation( const sfm::SfMData * sfmData, const Regions_or_Features_ProviderT& regionsPerView, const Pair pairIndex, const matching::MatchesPerDescType & putativeMatchesPerType, matching::MatchesPerDescType & out_geometricInliersPerType) { using namespace aliceVision; using namespace aliceVision::robustEstimation; out_geometricInliersPerType.clear(); // Get back corresponding view index const IndexT viewId_I = pairIndex.first; const IndexT viewId_J = pairIndex.second; const std::vector<feature::EImageDescriberType> descTypes = regionsPerView.getCommonDescTypes(pairIndex); if(descTypes.empty()) return EstimationStatus(false, false); // Retrieve all 2D features as undistorted positions into flat arrays Mat xI, xJ; MatchesPairToMat(pairIndex, putativeMatchesPerType, sfmData, regionsPerView, descTypes, xI, xJ); std::cout << "Pair id. : " << pairIndex << std::endl; std::cout << "|- putative: " << putativeMatchesPerType.at(feature::EImageDescriberType::SIFT).size() << std::endl; std::cout << "|- xI: " << xI.rows() << "x" << xI.cols() << std::endl; std::cout << "|- xJ: " << xJ.rows() << "x" << xJ.cols() << std::endl; const feature::Regions& regionsSIFT_I = regionsPerView.getRegions(viewId_I, descTypes.at(0)); const feature::Regions& regionsSIFT_J = regionsPerView.getRegions(viewId_J, descTypes.at(0)); const std::vector<feature::SIOPointFeature> allSIFTFeaturesI = getSIOPointFeatures(regionsSIFT_I); const std::vector<feature::SIOPointFeature> allSIFTfeaturesJ = getSIOPointFeatures(regionsSIFT_J); matching::IndMatches putativeSIFTMatches = putativeMatchesPerType.at(feature::EImageDescriberType::SIFT); // std::vector<feature::SIOPointFeature> putativeFeaturesI, putativeFeaturesJ; // putativeFeaturesI.reserve(putativeSIFTMatches.size()); // putativeFeaturesJ.reserve(putativeSIFTMatches.size()); // for (const matching::IndMatch & idMatch : putativeSIFTMatches) // { // putativeFeaturesI.push_back(allSIFTFeaturesI.at(idMatch._i)); // putativeFeaturesJ.push_back(allSIFTfeaturesJ.at(idMatch._j)); // } if (viewId_I == 200563944 && viewId_J == 1112206013) // MATLAB exemple { std::cout << "|- #matches: " << putativeSIFTMatches.size() << std::endl; std::cout << "|- allSIFTFeaturesI : " << allSIFTFeaturesI.size() << std::endl; std::cout << "|- allSIFTfeaturesJ : " << allSIFTfeaturesJ.size() << std::endl; // std::cout << "|- putativeFeaturesI : " << putativeFeaturesI.size() << std::endl; // std::cout << "|- putativeFeaturesJ : " << putativeFeaturesJ.size() << std::endl; // std::cout << "-------" << std::endl; // std::cout << "xI : " << std::endl; // std::cout << xI << std::endl; // std::cout << "putativeFeaturesI : " << std::endl; // std::cout << putativeFeaturesI << std::endl; std::size_t nbMatches = putativeSIFTMatches.size(); // (?) make a map std::vector<Mat3> homographies; std::vector<std::vector<IndexT>> planarMatchesPerH; for (IndexT iTransform = 0; iTransform < _maxNbHomographies; ++iTransform) { for (IndexT iMatch = 0; iMatch < nbMatches; ++iMatch) { // [TODO] Add 1st improvment // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) std::vector<IndexT> planarMatchesIds; Mat3 homographie; growHomography(allSIFTFeaturesI, allSIFTfeaturesJ, putativeSIFTMatches, iMatch, planarMatchesIds, homographie); if (!planarMatchesIds.empty()) { homographies.push_back(homographie); planarMatchesPerH.push_back(planarMatchesIds); } } } } // Check if resection has strong support const bool hasStrongSupport = true; return EstimationStatus(true, hasStrongSupport); } /** * @brief Geometry_guided_matching * @param sfm_data * @param regionsPerView * @param pairIndex * @param dDistanceRatio * @param matches * @return */ bool Geometry_guided_matching ( const sfm::SfMData * sfmData, const feature::RegionsPerView & regionsPerView, const Pair imageIdsPair, const double dDistanceRatio, matching::MatchesPerDescType & matches) override { /* ... */ return matches.getNbAllMatches() != 0; } private: // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) //-- See: YASM/relative_pose.h void growHomography(const std::vector<feature::SIOPointFeature> & featuresI, const std::vector<feature::SIOPointFeature> & featuresJ, const matching::IndMatches & putativeMatches, const IndexT & seedMatchId, std::vector<IndexT> & out_planarMatchesIndices, Mat3 & out_transformation) { assert(seedMatchId <= putativeMatches.size()); out_planarMatchesIndices.clear(); out_transformation = Mat3::Identity(); const matching::IndMatch & seedMatch = putativeMatches.at(seedMatchId); const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i); const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j); std::size_t currentTolerance; for (IndexT iRefineStep = 0; iRefineStep < _nbIterations; ++iRefineStep) { if (iRefineStep == 0) { computeSimilarityFromMatch(seedFeatureI, seedFeatureJ, out_transformation); std::cout << "featI: " << seedFeatureI << std::endl; std::cout << "featJ: " << seedFeatureJ << std::endl; std::cout << "S = " << out_transformation << std::endl; getchar(); currentTolerance = _similarityTolerance; } else if (iRefineStep <= 4) { estimateAffinity(); currentTolerance = _affinityTolerance; } else { estimateHomography(); currentTolerance = _homographyTolerance; } findTransformationInliers(); } } /** * @brief computeSimilarityFromMatch * see: alicevision::sfm::computeSimilarity() [sfm/utils/alignment.cpp] * alicevision::geometry::ACRansac_FindRTS() [geometry/rigidTransformation3D(_test).hpp] */ void computeSimilarityFromMatch(const feature::SIOPointFeature & feat1, const feature::SIOPointFeature & feat2, Mat3 & S) { computeSimilarityFromMatch(feat1.coords(), feat1.scale(), feat1.orientation(), feat2.coords(), feat2.scale(), feat2.orientation(), S); } /** * @brief computeSimilarityFromMatch * Source: https://github.com/fsrajer/yasfm/blob/master/YASFM/relative_pose.cpp#L1649 * @param coord1 * @param scale1 * @param orientation1 * @param coord2 * @param scale2 * @param orientation2 * @param S */ void computeSimilarityFromMatch(const Vec2f & coord1, double scale1, double orientation1, const Vec2f & coord2, double scale2, double orientation2, Mat3 & S) { double c1 = cos(orientation1), s1 = sin(orientation1), c2 = cos(orientation2), s2 = sin(orientation2); Mat3 A1,A2; A1 << scale1*c1,scale1*(-s1),coord1(0), scale1*s1,scale1*c1,coord1(1), 0,0,1; A2 << scale2*c2,scale2*(-s2),coord2(0), scale2*s2,scale2*c2,coord2(1), 0,0,1; S = A2*A1.inverse(); } /** * @brief estimateAffinity * see: alicevision::Affine2DFromCorrespondencesLinear() [multiview/affineSolver(_test).hpp] */ void estimateAffinity() { // std::cout << "estimateAffinity" << std::endl; } /** * @brief estimateHomography * see: by DLT: alicevision::homography::kernel::FourPointSolver::Solve() [multiview/homographyKernelSolver.hpp] * by RANSAC: alicevision::matchingImageCOllection::geometricEstimation() [matchingImageCollection/GeometricFilterMatrix_H_AC.hpp] */ void estimateHomography() { // std::cout << "estimateHomography" << std::endl; } /** * @brief findHomographyInliers Test the reprojection error */ void findTransformationInliers() { // std::cout << "findHomographyInliers" << std::endl; } //-- Stored data std::vector<Mat3> _Hs; //-- Options std::size_t _maxNbHomographies; // = MaxHoms std::size_t _minRemainingMatches; // = MinInsNum // growHomography function: std::size_t _similarityTolerance; // = SimTol std::size_t _affinityTolerance; // = AffTol std::size_t _homographyTolerance; // = HomTol std::size_t _minNbPlanarMatches; // = MinIns std::size_t _nbIterations; // = RefIterNum std::size_t _maxFractionPlanarMatches; // = StopInsFrac }; } // namespace matchingImageCollection } // namespace aliceVision <commit_msg>[Hgrowing] 'findTransformationInliers' integration<commit_after>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #pragma once //#include "aliceVision/multiview/homographyKernelSolver.hpp" //#include "aliceVision/robustEstimation/ACRansac.hpp" //#include "aliceVision/robustEstimation/ACRansacKernelAdaptator.hpp" //#include "aliceVision/robustEstimation/guidedMatching.hpp" #include "aliceVision/matching/IndMatch.hpp" //#include "aliceVision/matching/IndMatchDecorator.hpp" #include "aliceVision/sfm/SfMData.hpp" #include "aliceVision/feature/RegionsPerView.hpp" #include "aliceVision/matchingImageCollection/GeometricFilterMatrix.hpp" #include "Eigen/Geometry" namespace aliceVision { namespace matchingImageCollection { //-- Multiple homography matrices estimation template functor, based on homography growing, used for filter pair of putative correspondences struct GeometricFilterMatrix_HGrowing : public GeometricFilterMatrix { GeometricFilterMatrix_HGrowing( double dPrecision = std::numeric_limits<double>::infinity(), size_t iteration = 1024) : GeometricFilterMatrix(dPrecision, std::numeric_limits<double>::infinity(), iteration) , _maxNbHomographies(10) , _minRemainingMatches(20) , _similarityTolerance(10) , _affinityTolerance(10) , _homographyTolerance(5) , _minNbPlanarMatches(6) , _nbIterations(8) , _maxFractionPlanarMatches(0.7) { _Hs.push_back(Mat3::Identity()); } /** * @brief Given two sets of image points, it estimates the homography matrix * relating them using a robust method (like A Contrario Ransac). */ template<typename Regions_or_Features_ProviderT> EstimationStatus geometricEstimation( const sfm::SfMData * sfmData, const Regions_or_Features_ProviderT& regionsPerView, const Pair pairIndex, const matching::MatchesPerDescType & putativeMatchesPerType, matching::MatchesPerDescType & out_geometricInliersPerType) { using namespace aliceVision; using namespace aliceVision::robustEstimation; out_geometricInliersPerType.clear(); // Get back corresponding view index const IndexT viewId_I = pairIndex.first; const IndexT viewId_J = pairIndex.second; const std::vector<feature::EImageDescriberType> descTypes = regionsPerView.getCommonDescTypes(pairIndex); if(descTypes.empty()) return EstimationStatus(false, false); // Retrieve all 2D features as undistorted positions into flat arrays Mat xI, xJ; MatchesPairToMat(pairIndex, putativeMatchesPerType, sfmData, regionsPerView, descTypes, xI, xJ); std::cout << "Pair id. : " << pairIndex << std::endl; std::cout << "|- putative: " << putativeMatchesPerType.at(feature::EImageDescriberType::SIFT).size() << std::endl; std::cout << "|- xI: " << xI.rows() << "x" << xI.cols() << std::endl; std::cout << "|- xJ: " << xJ.rows() << "x" << xJ.cols() << std::endl; const feature::Regions& regionsSIFT_I = regionsPerView.getRegions(viewId_I, descTypes.at(0)); const feature::Regions& regionsSIFT_J = regionsPerView.getRegions(viewId_J, descTypes.at(0)); const std::vector<feature::SIOPointFeature> allSIFTFeaturesI = getSIOPointFeatures(regionsSIFT_I); const std::vector<feature::SIOPointFeature> allSIFTfeaturesJ = getSIOPointFeatures(regionsSIFT_J); matching::IndMatches putativeSIFTMatches = putativeMatchesPerType.at(feature::EImageDescriberType::SIFT); // std::vector<feature::SIOPointFeature> putativeFeaturesI, putativeFeaturesJ; // putativeFeaturesI.reserve(putativeSIFTMatches.size()); // putativeFeaturesJ.reserve(putativeSIFTMatches.size()); // for (const matching::IndMatch & idMatch : putativeSIFTMatches) // { // putativeFeaturesI.push_back(allSIFTFeaturesI.at(idMatch._i)); // putativeFeaturesJ.push_back(allSIFTfeaturesJ.at(idMatch._j)); // } if (viewId_I == 200563944 && viewId_J == 1112206013) // MATLAB exemple { std::cout << "|- #matches: " << putativeSIFTMatches.size() << std::endl; std::cout << "|- allSIFTFeaturesI : " << allSIFTFeaturesI.size() << std::endl; std::cout << "|- allSIFTfeaturesJ : " << allSIFTfeaturesJ.size() << std::endl; // std::cout << "|- putativeFeaturesI : " << putativeFeaturesI.size() << std::endl; // std::cout << "|- putativeFeaturesJ : " << putativeFeaturesJ.size() << std::endl; // std::cout << "-------" << std::endl; // std::cout << "xI : " << std::endl; // std::cout << xI << std::endl; // std::cout << "putativeFeaturesI : " << std::endl; // std::cout << putativeFeaturesI << std::endl; std::size_t nbMatches = putativeSIFTMatches.size(); // (?) make a map std::vector<Mat3> homographies; std::vector<std::vector<IndexT>> planarMatchesPerH; for (IndexT iTransform = 0; iTransform < _maxNbHomographies; ++iTransform) { for (IndexT iMatch = 0; iMatch < nbMatches; ++iMatch) { // [TODO] Add 1st improvment // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) std::vector<IndexT> planarMatchesIds; Mat3 homographie; growHomography(allSIFTFeaturesI, allSIFTfeaturesJ, putativeSIFTMatches, iMatch, planarMatchesIds, homographie); if (!planarMatchesIds.empty()) { homographies.push_back(homographie); planarMatchesPerH.push_back(planarMatchesIds); } } } } // Check if resection has strong support const bool hasStrongSupport = true; return EstimationStatus(true, hasStrongSupport); } /** * @brief Geometry_guided_matching * @param sfm_data * @param regionsPerView * @param pairIndex * @param dDistanceRatio * @param matches * @return */ bool Geometry_guided_matching ( const sfm::SfMData * sfmData, const feature::RegionsPerView & regionsPerView, const Pair imageIdsPair, const double dDistanceRatio, matching::MatchesPerDescType & matches) override { /* ... */ return matches.getNbAllMatches() != 0; } private: // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) //-- See: YASM/relative_pose.h void growHomography(const std::vector<feature::SIOPointFeature> & featuresI, const std::vector<feature::SIOPointFeature> & featuresJ, const matching::IndMatches & matches, const IndexT & seedMatchId, std::vector<IndexT> & planarMatchesIndices, Mat3 & transformation) { assert(seedMatchId <= matches.size()); planarMatchesIndices.clear(); transformation = Mat3::Identity(); const matching::IndMatch & seedMatch = matches.at(seedMatchId); const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i); const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j); std::size_t currTolerance; for (IndexT iRefineStep = 0; iRefineStep < _nbIterations; ++iRefineStep) { if (iRefineStep == 0) { computeSimilarityFromMatch(seedFeatureI, seedFeatureJ, transformation); std::cout << "featI: " << seedFeatureI << std::endl; std::cout << "featJ: " << seedFeatureJ << std::endl; std::cout << "S = " << transformation << std::endl; currTolerance = _similarityTolerance; } else if (iRefineStep <= 4) { estimateAffinity(); currTolerance = _affinityTolerance; } else { estimateHomography(); currTolerance = _homographyTolerance; } findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices); std::cout << "#Inliers = " << planarMatchesIndices.size() << std::endl; std::cout << planarMatchesIndices << std::endl; getchar(); } } /** * @brief findHomographyInliers Test the reprojection error */ void findTransformationInliers(const std::vector<feature::SIOPointFeature> & featuresI, const std::vector<feature::SIOPointFeature> & featuresJ, const matching::IndMatches & matches, const Mat3 & transformation, const std::size_t tolerance, std::vector<IndexT> & planarMatchesIndices) { planarMatchesIndices.clear(); for (IndexT iMatch = 0; iMatch < matches.size(); ++iMatch) { const feature::SIOPointFeature & featI = featuresI.at(matches.at(iMatch)._i); const feature::SIOPointFeature & featJ = featuresJ.at(matches.at(iMatch)._j); Vec2 ptI(featI.x(), featI.y()); Vec2 ptJ(featJ.x(), featJ.y()); Vec3 ptIp_hom = transformation * ptI.homogeneous(); float dist = (ptJ - ptIp_hom.hnormalized()).squaredNorm(); if (dist < tolerance * tolerance) planarMatchesIndices.push_back(iMatch); } } /** * @brief computeSimilarityFromMatch * see: alicevision::sfm::computeSimilarity() [sfm/utils/alignment.cpp] * alicevision::geometry::ACRansac_FindRTS() [geometry/rigidTransformation3D(_test).hpp] */ void computeSimilarityFromMatch(const feature::SIOPointFeature & feat1, const feature::SIOPointFeature & feat2, Mat3 & S) { computeSimilarityFromMatch(feat1.coords(), feat1.scale(), feat1.orientation(), feat2.coords(), feat2.scale(), feat2.orientation(), S); } /** * @brief computeSimilarityFromMatch * Source: https://github.com/fsrajer/yasfm/blob/master/YASFM/relative_pose.cpp#L1649 * @param coord1 * @param scale1 * @param orientation1 * @param coord2 * @param scale2 * @param orientation2 * @param S */ void computeSimilarityFromMatch(const Vec2f & coord1, double scale1, double orientation1, const Vec2f & coord2, double scale2, double orientation2, Mat3 & S) { double c1 = cos(orientation1), s1 = sin(orientation1), c2 = cos(orientation2), s2 = sin(orientation2); Mat3 A1,A2; A1 << scale1*c1,scale1*(-s1),coord1(0), scale1*s1,scale1*c1,coord1(1), 0,0,1; A2 << scale2*c2,scale2*(-s2),coord2(0), scale2*s2,scale2*c2,coord2(1), 0,0,1; S = A2*A1.inverse(); } /** * @brief estimateAffinity * see: alicevision::Affine2DFromCorrespondencesLinear() [multiview/affineSolver(_test).hpp] */ void estimateAffinity() { // std::cout << "estimateAffinity" << std::endl; } /** * @brief estimateHomography * see: by DLT: alicevision::homography::kernel::FourPointSolver::Solve() [multiview/homographyKernelSolver.hpp] * by RANSAC: alicevision::matchingImageCOllection::geometricEstimation() [matchingImageCollection/GeometricFilterMatrix_H_AC.hpp] */ void estimateHomography() { // std::cout << "estimateHomography" << std::endl; } //-- Stored data std::vector<Mat3> _Hs; //-- Options std::size_t _maxNbHomographies; // = MaxHoms std::size_t _minRemainingMatches; // = MinInsNum // growHomography function: std::size_t _similarityTolerance; // = SimTol std::size_t _affinityTolerance; // = AffTol std::size_t _homographyTolerance; // = HomTol std::size_t _minNbPlanarMatches; // = MinIns std::size_t _nbIterations; // = RefIterNum std::size_t _maxFractionPlanarMatches; // = StopInsFrac }; } // namespace matchingImageCollection } // namespace aliceVision <|endoftext|>
<commit_before>// Description for Color struct and example colors // William Immendorf - 2016 #include <string> #pragma once namespace EquParser { struct Color { std::string name = ""; float red = 0.0f; float green = 0.0f; float blue = 0.0f; Color(std::string name, float red, float green, float blue) : name(name), red(red), green(green), blue(blue) { } }; const Color Colors[3] = { { "Black", 0.0f, 0.0f, 0.0f }, { "Red", 1.0f, 0.0f, 0.0f }, { "Green", 0.0f, 1.0f, 0.0f } }; } <commit_msg>Add blue color<commit_after>// Description for Color struct and example colors // William Immendorf - 2016 #include <string> #pragma once namespace EquParser { struct Color { std::string name = ""; float red = 0.0f; float green = 0.0f; float blue = 0.0f; Color(std::string name, float red, float green, float blue) : name(name), red(red), green(green), blue(blue) { } }; const Color Colors[4] = { { "Black", 0.0f, 0.0f, 0.0f }, { "Red", 1.0f, 0.0f, 0.0f }, { "Green", 0.0f, 1.0f, 0.0f }, { "Blue", 0.0f, 0.0f, 1.0f } }; } <|endoftext|>
<commit_before>#include "Type.h" // to avoid compiler confusion, python.hpp must be include before Halide headers #include <boost/format.hpp> #include <boost/python.hpp> #include "no_compare_indexing_suite.h" #include "../../src/Type.h" #include "../../src/Expr.h" #include <vector> #include <string> namespace h = Halide; std::string type_code_to_string(const h::Type &t) { std::string code_string = "unknown"; switch(t.code()) { case h::Type::UInt: code_string = "UInt"; break; case h::Type::Int: code_string = "Int"; break; case h::Type::Float: code_string = "Float"; break; case h::Type::Handle: code_string = "Handle"; break; default: code_string = "unknown"; } return code_string; } std::string type_repr(const h::Type &t) { auto message_format = boost::format("<halide.Type code '%s' with %i bits and %i lanes>"); return boost::str(message_format % type_code_to_string(t) % t.bits() % t.lanes()); } void defineType() { using Halide::Type; namespace p = boost::python; bool (Type::*can_represent_other_type)(Type) const = &Type::can_represent; p::class_<Type>("Type", "Default constructor initializes everything to predictable-but-unlikely values", p::no_init) .def(p::init<halide_type_code_t, int, int>(p::args("code", "bits", "lanes"))) .def(p::init<h::Type>(p::args("that"), "Copy constructor")) .def("bits", &Type::bits, "The number of bits of precision of a single scalar value of this type.") .def("bytes", &Type::bytes, "The number of bytes required to store a single scalar value of this type. Ignores vector width.") .def("lanes", &Type::lanes, "How many elements (if a vector type). Should be 1 for scalar types.") .def("is_bool", &Type::is_bool, p::arg("self"), "Is this type boolean (represented as UInt(1))?") .def("is_vector", &Type::is_vector, p::arg("self"), "Is this type a vector type? (width > 1)") .def("is_scalar", &Type::is_scalar, p::arg("self"), "Is this type a scalar type? (width == 1)") .def("is_float", &Type::is_float, p::arg("self"), "Is this type a floating point type (float or double).") .def("is_int", &Type::is_int, p::arg("self"), "Is this type a signed integer type?") .def("is_uint", &Type::is_uint, p::arg("self"), "Is this type an unsigned integer type?") .def("is_handle", &Type::is_handle, p::arg("self"), "Is this type an opaque handle type (void *)") .def(p::self == p::self) .def(p::self != p::self) .def("with_lanes", &Type::with_lanes, p::args("self", "w"), "Produce a copy of this type, with 'lanes' vector lanes") .def("with_bits", &Type::with_bits, p::args("self", "w"), "Produce a copy of this type, with 'bits' bits") .def("element_of", &Type::element_of, p::arg("self"), "Produce the type of a single element of this vector type") .def("can_represent", can_represent_other_type, p::arg("other"), "Can this type represent all values of another type?") .def("max", &Type::max, p::arg("self"), "Return an expression which is the maximum value of this type") .def("min", &Type::min, p::arg("self"), "Return an expression which is the minimum value of this type") .def("__repr__", &type_repr, p::arg("self"), "Return a string containing a printable representation of a Type object.") ; p::def("Int", h::Int, (p::arg("bits"), p::arg("width")=1), "Constructing an signed integer type"); p::def("UInt", h::UInt, (p::arg("bits"), p::arg("width")=1), "Constructing an unsigned integer type"); p::def("Float", h::Float, (p::arg("bits"), p::arg("width")=1), "Constructing a floating-point type"); p::def("Bool", h::Bool, (p::arg("width")=1), "Construct a boolean type"); p::def("Handle", h::Handle, (p::arg("width")=1), "Construct a handle type"); p::class_< std::vector<Type> >("TypesVector") .def( no_compare_indexing_suite< std::vector<Type> >() ); return; } <commit_msg>Fix python bindings<commit_after>#include "Type.h" // to avoid compiler confusion, python.hpp must be include before Halide headers #include <boost/format.hpp> #include <boost/python.hpp> #include "no_compare_indexing_suite.h" #include "../../src/Type.h" #include "../../src/Expr.h" #include <vector> #include <string> namespace h = Halide; std::string type_code_to_string(const h::Type &t) { std::string code_string = "unknown"; switch(t.code()) { case h::Type::UInt: code_string = "UInt"; break; case h::Type::Int: code_string = "Int"; break; case h::Type::Float: code_string = "Float"; break; case h::Type::Handle: code_string = "Handle"; break; default: code_string = "unknown"; } return code_string; } Halide::Type make_handle(int lanes) { return Halide::Handle(lanes, nullptr); } std::string type_repr(const h::Type &t) { auto message_format = boost::format("<halide.Type code '%s' with %i bits and %i lanes>"); return boost::str(message_format % type_code_to_string(t) % t.bits() % t.lanes()); } void defineType() { using Halide::Type; namespace p = boost::python; bool (Type::*can_represent_other_type)(Type) const = &Type::can_represent; p::class_<Type>("Type", "Default constructor initializes everything to predictable-but-unlikely values", p::no_init) .def(p::init<halide_type_code_t, int, int>(p::args("code", "bits", "lanes"))) .def(p::init<h::Type>(p::args("that"), "Copy constructor")) .def("bits", &Type::bits, "The number of bits of precision of a single scalar value of this type.") .def("bytes", &Type::bytes, "The number of bytes required to store a single scalar value of this type. Ignores vector lanes.") .def("lanes", &Type::lanes, "How many elements (if a vector type). Should be 1 for scalar types.") .def("is_bool", &Type::is_bool, p::arg("self"), "Is this type boolean (represented as UInt(1))?") .def("is_vector", &Type::is_vector, p::arg("self"), "Is this type a vector type? (lanes > 1)") .def("is_scalar", &Type::is_scalar, p::arg("self"), "Is this type a scalar type? (lanes == 1)") .def("is_float", &Type::is_float, p::arg("self"), "Is this type a floating point type (float or double).") .def("is_int", &Type::is_int, p::arg("self"), "Is this type a signed integer type?") .def("is_uint", &Type::is_uint, p::arg("self"), "Is this type an unsigned integer type?") .def("is_handle", &Type::is_handle, p::arg("self"), "Is this type an opaque handle type (void *)") .def(p::self == p::self) .def(p::self != p::self) .def("with_lanes", &Type::with_lanes, p::args("self", "w"), "Produce a copy of this type, with 'lanes' vector lanes") .def("with_bits", &Type::with_bits, p::args("self", "w"), "Produce a copy of this type, with 'bits' bits") .def("element_of", &Type::element_of, p::arg("self"), "Produce the type of a single element of this vector type") .def("can_represent", can_represent_other_type, p::arg("other"), "Can this type represent all values of another type?") .def("max", &Type::max, p::arg("self"), "Return an expression which is the maximum value of this type") .def("min", &Type::min, p::arg("self"), "Return an expression which is the minimum value of this type") .def("__repr__", &type_repr, p::arg("self"), "Return a string containing a printable representation of a Type object.") ; p::def("Int", h::Int, (p::arg("bits"), p::arg("lanes")=1), "Constructing an signed integer type"); p::def("UInt", h::UInt, (p::arg("bits"), p::arg("lanes")=1), "Constructing an unsigned integer type"); p::def("Float", h::Float, (p::arg("bits"), p::arg("lanes")=1), "Constructing a floating-point type"); p::def("Bool", h::Bool, (p::arg("lanes")=1), "Construct a boolean type"); p::def("Handle", make_handle, (p::arg("lanes")=1), "Construct a handle type"); p::class_< std::vector<Type> >("TypesVector") .def( no_compare_indexing_suite< std::vector<Type> >() ); return; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_mss_draminit_training.H /// @brief Train DRAM /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP FW Owner: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_DRAMINIT_TRAINING__ #define __P9_MSS_DRAMINIT_TRAINING__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_draminit_training_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>&); extern "C" { /// /// @brief Train dram /// @param[in] i_target, the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ); } #endif <commit_msg>Initial commit of memory subsystem<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_mss_draminit_training.H /// @brief Train DRAM /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_DRAMINIT_TRAINING__ #define __P9_MSS_DRAMINIT_TRAINING__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_draminit_training_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>&); extern "C" { /// /// @brief Train dram, assumes effective config has run /// @param[in] i_target, the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ); } #endif <|endoftext|>
<commit_before>//===- CoverageReport.cpp - Code coverage report -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements rendering of a code coverage report. // //===----------------------------------------------------------------------===// #include "CoverageReport.h" #include "RenderingSupport.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/Path.h" #include <numeric> using namespace llvm; namespace { /// \brief Helper struct which prints trimmed and aligned columns. struct Column { enum TrimKind { NoTrim, WidthTrim, RightTrim }; enum AlignmentKind { LeftAlignment, RightAlignment }; StringRef Str; unsigned Width; TrimKind Trim; AlignmentKind Alignment; Column(StringRef Str, unsigned Width) : Str(Str), Width(Width), Trim(WidthTrim), Alignment(LeftAlignment) {} Column &set(TrimKind Value) { Trim = Value; return *this; } Column &set(AlignmentKind Value) { Alignment = Value; return *this; } void render(raw_ostream &OS) const { if (Str.size() <= Width) { if (Alignment == RightAlignment) { OS.indent(Width - Str.size()); OS << Str; return; } OS << Str; OS.indent(Width - Str.size()); return; } switch (Trim) { case NoTrim: OS << Str; break; case WidthTrim: OS << Str.substr(0, Width); break; case RightTrim: OS << Str.substr(0, Width - 3) << "..."; break; } } }; raw_ostream &operator<<(raw_ostream &OS, const Column &Value) { Value.render(OS); return OS; } Column column(StringRef Str, unsigned Width) { return Column(Str, Width); } template <typename T> Column column(StringRef Str, unsigned Width, const T &Value) { return Column(Str, Width).set(Value); } // Specify the default column widths. size_t FileReportColumns[] = {25, 12, 18, 10, 12, 18, 10, 16, 16, 10, 12, 18, 10}; size_t FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8}; /// \brief Adjust column widths to fit long file paths and function names. void adjustColumnWidths(ArrayRef<StringRef> Files, ArrayRef<StringRef> Functions) { for (StringRef Filename : Files) FileReportColumns[0] = std::max(FileReportColumns[0], Filename.size()); for (StringRef Funcname : Functions) FunctionReportColumns[0] = std::max(FunctionReportColumns[0], Funcname.size()); } /// \brief Prints a horizontal divider long enough to cover the given column /// widths. void renderDivider(ArrayRef<size_t> ColumnWidths, raw_ostream &OS) { size_t Length = std::accumulate(ColumnWidths.begin(), ColumnWidths.end(), 0); for (size_t I = 0; I < Length; ++I) OS << '-'; } /// \brief Return the color which correponds to the coverage percentage of a /// certain metric. template <typename T> raw_ostream::Colors determineCoveragePercentageColor(const T &Info) { if (Info.isFullyCovered()) return raw_ostream::GREEN; return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW : raw_ostream::RED; } /// \brief Get the number of redundant path components in each path in \p Paths. unsigned getNumRedundantPathComponents(ArrayRef<std::string> Paths) { // To start, set the number of redundant path components to the maximum // possible value. SmallVector<StringRef, 8> FirstPathComponents{sys::path::begin(Paths[0]), sys::path::end(Paths[0])}; unsigned NumRedundant = FirstPathComponents.size(); for (unsigned I = 1, E = Paths.size(); NumRedundant > 0 && I < E; ++I) { StringRef Path = Paths[I]; for (const auto &Component : enumerate(make_range(sys::path::begin(Path), sys::path::end(Path)))) { // Do not increase the number of redundant components: that would remove // useful parts of already-visited paths. if (Component.Index >= NumRedundant) break; // Lower the number of redundant components when there's a mismatch // between the first path, and the path under consideration. if (FirstPathComponents[Component.Index] != Component.Value) { NumRedundant = Component.Index; break; } } } return NumRedundant; } /// \brief Determine the length of the longest redundant prefix of the paths in /// \p Paths. unsigned getRedundantPrefixLen(ArrayRef<std::string> Paths) { // If there's at most one path, no path components are redundant. if (Paths.size() <= 1) return 0; unsigned PrefixLen = 0; unsigned NumRedundant = getNumRedundantPathComponents(Paths); auto Component = sys::path::begin(Paths[0]); for (unsigned I = 0; I < NumRedundant; ++I) { auto LastComponent = Component; ++Component; PrefixLen += Component - LastComponent; } return PrefixLen; } } // end anonymous namespace namespace llvm { void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) const { auto FileCoverageColor = determineCoveragePercentageColor(File.RegionCoverage); auto FuncCoverageColor = determineCoveragePercentageColor(File.FunctionCoverage); auto InstantiationCoverageColor = determineCoveragePercentageColor(File.InstantiationCoverage); auto LineCoverageColor = determineCoveragePercentageColor(File.LineCoverage); SmallString<256> FileName = File.Name; sys::path::remove_dots(FileName, /*remove_dot_dots=*/true); sys::path::native(FileName); OS << column(FileName, FileReportColumns[0], Column::NoTrim) << format("%*u", FileReportColumns[1], (unsigned)File.RegionCoverage.NumRegions); Options.colored_ostream(OS, FileCoverageColor) << format( "%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered); if (File.RegionCoverage.NumRegions) Options.colored_ostream(OS, FileCoverageColor) << format("%*.2f", FileReportColumns[3] - 1, File.RegionCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[3], Column::RightAlignment); OS << format("%*u", FileReportColumns[4], (unsigned)File.FunctionCoverage.NumFunctions); OS << format("%*u", FileReportColumns[5], (unsigned)(File.FunctionCoverage.NumFunctions - File.FunctionCoverage.Executed)); if (File.FunctionCoverage.NumFunctions) Options.colored_ostream(OS, FuncCoverageColor) << format("%*.2f", FileReportColumns[6] - 1, File.FunctionCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[6], Column::RightAlignment); OS << format("%*u", FileReportColumns[7], (unsigned)File.InstantiationCoverage.NumFunctions); OS << format("%*u", FileReportColumns[8], (unsigned)(File.InstantiationCoverage.NumFunctions - File.InstantiationCoverage.Executed)); if (File.InstantiationCoverage.NumFunctions) Options.colored_ostream(OS, InstantiationCoverageColor) << format("%*.2f", FileReportColumns[9] - 1, File.InstantiationCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[9], Column::RightAlignment); OS << format("%*u", FileReportColumns[10], (unsigned)File.LineCoverage.NumLines); Options.colored_ostream(OS, LineCoverageColor) << format( "%*u", FileReportColumns[11], (unsigned)File.LineCoverage.NotCovered); if (File.LineCoverage.NumLines) Options.colored_ostream(OS, LineCoverageColor) << format("%*.2f", FileReportColumns[12] - 1, File.LineCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[12], Column::RightAlignment); OS << "\n"; } void CoverageReport::render(const FunctionCoverageSummary &Function, const DemangleCache &DC, raw_ostream &OS) const { auto FuncCoverageColor = determineCoveragePercentageColor(Function.RegionCoverage); auto LineCoverageColor = determineCoveragePercentageColor(Function.LineCoverage); OS << column(DC.demangle(Function.Name), FunctionReportColumns[0], Column::RightTrim) << format("%*u", FunctionReportColumns[1], (unsigned)Function.RegionCoverage.NumRegions); Options.colored_ostream(OS, FuncCoverageColor) << format("%*u", FunctionReportColumns[2], (unsigned)Function.RegionCoverage.NotCovered); Options.colored_ostream( OS, determineCoveragePercentageColor(Function.RegionCoverage)) << format("%*.2f", FunctionReportColumns[3] - 1, Function.RegionCoverage.getPercentCovered()) << '%'; OS << format("%*u", FunctionReportColumns[4], (unsigned)Function.LineCoverage.NumLines); Options.colored_ostream(OS, LineCoverageColor) << format("%*u", FunctionReportColumns[5], (unsigned)Function.LineCoverage.NotCovered); Options.colored_ostream( OS, determineCoveragePercentageColor(Function.LineCoverage)) << format("%*.2f", FunctionReportColumns[6] - 1, Function.LineCoverage.getPercentCovered()) << '%'; OS << "\n"; } void CoverageReport::renderFunctionReports(ArrayRef<std::string> Files, const DemangleCache &DC, raw_ostream &OS) { bool isFirst = true; for (StringRef Filename : Files) { auto Functions = Coverage.getCoveredFunctions(Filename); if (isFirst) isFirst = false; else OS << "\n"; std::vector<StringRef> Funcnames; for (const auto &F : Functions) Funcnames.emplace_back(DC.demangle(F.Name)); adjustColumnWidths({}, Funcnames); OS << "File '" << Filename << "':\n"; OS << column("Name", FunctionReportColumns[0]) << column("Regions", FunctionReportColumns[1], Column::RightAlignment) << column("Miss", FunctionReportColumns[2], Column::RightAlignment) << column("Cover", FunctionReportColumns[3], Column::RightAlignment) << column("Lines", FunctionReportColumns[4], Column::RightAlignment) << column("Miss", FunctionReportColumns[5], Column::RightAlignment) << column("Cover", FunctionReportColumns[6], Column::RightAlignment); OS << "\n"; renderDivider(FunctionReportColumns, OS); OS << "\n"; FunctionCoverageSummary Totals("TOTAL"); for (const auto &F : Functions) { FunctionCoverageSummary Function = FunctionCoverageSummary::get(F); ++Totals.ExecutionCount; Totals.RegionCoverage += Function.RegionCoverage; Totals.LineCoverage += Function.LineCoverage; render(Function, DC, OS); } if (Totals.ExecutionCount) { renderDivider(FunctionReportColumns, OS); OS << "\n"; render(Totals, DC, OS); } } } std::vector<FileCoverageSummary> CoverageReport::prepareFileReports(const coverage::CoverageMapping &Coverage, FileCoverageSummary &Totals, ArrayRef<std::string> Files) { std::vector<FileCoverageSummary> FileReports; unsigned LCP = getRedundantPrefixLen(Files); for (StringRef Filename : Files) { FileCoverageSummary Summary(Filename.drop_front(LCP)); // Map source locations to aggregate function coverage summaries. DenseMap<std::pair<unsigned, unsigned>, FunctionCoverageSummary> Summaries; for (const auto &F : Coverage.getCoveredFunctions(Filename)) { FunctionCoverageSummary Function = FunctionCoverageSummary::get(F); auto StartLoc = F.CountedRegions[0].startLoc(); auto UniquedSummary = Summaries.insert({StartLoc, Function}); if (!UniquedSummary.second) UniquedSummary.first->second.update(Function); Summary.addInstantiation(Function); Totals.addInstantiation(Function); } for (const auto &UniquedSummary : Summaries) { const FunctionCoverageSummary &FCS = UniquedSummary.second; Summary.addFunction(FCS); Totals.addFunction(FCS); } FileReports.push_back(Summary); } return FileReports; } void CoverageReport::renderFileReports(raw_ostream &OS) const { std::vector<std::string> UniqueSourceFiles; for (StringRef SF : Coverage.getUniqueSourceFiles()) UniqueSourceFiles.emplace_back(SF.str()); renderFileReports(OS, UniqueSourceFiles); } void CoverageReport::renderFileReports(raw_ostream &OS, ArrayRef<std::string> Files) const { FileCoverageSummary Totals("TOTAL"); auto FileReports = prepareFileReports(Coverage, Totals, Files); std::vector<StringRef> Filenames; for (const FileCoverageSummary &FCS : FileReports) Filenames.emplace_back(FCS.Name); adjustColumnWidths(Filenames, {}); OS << column("Filename", FileReportColumns[0]) << column("Regions", FileReportColumns[1], Column::RightAlignment) << column("Missed Regions", FileReportColumns[2], Column::RightAlignment) << column("Cover", FileReportColumns[3], Column::RightAlignment) << column("Functions", FileReportColumns[4], Column::RightAlignment) << column("Missed Functions", FileReportColumns[5], Column::RightAlignment) << column("Executed", FileReportColumns[6], Column::RightAlignment) << column("Instantiations", FileReportColumns[7], Column::RightAlignment) << column("Missed Insts.", FileReportColumns[8], Column::RightAlignment) << column("Executed", FileReportColumns[9], Column::RightAlignment) << column("Lines", FileReportColumns[10], Column::RightAlignment) << column("Missed Lines", FileReportColumns[11], Column::RightAlignment) << column("Cover", FileReportColumns[12], Column::RightAlignment) << "\n"; renderDivider(FileReportColumns, OS); OS << "\n"; for (const FileCoverageSummary &FCS : FileReports) render(FCS, OS); renderDivider(FileReportColumns, OS); OS << "\n"; render(Totals, OS); } } // end namespace llvm <commit_msg>Use the new member accessors of llvm::enumerate.<commit_after>//===- CoverageReport.cpp - Code coverage report -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements rendering of a code coverage report. // //===----------------------------------------------------------------------===// #include "CoverageReport.h" #include "RenderingSupport.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/Path.h" #include <numeric> using namespace llvm; namespace { /// \brief Helper struct which prints trimmed and aligned columns. struct Column { enum TrimKind { NoTrim, WidthTrim, RightTrim }; enum AlignmentKind { LeftAlignment, RightAlignment }; StringRef Str; unsigned Width; TrimKind Trim; AlignmentKind Alignment; Column(StringRef Str, unsigned Width) : Str(Str), Width(Width), Trim(WidthTrim), Alignment(LeftAlignment) {} Column &set(TrimKind Value) { Trim = Value; return *this; } Column &set(AlignmentKind Value) { Alignment = Value; return *this; } void render(raw_ostream &OS) const { if (Str.size() <= Width) { if (Alignment == RightAlignment) { OS.indent(Width - Str.size()); OS << Str; return; } OS << Str; OS.indent(Width - Str.size()); return; } switch (Trim) { case NoTrim: OS << Str; break; case WidthTrim: OS << Str.substr(0, Width); break; case RightTrim: OS << Str.substr(0, Width - 3) << "..."; break; } } }; raw_ostream &operator<<(raw_ostream &OS, const Column &Value) { Value.render(OS); return OS; } Column column(StringRef Str, unsigned Width) { return Column(Str, Width); } template <typename T> Column column(StringRef Str, unsigned Width, const T &Value) { return Column(Str, Width).set(Value); } // Specify the default column widths. size_t FileReportColumns[] = {25, 12, 18, 10, 12, 18, 10, 16, 16, 10, 12, 18, 10}; size_t FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8}; /// \brief Adjust column widths to fit long file paths and function names. void adjustColumnWidths(ArrayRef<StringRef> Files, ArrayRef<StringRef> Functions) { for (StringRef Filename : Files) FileReportColumns[0] = std::max(FileReportColumns[0], Filename.size()); for (StringRef Funcname : Functions) FunctionReportColumns[0] = std::max(FunctionReportColumns[0], Funcname.size()); } /// \brief Prints a horizontal divider long enough to cover the given column /// widths. void renderDivider(ArrayRef<size_t> ColumnWidths, raw_ostream &OS) { size_t Length = std::accumulate(ColumnWidths.begin(), ColumnWidths.end(), 0); for (size_t I = 0; I < Length; ++I) OS << '-'; } /// \brief Return the color which correponds to the coverage percentage of a /// certain metric. template <typename T> raw_ostream::Colors determineCoveragePercentageColor(const T &Info) { if (Info.isFullyCovered()) return raw_ostream::GREEN; return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW : raw_ostream::RED; } /// \brief Get the number of redundant path components in each path in \p Paths. unsigned getNumRedundantPathComponents(ArrayRef<std::string> Paths) { // To start, set the number of redundant path components to the maximum // possible value. SmallVector<StringRef, 8> FirstPathComponents{sys::path::begin(Paths[0]), sys::path::end(Paths[0])}; unsigned NumRedundant = FirstPathComponents.size(); for (unsigned I = 1, E = Paths.size(); NumRedundant > 0 && I < E; ++I) { StringRef Path = Paths[I]; for (const auto &Component : enumerate(make_range(sys::path::begin(Path), sys::path::end(Path)))) { // Do not increase the number of redundant components: that would remove // useful parts of already-visited paths. if (Component.index() >= NumRedundant) break; // Lower the number of redundant components when there's a mismatch // between the first path, and the path under consideration. if (FirstPathComponents[Component.index()] != Component.value()) { NumRedundant = Component.index(); break; } } } return NumRedundant; } /// \brief Determine the length of the longest redundant prefix of the paths in /// \p Paths. unsigned getRedundantPrefixLen(ArrayRef<std::string> Paths) { // If there's at most one path, no path components are redundant. if (Paths.size() <= 1) return 0; unsigned PrefixLen = 0; unsigned NumRedundant = getNumRedundantPathComponents(Paths); auto Component = sys::path::begin(Paths[0]); for (unsigned I = 0; I < NumRedundant; ++I) { auto LastComponent = Component; ++Component; PrefixLen += Component - LastComponent; } return PrefixLen; } } // end anonymous namespace namespace llvm { void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) const { auto FileCoverageColor = determineCoveragePercentageColor(File.RegionCoverage); auto FuncCoverageColor = determineCoveragePercentageColor(File.FunctionCoverage); auto InstantiationCoverageColor = determineCoveragePercentageColor(File.InstantiationCoverage); auto LineCoverageColor = determineCoveragePercentageColor(File.LineCoverage); SmallString<256> FileName = File.Name; sys::path::remove_dots(FileName, /*remove_dot_dots=*/true); sys::path::native(FileName); OS << column(FileName, FileReportColumns[0], Column::NoTrim) << format("%*u", FileReportColumns[1], (unsigned)File.RegionCoverage.NumRegions); Options.colored_ostream(OS, FileCoverageColor) << format( "%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered); if (File.RegionCoverage.NumRegions) Options.colored_ostream(OS, FileCoverageColor) << format("%*.2f", FileReportColumns[3] - 1, File.RegionCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[3], Column::RightAlignment); OS << format("%*u", FileReportColumns[4], (unsigned)File.FunctionCoverage.NumFunctions); OS << format("%*u", FileReportColumns[5], (unsigned)(File.FunctionCoverage.NumFunctions - File.FunctionCoverage.Executed)); if (File.FunctionCoverage.NumFunctions) Options.colored_ostream(OS, FuncCoverageColor) << format("%*.2f", FileReportColumns[6] - 1, File.FunctionCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[6], Column::RightAlignment); OS << format("%*u", FileReportColumns[7], (unsigned)File.InstantiationCoverage.NumFunctions); OS << format("%*u", FileReportColumns[8], (unsigned)(File.InstantiationCoverage.NumFunctions - File.InstantiationCoverage.Executed)); if (File.InstantiationCoverage.NumFunctions) Options.colored_ostream(OS, InstantiationCoverageColor) << format("%*.2f", FileReportColumns[9] - 1, File.InstantiationCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[9], Column::RightAlignment); OS << format("%*u", FileReportColumns[10], (unsigned)File.LineCoverage.NumLines); Options.colored_ostream(OS, LineCoverageColor) << format( "%*u", FileReportColumns[11], (unsigned)File.LineCoverage.NotCovered); if (File.LineCoverage.NumLines) Options.colored_ostream(OS, LineCoverageColor) << format("%*.2f", FileReportColumns[12] - 1, File.LineCoverage.getPercentCovered()) << '%'; else OS << column("-", FileReportColumns[12], Column::RightAlignment); OS << "\n"; } void CoverageReport::render(const FunctionCoverageSummary &Function, const DemangleCache &DC, raw_ostream &OS) const { auto FuncCoverageColor = determineCoveragePercentageColor(Function.RegionCoverage); auto LineCoverageColor = determineCoveragePercentageColor(Function.LineCoverage); OS << column(DC.demangle(Function.Name), FunctionReportColumns[0], Column::RightTrim) << format("%*u", FunctionReportColumns[1], (unsigned)Function.RegionCoverage.NumRegions); Options.colored_ostream(OS, FuncCoverageColor) << format("%*u", FunctionReportColumns[2], (unsigned)Function.RegionCoverage.NotCovered); Options.colored_ostream( OS, determineCoveragePercentageColor(Function.RegionCoverage)) << format("%*.2f", FunctionReportColumns[3] - 1, Function.RegionCoverage.getPercentCovered()) << '%'; OS << format("%*u", FunctionReportColumns[4], (unsigned)Function.LineCoverage.NumLines); Options.colored_ostream(OS, LineCoverageColor) << format("%*u", FunctionReportColumns[5], (unsigned)Function.LineCoverage.NotCovered); Options.colored_ostream( OS, determineCoveragePercentageColor(Function.LineCoverage)) << format("%*.2f", FunctionReportColumns[6] - 1, Function.LineCoverage.getPercentCovered()) << '%'; OS << "\n"; } void CoverageReport::renderFunctionReports(ArrayRef<std::string> Files, const DemangleCache &DC, raw_ostream &OS) { bool isFirst = true; for (StringRef Filename : Files) { auto Functions = Coverage.getCoveredFunctions(Filename); if (isFirst) isFirst = false; else OS << "\n"; std::vector<StringRef> Funcnames; for (const auto &F : Functions) Funcnames.emplace_back(DC.demangle(F.Name)); adjustColumnWidths({}, Funcnames); OS << "File '" << Filename << "':\n"; OS << column("Name", FunctionReportColumns[0]) << column("Regions", FunctionReportColumns[1], Column::RightAlignment) << column("Miss", FunctionReportColumns[2], Column::RightAlignment) << column("Cover", FunctionReportColumns[3], Column::RightAlignment) << column("Lines", FunctionReportColumns[4], Column::RightAlignment) << column("Miss", FunctionReportColumns[5], Column::RightAlignment) << column("Cover", FunctionReportColumns[6], Column::RightAlignment); OS << "\n"; renderDivider(FunctionReportColumns, OS); OS << "\n"; FunctionCoverageSummary Totals("TOTAL"); for (const auto &F : Functions) { FunctionCoverageSummary Function = FunctionCoverageSummary::get(F); ++Totals.ExecutionCount; Totals.RegionCoverage += Function.RegionCoverage; Totals.LineCoverage += Function.LineCoverage; render(Function, DC, OS); } if (Totals.ExecutionCount) { renderDivider(FunctionReportColumns, OS); OS << "\n"; render(Totals, DC, OS); } } } std::vector<FileCoverageSummary> CoverageReport::prepareFileReports(const coverage::CoverageMapping &Coverage, FileCoverageSummary &Totals, ArrayRef<std::string> Files) { std::vector<FileCoverageSummary> FileReports; unsigned LCP = getRedundantPrefixLen(Files); for (StringRef Filename : Files) { FileCoverageSummary Summary(Filename.drop_front(LCP)); // Map source locations to aggregate function coverage summaries. DenseMap<std::pair<unsigned, unsigned>, FunctionCoverageSummary> Summaries; for (const auto &F : Coverage.getCoveredFunctions(Filename)) { FunctionCoverageSummary Function = FunctionCoverageSummary::get(F); auto StartLoc = F.CountedRegions[0].startLoc(); auto UniquedSummary = Summaries.insert({StartLoc, Function}); if (!UniquedSummary.second) UniquedSummary.first->second.update(Function); Summary.addInstantiation(Function); Totals.addInstantiation(Function); } for (const auto &UniquedSummary : Summaries) { const FunctionCoverageSummary &FCS = UniquedSummary.second; Summary.addFunction(FCS); Totals.addFunction(FCS); } FileReports.push_back(Summary); } return FileReports; } void CoverageReport::renderFileReports(raw_ostream &OS) const { std::vector<std::string> UniqueSourceFiles; for (StringRef SF : Coverage.getUniqueSourceFiles()) UniqueSourceFiles.emplace_back(SF.str()); renderFileReports(OS, UniqueSourceFiles); } void CoverageReport::renderFileReports(raw_ostream &OS, ArrayRef<std::string> Files) const { FileCoverageSummary Totals("TOTAL"); auto FileReports = prepareFileReports(Coverage, Totals, Files); std::vector<StringRef> Filenames; for (const FileCoverageSummary &FCS : FileReports) Filenames.emplace_back(FCS.Name); adjustColumnWidths(Filenames, {}); OS << column("Filename", FileReportColumns[0]) << column("Regions", FileReportColumns[1], Column::RightAlignment) << column("Missed Regions", FileReportColumns[2], Column::RightAlignment) << column("Cover", FileReportColumns[3], Column::RightAlignment) << column("Functions", FileReportColumns[4], Column::RightAlignment) << column("Missed Functions", FileReportColumns[5], Column::RightAlignment) << column("Executed", FileReportColumns[6], Column::RightAlignment) << column("Instantiations", FileReportColumns[7], Column::RightAlignment) << column("Missed Insts.", FileReportColumns[8], Column::RightAlignment) << column("Executed", FileReportColumns[9], Column::RightAlignment) << column("Lines", FileReportColumns[10], Column::RightAlignment) << column("Missed Lines", FileReportColumns[11], Column::RightAlignment) << column("Cover", FileReportColumns[12], Column::RightAlignment) << "\n"; renderDivider(FileReportColumns, OS); OS << "\n"; for (const FileCoverageSummary &FCS : FileReports) render(FCS, OS); renderDivider(FileReportColumns, OS); OS << "\n"; render(Totals, OS); } } // end namespace llvm <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/logging.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/download/download_util.h" #include "testing/gtest/include/gtest/gtest.h" class DownloadManagerTest : public testing::Test { public: DownloadManagerTest() { download_manager_ = new DownloadManager(); download_util::InitializeExeTypes(&download_manager_->exe_types_); } void GetGeneratedFilename(const std::string& content_disposition, const std::wstring& url, const std::string& mime_type, std::wstring* generated_name_string) { DownloadCreateInfo info; info.content_disposition = content_disposition; info.url = url; info.mime_type = mime_type; FilePath generated_name; download_manager_->GenerateFilename(&info, &generated_name); *generated_name_string = generated_name.ToWStringHack(); } protected: scoped_refptr<DownloadManager> download_manager_; MessageLoopForUI message_loop_; DISALLOW_EVIL_CONSTRUCTORS(DownloadManagerTest); }; namespace { const struct { const char* disposition; const wchar_t* url; const char* mime_type; const wchar_t* expected_name; } kGeneratedFiles[] = { // No 'filename' keyword in the disposition, use the URL {"a_file_name.txt", L"http://www.evil.com/my_download.txt", "text/plain", L"my_download.txt"}, // Disposition has relative paths, remove them {"filename=../../../../././../a_file_name.txt", L"http://www.evil.com/my_download.txt", "text/plain", L"a_file_name.txt"}, // Disposition has parent directories, remove them {"filename=dir1/dir2/a_file_name.txt", L"http://www.evil.com/my_download.txt", "text/plain", L"a_file_name.txt"}, // No useful information in disposition or URL, use default {"", L"http://www.truncated.com/path/", "text/plain", L"download.txt"}, // Spaces in the disposition file name {"filename=My Downloaded File.exe", L"http://www.frontpagehacker.com/a_download.exe", "application/octet-stream", L"My Downloaded File.exe"}, {"filename=my-cat", L"http://www.example.com/my-cat", "image/jpeg", L"my-cat.jpg"}, {"filename=my-cat", L"http://www.example.com/my-cat", "text/plain", L"my-cat.txt"}, {"filename=my-cat", L"http://www.example.com/my-cat", "text/html", L"my-cat.htm"}, {"filename=my-cat", L"http://www.example.com/my-cat", "dance/party", L"my-cat"}, {"filename=my-cat.jpg", L"http://www.example.com/my-cat.jpg", "text/plain", L"my-cat.jpg"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "image/jpeg", L"evil.jpg"}, {"filename=ok.exe", L"http://www.goodguy.com/ok.exe", "binary/octet-stream", L"ok.exe"}, {"filename=evil.exe.exe", L"http://www.goodguy.com/evil.exe.exe", "dance/party", L"evil.exe.download"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "application/xml", L"evil.xml"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "application/html+xml", L"evil.download"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "application/rss+xml", L"evil.download"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "application/x-javascript", L"utils.js"}, {"filename=contacts.js", L"http://www.goodguy.com/contacts.js", "application/json", L"contacts.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "text/javascript", L"utils.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "text/javascript;version=2", L"utils.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "application/ecmascript", L"utils.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "application/ecmascript;version=4", L"utils.js"}, {"filename=program.exe", L"http://www.goodguy.com/program.exe", "application/foo-bar", L"program.exe"}, {"filename=../foo.txt", L"http://www.evil.com/../foo.txt", "text/plain", L"foo.txt"}, {"filename=..\\foo.txt", L"http://www.evil.com/..\\foo.txt", "text/plain", L"foo.txt"}, {"filename=.hidden", L"http://www.evil.com/.hidden", "text/plain", L"hidden.txt"}, {"filename=trailing.", L"http://www.evil.com/trailing.", "dance/party", L"trailing"}, {"filename=trailing.", L"http://www.evil.com/trailing.", "text/plain", L"trailing.txt"}, {"filename=.", L"http://www.evil.com/.", "dance/party", L"download"}, {"filename=..", L"http://www.evil.com/..", "dance/party", L"download"}, {"filename=...", L"http://www.evil.com/...", "dance/party", L"download"}, {"a_file_name.txt", L"http://www.evil.com/", "image/jpeg", L"download.jpg"}, {"filename=", L"http://www.evil.com/", "image/jpeg", L"download.jpg"}, {"filename=simple", L"http://www.example.com/simple", "application/octet-stream", L"simple"}, {"filename=COM1", L"http://www.goodguy.com/COM1", "application/foo-bar", L"_COM1"}, {"filename=COM4.txt", L"http://www.goodguy.com/COM4.txt", "text/plain", L"_COM4.txt"}, {"filename=lpt1.TXT", L"http://www.goodguy.com/lpt1.TXT", "text/plain", L"_lpt1.TXT"}, {"filename=clock$.txt", L"http://www.goodguy.com/clock$.txt", "text/plain", L"_clock$.txt"}, {"filename=mycom1.foo", L"http://www.goodguy.com/mycom1.foo", "text/plain", L"mycom1.foo"}, {"filename=Setup.exe.local", L"http://www.badguy.com/Setup.exe.local", "application/foo-bar", L"Setup.exe.download"}, {"filename=Setup.exe.local.local", L"http://www.badguy.com/Setup.exe.local", "application/foo-bar", L"Setup.exe.local.download"}, {"filename=Setup.exe.lnk", L"http://www.badguy.com/Setup.exe.lnk", "application/foo-bar", L"Setup.exe.download"}, {"filename=Desktop.ini", L"http://www.badguy.com/Desktop.ini", "application/foo-bar", L"_Desktop.ini"}, {"filename=Thumbs.db", L"http://www.badguy.com/Thumbs.db", "application/foo-bar", L"_Thumbs.db"}, {"filename=source.srf", L"http://www.hotmail.com", "image/jpeg", L"source.srf.jpg"}, {"filename=source.jpg", L"http://www.hotmail.com", "application/x-javascript", L"source.jpg"}, // NetUtilTest.{GetSuggestedFilename, GetFileNameFromCD} test these // more thoroughly. Tested below are a small set of samples. {"attachment; filename=\"%EC%98%88%EC%88%A0%20%EC%98%88%EC%88%A0.jpg\"", L"http://www.examples.com/", "image/jpeg", L"\uc608\uc220 \uc608\uc220.jpg"}, {"attachment; name=abc de.pdf", L"http://www.examples.com/q.cgi?id=abc", "application/octet-stream", L"abc de.pdf"}, {"filename=\"=?EUC-JP?Q?=B7=DD=BD=D13=2Epng?=\"", L"http://www.example.com/path", "image/png", L"\x82b8\x8853" L"3.png"}, // The following two have invalid CD headers and filenames come // from the URL. {"attachment; filename==?iiso88591?Q?caf=EG?=", L"http://www.example.com/test%20123", "image/jpeg", L"test 123.jpg"}, {"malformed_disposition", L"http://www.google.com/%EC%98%88%EC%88%A0%20%EC%98%88%EC%88%A0.jpg", "image/jpeg", L"\uc608\uc220 \uc608\uc220.jpg"}, // Invalid C-D. No filename from URL. Falls back to 'download'. {"attachment; filename==?iso88591?Q?caf=E3?", L"http://www.google.com/path1/path2/", "image/jpeg", L"download.jpg"}, // TODO(darin): Add some raw 8-bit Content-Disposition tests. }; } // namespace // Tests to ensure that the file names we generate from hints from the server // (content-disposition, URL name, etc) don't cause security holes. TEST_F(DownloadManagerTest, TestDownloadFilename) { for (int i = 0; i < arraysize(kGeneratedFiles); ++i) { std::wstring file_name; GetGeneratedFilename(kGeneratedFiles[i].disposition, kGeneratedFiles[i].url, kGeneratedFiles[i].mime_type, &file_name); EXPECT_EQ(kGeneratedFiles[i].expected_name, file_name); } } namespace { const struct { const FilePath::CharType* path; const char* mime_type; const FilePath::CharType* expected_path; } kSafeFilenameCases[] = { { FILE_PATH_LITERAL("C:\\foo\\bar.htm"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.htm") }, { FILE_PATH_LITERAL("C:\\foo\\bar.html"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.html") }, { FILE_PATH_LITERAL("C:\\foo\\bar"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.htm") }, { FILE_PATH_LITERAL("C:\\bar.html"), "image/png", FILE_PATH_LITERAL("C:\\bar.png") }, { FILE_PATH_LITERAL("C:\\bar"), "image/png", FILE_PATH_LITERAL("C:\\bar.png") }, { FILE_PATH_LITERAL("C:\\foo\\bar.exe"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.htm") }, { FILE_PATH_LITERAL("C:\\foo\\bar.exe"), "image/gif", FILE_PATH_LITERAL("C:\\foo\\bar.gif") }, { FILE_PATH_LITERAL("C:\\foo\\google.com"), "text/html", FILE_PATH_LITERAL("C:\\foo\\google.htm") }, { FILE_PATH_LITERAL("C:\\foo\\con.htm"), "text/html", FILE_PATH_LITERAL("C:\\foo\\_con.htm") }, { FILE_PATH_LITERAL("C:\\foo\\con"), "text/html", FILE_PATH_LITERAL("C:\\foo\\_con.htm") }, }; } // namespace TEST_F(DownloadManagerTest, GetSafeFilename) { for (int i = 0; i < arraysize(kSafeFilenameCases); ++i) { FilePath path(kSafeFilenameCases[i].path); download_manager_->GenerateSafeFilename(kSafeFilenameCases[i].mime_type, &path); EXPECT_EQ(kSafeFilenameCases[i].expected_path, path.value()); } } <commit_msg>disable download test while sid fixes offline<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/logging.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/download/download_util.h" #include "testing/gtest/include/gtest/gtest.h" class DownloadManagerTest : public testing::Test { public: DownloadManagerTest() { download_manager_ = new DownloadManager(); download_util::InitializeExeTypes(&download_manager_->exe_types_); } void GetGeneratedFilename(const std::string& content_disposition, const std::wstring& url, const std::string& mime_type, std::wstring* generated_name_string) { DownloadCreateInfo info; info.content_disposition = content_disposition; info.url = url; info.mime_type = mime_type; FilePath generated_name; download_manager_->GenerateFilename(&info, &generated_name); *generated_name_string = generated_name.ToWStringHack(); } protected: scoped_refptr<DownloadManager> download_manager_; MessageLoopForUI message_loop_; DISALLOW_EVIL_CONSTRUCTORS(DownloadManagerTest); }; namespace { const struct { const char* disposition; const wchar_t* url; const char* mime_type; const wchar_t* expected_name; } kGeneratedFiles[] = { // No 'filename' keyword in the disposition, use the URL {"a_file_name.txt", L"http://www.evil.com/my_download.txt", "text/plain", L"my_download.txt"}, // Disposition has relative paths, remove them {"filename=../../../../././../a_file_name.txt", L"http://www.evil.com/my_download.txt", "text/plain", L"a_file_name.txt"}, // Disposition has parent directories, remove them {"filename=dir1/dir2/a_file_name.txt", L"http://www.evil.com/my_download.txt", "text/plain", L"a_file_name.txt"}, // No useful information in disposition or URL, use default {"", L"http://www.truncated.com/path/", "text/plain", L"download.txt"}, // Spaces in the disposition file name {"filename=My Downloaded File.exe", L"http://www.frontpagehacker.com/a_download.exe", "application/octet-stream", L"My Downloaded File.exe"}, {"filename=my-cat", L"http://www.example.com/my-cat", "image/jpeg", L"my-cat.jpg"}, {"filename=my-cat", L"http://www.example.com/my-cat", "text/plain", L"my-cat.txt"}, {"filename=my-cat", L"http://www.example.com/my-cat", "text/html", L"my-cat.htm"}, {"filename=my-cat", L"http://www.example.com/my-cat", "dance/party", L"my-cat"}, {"filename=my-cat.jpg", L"http://www.example.com/my-cat.jpg", "text/plain", L"my-cat.jpg"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "image/jpeg", L"evil.jpg"}, {"filename=ok.exe", L"http://www.goodguy.com/ok.exe", "binary/octet-stream", L"ok.exe"}, {"filename=evil.exe.exe", L"http://www.goodguy.com/evil.exe.exe", "dance/party", L"evil.exe.download"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "application/xml", L"evil.xml"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "application/html+xml", L"evil.download"}, {"filename=evil.exe", L"http://www.goodguy.com/evil.exe", "application/rss+xml", L"evil.download"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "application/x-javascript", L"utils.js"}, {"filename=contacts.js", L"http://www.goodguy.com/contacts.js", "application/json", L"contacts.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "text/javascript", L"utils.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "text/javascript;version=2", L"utils.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "application/ecmascript", L"utils.js"}, {"filename=utils.js", L"http://www.goodguy.com/utils.js", "application/ecmascript;version=4", L"utils.js"}, {"filename=program.exe", L"http://www.goodguy.com/program.exe", "application/foo-bar", L"program.exe"}, {"filename=../foo.txt", L"http://www.evil.com/../foo.txt", "text/plain", L"foo.txt"}, {"filename=..\\foo.txt", L"http://www.evil.com/..\\foo.txt", "text/plain", L"foo.txt"}, {"filename=.hidden", L"http://www.evil.com/.hidden", "text/plain", L"hidden.txt"}, {"filename=trailing.", L"http://www.evil.com/trailing.", "dance/party", L"trailing"}, {"filename=trailing.", L"http://www.evil.com/trailing.", "text/plain", L"trailing.txt"}, {"filename=.", L"http://www.evil.com/.", "dance/party", L"download"}, {"filename=..", L"http://www.evil.com/..", "dance/party", L"download"}, {"filename=...", L"http://www.evil.com/...", "dance/party", L"download"}, {"a_file_name.txt", L"http://www.evil.com/", "image/jpeg", L"download.jpg"}, {"filename=", L"http://www.evil.com/", "image/jpeg", L"download.jpg"}, {"filename=simple", L"http://www.example.com/simple", "application/octet-stream", L"simple"}, {"filename=COM1", L"http://www.goodguy.com/COM1", "application/foo-bar", L"_COM1"}, {"filename=COM4.txt", L"http://www.goodguy.com/COM4.txt", "text/plain", L"_COM4.txt"}, {"filename=lpt1.TXT", L"http://www.goodguy.com/lpt1.TXT", "text/plain", L"_lpt1.TXT"}, {"filename=clock$.txt", L"http://www.goodguy.com/clock$.txt", "text/plain", L"_clock$.txt"}, {"filename=mycom1.foo", L"http://www.goodguy.com/mycom1.foo", "text/plain", L"mycom1.foo"}, {"filename=Setup.exe.local", L"http://www.badguy.com/Setup.exe.local", "application/foo-bar", L"Setup.exe.download"}, {"filename=Setup.exe.local.local", L"http://www.badguy.com/Setup.exe.local", "application/foo-bar", L"Setup.exe.local.download"}, {"filename=Setup.exe.lnk", L"http://www.badguy.com/Setup.exe.lnk", "application/foo-bar", L"Setup.exe.download"}, {"filename=Desktop.ini", L"http://www.badguy.com/Desktop.ini", "application/foo-bar", L"_Desktop.ini"}, {"filename=Thumbs.db", L"http://www.badguy.com/Thumbs.db", "application/foo-bar", L"_Thumbs.db"}, {"filename=source.srf", L"http://www.hotmail.com", "image/jpeg", L"source.srf.jpg"}, {"filename=source.jpg", L"http://www.hotmail.com", "application/x-javascript", L"source.jpg"}, // NetUtilTest.{GetSuggestedFilename, GetFileNameFromCD} test these // more thoroughly. Tested below are a small set of samples. {"attachment; filename=\"%EC%98%88%EC%88%A0%20%EC%98%88%EC%88%A0.jpg\"", L"http://www.examples.com/", "image/jpeg", L"\uc608\uc220 \uc608\uc220.jpg"}, {"attachment; name=abc de.pdf", L"http://www.examples.com/q.cgi?id=abc", "application/octet-stream", L"abc de.pdf"}, {"filename=\"=?EUC-JP?Q?=B7=DD=BD=D13=2Epng?=\"", L"http://www.example.com/path", "image/png", L"\x82b8\x8853" L"3.png"}, // The following two have invalid CD headers and filenames come // from the URL. {"attachment; filename==?iiso88591?Q?caf=EG?=", L"http://www.example.com/test%20123", "image/jpeg", L"test 123.jpg"}, {"malformed_disposition", L"http://www.google.com/%EC%98%88%EC%88%A0%20%EC%98%88%EC%88%A0.jpg", "image/jpeg", L"\uc608\uc220 \uc608\uc220.jpg"}, // Invalid C-D. No filename from URL. Falls back to 'download'. {"attachment; filename==?iso88591?Q?caf=E3?", L"http://www.google.com/path1/path2/", "image/jpeg", L"download.jpg"}, // TODO(darin): Add some raw 8-bit Content-Disposition tests. }; } // namespace // Tests to ensure that the file names we generate from hints from the server // (content-disposition, URL name, etc) don't cause security holes. TEST_F(DownloadManagerTest, DISABLED_TestDownloadFilename) { for (int i = 0; i < arraysize(kGeneratedFiles); ++i) { std::wstring file_name; GetGeneratedFilename(kGeneratedFiles[i].disposition, kGeneratedFiles[i].url, kGeneratedFiles[i].mime_type, &file_name); EXPECT_EQ(kGeneratedFiles[i].expected_name, file_name); } } namespace { const struct { const FilePath::CharType* path; const char* mime_type; const FilePath::CharType* expected_path; } kSafeFilenameCases[] = { { FILE_PATH_LITERAL("C:\\foo\\bar.htm"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.htm") }, { FILE_PATH_LITERAL("C:\\foo\\bar.html"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.html") }, { FILE_PATH_LITERAL("C:\\foo\\bar"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.htm") }, { FILE_PATH_LITERAL("C:\\bar.html"), "image/png", FILE_PATH_LITERAL("C:\\bar.png") }, { FILE_PATH_LITERAL("C:\\bar"), "image/png", FILE_PATH_LITERAL("C:\\bar.png") }, { FILE_PATH_LITERAL("C:\\foo\\bar.exe"), "text/html", FILE_PATH_LITERAL("C:\\foo\\bar.htm") }, { FILE_PATH_LITERAL("C:\\foo\\bar.exe"), "image/gif", FILE_PATH_LITERAL("C:\\foo\\bar.gif") }, { FILE_PATH_LITERAL("C:\\foo\\google.com"), "text/html", FILE_PATH_LITERAL("C:\\foo\\google.htm") }, { FILE_PATH_LITERAL("C:\\foo\\con.htm"), "text/html", FILE_PATH_LITERAL("C:\\foo\\_con.htm") }, { FILE_PATH_LITERAL("C:\\foo\\con"), "text/html", FILE_PATH_LITERAL("C:\\foo\\_con.htm") }, }; } // namespace TEST_F(DownloadManagerTest, GetSafeFilename) { for (int i = 0; i < arraysize(kSafeFilenameCases); ++i) { FilePath path(kSafeFilenameCases[i].path); download_manager_->GenerateSafeFilename(kSafeFilenameCases[i].mime_type, &path); EXPECT_EQ(kSafeFilenameCases[i].expected_path, path.value()); } } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" class ExtensionManagementTest : public ExtensionBrowserTest { protected: // Helper method that returns whether the extension is at the given version. // This calls version(), which must be defined in the extension's bg page, // as well as asking the extension itself. // // Note that 'version' here means something different than the version field // in the extension's manifest. We use the version as reported by the // background page to test how overinstalling crx files with the same // manifest version works. bool IsExtensionAtVersion(Extension* extension, const std::string& expected_version) { // Test that the extension's version from the manifest and reported by the // background page is correct. This is to ensure that the processes are in // sync with the Extension. ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension); EXPECT_TRUE(ext_host); if (!ext_host) return false; std::string version_from_bg; bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString( ext_host->render_view_host(), L"", L"version()", &version_from_bg); EXPECT_TRUE(exec); if (!exec) return false; if (version_from_bg != expected_version || extension->VersionString() != expected_version) return false; return true; } // Helper method that installs a low permission extension then updates // to the second version requiring increased permissions. Returns whether // the operation was completed successfully. bool InstallAndUpdateIncreasingPermissionsExtension() { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t size_before = service->extensions()->size(); // Install the initial version, which should happen just fine. if (!InstallExtension( test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1)) return false; // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. if (service->extensions()->size() != size_before + 1) return false; if (!UpdateExtension( service->extensions()->at(size_before)->id(), test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1)) return false; EXPECT_EQ(size_before, service->extensions()->size()); if (service->disabled_extensions()->size() != 1u) return false; return true; } }; // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); FilePath old_path = service->extensions()->back()->path(); // Install an extension with the same version. The previous install should be // overwritten. ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_same_version.crx"), 0)); FilePath new_path = service->extensions()->back()->path(); EXPECT_FALSE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); EXPECT_NE(old_path.value(), new_path.value()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); // Cancel this install. StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx")); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } #if defined(OS_MACOSX) // See http://crbug.com/46097 #define MAYBE_Incognito FLAKY_Incognito #else #define MAYBE_Incognito Incognito #endif // Tests that installing and uninstalling extensions don't crash with an // incognito window open. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_Incognito) { // Open an incognito window to the extensions management page. We just // want to make sure that we don't crash while playing with extensions when // this guy is around. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL(chrome::kChromeUIExtensionsURL)); ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1)); UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf"); } // Tests the process of updating an extension to one that requires higher // permissions. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try reenabling it. service->EnableExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that we can uninstall a disabled extension. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try uninstalling it. UninstallExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that disabling and re-enabling an extension works. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) { ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); // Load an extension, expect the background page to be available. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("good").AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"))); ASSERT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); Extension* extension = service->extensions()->at(size_before); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // After disabling, the background page should go away. service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(1u, service->disabled_extensions()->size()); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // And bring it back. service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); } // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1)); listener1.WaitUntilSatisfied(); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_TRUE(service->HasInstalledExtensions()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("1.0", extensions->at(size_before)->VersionString()); // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); // Run autoupdate and make sure version 2 of the extension was installed. ExtensionTestMessageListener listener2("v2 installed", false); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); listener2.WaitUntilSatisfied(); extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v3.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstallError()); // Make sure the extension state is the same as before. extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); } // See http://crbug.com/57378 for flakiness details. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, FLAKY_ExternalUrlUpdate) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const char* kExtensionId = "ogjcoiohnmldgjemafoockdghcjciccf"; // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); // The code that reads external_extensions.json uses this method to inform // the ExtensionsService of an extension to download. Using the real code // is race-prone, because instantating the ExtensionService starts a read // of external_extensions.json before this test function starts. service->AddPendingExtensionFromExternalUpdateUrl( kExtensionId, GURL("http://localhost/autoupdate/manifest")); // Run autoupdate and make sure version 2 of the extension was installed. service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ(kExtensionId, extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Uninstalling the extension should set a pref that keeps the extension from // being installed again the next time external_extensions.json is read. UninstallExtension(kExtensionId); std::set<std::string> killed_ids; service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() != killed_ids.find(kExtensionId)) << "Uninstalling should set kill bit on externaly installed extension."; // Installing from non-external source. ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Reinstalling should clear the kill bit."; // Uninstalling from a non-external source should not set the kill bit. UninstallExtension(kExtensionId); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Uninstalling non-external extension should not set kill bit."; } <commit_msg>Unmark ExtensionManagementTest.Incognito as FLAKY on Mac.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" class ExtensionManagementTest : public ExtensionBrowserTest { protected: // Helper method that returns whether the extension is at the given version. // This calls version(), which must be defined in the extension's bg page, // as well as asking the extension itself. // // Note that 'version' here means something different than the version field // in the extension's manifest. We use the version as reported by the // background page to test how overinstalling crx files with the same // manifest version works. bool IsExtensionAtVersion(Extension* extension, const std::string& expected_version) { // Test that the extension's version from the manifest and reported by the // background page is correct. This is to ensure that the processes are in // sync with the Extension. ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension); EXPECT_TRUE(ext_host); if (!ext_host) return false; std::string version_from_bg; bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString( ext_host->render_view_host(), L"", L"version()", &version_from_bg); EXPECT_TRUE(exec); if (!exec) return false; if (version_from_bg != expected_version || extension->VersionString() != expected_version) return false; return true; } // Helper method that installs a low permission extension then updates // to the second version requiring increased permissions. Returns whether // the operation was completed successfully. bool InstallAndUpdateIncreasingPermissionsExtension() { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t size_before = service->extensions()->size(); // Install the initial version, which should happen just fine. if (!InstallExtension( test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1)) return false; // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. if (service->extensions()->size() != size_before + 1) return false; if (!UpdateExtension( service->extensions()->at(size_before)->id(), test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1)) return false; EXPECT_EQ(size_before, service->extensions()->size()); if (service->disabled_extensions()->size() != 1u) return false; return true; } }; // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); FilePath old_path = service->extensions()->back()->path(); // Install an extension with the same version. The previous install should be // overwritten. ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_same_version.crx"), 0)); FilePath new_path = service->extensions()->back()->path(); EXPECT_FALSE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); EXPECT_NE(old_path.value(), new_path.value()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); // Cancel this install. StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx")); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } // Tests that installing and uninstalling extensions don't crash with an // incognito window open. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) { // Open an incognito window to the extensions management page. We just // want to make sure that we don't crash while playing with extensions when // this guy is around. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL(chrome::kChromeUIExtensionsURL)); ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1)); UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf"); } // Tests the process of updating an extension to one that requires higher // permissions. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try reenabling it. service->EnableExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that we can uninstall a disabled extension. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try uninstalling it. UninstallExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that disabling and re-enabling an extension works. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) { ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); // Load an extension, expect the background page to be available. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("good").AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"))); ASSERT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); Extension* extension = service->extensions()->at(size_before); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // After disabling, the background page should go away. service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(1u, service->disabled_extensions()->size()); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // And bring it back. service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); } // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1)); listener1.WaitUntilSatisfied(); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_TRUE(service->HasInstalledExtensions()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("1.0", extensions->at(size_before)->VersionString()); // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); // Run autoupdate and make sure version 2 of the extension was installed. ExtensionTestMessageListener listener2("v2 installed", false); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); listener2.WaitUntilSatisfied(); extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v3.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstallError()); // Make sure the extension state is the same as before. extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); } // See http://crbug.com/57378 for flakiness details. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, FLAKY_ExternalUrlUpdate) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const char* kExtensionId = "ogjcoiohnmldgjemafoockdghcjciccf"; // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); // The code that reads external_extensions.json uses this method to inform // the ExtensionsService of an extension to download. Using the real code // is race-prone, because instantating the ExtensionService starts a read // of external_extensions.json before this test function starts. service->AddPendingExtensionFromExternalUpdateUrl( kExtensionId, GURL("http://localhost/autoupdate/manifest")); // Run autoupdate and make sure version 2 of the extension was installed. service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ(kExtensionId, extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Uninstalling the extension should set a pref that keeps the extension from // being installed again the next time external_extensions.json is read. UninstallExtension(kExtensionId); std::set<std::string> killed_ids; service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() != killed_ids.find(kExtensionId)) << "Uninstalling should set kill bit on externaly installed extension."; // Installing from non-external source. ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Reinstalling should clear the kill bit."; // Uninstalling from a non-external source should not set the kill bit. UninstallExtension(kExtensionId); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Uninstalling non-external extension should not set kill bit."; } <|endoftext|>
<commit_before>#ifndef SILICIUM_LINUX_FILE_DESCRIPTOR_HPP #define SILICIUM_LINUX_FILE_DESCRIPTOR_HPP #include <boost/config.hpp> #include <unistd.h> namespace Si { namespace linux { inline void terminating_close(int file) BOOST_NOEXCEPT { if (close(file) < 0) { //it is intended that this will terminate the process because of noexcept throw boost::system::system_error(errno, boost::system::system_category()); } } struct file_descriptor : private boost::noncopyable { int handle; file_descriptor() BOOST_NOEXCEPT : handle(-1) { } file_descriptor(file_descriptor &&other) BOOST_NOEXCEPT : handle(-1) { swap(other); } explicit file_descriptor(int handle) BOOST_NOEXCEPT : handle(handle) { } file_descriptor &operator = (file_descriptor &&other) BOOST_NOEXCEPT { swap(other); return *this; } void swap(file_descriptor &other) BOOST_NOEXCEPT { using std::swap; swap(handle, other.handle); } void close() BOOST_NOEXCEPT { file_descriptor().swap(*this); } ~file_descriptor() BOOST_NOEXCEPT { if (handle >= 0) { terminating_close(handle); } } }; } } #endif <commit_msg>add open_reading for Linux<commit_after>#ifndef SILICIUM_LINUX_FILE_DESCRIPTOR_HPP #define SILICIUM_LINUX_FILE_DESCRIPTOR_HPP #include <boost/config.hpp> #include <boost/filesystem/path.hpp> #include <unistd.h> #include <fcntl.h> namespace Si { namespace linux { inline void terminating_close(int file) BOOST_NOEXCEPT { if (close(file) < 0) { //it is intended that this will terminate the process because of noexcept throw boost::system::system_error(errno, boost::system::system_category()); } } struct file_descriptor : private boost::noncopyable { int handle; file_descriptor() BOOST_NOEXCEPT : handle(-1) { } file_descriptor(file_descriptor &&other) BOOST_NOEXCEPT : handle(-1) { swap(other); } explicit file_descriptor(int handle) BOOST_NOEXCEPT : handle(handle) { } file_descriptor &operator = (file_descriptor &&other) BOOST_NOEXCEPT { swap(other); return *this; } void swap(file_descriptor &other) BOOST_NOEXCEPT { using std::swap; swap(handle, other.handle); } void close() BOOST_NOEXCEPT { file_descriptor().swap(*this); } ~file_descriptor() BOOST_NOEXCEPT { if (handle >= 0) { terminating_close(handle); } } }; inline Si::linux::file_descriptor open_reading(boost::filesystem::path const &name) { int const fd = ::open(name.c_str(), O_RDONLY); if (fd < 0) { boost::throw_exception(boost::system::system_error(boost::system::error_code(errno, boost::system::system_category()))); } return Si::linux::file_descriptor(fd); } } } #endif <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/evaluator/vehicle/semantic_lstm_evaluator.h" #include <omp.h> #include <unordered_map> #include "cyber/common/file.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/common/prediction_util.h" #include "modules/prediction/common/semantic_map.h" namespace apollo { namespace prediction { using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; SemanticLSTMEvaluator::SemanticLSTMEvaluator() : device_(torch::kCPU) { evaluator_type_ = ObstacleConf::SEMANTIC_LSTM_EVALUATOR; LoadModel(); } void SemanticLSTMEvaluator::Clear() {} bool SemanticLSTMEvaluator::Evaluate(Obstacle* obstacle_ptr) { omp_set_num_threads(1); obstacle_ptr->SetEvaluatorType(evaluator_type_); Clear(); CHECK_NOTNULL(obstacle_ptr); int id = obstacle_ptr->id(); if (!obstacle_ptr->latest_feature().IsInitialized()) { AERROR << "Obstacle [" << id << "] has no latest feature."; return false; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); CHECK_NOTNULL(latest_feature_ptr); if (!FLAGS_enable_semantic_map) { ADEBUG << "Not enable semantic map, exit semantic_lstm_evaluator."; return false; } cv::Mat feature_map; if (!SemanticMap::Instance()->GetMapById(id, &feature_map)) { return false; } // Process the feature_map cv::cvtColor(feature_map, feature_map, CV_BGR2RGB); cv::Mat img_float; feature_map.convertTo(img_float, CV_32F, 1.0 / 255); torch::Tensor img_tensor = torch::from_blob(img_float.data, {1, 224, 224, 3}); img_tensor = img_tensor.permute({0, 3, 1, 2}); img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229); img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224); img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225); // Extract features of pos_history std::vector<std::pair<double, double>> pos_history(20, {0.0, 0.0}); if (!ExtractObstacleHistory(obstacle_ptr, &pos_history)) { ADEBUG << "Obstacle [" << id << "] failed to extract obstacle history"; return false; } // Process obstacle_history // TODO(Hongyi): move magic numbers to parameters and gflags torch::Tensor obstacle_pos = torch::zeros({1, 20, 2}); torch::Tensor obstacle_pos_step = torch::zeros({1, 20, 2}); for (int i = 0; i < 20; ++i) { obstacle_pos[0][19 - i][0] = pos_history[i].first; obstacle_pos[0][19 - i][1] = pos_history[i].second; if (i == 19 || (i > 0 && pos_history[i].first == 0.0)) { break; } obstacle_pos_step[0][19 - i][0] = pos_history[i].first - pos_history[i + 1].first; obstacle_pos_step[0][19 - i][1] = pos_history[i].second - pos_history[i + 1].second; } // Build input features for torch std::vector<torch::jit::IValue> torch_inputs; torch_inputs.push_back(c10::ivalue::Tuple::create( {std::move(img_tensor.to(device_)), std::move(obstacle_pos.to(device_)), std::move(obstacle_pos_step.to(device_))}, c10::TupleType::create( std::vector<c10::TypePtr>(3, c10::TensorType::create())))); // Compute pred_traj std::vector<double> pred_traj; auto start_time = std::chrono::system_clock::now(); at::Tensor torch_output_tensor = torch_model_.forward(torch_inputs).toTensor().to(torch::kCPU); auto end_time = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_time - start_time; AERROR << "Semantic_LSTM_evaluator used time: " << diff.count() * 1000 << " ms."; auto torch_output = torch_output_tensor.accessor<float, 3>(); // Get the trajectory double pos_x = latest_feature_ptr->position().x(); double pos_y = latest_feature_ptr->position().y(); Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory(); trajectory->set_probability(1.0); for (size_t i = 0; i < 30; ++i) { TrajectoryPoint* point = trajectory->add_trajectory_point(); double dx = static_cast<double>(torch_output[0][i][0]); double dy = static_cast<double>(torch_output[0][i][1]); Vec2d offset(dx, dy); Vec2d rotated_offset = offset.rotate(latest_feature_ptr->velocity_heading()); double point_x = pos_x + rotated_offset.x(); double point_y = pos_y + rotated_offset.y(); point->mutable_path_point()->set_x(point_x); point->mutable_path_point()->set_y(point_y); point->set_relative_time(static_cast<double>(i) * FLAGS_prediction_trajectory_time_resolution); } return true; } bool SemanticLSTMEvaluator::ExtractObstacleHistory( Obstacle* obstacle_ptr, std::vector<std::pair<double, double>>* pos_history) { pos_history->resize(20, {0.0, 0.0}); const Feature& obs_curr_feature = obstacle_ptr->latest_feature(); double obs_curr_heading = obs_curr_feature.velocity_heading(); std::pair<double, double> obs_curr_pos = std::make_pair( obs_curr_feature.position().x(), obs_curr_feature.position().y()); for (std::size_t i = 0; i < obstacle_ptr->history_size() && i < 20; ++i) { const Feature& feature = obstacle_ptr->feature(i); if (!feature.IsInitialized()) { break; } pos_history->at(i) = WorldCoordToObjCoord( std::make_pair(feature.position().x(), feature.position().y()), obs_curr_pos, obs_curr_heading); } return true; } void SemanticLSTMEvaluator::LoadModel() { if (FLAGS_use_cuda && torch::cuda::is_available()) { ADEBUG << "CUDA is available"; device_ = torch::Device(torch::kCUDA); } torch::set_num_threads(1); // TODO(Hongyi): change model file name and gflag torch_model_ = torch::jit::load(FLAGS_torch_vehicle_junction_map_file, device_); } } // namespace prediction } // namespace apollo <commit_msg>Prediction: add theta for semantic_LSTM<commit_after>/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/evaluator/vehicle/semantic_lstm_evaluator.h" #include <omp.h> #include <unordered_map> #include "cyber/common/file.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/common/prediction_util.h" #include "modules/prediction/common/semantic_map.h" namespace apollo { namespace prediction { using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; SemanticLSTMEvaluator::SemanticLSTMEvaluator() : device_(torch::kCPU) { evaluator_type_ = ObstacleConf::SEMANTIC_LSTM_EVALUATOR; LoadModel(); } void SemanticLSTMEvaluator::Clear() {} bool SemanticLSTMEvaluator::Evaluate(Obstacle* obstacle_ptr) { omp_set_num_threads(1); obstacle_ptr->SetEvaluatorType(evaluator_type_); Clear(); CHECK_NOTNULL(obstacle_ptr); int id = obstacle_ptr->id(); if (!obstacle_ptr->latest_feature().IsInitialized()) { AERROR << "Obstacle [" << id << "] has no latest feature."; return false; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); CHECK_NOTNULL(latest_feature_ptr); if (!FLAGS_enable_semantic_map) { ADEBUG << "Not enable semantic map, exit semantic_lstm_evaluator."; return false; } cv::Mat feature_map; if (!SemanticMap::Instance()->GetMapById(id, &feature_map)) { return false; } // Process the feature_map cv::cvtColor(feature_map, feature_map, CV_BGR2RGB); cv::Mat img_float; feature_map.convertTo(img_float, CV_32F, 1.0 / 255); torch::Tensor img_tensor = torch::from_blob(img_float.data, {1, 224, 224, 3}); img_tensor = img_tensor.permute({0, 3, 1, 2}); img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229); img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224); img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225); // Extract features of pos_history std::vector<std::pair<double, double>> pos_history(20, {0.0, 0.0}); if (!ExtractObstacleHistory(obstacle_ptr, &pos_history)) { ADEBUG << "Obstacle [" << id << "] failed to extract obstacle history"; return false; } // Process obstacle_history // TODO(Hongyi): move magic numbers to parameters and gflags torch::Tensor obstacle_pos = torch::zeros({1, 20, 2}); torch::Tensor obstacle_pos_step = torch::zeros({1, 20, 2}); for (int i = 0; i < 20; ++i) { obstacle_pos[0][19 - i][0] = pos_history[i].first; obstacle_pos[0][19 - i][1] = pos_history[i].second; if (i == 19 || (i > 0 && pos_history[i].first == 0.0)) { break; } obstacle_pos_step[0][19 - i][0] = pos_history[i].first - pos_history[i + 1].first; obstacle_pos_step[0][19 - i][1] = pos_history[i].second - pos_history[i + 1].second; } // Build input features for torch std::vector<torch::jit::IValue> torch_inputs; torch_inputs.push_back(c10::ivalue::Tuple::create( {std::move(img_tensor.to(device_)), std::move(obstacle_pos.to(device_)), std::move(obstacle_pos_step.to(device_))}, c10::TupleType::create( std::vector<c10::TypePtr>(3, c10::TensorType::create())))); // Compute pred_traj std::vector<double> pred_traj; auto start_time = std::chrono::system_clock::now(); at::Tensor torch_output_tensor = torch_model_.forward(torch_inputs).toTensor().to(torch::kCPU); auto end_time = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_time - start_time; AERROR << "Semantic_LSTM_evaluator used time: " << diff.count() * 1000 << " ms."; auto torch_output = torch_output_tensor.accessor<float, 3>(); // Get the trajectory double pos_x = latest_feature_ptr->position().x(); double pos_y = latest_feature_ptr->position().y(); Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory(); trajectory->set_probability(1.0); for (int i = 0; i < 30; ++i) { TrajectoryPoint* point = trajectory->add_trajectory_point(); double dx = static_cast<double>(torch_output[0][i][0]); double dy = static_cast<double>(torch_output[0][i][1]); Vec2d offset(dx, dy); Vec2d rotated_offset = offset.rotate(latest_feature_ptr->velocity_heading()); double point_x = pos_x + rotated_offset.x(); double point_y = pos_y + rotated_offset.y(); point->mutable_path_point()->set_x(point_x); point->mutable_path_point()->set_y(point_y); if (i < 10) { // use origin heading for the first second point->mutable_path_point()->set_theta( latest_feature_ptr->velocity_heading()); } else { point->mutable_path_point()->set_theta( std::atan2(trajectory->trajectory_point(i).path_point().y() - trajectory->trajectory_point(i - 1).path_point().y(), trajectory->trajectory_point(i).path_point().x() - trajectory->trajectory_point(i - 1).path_point().x())); } point->set_relative_time(static_cast<double>(i) * FLAGS_prediction_trajectory_time_resolution); } return true; } bool SemanticLSTMEvaluator::ExtractObstacleHistory( Obstacle* obstacle_ptr, std::vector<std::pair<double, double>>* pos_history) { pos_history->resize(20, {0.0, 0.0}); const Feature& obs_curr_feature = obstacle_ptr->latest_feature(); double obs_curr_heading = obs_curr_feature.velocity_heading(); std::pair<double, double> obs_curr_pos = std::make_pair( obs_curr_feature.position().x(), obs_curr_feature.position().y()); for (std::size_t i = 0; i < obstacle_ptr->history_size() && i < 20; ++i) { const Feature& feature = obstacle_ptr->feature(i); if (!feature.IsInitialized()) { break; } pos_history->at(i) = WorldCoordToObjCoord( std::make_pair(feature.position().x(), feature.position().y()), obs_curr_pos, obs_curr_heading); } return true; } void SemanticLSTMEvaluator::LoadModel() { if (FLAGS_use_cuda && torch::cuda::is_available()) { ADEBUG << "CUDA is available"; device_ = torch::Device(torch::kCUDA); } torch::set_num_threads(1); // TODO(Hongyi): change model file name and gflag torch_model_ = torch::jit::load(FLAGS_torch_vehicle_junction_map_file, device_); } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>/******************************************************************************* * SOMAR - Stratified Ocean Model with Adaptive Refinement * Developed by Ed Santilli & Alberto Scotti * Copyright (C) 2014 University of North Carolina at Chapel Hill * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * For up-to-date contact information, please visit the repository homepage, * https://github.com/somarhub. ******************************************************************************/ #include "LockExchangeBCUtil.H" #include "EllipticBCUtils.H" // ----------------------------------------------------------------------------- // Default constructor // ----------------------------------------------------------------------------- LockExchangeBCUtil::LockExchangeBCUtil () {;} // ----------------------------------------------------------------------------- // Default destructor // ----------------------------------------------------------------------------- LockExchangeBCUtil::~LockExchangeBCUtil () {;} // ----------------------------------------------------------------------------- // This object is its own factory // ----------------------------------------------------------------------------- PhysBCUtil* LockExchangeBCUtil::newPhysBCUtil () const { PhysBCUtil* newBCPtr = new LockExchangeBCUtil(); return newBCPtr; } // ************************ ICs / background fields **************************** #include "CONSTANTS.H" #include "BoxIterator.H" // ----------------------------------------------------------------------------- // Fills a FAB with the initial scalars // ----------------------------------------------------------------------------- void LockExchangeBCUtil::setScalarIC (FArrayBox& a_scalarFAB, const int a_scalarComp, const LevelGeometry& a_levGeo, const DataIndex& a_di) const { CH_assert(a_scalarFAB.nComp() == 1); if (a_scalarComp == 0) { // Gather geometric info const Box domBox = a_levGeo.getDomain().domainBox(); const Box dataBox = a_scalarFAB.box(); const RealVect& dx = a_levGeo.getDx(); const IntVect ex = BASISV(0); // Compute Cartesian cell coordinates FArrayBox xposFAB(surroundingNodes(dataBox,0), 1); LevelGeometry::getGeoSourcePtr()->fill_physCoor(xposFAB, 0, 0, dx); FArrayBox yposFAB(dataBox, 1); LevelGeometry::getGeoSourcePtr()->fill_physCoor(yposFAB, 0, 1, dx); // Define IC parameters // Option #1: Interface at center of domain. // const Real x0 = Real(domBox.smallEnd(0)) * dx[0]; // const Real xhalf = x0 + 0.5 * a_levGeo.getDomainLength(0); // Option #2: Interface at x = 0. const Real xhalf = 0.0; const Real pertA = 0.025; const Real pertK = 2.0 * Pi / a_levGeo.getDomainLength(1); const Real smoothingFactor = 2.0; const Real bmin = 0.0; const Real bmax = 1.0; // Loop over databox and set buoyancy IC. BoxIterator bit(dataBox); for (bit.reset(); bit.ok(); ++bit) { const IntVect& cc = bit(); Real xl = xposFAB(cc ,0); Real xr = xposFAB(cc+ex,0); Real y = yposFAB(cc ,0); Real ifx = xhalf + pertA * sin(pertK * y); if (xr < ifx) { // Left values a_scalarFAB(cc,a_scalarComp) = bmin; } else if (ifx < xl) { // Right values a_scalarFAB(cc,a_scalarComp) = bmax; } else { // Interface is inside this cell. Use smoothing. Real frac = (ifx - xr) / (xl - xr); frac = 2.0 * frac - 1.0; frac = tanh(smoothingFactor * frac); a_scalarFAB(cc,a_scalarComp) = bmin + bmax * 0.5 * (frac + 1.0); } } } else { MayDay::Error("LockExchangeBCUtil::setScalarIC received a_scalarComp > 0"); } } // ----------------------------------------------------------------------------- // basicScalarFuncBC (Extrapolate BCs) // Sets physical BCs on a generic passive scalar. // Chombo uses 1st order extrap // ----------------------------------------------------------------------------- BCMethodHolder LockExchangeBCUtil::basicScalarFuncBC () const { BCMethodHolder holder; // Solid wall and outflow RefCountedPtr<BCGhostClass> BCPtr( new EllipticExtrapBCGhostClass(1, // extrap order IntVect::Unit, IntVect::Unit) ); holder.addBCMethod(BCPtr); return holder; } // ----------------------------------------------------------------------------- // basicVelFuncBC // Sets physical BCs on velocities. // ----------------------------------------------------------------------------- BCMethodHolder LockExchangeBCUtil::basicVelFuncBC (int a_veldir, bool a_isViscous) const { bool isViscous = a_isViscous; // Set to false for free-slip BCs. BCMethodHolder holder; RefCountedPtr<BCGhostClass> velBCPtr = RefCountedPtr<BCGhostClass>( new BasicVelocityBCGhostClass(0.0, //s_inflowVel, -1, //s_inflowDir, Side::Lo, //s_inflowSide, -1, //s_outflowDir, Side::Lo, //s_outflowSide, a_veldir, isViscous) ); holder.addBCMethod(velBCPtr); return holder; } <commit_msg>Lock exchange code avoids perturbation in 2D mode.<commit_after>/******************************************************************************* * SOMAR - Stratified Ocean Model with Adaptive Refinement * Developed by Ed Santilli & Alberto Scotti * Copyright (C) 2014 University of North Carolina at Chapel Hill * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * For up-to-date contact information, please visit the repository homepage, * https://github.com/somarhub. ******************************************************************************/ #include "LockExchangeBCUtil.H" #include "EllipticBCUtils.H" // ----------------------------------------------------------------------------- // Default constructor // ----------------------------------------------------------------------------- LockExchangeBCUtil::LockExchangeBCUtil () {;} // ----------------------------------------------------------------------------- // Default destructor // ----------------------------------------------------------------------------- LockExchangeBCUtil::~LockExchangeBCUtil () {;} // ----------------------------------------------------------------------------- // This object is its own factory // ----------------------------------------------------------------------------- PhysBCUtil* LockExchangeBCUtil::newPhysBCUtil () const { PhysBCUtil* newBCPtr = new LockExchangeBCUtil(); return newBCPtr; } // ************************ ICs / background fields **************************** #include "CONSTANTS.H" #include "BoxIterator.H" // ----------------------------------------------------------------------------- // Fills a FAB with the initial scalars // ----------------------------------------------------------------------------- void LockExchangeBCUtil::setScalarIC (FArrayBox& a_scalarFAB, const int a_scalarComp, const LevelGeometry& a_levGeo, const DataIndex& a_di) const { CH_assert(a_scalarFAB.nComp() == 1); if (a_scalarComp == 0) { // Gather geometric info const Box domBox = a_levGeo.getDomain().domainBox(); const Box dataBox = a_scalarFAB.box(); const RealVect& dx = a_levGeo.getDx(); const IntVect ex = BASISV(0); // Compute Cartesian cell coordinates FArrayBox xposFAB(surroundingNodes(dataBox,0), 1); LevelGeometry::getGeoSourcePtr()->fill_physCoor(xposFAB, 0, 0, dx); FArrayBox yposFAB(dataBox, 1); LevelGeometry::getGeoSourcePtr()->fill_physCoor(yposFAB, 0, 1, dx); // Define IC parameters // Option #1: Interface at center of domain. // const Real x0 = Real(domBox.smallEnd(0)) * dx[0]; // const Real xhalf = x0 + 0.5 * a_levGeo.getDomainLength(0); // Option #2: Interface at x = 0. const Real xhalf = 0.0; const Real pertA = ((SpaceDim > 2)? 0.025: 0.0); const Real pertK = 2.0 * Pi / a_levGeo.getDomainLength(1); const Real smoothingFactor = 2.0; const Real bmin = 0.0; const Real bmax = 1.0; // Loop over databox and set buoyancy IC. BoxIterator bit(dataBox); for (bit.reset(); bit.ok(); ++bit) { const IntVect& cc = bit(); Real xl = xposFAB(cc ,0); Real xr = xposFAB(cc+ex,0); Real y = yposFAB(cc ,0); Real ifx = xhalf + pertA * sin(pertK * y); if (xr < ifx) { // Left values a_scalarFAB(cc,a_scalarComp) = bmin; } else if (ifx < xl) { // Right values a_scalarFAB(cc,a_scalarComp) = bmax; } else { // Interface is inside this cell. Use smoothing. Real frac = (ifx - xr) / (xl - xr); frac = 2.0 * frac - 1.0; frac = tanh(smoothingFactor * frac); a_scalarFAB(cc,a_scalarComp) = bmin + bmax * 0.5 * (frac + 1.0); } } } else { MayDay::Error("LockExchangeBCUtil::setScalarIC received a_scalarComp > 0"); } } // ----------------------------------------------------------------------------- // basicScalarFuncBC (Extrapolate BCs) // Sets physical BCs on a generic passive scalar. // Chombo uses 1st order extrap // ----------------------------------------------------------------------------- BCMethodHolder LockExchangeBCUtil::basicScalarFuncBC () const { BCMethodHolder holder; // Solid wall and outflow RefCountedPtr<BCGhostClass> BCPtr( new EllipticExtrapBCGhostClass(1, // extrap order IntVect::Unit, IntVect::Unit) ); holder.addBCMethod(BCPtr); return holder; } // ----------------------------------------------------------------------------- // basicVelFuncBC // Sets physical BCs on velocities. // ----------------------------------------------------------------------------- BCMethodHolder LockExchangeBCUtil::basicVelFuncBC (int a_veldir, bool a_isViscous) const { bool isViscous = a_isViscous; // Set to false for free-slip BCs. BCMethodHolder holder; RefCountedPtr<BCGhostClass> velBCPtr = RefCountedPtr<BCGhostClass>( new BasicVelocityBCGhostClass(0.0, //s_inflowVel, -1, //s_inflowDir, Side::Lo, //s_inflowSide, -1, //s_outflowDir, Side::Lo, //s_outflowSide, a_veldir, isViscous) ); holder.addBCMethod(velBCPtr); return holder; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/profile.h" #include "chrome/browser/extensions/extension_view.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // How long to wait for the extension to put up a javascript alert before giving // up. const int kAlertTimeoutMs = 10000; // The extension we're using as our test case. const char* kExtensionId = "com.google.myextension1"; // This class starts up an extension process and waits until it tries to put // up a javascript alert. class MockExtensionView : public ExtensionView { public: MockExtensionView(const GURL& url, Profile* profile) : ExtensionView(url, profile), got_message_(false) { InitHidden(); MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask, kAlertTimeoutMs); ui_test_utils::RunMessageLoop(); } bool got_message() { return got_message_; } private: virtual void RunJavaScriptMessage( const std::wstring& message, const std::wstring& default_prompt, const int flags, IPC::Message* reply_msg, bool* did_suppress_message) { got_message_ = true; MessageLoopForUI::current()->Quit(); } bool got_message_; }; // This class waits for a specific extension to be loaded. class ExtensionLoadedObserver : public NotificationObserver { public: explicit ExtensionLoadedObserver() : extension_(NULL) { registrar_.Add(this, NotificationType::EXTENSIONS_LOADED, NotificationService::AllSources()); ui_test_utils::RunMessageLoop(); } Extension* extension() { return extension_; } private: virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::EXTENSIONS_LOADED) { ExtensionList* extensions = Details<ExtensionList>(details).ptr(); for (size_t i = 0; i < (*extensions).size(); i++) { if ((*extensions)[i]->id() == kExtensionId) { extension_ = (*extensions)[i]; MessageLoopForUI::current()->Quit(); break; } } } else { NOTREACHED(); } } NotificationRegistrar registrar_; Extension* extension_; }; } // namespace class ExtensionViewTest : public InProcessBrowserTest { }; IN_PROC_BROWSER_TEST_F(ExtensionViewTest, TestMe) { // Get the path to our extension. FilePath path; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path)); path = path.AppendASCII("extensions"). AppendASCII("good").AppendASCII("extension1").AppendASCII("1"); // Load it. Profile* profile = browser()->profile(); profile->GetExtensionsService()->Init(); profile->GetExtensionsService()->LoadExtension(path); // Now wait for it to load, and grab a pointer to it. Extension* extension = ExtensionLoadedObserver().extension(); ASSERT_TRUE(extension); GURL url = Extension::GetResourceURL(extension->url(), "index.html"); // Start the extension process and wait for it to show a javascript alert. MockExtensionView view(url, profile); EXPECT_TRUE(view.got_message()); } <commit_msg>Disable the ExtensionViewTest while I investigate why it's hanging on the buildbots.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/profile.h" #include "chrome/browser/extensions/extension_view.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // How long to wait for the extension to put up a javascript alert before giving // up. const int kAlertTimeoutMs = 10000; // The extension we're using as our test case. const char* kExtensionId = "com.google.myextension1"; // This class starts up an extension process and waits until it tries to put // up a javascript alert. class MockExtensionView : public ExtensionView { public: MockExtensionView(const GURL& url, Profile* profile) : ExtensionView(url, profile), got_message_(false) { InitHidden(); MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask, kAlertTimeoutMs); ui_test_utils::RunMessageLoop(); } bool got_message() { return got_message_; } private: virtual void RunJavaScriptMessage( const std::wstring& message, const std::wstring& default_prompt, const int flags, IPC::Message* reply_msg, bool* did_suppress_message) { got_message_ = true; MessageLoopForUI::current()->Quit(); } bool got_message_; }; // This class waits for a specific extension to be loaded. class ExtensionLoadedObserver : public NotificationObserver { public: explicit ExtensionLoadedObserver() : extension_(NULL) { registrar_.Add(this, NotificationType::EXTENSIONS_LOADED, NotificationService::AllSources()); ui_test_utils::RunMessageLoop(); } Extension* extension() { return extension_; } private: virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::EXTENSIONS_LOADED) { ExtensionList* extensions = Details<ExtensionList>(details).ptr(); for (size_t i = 0; i < (*extensions).size(); i++) { if ((*extensions)[i]->id() == kExtensionId) { extension_ = (*extensions)[i]; MessageLoopForUI::current()->Quit(); break; } } } else { NOTREACHED(); } } NotificationRegistrar registrar_; Extension* extension_; }; } // namespace class ExtensionViewTest : public InProcessBrowserTest { }; IN_PROC_BROWSER_TEST_F(ExtensionViewTest, DISABLED_TestMe) { // Get the path to our extension. FilePath path; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path)); path = path.AppendASCII("extensions"). AppendASCII("good").AppendASCII("extension1").AppendASCII("1"); // Load it. Profile* profile = browser()->profile(); profile->GetExtensionsService()->Init(); profile->GetExtensionsService()->LoadExtension(path); // Now wait for it to load, and grab a pointer to it. Extension* extension = ExtensionLoadedObserver().extension(); ASSERT_TRUE(extension); GURL url = Extension::GetResourceURL(extension->url(), "index.html"); // Start the extension process and wait for it to show a javascript alert. MockExtensionView view(url, profile); EXPECT_TRUE(view.got_message()); } <|endoftext|>
<commit_before>/* * Unit testing for extremely simple simulator * Copyright 2018 MIPT-MIPS */ #include "../func_sim.h" // Catch2 #include <catch.hpp> // Module #include <memory/elf/elf_loader.h> #include <memory/memory.h> #include <mips/mips.h> #include <sstream> static const std::string valid_elf_file = TEST_PATH "/tt.core32.out"; static const std::string smc_code = TEST_PATH "/smc.out"; // TODO: remove that class, use true FuncSim interfaces instead template <typename ISA> struct FuncSimAndMemory : FuncSim<ISA> { std::unique_ptr<FuncMemory> mem; FuncSimAndMemory() : FuncSim<ISA>(), mem( FuncMemory::create_hierarchied_memory()) { this->set_memory( mem.get()); } void init( const std::string& tr) { ::load_elf_file( mem.get(), tr); FuncSim<ISA>::init(); } auto run_trace( const std::string& tr, uint64 steps) { ::load_elf_file( mem.get(), tr); return FuncSim<ISA>::run( steps); } auto run_trace_no_limit( const std::string& tr) { ::load_elf_file( mem.get(), tr); return FuncSim<ISA>::run_no_limit(); } }; TEST_CASE( "Process_Wrong_Args_Of_Constr: Func_Sim_init") { // Just call a constructor CHECK_NOTHROW( FuncSimAndMemory<MIPS32>() ); // Call constructor and init CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().init( valid_elf_file) ); // Do bad init CHECK_THROWS_AS( FuncSimAndMemory<MIPS32>().init( "./1234567890/qwertyuop"), InvalidElfFile); } TEST_CASE( "Make_A_Step: Func_Sim") { FuncSimAndMemory<MIPS32> simulator; simulator.init( valid_elf_file); CHECK( simulator.step().string_dump().find("lui $at, 0x41\t [ $at = 0x410000 ]") != std::string::npos); } TEST_CASE( "Run one instruction: Func_Sim") { CHECK( FuncSimAndMemory<MIPS32>().run_trace( smc_code, 1) == Trap::NO_TRAP); } TEST_CASE( "Run_SMC_trace: Func_Sim") { CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( smc_code)); } TEST_CASE( "Torture_Test: Func_Sim") { // MIPS 32 Little-endian CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( TEST_PATH "/tt.core.universal.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( TEST_PATH "/tt.core32.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( TEST_PATH "/tt.core32.le.out") ); // MIPS 64 Little-Endian CHECK_NOTHROW( FuncSimAndMemory<MIPS64>().run_trace_no_limit( TEST_PATH "/tt.core.universal.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS64>().run_trace_no_limit( TEST_PATH "/tt.core64.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS64>().run_trace_no_limit( TEST_PATH "/tt.core64.le.out") ); } <commit_msg>Test that FuncSim checker does nothing<commit_after>/* * Unit testing for extremely simple simulator * Copyright 2018 MIPT-MIPS */ #include "../func_sim.h" // Catch2 #include <catch.hpp> // Module #include <memory/elf/elf_loader.h> #include <memory/memory.h> #include <mips/mips.h> #include <sstream> static const std::string valid_elf_file = TEST_PATH "/tt.core32.out"; static const std::string smc_code = TEST_PATH "/smc.out"; // TODO: remove that class, use true FuncSim interfaces instead template <typename ISA> struct FuncSimAndMemory : FuncSim<ISA> { std::unique_ptr<FuncMemory> mem; FuncSimAndMemory() : FuncSim<ISA>(), mem( FuncMemory::create_hierarchied_memory()) { this->set_memory( mem.get()); } void init( const std::string& tr) { ::load_elf_file( mem.get(), tr); FuncSim<ISA>::init(); } auto run_trace( const std::string& tr, uint64 steps) { ::load_elf_file( mem.get(), tr); return FuncSim<ISA>::run( steps); } auto run_trace_no_limit( const std::string& tr) { ::load_elf_file( mem.get(), tr); return FuncSim<ISA>::run_no_limit(); } }; TEST_CASE( "Process_Wrong_Args_Of_Constr: Func_Sim_init") { // Just call a constructor CHECK_NOTHROW( FuncSimAndMemory<MIPS32>() ); // Call constructor and init CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().init( valid_elf_file) ); // Do bad init CHECK_THROWS_AS( FuncSimAndMemory<MIPS32>().init( "./1234567890/qwertyuop"), InvalidElfFile); } TEST_CASE( "Make_A_Step: Func_Sim") { FuncSimAndMemory<MIPS32> simulator; simulator.init( valid_elf_file); CHECK( simulator.step().string_dump().find("lui $at, 0x41\t [ $at = 0x410000 ]") != std::string::npos); } TEST_CASE( "FuncSim: make a step with checker") { FuncSimAndMemory<MIPS32> simulator; simulator.init( valid_elf_file); simulator.init_checker(); CHECK( simulator.step().string_dump().find("lui $at, 0x41\t [ $at = 0x410000 ]") != std::string::npos); } TEST_CASE( "Run one instruction: Func_Sim") { CHECK( FuncSimAndMemory<MIPS32>().run_trace( smc_code, 1) == Trap::NO_TRAP); } TEST_CASE( "Run_SMC_trace: Func_Sim") { CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( smc_code)); } TEST_CASE( "Torture_Test: Func_Sim") { // MIPS 32 Little-endian CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( TEST_PATH "/tt.core.universal.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( TEST_PATH "/tt.core32.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS32>().run_trace_no_limit( TEST_PATH "/tt.core32.le.out") ); // MIPS 64 Little-Endian CHECK_NOTHROW( FuncSimAndMemory<MIPS64>().run_trace_no_limit( TEST_PATH "/tt.core.universal.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS64>().run_trace_no_limit( TEST_PATH "/tt.core64.out") ); CHECK_NOTHROW( FuncSimAndMemory<MIPS64>().run_trace_no_limit( TEST_PATH "/tt.core64.le.out") ); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" extern "C" { #include <sandbox.h> } #include "base/sys_info.h" RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // This call doesn't work when the sandbox is enabled, the implementation // caches it's return value so we call it here and then future calls will // succeed. DebugUtil::BeingDebugged(); // Cache the System info information, since we can't query certain attributes // with the Sandbox enabled. base::SysInfo::CacheSysInfo(); char* error_buff = NULL; int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED, &error_buff); bool success = (error == 0 && error_buff == NULL); if (error == -1) { LOG(ERROR) << "Failed to Initialize Sandbox: " << error_buff; } sandbox_free_error(error_buff); return success; } void RendererMainPlatformDelegate::RunSandboxTests() { // TODO(port): Run sandbox unit test here. } <commit_msg>Call InitWebCoreSystemInterface() on OS X.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" extern "C" { #include <sandbox.h> } #include "base/sys_info.h" #include "third_party/WebKit/WebKit/mac/WebCoreSupport/WebSystemInterface.h" RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { // Load WebKit system interfaces. InitWebCoreSystemInterface(); } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // This call doesn't work when the sandbox is enabled, the implementation // caches it's return value so we call it here and then future calls will // succeed. DebugUtil::BeingDebugged(); // Cache the System info information, since we can't query certain attributes // with the Sandbox enabled. base::SysInfo::CacheSysInfo(); char* error_buff = NULL; int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED, &error_buff); bool success = (error == 0 && error_buff == NULL); if (error == -1) { LOG(ERROR) << "Failed to Initialize Sandbox: " << error_buff; } sandbox_free_error(error_buff); return success; } void RendererMainPlatformDelegate::RunSandboxTests() { // TODO(port): Run sandbox unit test here. } <|endoftext|>
<commit_before>#include <tuple> #include "otc/otcli.h" #include "otc/debug.h" #include "otc/greedy_forest.h" #include "otc/embedding.h" #include "otc/embedded_tree.h" using namespace otc; std::unique_ptr<TreeMappedWithSplits> cloneTree(const TreeMappedWithSplits &); template<typename T, typename U> void updateAncestralPathOttIdSet(T * nd, const OttIdSet & oldEls, const OttIdSet newEls, std::map<const T *, NodeEmbedding<T, U> > & m); template<typename T, typename U> inline void updateAncestralPathOttIdSet(T * nd, const OttIdSet & oldEls, const OttIdSet newEls, std::map<const T *, NodeEmbedding<T, U> > & m) { for (auto anc : iter_anc(*nd)) { auto & ant = m.at(anc); ant.updateAllPathsOttIdSets(oldEls, newEls); } } //currently not copying names std::unique_ptr<TreeMappedWithSplits> cloneTree(const TreeMappedWithSplits &tree) { TreeMappedWithSplits * rawTreePtr = new TreeMappedWithSplits(); try { NodeWithSplits * newRoot = rawTreePtr->createRoot(); auto r = tree.getRoot(); assert(r->hasOttId()); newRoot->setOttId(r->getOttId()); std::map<const NodeWithSplits *, NodeWithSplits *> templateToNew; templateToNew[r]= newRoot; std::map<long, NodeWithSplits *> & newMap = rawTreePtr->getData().ottIdToNode; rawTreePtr->getData().desIdSetsContainInternals = tree.getData().desIdSetsContainInternals; for (auto nd : iter_pre_const(tree)) { auto p = nd->getParent(); if (p == nullptr) { continue; } auto t2nIt = templateToNew.find(p); assert(t2nIt != templateToNew.end()); auto ntp = t2nIt->second; auto nn = rawTreePtr->createChild(ntp); assert(templateToNew.find(nd) == templateToNew.end()); templateToNew[nd] = nn; if (nd->hasOttId()) { nn->setOttId(nd->getOttId()); newMap[nd->getOttId()] = nn; } else { assert(false); } nn->getData().desIds = nd->getData().desIds; } } catch (...) { delete rawTreePtr; throw; } return std::unique_ptr<TreeMappedWithSplits>(rawTreePtr); } class ScaffoldedSupertree : public TaxonomyDependentTreeProcessor<TreeMappedWithSplits>, public EmbeddedTree { public: int numErrors; OttIdSet tabooIds; std::map<std::unique_ptr<TreeMappedWithSplits>, std::size_t> inputTreesToIndex; std::vector<TreeMappedWithSplits *> treePtrByIndex; bool doReportAllContested; bool doConstructSupertree; std::list<long> idsListToReportOn; std::list<long> idListForDotExport; TreeMappedWithSplits * taxonomyAsSource; int currDotFileIndex; void resolveOrCollapse(NodeWithSplits * scaffoldNd, SupertreeContextWithSplits & sc) { auto & thr = taxoToEmbedding[scaffoldNd]; if (thr.isContested()) { if (thr.highRankingTreesPreserveMonophyly(sc.numTrees)) { thr.resolveGivenContestedMonophyly(*scaffoldNd, sc); } else { thr.constructPhyloGraphAndCollapseIfNecessary(*scaffoldNd, sc); } } else { thr.resolveGivenUncontestedMonophyly(*scaffoldNd, sc); } } void constructSupertree() { const auto numTrees = treePtrByIndex.size(); TreeMappedWithSplits * tax = taxonomy.get(); SupertreeContextWithSplits sc{numTrees, taxoToEmbedding, *tax}; writeNumberedDot(taxonomy->getRoot(), true, false); writeNumberedDot(taxonomy->getRoot(), true, true); LOG(DEBUG) << "Before supertree "; writeTreeAsNewick(std::cerr, *taxonomy); std::cerr << '\n'; for (auto nd : iter_post_internal(*taxonomy)) { writeNumberedDot(nd, false, false); writeNumberedDot(nd, false, true); if (nd == taxonomy->getRoot()) ///TEMP!!!! resolveOrCollapse(nd, sc); LOG(DEBUG) << "After handling " << nd->getOttId(); writeTreeAsNewick(std::cerr, *taxonomy); std::cerr << '\n'; } } void writeNumberedDot(NodeWithSplits * nd, bool entireSubtree, bool includeLastTree) { std::string fn = "ScaffSuperTree" + std::to_string(currDotFileIndex++) + ".dot"; LOG(DEBUG) << "writing DOT file \"" << fn << "\""; std::ofstream out; out.open(fn); try { const auto & thr = taxoToEmbedding[nd]; writeDOTExport(out, thr, nd, treePtrByIndex, entireSubtree, includeLastTree); } catch (...) { out.close(); throw; } LOG(DEBUG) << "finished DOT file \"" << fn << "\""; } virtual ~ScaffoldedSupertree(){} ScaffoldedSupertree() :TaxonomyDependentTreeProcessor<TreeMappedWithSplits>(), numErrors(0), doReportAllContested(false), doConstructSupertree(false), taxonomyAsSource(nullptr), currDotFileIndex(0) { } void reportAllConflicting(std::ostream & out, bool verbose) { std::map<std::size_t, unsigned long> nodeMappingDegree; std::map<std::size_t, unsigned long> passThroughDegree; std::map<std::size_t, unsigned long> loopDegree; unsigned long totalContested = 0; unsigned long redundContested = 0; unsigned long totalNumNodes = 0; for (auto nd : iter_node_internal(*taxonomy)) { const auto & thr = taxoToEmbedding[nd]; nodeMappingDegree[thr.getTotalNumNodeMappings()] += 1; passThroughDegree[thr.getTotalNumEdgeBelowTraversals()] += 1; loopDegree[thr.getTotalNumLoops()] += 1; totalNumNodes += 1; std::vector<NodeWithSplits *> aliasedBy = getNodesAliasedBy(nd, *taxonomy); if (thr.reportIfContested(out, nd, treePtrByIndex, aliasedBy, verbose)) { totalContested += 1; if (nd->getOutDegree() == 1) { redundContested += 1; } } } unsigned long m = std::max(loopDegree.rbegin()->first, passThroughDegree.rbegin()->first); m = std::max(m, nodeMappingDegree.rbegin()->first); out << "Degree\tNodeMaps\tEdgeMaps\tLoops\n"; for (unsigned long i = 0 ; i <= m; ++i) { out << i << '\t' << nodeMappingDegree[i]<< '\t' << passThroughDegree[i] << '\t' << loopDegree[i]<< '\n'; } out << totalNumNodes << " internals\n" << totalContested << " contested\n" << (totalNumNodes - totalContested) << " uncontested\n"; out << redundContested << " monotypic contested\n"; } bool summarize(const OTCLI &otCLI) override { if (doConstructSupertree) { cloneTaxonomyAsASourceTree(); constructSupertree(); writeTreeAsNewick(otCLI.out, *taxonomy); otCLI.out << '\n'; } std::ostream & out{otCLI.out}; assert (taxonomy != nullptr); if (doReportAllContested) { reportAllConflicting(out, otCLI.verbose); } else { for (auto tr : idsListToReportOn) { auto nd = taxonomy->getData().getNodeForOttId(tr); if (nd == nullptr) { throw OTCError(std::string("Unrecognized OTT ID in list of OTT IDs to report on: ") + std::to_string(tr)); } const auto & thr = taxoToEmbedding[nd]; std::vector<NodeWithSplits *> aliasedBy = getNodesAliasedBy(nd, *taxonomy); thr.reportIfContested(out, nd, treePtrByIndex, aliasedBy, otCLI.verbose); } } for (auto tr : idListForDotExport) { auto nd = taxonomy->getData().getNodeForOttId(tr); if (nd == nullptr) { throw OTCError(std::string("Unrecognized OTT ID in list of OTT IDs to export to DOT: ") + std::to_string(tr)); } for (auto n : iter_pre_n_const(nd)) { const auto & thr = taxoToEmbedding[n]; writeDOTExport(out, thr, n, treePtrByIndex, false, false); } } return true; } bool processTaxonomyTree(OTCLI & otCLI) override { TaxonomyDependentTreeProcessor<TreeMappedWithSplits>::processTaxonomyTree(otCLI); checkTreeInvariants(*taxonomy); suppressMonotypicTaxaPreserveDeepestDangle(*taxonomy); checkTreeInvariants(*taxonomy); for (auto nd : iter_node(*taxonomy)) { taxoToEmbedding.emplace(nd, NodeEmbeddingWithSplits{}); } return true; } bool processSourceTree(OTCLI & otCLI, std::unique_ptr<TreeMappedWithSplits> treeup) override { assert(treeup != nullptr); assert(taxonomy != nullptr); // Store the tree pointer with a map to its index, and an alias for fast index->tree. std::size_t treeIndex = inputTreesToIndex.size(); assert(treeIndex == treePtrByIndex.size()); TreeMappedWithSplits * raw = treeup.get(); inputTreesToIndex[std::move(treeup)] = treeIndex; treePtrByIndex.push_back(raw); // Store the tree's filename raw->setName(otCLI.currentFilename); embedNewTree(*taxonomy, *raw, treeIndex); otCLI.out << "# pathPairings = " << pathPairings.size() << '\n'; return true; } bool cloneTaxonomyAsASourceTree() { assert(taxonomy != nullptr); assert(taxonomyAsSource == nullptr); std::unique_ptr<TreeMappedWithSplits> tree = std::move(cloneTree(*taxonomy)); taxonomyAsSource = tree.get(); std::size_t treeIndex = inputTreesToIndex.size(); TreeMappedWithSplits * raw = tree.get(); inputTreesToIndex[std::move(tree)] = treeIndex; treePtrByIndex.push_back(taxonomyAsSource); // Store the tree's filename raw->setName("TAXONOMY"); threadTaxonomyClone(*taxonomy, *taxonomyAsSource, treeIndex); return true; } }; bool handleReportAllFlag(OTCLI & otCLI, const std::string &); bool handleReportOnNodesFlag(OTCLI & otCLI, const std::string &); bool handleDotNodesFlag(OTCLI & otCLI, const std::string &narg); bool handleSuperTreeFlag(OTCLI & otCLI, const std::string &narg); bool handleReportAllFlag(OTCLI & otCLI, const std::string &) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); proc->doReportAllContested = true; return true; } bool handleSuperTreeFlag(OTCLI & otCLI, const std::string &) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); proc->doConstructSupertree = true; return true; } bool handleReportOnNodesFlag(OTCLI & otCLI, const std::string &narg) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); if (narg.empty()) { throw OTCError("Expecting a list of IDs after the -b argument."); } auto rs = split_string(narg, ','); for (auto word : rs) { auto ottId = ottIDFromName(word); if (ottId < 0) { throw OTCError(std::string("Expecting a list of IDs after the -b argument. Offending word: ") + word); } proc->idsListToReportOn.push_back(ottId); } return true; } bool handleDotNodesFlag(OTCLI & otCLI, const std::string &narg) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); if (narg.empty()) { throw OTCError("Expecting a list of IDs after the -d argument."); } auto rs = split_string(narg, ','); for (auto word : rs) { auto ottId = ottIDFromName(word); if (ottId < 0) { throw OTCError(std::string("Expecting a list of IDs after the -d argument. Offending word: ") + word); } proc->idListForDotExport.push_back(ottId); } return true; } int main(int argc, char *argv[]) { OTCLI otCLI("otcscaffoldedsupertree", "takes at least 2 newick file paths: a full taxonomy tree, and some number of input trees. Crashes or emits bogus output.", "taxonomy.tre inp1.tre inp2.tre"); ScaffoldedSupertree proc; otCLI.addFlag('a', "Write a report of all contested nodes", handleReportAllFlag, false); otCLI.addFlag('s', "Compute a supertree", handleSuperTreeFlag, false); otCLI.addFlag('b', "IDLIST should be a list of OTT IDs. A status report will be generated for those nodes", handleReportOnNodesFlag, true); otCLI.addFlag('d', "IDLIST should be a list of OTT IDs. A DOT file of the nodes will be generated ", handleDotNodesFlag, true); return taxDependentTreeProcessingMain(otCLI, argc, argv, proc, 2, true); } <commit_msg>using the pretty graphs to debug means we can do the resolve step for every node<commit_after>#include <tuple> #include "otc/otcli.h" #include "otc/debug.h" #include "otc/greedy_forest.h" #include "otc/embedding.h" #include "otc/embedded_tree.h" using namespace otc; std::unique_ptr<TreeMappedWithSplits> cloneTree(const TreeMappedWithSplits &); template<typename T, typename U> void updateAncestralPathOttIdSet(T * nd, const OttIdSet & oldEls, const OttIdSet newEls, std::map<const T *, NodeEmbedding<T, U> > & m); template<typename T, typename U> inline void updateAncestralPathOttIdSet(T * nd, const OttIdSet & oldEls, const OttIdSet newEls, std::map<const T *, NodeEmbedding<T, U> > & m) { for (auto anc : iter_anc(*nd)) { auto & ant = m.at(anc); ant.updateAllPathsOttIdSets(oldEls, newEls); } } //currently not copying names std::unique_ptr<TreeMappedWithSplits> cloneTree(const TreeMappedWithSplits &tree) { TreeMappedWithSplits * rawTreePtr = new TreeMappedWithSplits(); try { NodeWithSplits * newRoot = rawTreePtr->createRoot(); auto r = tree.getRoot(); assert(r->hasOttId()); newRoot->setOttId(r->getOttId()); std::map<const NodeWithSplits *, NodeWithSplits *> templateToNew; templateToNew[r]= newRoot; std::map<long, NodeWithSplits *> & newMap = rawTreePtr->getData().ottIdToNode; rawTreePtr->getData().desIdSetsContainInternals = tree.getData().desIdSetsContainInternals; for (auto nd : iter_pre_const(tree)) { auto p = nd->getParent(); if (p == nullptr) { continue; } auto t2nIt = templateToNew.find(p); assert(t2nIt != templateToNew.end()); auto ntp = t2nIt->second; auto nn = rawTreePtr->createChild(ntp); assert(templateToNew.find(nd) == templateToNew.end()); templateToNew[nd] = nn; if (nd->hasOttId()) { nn->setOttId(nd->getOttId()); newMap[nd->getOttId()] = nn; } else { assert(false); } nn->getData().desIds = nd->getData().desIds; } } catch (...) { delete rawTreePtr; throw; } return std::unique_ptr<TreeMappedWithSplits>(rawTreePtr); } class ScaffoldedSupertree : public TaxonomyDependentTreeProcessor<TreeMappedWithSplits>, public EmbeddedTree { public: int numErrors; OttIdSet tabooIds; std::map<std::unique_ptr<TreeMappedWithSplits>, std::size_t> inputTreesToIndex; std::vector<TreeMappedWithSplits *> treePtrByIndex; bool doReportAllContested; bool doConstructSupertree; std::list<long> idsListToReportOn; std::list<long> idListForDotExport; TreeMappedWithSplits * taxonomyAsSource; int currDotFileIndex; void resolveOrCollapse(NodeWithSplits * scaffoldNd, SupertreeContextWithSplits & sc) { auto & thr = taxoToEmbedding[scaffoldNd]; if (thr.isContested()) { if (thr.highRankingTreesPreserveMonophyly(sc.numTrees)) { thr.resolveGivenContestedMonophyly(*scaffoldNd, sc); } else { thr.constructPhyloGraphAndCollapseIfNecessary(*scaffoldNd, sc); } } else { thr.resolveGivenUncontestedMonophyly(*scaffoldNd, sc); } } void constructSupertree() { const auto numTrees = treePtrByIndex.size(); TreeMappedWithSplits * tax = taxonomy.get(); SupertreeContextWithSplits sc{numTrees, taxoToEmbedding, *tax}; writeNumberedDot(taxonomy->getRoot(), true, false); writeNumberedDot(taxonomy->getRoot(), true, true); LOG(DEBUG) << "Before supertree "; writeTreeAsNewick(std::cerr, *taxonomy); std::cerr << '\n'; for (auto nd : iter_post_internal(*taxonomy)) { writeNumberedDot(nd, false, false); writeNumberedDot(nd, false, true); resolveOrCollapse(nd, sc); LOG(DEBUG) << "After handling " << nd->getOttId(); writeTreeAsNewick(std::cerr, *taxonomy); std::cerr << '\n'; writeNumberedDot(taxonomy->getRoot(), true, false); writeNumberedDot(taxonomy->getRoot(), true, true); } } void writeNumberedDot(NodeWithSplits * nd, bool entireSubtree, bool includeLastTree) { std::string fn = "ScaffSuperTree" + std::to_string(currDotFileIndex++) + ".dot"; LOG(DEBUG) << "writing DOT file \"" << fn << "\""; std::ofstream out; out.open(fn); try { const auto & thr = taxoToEmbedding[nd]; writeDOTExport(out, thr, nd, treePtrByIndex, entireSubtree, includeLastTree); } catch (...) { out.close(); throw; } LOG(DEBUG) << "finished DOT file \"" << fn << "\""; } virtual ~ScaffoldedSupertree(){} ScaffoldedSupertree() :TaxonomyDependentTreeProcessor<TreeMappedWithSplits>(), numErrors(0), doReportAllContested(false), doConstructSupertree(false), taxonomyAsSource(nullptr), currDotFileIndex(0) { } void reportAllConflicting(std::ostream & out, bool verbose) { std::map<std::size_t, unsigned long> nodeMappingDegree; std::map<std::size_t, unsigned long> passThroughDegree; std::map<std::size_t, unsigned long> loopDegree; unsigned long totalContested = 0; unsigned long redundContested = 0; unsigned long totalNumNodes = 0; for (auto nd : iter_node_internal(*taxonomy)) { const auto & thr = taxoToEmbedding[nd]; nodeMappingDegree[thr.getTotalNumNodeMappings()] += 1; passThroughDegree[thr.getTotalNumEdgeBelowTraversals()] += 1; loopDegree[thr.getTotalNumLoops()] += 1; totalNumNodes += 1; std::vector<NodeWithSplits *> aliasedBy = getNodesAliasedBy(nd, *taxonomy); if (thr.reportIfContested(out, nd, treePtrByIndex, aliasedBy, verbose)) { totalContested += 1; if (nd->getOutDegree() == 1) { redundContested += 1; } } } unsigned long m = std::max(loopDegree.rbegin()->first, passThroughDegree.rbegin()->first); m = std::max(m, nodeMappingDegree.rbegin()->first); out << "Degree\tNodeMaps\tEdgeMaps\tLoops\n"; for (unsigned long i = 0 ; i <= m; ++i) { out << i << '\t' << nodeMappingDegree[i]<< '\t' << passThroughDegree[i] << '\t' << loopDegree[i]<< '\n'; } out << totalNumNodes << " internals\n" << totalContested << " contested\n" << (totalNumNodes - totalContested) << " uncontested\n"; out << redundContested << " monotypic contested\n"; } bool summarize(const OTCLI &otCLI) override { if (doConstructSupertree) { cloneTaxonomyAsASourceTree(); constructSupertree(); writeTreeAsNewick(otCLI.out, *taxonomy); otCLI.out << '\n'; } std::ostream & out{otCLI.out}; assert (taxonomy != nullptr); if (doReportAllContested) { reportAllConflicting(out, otCLI.verbose); } else { for (auto tr : idsListToReportOn) { auto nd = taxonomy->getData().getNodeForOttId(tr); if (nd == nullptr) { throw OTCError(std::string("Unrecognized OTT ID in list of OTT IDs to report on: ") + std::to_string(tr)); } const auto & thr = taxoToEmbedding[nd]; std::vector<NodeWithSplits *> aliasedBy = getNodesAliasedBy(nd, *taxonomy); thr.reportIfContested(out, nd, treePtrByIndex, aliasedBy, otCLI.verbose); } } for (auto tr : idListForDotExport) { auto nd = taxonomy->getData().getNodeForOttId(tr); if (nd == nullptr) { throw OTCError(std::string("Unrecognized OTT ID in list of OTT IDs to export to DOT: ") + std::to_string(tr)); } for (auto n : iter_pre_n_const(nd)) { const auto & thr = taxoToEmbedding[n]; writeDOTExport(out, thr, n, treePtrByIndex, false, false); } } return true; } bool processTaxonomyTree(OTCLI & otCLI) override { TaxonomyDependentTreeProcessor<TreeMappedWithSplits>::processTaxonomyTree(otCLI); checkTreeInvariants(*taxonomy); suppressMonotypicTaxaPreserveDeepestDangle(*taxonomy); checkTreeInvariants(*taxonomy); for (auto nd : iter_node(*taxonomy)) { taxoToEmbedding.emplace(nd, NodeEmbeddingWithSplits{}); } return true; } bool processSourceTree(OTCLI & otCLI, std::unique_ptr<TreeMappedWithSplits> treeup) override { assert(treeup != nullptr); assert(taxonomy != nullptr); // Store the tree pointer with a map to its index, and an alias for fast index->tree. std::size_t treeIndex = inputTreesToIndex.size(); assert(treeIndex == treePtrByIndex.size()); TreeMappedWithSplits * raw = treeup.get(); inputTreesToIndex[std::move(treeup)] = treeIndex; treePtrByIndex.push_back(raw); // Store the tree's filename raw->setName(otCLI.currentFilename); embedNewTree(*taxonomy, *raw, treeIndex); otCLI.out << "# pathPairings = " << pathPairings.size() << '\n'; return true; } bool cloneTaxonomyAsASourceTree() { assert(taxonomy != nullptr); assert(taxonomyAsSource == nullptr); std::unique_ptr<TreeMappedWithSplits> tree = std::move(cloneTree(*taxonomy)); taxonomyAsSource = tree.get(); std::size_t treeIndex = inputTreesToIndex.size(); TreeMappedWithSplits * raw = tree.get(); inputTreesToIndex[std::move(tree)] = treeIndex; treePtrByIndex.push_back(taxonomyAsSource); // Store the tree's filename raw->setName("TAXONOMY"); threadTaxonomyClone(*taxonomy, *taxonomyAsSource, treeIndex); return true; } }; bool handleReportAllFlag(OTCLI & otCLI, const std::string &); bool handleReportOnNodesFlag(OTCLI & otCLI, const std::string &); bool handleDotNodesFlag(OTCLI & otCLI, const std::string &narg); bool handleSuperTreeFlag(OTCLI & otCLI, const std::string &narg); bool handleReportAllFlag(OTCLI & otCLI, const std::string &) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); proc->doReportAllContested = true; return true; } bool handleSuperTreeFlag(OTCLI & otCLI, const std::string &) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); proc->doConstructSupertree = true; return true; } bool handleReportOnNodesFlag(OTCLI & otCLI, const std::string &narg) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); if (narg.empty()) { throw OTCError("Expecting a list of IDs after the -b argument."); } auto rs = split_string(narg, ','); for (auto word : rs) { auto ottId = ottIDFromName(word); if (ottId < 0) { throw OTCError(std::string("Expecting a list of IDs after the -b argument. Offending word: ") + word); } proc->idsListToReportOn.push_back(ottId); } return true; } bool handleDotNodesFlag(OTCLI & otCLI, const std::string &narg) { ScaffoldedSupertree * proc = static_cast<ScaffoldedSupertree *>(otCLI.blob); assert(proc != nullptr); if (narg.empty()) { throw OTCError("Expecting a list of IDs after the -d argument."); } auto rs = split_string(narg, ','); for (auto word : rs) { auto ottId = ottIDFromName(word); if (ottId < 0) { throw OTCError(std::string("Expecting a list of IDs after the -d argument. Offending word: ") + word); } proc->idListForDotExport.push_back(ottId); } return true; } int main(int argc, char *argv[]) { OTCLI otCLI("otcscaffoldedsupertree", "takes at least 2 newick file paths: a full taxonomy tree, and some number of input trees. Crashes or emits bogus output.", "taxonomy.tre inp1.tre inp2.tre"); ScaffoldedSupertree proc; otCLI.addFlag('a', "Write a report of all contested nodes", handleReportAllFlag, false); otCLI.addFlag('s', "Compute a supertree", handleSuperTreeFlag, false); otCLI.addFlag('b', "IDLIST should be a list of OTT IDs. A status report will be generated for those nodes", handleReportOnNodesFlag, true); otCLI.addFlag('d', "IDLIST should be a list of OTT IDs. A DOT file of the nodes will be generated ", handleDotNodesFlag, true); return taxDependentTreeProcessingMain(otCLI, argc, argv, proc, 2, true); } <|endoftext|>
<commit_before>//===--- BracesAroundStatementsCheck.cpp - clang-tidy ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BracesAroundStatementsCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Lexer.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace readability { namespace { tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM, const ASTContext *Context) { Token Tok; SourceLocation Beginning = Lexer::GetBeginningOfToken(Loc, SM, Context->getLangOpts()); const bool Invalid = Lexer::getRawToken(Beginning, Tok, SM, Context->getLangOpts()); assert(!Invalid && "Expected a valid token."); if (Invalid) return tok::NUM_TOKENS; return Tok.getKind(); } SourceLocation forwardSkipWhitespaceAndComments(SourceLocation Loc, const SourceManager &SM, const ASTContext *Context) { assert(Loc.isValid()); for (;;) { while (isWhitespace(*FullSourceLoc(Loc, SM).getCharacterData())) Loc = Loc.getLocWithOffset(1); tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind == tok::NUM_TOKENS || TokKind != tok::comment) return Loc; // Fast-forward current token. Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); } } SourceLocation findEndLocation(SourceLocation LastTokenLoc, const SourceManager &SM, const ASTContext *Context) { SourceLocation Loc = LastTokenLoc; // Loc points to the beginning of the last (non-comment non-ws) token // before end or ';'. assert(Loc.isValid()); bool SkipEndWhitespaceAndComments = true; tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind == tok::NUM_TOKENS || TokKind == tok::semi || TokKind == tok::r_brace) { // If we are at ";" or "}", we found the last token. We could use as well // `if (isa<NullStmt>(S))`, but it wouldn't work for nested statements. SkipEndWhitespaceAndComments = false; } Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); // Loc points past the last token before end or after ';'. if (SkipEndWhitespaceAndComments) { Loc = forwardSkipWhitespaceAndComments(Loc, SM, Context); tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind == tok::semi) Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); } for (;;) { assert(Loc.isValid()); while (isHorizontalWhitespace(*FullSourceLoc(Loc, SM).getCharacterData())) Loc = Loc.getLocWithOffset(1); if (isVerticalWhitespace(*FullSourceLoc(Loc, SM).getCharacterData())) { // EOL, insert brace before. break; } tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind != tok::comment) { // Non-comment token, insert brace before. break; } SourceLocation TokEndLoc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); SourceRange TokRange(Loc, TokEndLoc); StringRef Comment = Lexer::getSourceText( CharSourceRange::getTokenRange(TokRange), SM, Context->getLangOpts()); if (Comment.startswith("/*") && Comment.find('\n') != StringRef::npos) { // Multi-line block comment, insert brace before. break; } // else: Trailing comment, insert brace after the newline. // Fast-forward current token. Loc = TokEndLoc; } return Loc; } } // namespace BracesAroundStatementsCheck::BracesAroundStatementsCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), // Always add braces by default. ShortStatementLines(Options.get("ShortStatementLines", 0U)) {} void BracesAroundStatementsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "ShortStatementLines", ShortStatementLines); } void BracesAroundStatementsCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(ifStmt().bind("if"), this); Finder->addMatcher(whileStmt().bind("while"), this); Finder->addMatcher(doStmt().bind("do"), this); Finder->addMatcher(forStmt().bind("for"), this); Finder->addMatcher(cxxForRangeStmt().bind("for-range"), this); } void BracesAroundStatementsCheck::check(const MatchFinder::MatchResult &Result) { const SourceManager &SM = *Result.SourceManager; const ASTContext *Context = Result.Context; // Get location of closing parenthesis or 'do' to insert opening brace. if (auto S = Result.Nodes.getNodeAs<ForStmt>("for")) { checkStmt(Result, S->getBody(), S->getRParenLoc()); } else if (auto S = Result.Nodes.getNodeAs<CXXForRangeStmt>("for-range")) { checkStmt(Result, S->getBody(), S->getRParenLoc()); } else if (auto S = Result.Nodes.getNodeAs<DoStmt>("do")) { checkStmt(Result, S->getBody(), S->getDoLoc(), S->getWhileLoc()); } else if (auto S = Result.Nodes.getNodeAs<WhileStmt>("while")) { SourceLocation StartLoc = findRParenLoc(S, SM, Context); if (StartLoc.isInvalid()) return; checkStmt(Result, S->getBody(), StartLoc); } else if (auto S = Result.Nodes.getNodeAs<IfStmt>("if")) { SourceLocation StartLoc = findRParenLoc(S, SM, Context); if (StartLoc.isInvalid()) return; if (ForceBracesStmts.erase(S)) ForceBracesStmts.insert(S->getThen()); bool BracedIf = checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc()); const Stmt *Else = S->getElse(); if (Else && BracedIf) ForceBracesStmts.insert(Else); if (Else && !isa<IfStmt>(Else)) { // Omit 'else if' statements here, they will be handled directly. checkStmt(Result, Else, S->getElseLoc(), SourceLocation()); } } else { llvm_unreachable("Invalid match"); } } /// Find location of right parenthesis closing condition template <typename IfOrWhileStmt> SourceLocation BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S, const SourceManager &SM, const ASTContext *Context) { // Skip macros. if (S->getLocStart().isMacroID()) return SourceLocation(); static const char *const ErrorMessage = "cannot find location of closing parenthesis ')'"; SourceLocation CondEndLoc = S->getCond()->getLocEnd(); if (const DeclStmt *CondVar = S->getConditionVariableDeclStmt()) CondEndLoc = CondVar->getLocEnd(); assert(CondEndLoc.isValid()); SourceLocation PastCondEndLoc = Lexer::getLocForEndOfToken(CondEndLoc, 0, SM, Context->getLangOpts()); if (PastCondEndLoc.isInvalid()) { diag(CondEndLoc, ErrorMessage); return SourceLocation(); } SourceLocation RParenLoc = forwardSkipWhitespaceAndComments(PastCondEndLoc, SM, Context); if (RParenLoc.isInvalid()) { diag(PastCondEndLoc, ErrorMessage); return SourceLocation(); } tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, Context); if (TokKind != tok::r_paren) { diag(RParenLoc, ErrorMessage); return SourceLocation(); } return RParenLoc; } /// Determine if the statement needs braces around it, and add them if it does. /// Returns true if braces where added. bool BracesAroundStatementsCheck::checkStmt( const MatchFinder::MatchResult &Result, const Stmt *S, SourceLocation InitialLoc, SourceLocation EndLocHint) { // 1) If there's a corresponding "else" or "while", the check inserts "} " // right before that token. // 2) If there's a multi-line block comment starting on the same line after // the location we're inserting the closing brace at, or there's a non-comment // token, the check inserts "\n}" right before that token. // 3) Otherwise the check finds the end of line (possibly after some block or // line comments) and inserts "\n}" right before that EOL. if (!S || isa<CompoundStmt>(S)) { // Already inside braces. return false; } const SourceManager &SM = *Result.SourceManager; const ASTContext *Context = Result.Context; // Treat macros. CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(S->getSourceRange()), SM, Context->getLangOpts()); if (FileRange.isInvalid()) return false; // InitialLoc points at the last token before opening brace to be inserted. assert(InitialLoc.isValid()); // Convert InitialLoc to file location, if it's on the same macro expansion // level as the start of the statement. We also need file locations for // Lexer::getLocForEndOfToken working properly. InitialLoc = Lexer::makeFileCharRange( CharSourceRange::getCharRange(InitialLoc, S->getLocStart()), SM, Context->getLangOpts()) .getBegin(); if (InitialLoc.isInvalid()) return false; SourceLocation StartLoc = Lexer::getLocForEndOfToken(InitialLoc, 0, SM, Context->getLangOpts()); // StartLoc points at the location of the opening brace to be inserted. SourceLocation EndLoc; std::string ClosingInsertion; if (EndLocHint.isValid()) { EndLoc = EndLocHint; ClosingInsertion = "} "; } else { const auto FREnd = FileRange.getEnd().getLocWithOffset(-1); EndLoc = findEndLocation(FREnd, SM, Context); ClosingInsertion = "\n}"; } assert(StartLoc.isValid()); assert(EndLoc.isValid()); // Don't require braces for statements spanning less than certain number of // lines. if (ShortStatementLines && !ForceBracesStmts.erase(S)) { unsigned StartLine = SM.getSpellingLineNumber(StartLoc); unsigned EndLine = SM.getSpellingLineNumber(EndLoc); if (EndLine - StartLine < ShortStatementLines) return false; } auto Diag = diag(StartLoc, "statement should be inside braces"); Diag << FixItHint::CreateInsertion(StartLoc, " {") << FixItHint::CreateInsertion(EndLoc, ClosingInsertion); return true; } void BracesAroundStatementsCheck::onEndOfTranslationUnit() { ForceBracesStmts.clear(); } } // namespace readability } // namespace tidy } // namespace clang <commit_msg>[clang-tidy] Don't use diag() for debug output<commit_after>//===--- BracesAroundStatementsCheck.cpp - clang-tidy ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BracesAroundStatementsCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Lexer.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace readability { namespace { tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM, const ASTContext *Context) { Token Tok; SourceLocation Beginning = Lexer::GetBeginningOfToken(Loc, SM, Context->getLangOpts()); const bool Invalid = Lexer::getRawToken(Beginning, Tok, SM, Context->getLangOpts()); assert(!Invalid && "Expected a valid token."); if (Invalid) return tok::NUM_TOKENS; return Tok.getKind(); } SourceLocation forwardSkipWhitespaceAndComments(SourceLocation Loc, const SourceManager &SM, const ASTContext *Context) { assert(Loc.isValid()); for (;;) { while (isWhitespace(*FullSourceLoc(Loc, SM).getCharacterData())) Loc = Loc.getLocWithOffset(1); tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind == tok::NUM_TOKENS || TokKind != tok::comment) return Loc; // Fast-forward current token. Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); } } SourceLocation findEndLocation(SourceLocation LastTokenLoc, const SourceManager &SM, const ASTContext *Context) { SourceLocation Loc = LastTokenLoc; // Loc points to the beginning of the last (non-comment non-ws) token // before end or ';'. assert(Loc.isValid()); bool SkipEndWhitespaceAndComments = true; tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind == tok::NUM_TOKENS || TokKind == tok::semi || TokKind == tok::r_brace) { // If we are at ";" or "}", we found the last token. We could use as well // `if (isa<NullStmt>(S))`, but it wouldn't work for nested statements. SkipEndWhitespaceAndComments = false; } Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); // Loc points past the last token before end or after ';'. if (SkipEndWhitespaceAndComments) { Loc = forwardSkipWhitespaceAndComments(Loc, SM, Context); tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind == tok::semi) Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); } for (;;) { assert(Loc.isValid()); while (isHorizontalWhitespace(*FullSourceLoc(Loc, SM).getCharacterData())) Loc = Loc.getLocWithOffset(1); if (isVerticalWhitespace(*FullSourceLoc(Loc, SM).getCharacterData())) { // EOL, insert brace before. break; } tok::TokenKind TokKind = getTokenKind(Loc, SM, Context); if (TokKind != tok::comment) { // Non-comment token, insert brace before. break; } SourceLocation TokEndLoc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts()); SourceRange TokRange(Loc, TokEndLoc); StringRef Comment = Lexer::getSourceText( CharSourceRange::getTokenRange(TokRange), SM, Context->getLangOpts()); if (Comment.startswith("/*") && Comment.find('\n') != StringRef::npos) { // Multi-line block comment, insert brace before. break; } // else: Trailing comment, insert brace after the newline. // Fast-forward current token. Loc = TokEndLoc; } return Loc; } } // namespace BracesAroundStatementsCheck::BracesAroundStatementsCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), // Always add braces by default. ShortStatementLines(Options.get("ShortStatementLines", 0U)) {} void BracesAroundStatementsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "ShortStatementLines", ShortStatementLines); } void BracesAroundStatementsCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(ifStmt().bind("if"), this); Finder->addMatcher(whileStmt().bind("while"), this); Finder->addMatcher(doStmt().bind("do"), this); Finder->addMatcher(forStmt().bind("for"), this); Finder->addMatcher(cxxForRangeStmt().bind("for-range"), this); } void BracesAroundStatementsCheck::check(const MatchFinder::MatchResult &Result) { const SourceManager &SM = *Result.SourceManager; const ASTContext *Context = Result.Context; // Get location of closing parenthesis or 'do' to insert opening brace. if (auto S = Result.Nodes.getNodeAs<ForStmt>("for")) { checkStmt(Result, S->getBody(), S->getRParenLoc()); } else if (auto S = Result.Nodes.getNodeAs<CXXForRangeStmt>("for-range")) { checkStmt(Result, S->getBody(), S->getRParenLoc()); } else if (auto S = Result.Nodes.getNodeAs<DoStmt>("do")) { checkStmt(Result, S->getBody(), S->getDoLoc(), S->getWhileLoc()); } else if (auto S = Result.Nodes.getNodeAs<WhileStmt>("while")) { SourceLocation StartLoc = findRParenLoc(S, SM, Context); if (StartLoc.isInvalid()) return; checkStmt(Result, S->getBody(), StartLoc); } else if (auto S = Result.Nodes.getNodeAs<IfStmt>("if")) { SourceLocation StartLoc = findRParenLoc(S, SM, Context); if (StartLoc.isInvalid()) return; if (ForceBracesStmts.erase(S)) ForceBracesStmts.insert(S->getThen()); bool BracedIf = checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc()); const Stmt *Else = S->getElse(); if (Else && BracedIf) ForceBracesStmts.insert(Else); if (Else && !isa<IfStmt>(Else)) { // Omit 'else if' statements here, they will be handled directly. checkStmt(Result, Else, S->getElseLoc(), SourceLocation()); } } else { llvm_unreachable("Invalid match"); } } /// Find location of right parenthesis closing condition template <typename IfOrWhileStmt> SourceLocation BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S, const SourceManager &SM, const ASTContext *Context) { // Skip macros. if (S->getLocStart().isMacroID()) return SourceLocation(); SourceLocation CondEndLoc = S->getCond()->getLocEnd(); if (const DeclStmt *CondVar = S->getConditionVariableDeclStmt()) CondEndLoc = CondVar->getLocEnd(); assert(CondEndLoc.isValid()); SourceLocation PastCondEndLoc = Lexer::getLocForEndOfToken(CondEndLoc, 0, SM, Context->getLangOpts()); if (PastCondEndLoc.isInvalid()) return SourceLocation(); SourceLocation RParenLoc = forwardSkipWhitespaceAndComments(PastCondEndLoc, SM, Context); if (RParenLoc.isInvalid()) return SourceLocation(); tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, Context); if (TokKind != tok::r_paren) return SourceLocation(); return RParenLoc; } /// Determine if the statement needs braces around it, and add them if it does. /// Returns true if braces where added. bool BracesAroundStatementsCheck::checkStmt( const MatchFinder::MatchResult &Result, const Stmt *S, SourceLocation InitialLoc, SourceLocation EndLocHint) { // 1) If there's a corresponding "else" or "while", the check inserts "} " // right before that token. // 2) If there's a multi-line block comment starting on the same line after // the location we're inserting the closing brace at, or there's a non-comment // token, the check inserts "\n}" right before that token. // 3) Otherwise the check finds the end of line (possibly after some block or // line comments) and inserts "\n}" right before that EOL. if (!S || isa<CompoundStmt>(S)) { // Already inside braces. return false; } const SourceManager &SM = *Result.SourceManager; const ASTContext *Context = Result.Context; // Treat macros. CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(S->getSourceRange()), SM, Context->getLangOpts()); if (FileRange.isInvalid()) return false; // InitialLoc points at the last token before opening brace to be inserted. assert(InitialLoc.isValid()); // Convert InitialLoc to file location, if it's on the same macro expansion // level as the start of the statement. We also need file locations for // Lexer::getLocForEndOfToken working properly. InitialLoc = Lexer::makeFileCharRange( CharSourceRange::getCharRange(InitialLoc, S->getLocStart()), SM, Context->getLangOpts()) .getBegin(); if (InitialLoc.isInvalid()) return false; SourceLocation StartLoc = Lexer::getLocForEndOfToken(InitialLoc, 0, SM, Context->getLangOpts()); // StartLoc points at the location of the opening brace to be inserted. SourceLocation EndLoc; std::string ClosingInsertion; if (EndLocHint.isValid()) { EndLoc = EndLocHint; ClosingInsertion = "} "; } else { const auto FREnd = FileRange.getEnd().getLocWithOffset(-1); EndLoc = findEndLocation(FREnd, SM, Context); ClosingInsertion = "\n}"; } assert(StartLoc.isValid()); assert(EndLoc.isValid()); // Don't require braces for statements spanning less than certain number of // lines. if (ShortStatementLines && !ForceBracesStmts.erase(S)) { unsigned StartLine = SM.getSpellingLineNumber(StartLoc); unsigned EndLine = SM.getSpellingLineNumber(EndLoc); if (EndLine - StartLine < ShortStatementLines) return false; } auto Diag = diag(StartLoc, "statement should be inside braces"); Diag << FixItHint::CreateInsertion(StartLoc, " {") << FixItHint::CreateInsertion(EndLoc, ClosingInsertion); return true; } void BracesAroundStatementsCheck::onEndOfTranslationUnit() { ForceBracesStmts.clear(); } } // namespace readability } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process_util.h" #include "base/test/test_timeouts.h" #include "chrome/browser/service/service_process_control.h" #include "chrome/browser/service/service_process_control_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/service_process_util.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" class ServiceProcessControlBrowserTest : public InProcessBrowserTest { public: ServiceProcessControlBrowserTest() : service_process_handle_(base::kNullProcessHandle) { } ~ServiceProcessControlBrowserTest() { base::CloseProcessHandle(service_process_handle_); service_process_handle_ = base::kNullProcessHandle; // Delete all instances of ServiceProcessControl. ServiceProcessControlManager::GetInstance()->Shutdown(); } #if defined(OS_MACOSX) virtual void TearDown() { // ForceServiceProcessShutdown removes the process from launchd on Mac. ForceServiceProcessShutdown("", 0); } #endif // OS_MACOSX protected: void LaunchServiceProcessControl() { ServiceProcessControl* process = ServiceProcessControlManager::GetInstance()->GetProcessControl( browser()->profile()); process_ = process; // Launch the process asynchronously. process->Launch( NewRunnableMethod( this, &ServiceProcessControlBrowserTest::ProcessControlLaunched), NewRunnableMethod( this, &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed)); // Then run the message loop to keep things running. ui_test_utils::RunMessageLoop(); } // Send a remoting host status request and wait reply from the service. void SendRequestAndWait() { process()->GetCloudPrintProxyStatus(NewCallback( this, &ServiceProcessControlBrowserTest::CloudPrintStatusCallback)); ui_test_utils::RunMessageLoop(); } void CloudPrintStatusCallback( bool enabled, std::string email) { MessageLoop::current()->Quit(); } void Disconnect() { // This will delete all instances of ServiceProcessControl and close the IPC // connections. ServiceProcessControlManager::GetInstance()->Shutdown(); process_ = NULL; } void WaitForShutdown() { EXPECT_TRUE(base::WaitForSingleProcess( service_process_handle_, TestTimeouts::wait_for_terminate_timeout_ms())); } void ProcessControlLaunched() { base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); EXPECT_TRUE(base::OpenProcessHandleWithAccess( service_pid, base::kProcessAccessWaitForTermination, &service_process_handle_)); // Quit the current message. Post a QuitTask instead of just calling Quit() // because this can get invoked in the context of a Launch() call and we // may not be in Run() yet. MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } void ProcessControlLaunchFailed() { ADD_FAILURE(); // Quit the current message. MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } ServiceProcessControl* process() { return process_; } private: ServiceProcessControl* process_; base::ProcessHandle service_process_handle_; }; // They way that the IPC is implemented only works on windows. This has to // change when we implement a different scheme for IPC. // Times out flakily, http://crbug.com/70076. IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DISABLED_LaunchAndIPC) { LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); SendRequestAndWait(); // And then shutdown the service process. EXPECT_TRUE(process()->Shutdown()); } // This tests the case when a service process is launched when browser // starts but we try to launch it again in the remoting setup dialog. IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, LaunchTwice) { // Launch the service process the first time. LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); SendRequestAndWait(); // Launch the service process again. LaunchServiceProcessControl(); EXPECT_TRUE(process()->is_connected()); SendRequestAndWait(); // And then shutdown the service process. EXPECT_TRUE(process()->Shutdown()); } static void DecrementUntilZero(int* count) { (*count)--; if (!(*count)) MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } // Invoke multiple Launch calls in succession and ensure that all the tasks // get invoked. IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MultipleLaunchTasks) { ServiceProcessControl* process = ServiceProcessControlManager::GetInstance()->GetProcessControl( browser()->profile()); int launch_count = 5; for (int i = 0; i < launch_count; i++) { // Launch the process asynchronously. process->Launch( NewRunnableFunction(&DecrementUntilZero, &launch_count), new MessageLoop::QuitTask()); } // Then run the message loop to keep things running. ui_test_utils::RunMessageLoop(); EXPECT_EQ(0, launch_count); // And then shutdown the service process. EXPECT_TRUE(process->Shutdown()); } // Make sure using the same task for success and failure tasks works. IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, SameLaunchTask) { ServiceProcessControl* process = ServiceProcessControlManager::GetInstance()->GetProcessControl( browser()->profile()); int launch_count = 5; for (int i = 0; i < launch_count; i++) { // Launch the process asynchronously. Task * task = NewRunnableFunction(&DecrementUntilZero, &launch_count); process->Launch(task, task); } // Then run the message loop to keep things running. ui_test_utils::RunMessageLoop(); EXPECT_EQ(0, launch_count); // And then shutdown the service process. EXPECT_TRUE(process->Shutdown()); } // Tests whether disconnecting from the service IPC causes the service process // to die. IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DieOnDisconnect) { // Launch the service process. LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); Disconnect(); WaitForShutdown(); } //http://code.google.com/p/chromium/issues/detail?id=70793 IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DISABLED_ForceShutdown) { // Launch the service process. LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); chrome::VersionInfo version_info; ForceServiceProcessShutdown(version_info.Version(), service_pid); WaitForShutdown(); } IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, CheckPid) { base::ProcessId service_pid; EXPECT_FALSE(GetServiceProcessData(NULL, &service_pid)); // Launch the service process. LaunchServiceProcessControl(); EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); } DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControlBrowserTest); <commit_msg>Mark CheckPid,DieOnDisconnect,LaunchTwice,MultipleLaunchTasks,SameLaunchTask as FAILS on mac.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process_util.h" #include "base/test/test_timeouts.h" #include "chrome/browser/service/service_process_control.h" #include "chrome/browser/service/service_process_control_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/service_process_util.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" class ServiceProcessControlBrowserTest : public InProcessBrowserTest { public: ServiceProcessControlBrowserTest() : service_process_handle_(base::kNullProcessHandle) { } ~ServiceProcessControlBrowserTest() { base::CloseProcessHandle(service_process_handle_); service_process_handle_ = base::kNullProcessHandle; // Delete all instances of ServiceProcessControl. ServiceProcessControlManager::GetInstance()->Shutdown(); } #if defined(OS_MACOSX) virtual void TearDown() { // ForceServiceProcessShutdown removes the process from launchd on Mac. ForceServiceProcessShutdown("", 0); } #endif // OS_MACOSX protected: void LaunchServiceProcessControl() { ServiceProcessControl* process = ServiceProcessControlManager::GetInstance()->GetProcessControl( browser()->profile()); process_ = process; // Launch the process asynchronously. process->Launch( NewRunnableMethod( this, &ServiceProcessControlBrowserTest::ProcessControlLaunched), NewRunnableMethod( this, &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed)); // Then run the message loop to keep things running. ui_test_utils::RunMessageLoop(); } // Send a remoting host status request and wait reply from the service. void SendRequestAndWait() { process()->GetCloudPrintProxyStatus(NewCallback( this, &ServiceProcessControlBrowserTest::CloudPrintStatusCallback)); ui_test_utils::RunMessageLoop(); } void CloudPrintStatusCallback( bool enabled, std::string email) { MessageLoop::current()->Quit(); } void Disconnect() { // This will delete all instances of ServiceProcessControl and close the IPC // connections. ServiceProcessControlManager::GetInstance()->Shutdown(); process_ = NULL; } void WaitForShutdown() { EXPECT_TRUE(base::WaitForSingleProcess( service_process_handle_, TestTimeouts::wait_for_terminate_timeout_ms())); } void ProcessControlLaunched() { base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); EXPECT_TRUE(base::OpenProcessHandleWithAccess( service_pid, base::kProcessAccessWaitForTermination, &service_process_handle_)); // Quit the current message. Post a QuitTask instead of just calling Quit() // because this can get invoked in the context of a Launch() call and we // may not be in Run() yet. MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } void ProcessControlLaunchFailed() { ADD_FAILURE(); // Quit the current message. MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } ServiceProcessControl* process() { return process_; } private: ServiceProcessControl* process_; base::ProcessHandle service_process_handle_; }; // They way that the IPC is implemented only works on windows. This has to // change when we implement a different scheme for IPC. // Times out flakily, http://crbug.com/70076. IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DISABLED_LaunchAndIPC) { LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); SendRequestAndWait(); // And then shutdown the service process. EXPECT_TRUE(process()->Shutdown()); } // This tests the case when a service process is launched when browser // starts but we try to launch it again in the remoting setup dialog. // Fails on mac. http://crbug.com/75518 #if defined(OS_MACOSX) #define MAYBE_LaunchTwice FAILS_LaunchTwice #else #define MAYBE_LaunchTwice LaunchTwice #endif IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_LaunchTwice) { // Launch the service process the first time. LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); SendRequestAndWait(); // Launch the service process again. LaunchServiceProcessControl(); EXPECT_TRUE(process()->is_connected()); SendRequestAndWait(); // And then shutdown the service process. EXPECT_TRUE(process()->Shutdown()); } static void DecrementUntilZero(int* count) { (*count)--; if (!(*count)) MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } // Invoke multiple Launch calls in succession and ensure that all the tasks // get invoked. // Fails on mac. http://crbug.com/75518 #if defined(OS_MACOSX) #define MAYBE_MultipleLaunchTasks FAILS_MultipleLaunchTasks #else #define MAYBE_MultipleLaunchTasks MultipleLaunchTasks #endif IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_MultipleLaunchTasks) { ServiceProcessControl* process = ServiceProcessControlManager::GetInstance()->GetProcessControl( browser()->profile()); int launch_count = 5; for (int i = 0; i < launch_count; i++) { // Launch the process asynchronously. process->Launch( NewRunnableFunction(&DecrementUntilZero, &launch_count), new MessageLoop::QuitTask()); } // Then run the message loop to keep things running. ui_test_utils::RunMessageLoop(); EXPECT_EQ(0, launch_count); // And then shutdown the service process. EXPECT_TRUE(process->Shutdown()); } // Make sure using the same task for success and failure tasks works. // Fails on mac. http://crbug.com/75518 #if defined(OS_MACOSX) #define MAYBE_SameLaunchTask FAILS_SameLaunchTask #else #define MAYBE_SameLaunchTask SameLaunchTask #endif IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_SameLaunchTask) { ServiceProcessControl* process = ServiceProcessControlManager::GetInstance()->GetProcessControl( browser()->profile()); int launch_count = 5; for (int i = 0; i < launch_count; i++) { // Launch the process asynchronously. Task * task = NewRunnableFunction(&DecrementUntilZero, &launch_count); process->Launch(task, task); } // Then run the message loop to keep things running. ui_test_utils::RunMessageLoop(); EXPECT_EQ(0, launch_count); // And then shutdown the service process. EXPECT_TRUE(process->Shutdown()); } // Tests whether disconnecting from the service IPC causes the service process // to die. // Fails on mac. http://crbug.com/75518 #if defined(OS_MACOSX) #define MAYBE_DieOnDisconnect FAILS_DieOnDisconnect #else #define MAYBE_DieOnDisconnect DieOnDisconnect #endif IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_DieOnDisconnect) { // Launch the service process. LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); Disconnect(); WaitForShutdown(); } //http://code.google.com/p/chromium/issues/detail?id=70793 IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DISABLED_ForceShutdown) { // Launch the service process. LaunchServiceProcessControl(); // Make sure we are connected to the service process. EXPECT_TRUE(process()->is_connected()); base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); chrome::VersionInfo version_info; ForceServiceProcessShutdown(version_info.Version(), service_pid); WaitForShutdown(); } // Fails on mac. http://crbug.com/75518 #if defined(OS_MACOSX) #define MAYBE_CheckPid FAILS_CheckPid #else #define MAYBE_CheckPid CheckPid #endif IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_CheckPid) { base::ProcessId service_pid; EXPECT_FALSE(GetServiceProcessData(NULL, &service_pid)); // Launch the service process. LaunchServiceProcessControl(); EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); } DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControlBrowserTest); <|endoftext|>
<commit_before>#include <limits> #include <boost/foreach.hpp> #include "YankOpen.hpp" using namespace std; using namespace Geometry2d; REGISTER_PLAY_CATEGORY(Gameplay::Plays::YankOpen, "Playing") namespace Gameplay { namespace Plays { REGISTER_CONFIGURABLE(YankOpen) } } ConfigDouble *Gameplay::Plays::YankOpen::_offense_hysteresis; ConfigDouble *Gameplay::Plays::YankOpen::_support_backoff_thresh; ConfigDouble *Gameplay::Plays::YankOpen::_mark_hysteresis_coeff; ConfigDouble *Gameplay::Plays::YankOpen::_support_avoid_teammate_radius; ConfigDouble *Gameplay::Plays::YankOpen::_support_avoid_shot; ConfigDouble *Gameplay::Plays::YankOpen::_offense_support_ratio; ConfigDouble *Gameplay::Plays::YankOpen::_defense_support_ratio; ConfigBool *Gameplay::Plays::YankOpen::_useYank; void Gameplay::Plays::YankOpen::createConfiguration(Configuration *cfg) { _offense_hysteresis = new ConfigDouble(cfg, "YankOpen/Hystersis Coeff", 0.50); _support_backoff_thresh = new ConfigDouble(cfg, "YankOpen/Support Backoff Dist", 1.5); _mark_hysteresis_coeff = new ConfigDouble(cfg, "YankOpen/Mark Hystersis Coeff", 0.9); _support_avoid_teammate_radius = new ConfigDouble(cfg, "YankOpen/Support Avoid Teammate Dist", 0.5); _support_avoid_shot = new ConfigDouble(cfg, "YankOpen/Support Avoid Shot", 0.2); _offense_support_ratio = new ConfigDouble(cfg, "YankOpen/Offense Support Ratio", 0.7); _defense_support_ratio = new ConfigDouble(cfg, "YankOpen/Defense Support Ratio", 0.9); _useYank = new ConfigBool(cfg, "YankOpen/Use Yank", false); } Gameplay::Plays::YankOpen::YankOpen(GameplayModule *gameplay): Play(gameplay), _leftFullback(gameplay, Behaviors::Fullback::Left), _rightFullback(gameplay, Behaviors::Fullback::Right), _support(gameplay), _strikerBump(gameplay), _strikerFling(gameplay), _strikerYank(gameplay) { _leftFullback.otherFullbacks.insert(&_rightFullback); _rightFullback.otherFullbacks.insert(&_leftFullback); // use constant value of mark threshold for now _support.markLineThresh(1.0); } float Gameplay::Plays::YankOpen::score ( Gameplay::GameplayModule* gameplay ) { // only run if we are playing and not in a restart bool refApplicable = gameplay->state()->gameState.playing(); return refApplicable ? 0 : INFINITY; } bool Gameplay::Plays::YankOpen::run() { // handle assignments set<OurRobot *> available = _gameplay->playRobots(); // project the ball forward (dampened) const float proj_time = 0.75; // seconds to project const float dampen_factor = 0.9; // accounts for slowing over time Geometry2d::Point ballProj = ball().pos + ball().vel * proj_time * dampen_factor; // defense first - get closest to goal to choose sides properly assignNearest(_leftFullback.robot, available, Geometry2d::Point(-Field_GoalWidth/2, 0.0)); assignNearest(_rightFullback.robot, available, Geometry2d::Point(Field_GoalWidth/2, 0.0)); // determine whether to change offense players bool forward_reset = false; if (_strikerYank.robot && _support.robot && _support.robot->pos.distTo(ballProj) < *_offense_hysteresis * _strikerYank.robot->pos.distTo(ballProj)) { _strikerBump.robot = NULL; _strikerYank.robot = NULL; _strikerFling.robot = NULL; _strikerBump.restart(); _strikerYank.restart(); _strikerFling.restart(); _support.robot = NULL; forward_reset = true; } // choose offense, we want closest robot to ball to be striker // FIXME: need to assign more carefully to ensure that there is a robot available to kick if (assignNearest(_strikerYank.robot, available, ballProj)) { _strikerBump.robot = _strikerYank.robot; _strikerFling.robot = _strikerYank.robot; } // assignNearest(_support.robot, available, ballProj); // find the nearest opponent to the striker OpponentRobot* closestRobotToStriker = 0; float closestDistToStriker = numeric_limits<float>::infinity(); if (_strikerYank.robot) { BOOST_FOREACH(OpponentRobot* opp, state()->opp) { if (opp) { float d = opp->pos.distTo(_strikerYank.robot->pos); if (d < closestDistToStriker) { closestDistToStriker = d; closestRobotToStriker = opp; } } } } bool striker_engaged = _strikerYank.robot && closestDistToStriker < *_support_backoff_thresh; // pick as a mark target the furthest back opposing robot // and adjust mark ratio based on field position OpponentRobot* bestOpp = NULL; float bestDist = numeric_limits<float>::infinity(); float cur_dist = (_support.markRobot()) ? _support.markRobot()->pos.distTo(ballProj) : numeric_limits<float>::infinity(); size_t nrOppClose = 0; BOOST_FOREACH(OpponentRobot* opp, state()->opp) { const float oppPos = opp->pos.y; if (opp && opp->visible && oppPos > 0.1 && !(striker_engaged && opp == closestRobotToStriker)) { if (oppPos < bestDist) { bestDist = opp->pos.y; bestOpp = opp; } if (oppPos < Field_Length/2) { ++nrOppClose; } } } if (!bestOpp && _support.robot) { _support.robot->addText("No mark target"); } // use hysteresis for changing of the robot if (bestOpp && bestOpp->visible && (forward_reset || bestDist < cur_dist * *_mark_hysteresis_coeff)) _support.markRobot(bestOpp); // if we are further away, we can mark further from robot if (ballProj.y > Field_Length/2.0 && nrOppClose) _support.ratio(*_offense_support_ratio); else _support.ratio(*_defense_support_ratio); // adjust obstacles on markers if (_strikerYank.robot && _support.robot) { unsigned striker = _strikerYank.robot->shell(); _support.robot->avoidTeammateRadius(striker, *_support_avoid_teammate_radius); } // manually reset any kickers so they keep kicking if (_strikerYank.done()) { _strikerYank.restart(); } if (_strikerBump.done()) { _strikerBump.restart(); } if (_strikerFling.done()) { _strikerFling.restart(); } // execute behaviors // if (_striker.robot) _striker.run(); // TODO: choose which one to run if (*_useYank && _strikerYank.robot) _strikerYank.run(); if (!*_useYank && _strikerBump.robot) _strikerBump.run(); if (_support.robot) _support.run(); if (_leftFullback.robot) _leftFullback.run(); if (_rightFullback.robot) _rightFullback.run(); return true; } <commit_msg> sldkfjs<commit_after>#include <limits> #include <boost/foreach.hpp> #include "YankOpen.hpp" using namespace std; using namespace Geometry2d; REGISTER_PLAY_CATEGORY(Gameplay::Plays::YankOpen, "Playing") namespace Gameplay { namespace Plays { REGISTER_CONFIGURABLE(YankOpen) } } ConfigDouble *Gameplay::Plays::YankOpen::_offense_hysteresis; ConfigDouble *Gameplay::Plays::YankOpen::_support_backoff_thresh; ConfigDouble *Gameplay::Plays::YankOpen::_mark_hysteresis_coeff; ConfigDouble *Gameplay::Plays::YankOpen::_support_avoid_teammate_radius; ConfigDouble *Gameplay::Plays::YankOpen::_support_avoid_shot; ConfigDouble *Gameplay::Plays::YankOpen::_offense_support_ratio; ConfigDouble *Gameplay::Plays::YankOpen::_defense_support_ratio; ConfigBool *Gameplay::Plays::YankOpen::_useYank; void Gameplay::Plays::YankOpen::createConfiguration(Configuration *cfg) { _offense_hysteresis = new ConfigDouble(cfg, "YankOpen/Hystersis Coeff", 0.50); _support_backoff_thresh = new ConfigDouble(cfg, "YankOpen/Support Backoff Dist", 1.5); _mark_hysteresis_coeff = new ConfigDouble(cfg, "YankOpen/Mark Hystersis Coeff", 0.9); _support_avoid_teammate_radius = new ConfigDouble(cfg, "YankOpen/Support Avoid Teammate Dist", 0.5); _support_avoid_shot = new ConfigDouble(cfg, "YankOpen/Support Avoid Shot", 0.2); _offense_support_ratio = new ConfigDouble(cfg, "YankOpen/Offense Support Ratio", 0.7); _defense_support_ratio = new ConfigDouble(cfg, "YankOpen/Defense Support Ratio", 0.9); _useYank = new ConfigBool(cfg, "YankOpen/Use Yank", false); } Gameplay::Plays::YankOpen::YankOpen(GameplayModule *gameplay): Play(gameplay), _leftFullback(gameplay, Behaviors::Fullback::Left), _rightFullback(gameplay, Behaviors::Fullback::Right), _support(gameplay), _strikerBump(gameplay), _strikerFling(gameplay), _strikerYank(gameplay) { _leftFullback.otherFullbacks.insert(&_rightFullback); _rightFullback.otherFullbacks.insert(&_leftFullback); // use constant value of mark threshold for now _support.markLineThresh(1.0); } float Gameplay::Plays::YankOpen::score ( Gameplay::GameplayModule* gameplay ) { // only run if we are playing and not in a restart bool refApplicable = gameplay->state()->gameState.playing(); return refApplicable ? 0 : INFINITY; } bool Gameplay::Plays::YankOpen::run() { // handle assignments set<OurRobot *> available = _gameplay->playRobots(); // project the ball forward (dampened) const float proj_time = 0.75; // seconds to project const float dampen_factor = 0.9; // accounts for slowing over time Geometry2d::Point ballProj = ball().pos + ball().vel * proj_time * dampen_factor; // determine whether to change offense players bool forward_reset = false; // if (_strikerYank.robot && //_support.robot && // _support.robot->pos.distTo(ballProj) < *_offense_hysteresis * _strikerYank.robot->pos.distTo(ballProj)) { // _strikerBump.robot = NULL; // _strikerYank.robot = NULL; // _strikerFling.robot = NULL; // _strikerBump.restart(); // _strikerYank.restart(); // _strikerFling.restart(); // _support.robot = NULL; // forward_reset = true; // } // choose offense, we want closest robot to ball to be striker // FIXME: need to assign more carefully to ensure that there is a robot available to kick if (assignNearest(_strikerYank.robot, available, ballProj)) { _strikerBump.robot = _strikerYank.robot; _strikerFling.robot = _strikerYank.robot; } // assignNearest(_support.robot, available, ballProj); // find the nearest opponent to the striker OpponentRobot* closestRobotToStriker = 0; float closestDistToStriker = numeric_limits<float>::infinity(); if (_strikerYank.robot) { BOOST_FOREACH(OpponentRobot* opp, state()->opp) { if (opp) { float d = opp->pos.distTo(_strikerYank.robot->pos); if (d < closestDistToStriker) { closestDistToStriker = d; closestRobotToStriker = opp; } } } } bool striker_engaged = _strikerYank.robot && closestDistToStriker < *_support_backoff_thresh; // defense first - get closest to goal to choose sides properly assignNearest(_leftFullback.robot, available, Geometry2d::Point(-Field_GoalWidth/2, 0.0)); assignNearest(_rightFullback.robot, available, Geometry2d::Point(Field_GoalWidth/2, 0.0)); // pick as a mark target the furthest back opposing robot // and adjust mark ratio based on field position OpponentRobot* bestOpp = NULL; float bestDist = numeric_limits<float>::infinity(); float cur_dist = (_support.markRobot()) ? _support.markRobot()->pos.distTo(ballProj) : numeric_limits<float>::infinity(); size_t nrOppClose = 0; BOOST_FOREACH(OpponentRobot* opp, state()->opp) { const float oppPos = opp->pos.y; if (opp && opp->visible && oppPos > 0.1 && !(striker_engaged && opp == closestRobotToStriker)) { if (oppPos < bestDist) { bestDist = opp->pos.y; bestOpp = opp; } if (oppPos < Field_Length/2) { ++nrOppClose; } } } if (!bestOpp && _support.robot) { _support.robot->addText("No mark target"); } // use hysteresis for changing of the robot if (bestOpp && bestOpp->visible && (forward_reset || bestDist < cur_dist * *_mark_hysteresis_coeff)) _support.markRobot(bestOpp); // if we are further away, we can mark further from robot if (ballProj.y > Field_Length/2.0 && nrOppClose) _support.ratio(*_offense_support_ratio); else _support.ratio(*_defense_support_ratio); // adjust obstacles on markers if (_strikerYank.robot && _support.robot) { unsigned striker = _strikerYank.robot->shell(); _support.robot->avoidTeammateRadius(striker, *_support_avoid_teammate_radius); } // manually reset any kickers so they keep kicking if (_strikerYank.done()) { _strikerYank.restart(); } if (_strikerBump.done()) { _strikerBump.restart(); } if (_strikerFling.done()) { _strikerFling.restart(); } // execute behaviors // if (_striker.robot) _striker.run(); // TODO: choose which one to run if (*_useYank && _strikerYank.robot) _strikerYank.run(); if (!*_useYank && _strikerBump.robot) _strikerBump.run(); if (_support.robot) _support.run(); if (_leftFullback.robot) _leftFullback.run(); if (_rightFullback.robot) _rightFullback.run(); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/crypto_module_password_dialog_view.h" #include "base/basictypes.h" #include "base/bind.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/views/window.h" #include "googleurl/src/gurl.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/text_button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" int kInputPasswordMinWidth = 8; namespace browser { // CryptoModulePasswordDialogView //////////////////////////////////////////////////////////////////////////////// CryptoModulePasswordDialogView::CryptoModulePasswordDialogView( const std::string& slot_name, browser::CryptoModulePasswordReason reason, const std::string& server, const base::Callback<void(const char*)>& callback) : callback_(callback) { Init(server, slot_name, reason); } CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() { } void CryptoModulePasswordDialogView::Init( const std::string& server, const std::string& slot_name, browser::CryptoModulePasswordReason reason) { // Select an appropriate text for the reason. std::string text; const string16& server16 = UTF8ToUTF16(server); const string16& slot16 = UTF8ToUTF16(slot_name); switch (reason) { case browser::kCryptoModulePasswordKeygen: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16); break; case browser::kCryptoModulePasswordCertEnrollment: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16); break; case browser::kCryptoModulePasswordClientAuth: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16); break; case browser::kCryptoModulePasswordListCerts: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16); break; case browser::kCryptoModulePasswordCertImport: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16); break; case browser::kCryptoModulePasswordCertExport: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16); break; default: NOTREACHED(); } reason_label_ = new views::Label(UTF8ToUTF16(text)); reason_label_->SetMultiLine(true); password_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD)); password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED); password_entry_->SetController(this); views::GridLayout* layout = views::GridLayout::CreatePanel(this); SetLayoutManager(layout); views::ColumnSet* reason_column_set = layout->AddColumnSet(0); reason_column_set->AddColumn( views::GridLayout::LEADING, views::GridLayout::LEADING, 1, views::GridLayout::USE_PREF, 0, 0); views::ColumnSet* column_set = layout->AddColumnSet(1); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn( 0, views::kUnrelatedControlLargeHorizontalSpacing); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); layout->StartRow(0, 0); layout->AddView(reason_label_); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); layout->StartRow(0, 1); layout->AddView(password_label_); layout->AddView(password_entry_); } views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() { return password_entry_; } ui::ModalType CryptoModulePasswordDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } views::View* CryptoModulePasswordDialogView::GetContentsView() { return this; } string16 CryptoModulePasswordDialogView::GetDialogButtonLabel( ui::DialogButton button) const { return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ? IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL : IDS_CANCEL); } bool CryptoModulePasswordDialogView::Accept() { callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str()); const string16 empty; password_entry_->SetText(empty); return true; } bool CryptoModulePasswordDialogView::Cancel() { callback_.Run(static_cast<const char*>(NULL)); const string16 empty; password_entry_->SetText(empty); return true; } bool CryptoModulePasswordDialogView::HandleKeyEvent( views::Textfield* sender, const views::KeyEvent& keystroke) { return false; } void CryptoModulePasswordDialogView::ContentsChanged( views::Textfield* sender, const string16& new_contents) { } string16 CryptoModulePasswordDialogView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE); } void ShowCryptoModulePasswordDialog( const std::string& slot_name, bool retry, CryptoModulePasswordReason reason, const std::string& server, const CryptoModulePasswordCallback& callback) { CryptoModulePasswordDialogView* dialog = new CryptoModulePasswordDialogView(slot_name, reason, server, callback); views::Widget::CreateWindowWithParent(dialog, NULL)->Show(); } } // namespace browser <commit_msg>views: Create crypto dialog with Widget::CreateWindow() function.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/crypto_module_password_dialog_view.h" #include "base/basictypes.h" #include "base/bind.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/views/window.h" #include "googleurl/src/gurl.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/text_button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" int kInputPasswordMinWidth = 8; namespace browser { // CryptoModulePasswordDialogView //////////////////////////////////////////////////////////////////////////////// CryptoModulePasswordDialogView::CryptoModulePasswordDialogView( const std::string& slot_name, browser::CryptoModulePasswordReason reason, const std::string& server, const base::Callback<void(const char*)>& callback) : callback_(callback) { Init(server, slot_name, reason); } CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() { } void CryptoModulePasswordDialogView::Init( const std::string& server, const std::string& slot_name, browser::CryptoModulePasswordReason reason) { // Select an appropriate text for the reason. std::string text; const string16& server16 = UTF8ToUTF16(server); const string16& slot16 = UTF8ToUTF16(slot_name); switch (reason) { case browser::kCryptoModulePasswordKeygen: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16); break; case browser::kCryptoModulePasswordCertEnrollment: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16); break; case browser::kCryptoModulePasswordClientAuth: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16); break; case browser::kCryptoModulePasswordListCerts: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16); break; case browser::kCryptoModulePasswordCertImport: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16); break; case browser::kCryptoModulePasswordCertExport: text = l10n_util::GetStringFUTF8( IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16); break; default: NOTREACHED(); } reason_label_ = new views::Label(UTF8ToUTF16(text)); reason_label_->SetMultiLine(true); password_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD)); password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED); password_entry_->SetController(this); views::GridLayout* layout = views::GridLayout::CreatePanel(this); SetLayoutManager(layout); views::ColumnSet* reason_column_set = layout->AddColumnSet(0); reason_column_set->AddColumn( views::GridLayout::LEADING, views::GridLayout::LEADING, 1, views::GridLayout::USE_PREF, 0, 0); views::ColumnSet* column_set = layout->AddColumnSet(1); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn( 0, views::kUnrelatedControlLargeHorizontalSpacing); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); layout->StartRow(0, 0); layout->AddView(reason_label_); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); layout->StartRow(0, 1); layout->AddView(password_label_); layout->AddView(password_entry_); } views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() { return password_entry_; } ui::ModalType CryptoModulePasswordDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } views::View* CryptoModulePasswordDialogView::GetContentsView() { return this; } string16 CryptoModulePasswordDialogView::GetDialogButtonLabel( ui::DialogButton button) const { return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ? IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL : IDS_CANCEL); } bool CryptoModulePasswordDialogView::Accept() { callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str()); const string16 empty; password_entry_->SetText(empty); return true; } bool CryptoModulePasswordDialogView::Cancel() { callback_.Run(static_cast<const char*>(NULL)); const string16 empty; password_entry_->SetText(empty); return true; } bool CryptoModulePasswordDialogView::HandleKeyEvent( views::Textfield* sender, const views::KeyEvent& keystroke) { return false; } void CryptoModulePasswordDialogView::ContentsChanged( views::Textfield* sender, const string16& new_contents) { } string16 CryptoModulePasswordDialogView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE); } void ShowCryptoModulePasswordDialog( const std::string& slot_name, bool retry, CryptoModulePasswordReason reason, const std::string& server, const CryptoModulePasswordCallback& callback) { CryptoModulePasswordDialogView* dialog = new CryptoModulePasswordDialogView(slot_name, reason, server, callback); views::Widget::CreateWindow(dialog)->Show(); } } // namespace browser <|endoftext|>
<commit_before>//===-- StringExtractor.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "StringExtractor.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes static inline int xdigit_to_sint (char ch) { ch = tolower(ch); if (ch >= 'a' && ch <= 'f') return 10 + ch - 'a'; return ch - '0'; } static inline unsigned int xdigit_to_uint (uint8_t ch) { ch = tolower(ch); if (ch >= 'a' && ch <= 'f') return 10u + ch - 'a'; return ch - '0'; } //---------------------------------------------------------------------- // StringExtractor constructor //---------------------------------------------------------------------- StringExtractor::StringExtractor() : m_packet(), m_index (0) { } StringExtractor::StringExtractor(const char *packet_cstr) : m_packet(), m_index (0) { if (packet_cstr) m_packet.assign (packet_cstr); } //---------------------------------------------------------------------- // StringExtractor copy constructor //---------------------------------------------------------------------- StringExtractor::StringExtractor(const StringExtractor& rhs) : m_packet (rhs.m_packet), m_index (rhs.m_index) { } //---------------------------------------------------------------------- // StringExtractor assignment operator //---------------------------------------------------------------------- const StringExtractor& StringExtractor::operator=(const StringExtractor& rhs) { if (this != &rhs) { m_packet = rhs.m_packet; m_index = rhs.m_index; } return *this; } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- StringExtractor::~StringExtractor() { } char StringExtractor::GetChar (char fail_value) { if (m_index < m_packet.size()) { char ch = m_packet[m_index]; ++m_index; return ch; } m_index = UINT32_MAX; return fail_value; } uint32_t StringExtractor::GetNumHexASCIICharsAtFilePos (uint32_t max) const { uint32_t idx = m_index; const size_t size = m_packet.size(); while (idx < size && idx - m_index < max && isxdigit(m_packet[idx])) ++idx; return idx - m_index; } //---------------------------------------------------------------------- // Extract a signed character from two hex ASCII chars in the packet // string //---------------------------------------------------------------------- int8_t StringExtractor::GetHexS8 (int8_t fail_value) { if (GetNumHexASCIICharsAtFilePos(2)) { char hi_nibble_char = m_packet[m_index]; char lo_nibble_char = m_packet[m_index+1]; if (isxdigit(hi_nibble_char) && isxdigit(lo_nibble_char)) { char hi_nibble = xdigit_to_sint (hi_nibble_char); char lo_nibble = xdigit_to_sint (lo_nibble_char); m_index += 2; return (hi_nibble << 4) + lo_nibble; } } m_index = UINT32_MAX; return fail_value; } //---------------------------------------------------------------------- // Extract an unsigned character from two hex ASCII chars in the packet // string //---------------------------------------------------------------------- uint8_t StringExtractor::GetHexU8 (uint8_t fail_value) { if (GetNumHexASCIICharsAtFilePos(2)) { uint8_t hi_nibble_char = m_packet[m_index]; uint8_t lo_nibble_char = m_packet[m_index+1]; if (isxdigit(hi_nibble_char) && isxdigit(lo_nibble_char)) { uint8_t hi_nibble = xdigit_to_sint (hi_nibble_char); uint8_t lo_nibble = xdigit_to_sint (lo_nibble_char); m_index += 2; return (hi_nibble << 4) + lo_nibble; } } m_index = UINT32_MAX; return fail_value; } uint32_t StringExtractor::GetHexMaxU32 (bool little_endian, uint32_t fail_value) { uint32_t result = 0; uint32_t nibble_count = 0; if (little_endian) { uint32_t shift_amount = 0; while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint32_t... if (nibble_count >= (sizeof(uint32_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble_lo; uint8_t nibble_hi = xdigit_to_sint (m_packet[m_index]); ++m_index; if (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { nibble_lo = xdigit_to_sint (m_packet[m_index]); ++m_index; result |= ((uint32_t)nibble_hi << (shift_amount + 4)); result |= ((uint32_t)nibble_lo << shift_amount); nibble_count += 2; shift_amount += 8; } else { result |= ((uint32_t)nibble_hi << shift_amount); nibble_count += 1; shift_amount += 4; } } } else { while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint32_t... if (nibble_count >= (sizeof(uint32_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble = xdigit_to_sint (m_packet[m_index]); // Big Endian result <<= 4; result |= nibble; ++m_index; ++nibble_count; } } return result; } uint64_t StringExtractor::GetHexMaxU64 (bool little_endian, uint64_t fail_value) { uint64_t result = 0; uint32_t nibble_count = 0; if (little_endian) { uint32_t shift_amount = 0; while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint64_t... if (nibble_count >= (sizeof(uint64_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble_lo; uint8_t nibble_hi = xdigit_to_sint (m_packet[m_index]); ++m_index; if (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { nibble_lo = xdigit_to_sint (m_packet[m_index]); ++m_index; result |= ((uint64_t)nibble_hi << (shift_amount + 4)); result |= ((uint64_t)nibble_lo << shift_amount); nibble_count += 2; shift_amount += 8; } else { result |= ((uint64_t)nibble_hi << shift_amount); nibble_count += 1; shift_amount += 4; } } } else { while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint64_t... if (nibble_count >= (sizeof(uint64_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble = xdigit_to_sint (m_packet[m_index]); // Big Endian result <<= 4; result |= nibble; ++m_index; ++nibble_count; } } return result; } size_t StringExtractor::GetHexBytes (void *dst_void, size_t dst_len, uint8_t fail_fill_value) { uint8_t *dst = (uint8_t*)dst_void; size_t bytes_extracted = 0; while (bytes_extracted < dst_len && GetBytesLeft ()) { dst[bytes_extracted] = GetHexU8 (fail_fill_value); if (IsGood()) ++bytes_extracted; else break; } for (size_t i = bytes_extracted; i < dst_len; ++i) dst[i] = fail_fill_value; return bytes_extracted; } // Consume ASCII hex nibble character pairs until we have decoded byte_size // bytes of data. uint64_t StringExtractor::GetHexWithFixedSize (uint32_t byte_size, bool little_endian, uint64_t fail_value) { if (byte_size <= 8 && GetBytesLeft() >= byte_size * 2) { uint64_t result = 0; uint32_t i; if (little_endian) { // Little Endian uint32_t shift_amount; for (i = 0, shift_amount = 0; i < byte_size && m_index != UINT32_MAX; ++i, shift_amount += 8) { result |= ((uint64_t)GetHexU8() << shift_amount); } } else { // Big Endian for (i = 0; i < byte_size && m_index != UINT32_MAX; ++i) { result <<= 8; result |= GetHexU8(); } } } m_index = UINT32_MAX; return fail_value; } bool StringExtractor::GetNameColonValue (std::string &name, std::string &value) { // Read something in the form of NNNN:VVVV; where NNNN is any character // that is not a colon, followed by a ':' character, then a value (one or // more ';' chars), followed by a ';' if (m_index < m_packet.size()) { const size_t colon_idx = m_packet.find (':', m_index); if (colon_idx != std::string::npos) { const size_t semicolon_idx = m_packet.find (';', colon_idx); if (semicolon_idx != std::string::npos) { name.assign (m_packet, m_index, colon_idx - m_index); value.assign (m_packet, colon_idx + 1, semicolon_idx - (colon_idx + 1)); m_index = semicolon_idx + 1; return true; } } } m_index = UINT32_MAX; return false; } <commit_msg>Avoid tolower, it's slow and unnecessary.<commit_after>//===-- StringExtractor.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "StringExtractor.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes static inline int xdigit_to_sint (char ch) { if (ch >= 'a' && ch <= 'f') return 10 + ch - 'a'; if (ch >= 'A' && ch <= 'F') return 10 + ch - 'A'; return ch - '0'; } static inline unsigned int xdigit_to_uint (uint8_t ch) { if (ch >= 'a' && ch <= 'f') return 10u + ch - 'a'; if (ch >= 'A' && ch <= 'F') return 10u + ch - 'A'; return ch - '0'; } //---------------------------------------------------------------------- // StringExtractor constructor //---------------------------------------------------------------------- StringExtractor::StringExtractor() : m_packet(), m_index (0) { } StringExtractor::StringExtractor(const char *packet_cstr) : m_packet(), m_index (0) { if (packet_cstr) m_packet.assign (packet_cstr); } //---------------------------------------------------------------------- // StringExtractor copy constructor //---------------------------------------------------------------------- StringExtractor::StringExtractor(const StringExtractor& rhs) : m_packet (rhs.m_packet), m_index (rhs.m_index) { } //---------------------------------------------------------------------- // StringExtractor assignment operator //---------------------------------------------------------------------- const StringExtractor& StringExtractor::operator=(const StringExtractor& rhs) { if (this != &rhs) { m_packet = rhs.m_packet; m_index = rhs.m_index; } return *this; } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- StringExtractor::~StringExtractor() { } char StringExtractor::GetChar (char fail_value) { if (m_index < m_packet.size()) { char ch = m_packet[m_index]; ++m_index; return ch; } m_index = UINT32_MAX; return fail_value; } uint32_t StringExtractor::GetNumHexASCIICharsAtFilePos (uint32_t max) const { uint32_t idx = m_index; const size_t size = m_packet.size(); while (idx < size && idx - m_index < max && isxdigit(m_packet[idx])) ++idx; return idx - m_index; } //---------------------------------------------------------------------- // Extract a signed character from two hex ASCII chars in the packet // string //---------------------------------------------------------------------- int8_t StringExtractor::GetHexS8 (int8_t fail_value) { if (GetNumHexASCIICharsAtFilePos(2)) { char hi_nibble_char = m_packet[m_index]; char lo_nibble_char = m_packet[m_index+1]; if (isxdigit(hi_nibble_char) && isxdigit(lo_nibble_char)) { char hi_nibble = xdigit_to_sint (hi_nibble_char); char lo_nibble = xdigit_to_sint (lo_nibble_char); m_index += 2; return (hi_nibble << 4) + lo_nibble; } } m_index = UINT32_MAX; return fail_value; } //---------------------------------------------------------------------- // Extract an unsigned character from two hex ASCII chars in the packet // string //---------------------------------------------------------------------- uint8_t StringExtractor::GetHexU8 (uint8_t fail_value) { if (GetNumHexASCIICharsAtFilePos(2)) { uint8_t hi_nibble_char = m_packet[m_index]; uint8_t lo_nibble_char = m_packet[m_index+1]; if (isxdigit(hi_nibble_char) && isxdigit(lo_nibble_char)) { uint8_t hi_nibble = xdigit_to_sint (hi_nibble_char); uint8_t lo_nibble = xdigit_to_sint (lo_nibble_char); m_index += 2; return (hi_nibble << 4) + lo_nibble; } } m_index = UINT32_MAX; return fail_value; } uint32_t StringExtractor::GetHexMaxU32 (bool little_endian, uint32_t fail_value) { uint32_t result = 0; uint32_t nibble_count = 0; if (little_endian) { uint32_t shift_amount = 0; while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint32_t... if (nibble_count >= (sizeof(uint32_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble_lo; uint8_t nibble_hi = xdigit_to_sint (m_packet[m_index]); ++m_index; if (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { nibble_lo = xdigit_to_sint (m_packet[m_index]); ++m_index; result |= ((uint32_t)nibble_hi << (shift_amount + 4)); result |= ((uint32_t)nibble_lo << shift_amount); nibble_count += 2; shift_amount += 8; } else { result |= ((uint32_t)nibble_hi << shift_amount); nibble_count += 1; shift_amount += 4; } } } else { while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint32_t... if (nibble_count >= (sizeof(uint32_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble = xdigit_to_sint (m_packet[m_index]); // Big Endian result <<= 4; result |= nibble; ++m_index; ++nibble_count; } } return result; } uint64_t StringExtractor::GetHexMaxU64 (bool little_endian, uint64_t fail_value) { uint64_t result = 0; uint32_t nibble_count = 0; if (little_endian) { uint32_t shift_amount = 0; while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint64_t... if (nibble_count >= (sizeof(uint64_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble_lo; uint8_t nibble_hi = xdigit_to_sint (m_packet[m_index]); ++m_index; if (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { nibble_lo = xdigit_to_sint (m_packet[m_index]); ++m_index; result |= ((uint64_t)nibble_hi << (shift_amount + 4)); result |= ((uint64_t)nibble_lo << shift_amount); nibble_count += 2; shift_amount += 8; } else { result |= ((uint64_t)nibble_hi << shift_amount); nibble_count += 1; shift_amount += 4; } } } else { while (m_index < m_packet.size() && ::isxdigit (m_packet[m_index])) { // Make sure we don't exceed the size of a uint64_t... if (nibble_count >= (sizeof(uint64_t) * 2)) { m_index = UINT32_MAX; return fail_value; } uint8_t nibble = xdigit_to_sint (m_packet[m_index]); // Big Endian result <<= 4; result |= nibble; ++m_index; ++nibble_count; } } return result; } size_t StringExtractor::GetHexBytes (void *dst_void, size_t dst_len, uint8_t fail_fill_value) { uint8_t *dst = (uint8_t*)dst_void; size_t bytes_extracted = 0; while (bytes_extracted < dst_len && GetBytesLeft ()) { dst[bytes_extracted] = GetHexU8 (fail_fill_value); if (IsGood()) ++bytes_extracted; else break; } for (size_t i = bytes_extracted; i < dst_len; ++i) dst[i] = fail_fill_value; return bytes_extracted; } // Consume ASCII hex nibble character pairs until we have decoded byte_size // bytes of data. uint64_t StringExtractor::GetHexWithFixedSize (uint32_t byte_size, bool little_endian, uint64_t fail_value) { if (byte_size <= 8 && GetBytesLeft() >= byte_size * 2) { uint64_t result = 0; uint32_t i; if (little_endian) { // Little Endian uint32_t shift_amount; for (i = 0, shift_amount = 0; i < byte_size && m_index != UINT32_MAX; ++i, shift_amount += 8) { result |= ((uint64_t)GetHexU8() << shift_amount); } } else { // Big Endian for (i = 0; i < byte_size && m_index != UINT32_MAX; ++i) { result <<= 8; result |= GetHexU8(); } } } m_index = UINT32_MAX; return fail_value; } bool StringExtractor::GetNameColonValue (std::string &name, std::string &value) { // Read something in the form of NNNN:VVVV; where NNNN is any character // that is not a colon, followed by a ':' character, then a value (one or // more ';' chars), followed by a ';' if (m_index < m_packet.size()) { const size_t colon_idx = m_packet.find (':', m_index); if (colon_idx != std::string::npos) { const size_t semicolon_idx = m_packet.find (';', colon_idx); if (semicolon_idx != std::string::npos) { name.assign (m_packet, m_index, colon_idx - m_index); value.assign (m_packet, colon_idx + 1, semicolon_idx - (colon_idx + 1)); m_index = semicolon_idx + 1; return true; } } } m_index = UINT32_MAX; return false; } <|endoftext|>
<commit_before>// MFEM Example 33 // // Compile with: make ex33p // // Sample runs: mpirun -np 4 ex33p -m ../data/square-disc.mesh -alpha 0.33 -o 2 // mpirun -np 4 ex33p -m ../data/star.mesh -alpha 0.99 -o 3 // mpirun -np 4 ex33p -m ../data/inline-quad.mesh -alpha 0.2 -o 3 // mpirun -np 4 ex33p -m ../data/disc-nurbs.mesh -alpha 0.33 -o 3 // mpirun -np 4 ex33p -m ../data/l-shape.mesh -alpha 0.33 -o 3 -r 4 // // // Description: // // In this example we solve the following fractional PDE with MFEM: // // ( - Δ )^α u = f in Ω, u = 0 on ∂Ω, 0 < α < 1, // // To solve this FPDE, we rely on a rational approximation [2] of the normal // linear operator A^{-α}, where A = - Δ (with associated homogenous // boundary conditions). Namely, we first approximate the operator // // A^{-α} ≈ Σ_{i=0}^N c_i (A + d_i I)^{-1}, d_0 = 0, d_i > 0, // // where I is the L2-identity operator and the coefficients c_i and d_i // are generated offline to a prescribed accuracy in a pre-processing step. // We use the triple-A algorithm [1] to generate the rational approximation // that this partial fractional expansion derives from. We then solve N+1 // independent integer-order PDEs, // // A u_i + d_i u_i = c_i f in Ω, u_i = 0 on ∂Ω, i=0,...,N, // // using MFEM and sum u_i to arrive at an approximate solution of the FPDE // // u ≈ Σ_{i=0}^N u_i. // // // References: // // [1] Nakatsukasa, Y., Sète, O., & Trefethen, L. N. (2018). The AAA algorithm // for rational approximation. SIAM Journal on Scientific Computing, 40(3), // A1494-A1522. // // [2] Harizanov, S., Lazarov, R., Margenov, S., Marinov, P., & Pasciak, J. // (2020). Analysis of numerical methods for spectral fractional elliptic // equations based on the best uniform rational approximation. Journal of // Computational Physics, 408, 109285. // #include "mfem.hpp" #include <fstream> #include <iostream> #include "ex33.hpp" using namespace std; using namespace mfem; int main(int argc, char *argv[]) { // 0. Initialize MPI. MPI_Session mpi; int num_procs = mpi.WorldSize(); int myid = mpi.WorldRank(); // 1. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; int num_refs = 3; bool visualization = true; double alpha = 0.5; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree) or -1 for" " isoparametric space."); args.AddOption(&num_refs, "-r", "--refs", "Number of uniform refinements"); args.AddOption(&alpha, "-alpha", "--alpha", "Fractional exponent"); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } if (myid == 0) { args.PrintOptions(cout); } Array<double> coeffs, poles; // 2. Compute the coefficients that define the integer-order PDEs. ComputePartialFractionApproximation(alpha,coeffs,poles); // 3. Read the mesh from the given mesh file. Mesh mesh(mesh_file, 1, 1); int dim = mesh.Dimension(); // 4. Refine the mesh to increase the resolution. for (int i = 0; i < num_refs; i++) { mesh.UniformRefinement(); } ParMesh pmesh(MPI_COMM_WORLD, mesh); mesh.Clear(); // 5. Define a finite element space on the mesh. FiniteElementCollection *fec = new H1_FECollection(order, dim); ParFiniteElementSpace fespace(&pmesh, fec); if (myid == 0) { cout << "Number of finite element unknowns: " << fespace.GetTrueVSize() << endl; } // 6. Determine the list of true (i.e. conforming) essential boundary dofs. Array<int> ess_tdof_list; if (pmesh.bdr_attributes.Size()) { Array<int> ess_bdr(pmesh.bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } // 7. Define diffusion coefficient, load, and solution GridFunction. ConstantCoefficient f(1.0); ConstantCoefficient one(1.0); ParGridFunction u(&fespace); u = 0.; // 8. Prepare for visualization. char vishost[] = "localhost"; int visport = 19916; socketstream xout; socketstream uout; if (visualization) { xout.open(vishost, visport); xout.precision(8); uout.open(vishost, visport); uout.precision(8); } for (int i = 0; i<coeffs.Size(); i++) { // 9. Set up the linear form b(.) for integer-order PDE solve. ParLinearForm b(&fespace); ProductCoefficient cf(coeffs[i], f); b.AddDomainIntegrator(new DomainLFIntegrator(cf)); b.Assemble(); // 10. Define GridFunction for integer-order PDE solve. ParGridFunction x(&fespace); x = 0.0; // 11. Set up the bilinear form a(.,.) for integer-order PDE solve. ParBilinearForm a(&fespace); a.AddDomainIntegrator(new DiffusionIntegrator(one)); ConstantCoefficient c2(-poles[i]); a.AddDomainIntegrator(new MassIntegrator(c2)); a.Assemble(); // 12. Assemble the bilinear form and the corresponding linear system. OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); // 13. Solve the linear system A X = B. Solver *M = new OperatorJacobiSmoother(a, ess_tdof_list);; CGSolver cg(MPI_COMM_WORLD); cg.SetRelTol(1e-12); cg.SetMaxIter(2000); cg.SetPrintLevel(3); cg.SetPreconditioner(*M); cg.SetOperator(*A); cg.Mult(B, X); delete M; // 14. Recover the solution as a finite element grid function. a.RecoverFEMSolution(X, b, x); // 15. Accumulate integer-order PDE solutions. u+=x; // 16. Send the solutions by socket to a GLVis server. if (visualization) { xout << "parallel " << num_procs << " " << myid << "\n"; xout << "solution\n" << pmesh << x << flush; uout << "parallel " << num_procs << " " << myid << "\n"; uout << "solution\n" << pmesh << u << flush; } } delete fec; return 0; } <commit_msg>using amg prec in ex33p<commit_after>// MFEM Example 33 // // Compile with: make ex33p // // Sample runs: mpirun -np 4 ex33p -m ../data/square-disc.mesh -alpha 0.33 -o 2 // mpirun -np 4 ex33p -m ../data/star.mesh -alpha 0.99 -o 3 // mpirun -np 4 ex33p -m ../data/inline-quad.mesh -alpha 0.2 -o 3 // mpirun -np 4 ex33p -m ../data/disc-nurbs.mesh -alpha 0.33 -o 3 // mpirun -np 4 ex33p -m ../data/l-shape.mesh -alpha 0.33 -o 3 -r 4 // // // Description: // // In this example we solve the following fractional PDE with MFEM: // // ( - Δ )^α u = f in Ω, u = 0 on ∂Ω, 0 < α < 1, // // To solve this FPDE, we rely on a rational approximation [2] of the normal // linear operator A^{-α}, where A = - Δ (with associated homogenous // boundary conditions). Namely, we first approximate the operator // // A^{-α} ≈ Σ_{i=0}^N c_i (A + d_i I)^{-1}, d_0 = 0, d_i > 0, // // where I is the L2-identity operator and the coefficients c_i and d_i // are generated offline to a prescribed accuracy in a pre-processing step. // We use the triple-A algorithm [1] to generate the rational approximation // that this partial fractional expansion derives from. We then solve N+1 // independent integer-order PDEs, // // A u_i + d_i u_i = c_i f in Ω, u_i = 0 on ∂Ω, i=0,...,N, // // using MFEM and sum u_i to arrive at an approximate solution of the FPDE // // u ≈ Σ_{i=0}^N u_i. // // // References: // // [1] Nakatsukasa, Y., Sète, O., & Trefethen, L. N. (2018). The AAA algorithm // for rational approximation. SIAM Journal on Scientific Computing, 40(3), // A1494-A1522. // // [2] Harizanov, S., Lazarov, R., Margenov, S., Marinov, P., & Pasciak, J. // (2020). Analysis of numerical methods for spectral fractional elliptic // equations based on the best uniform rational approximation. Journal of // Computational Physics, 408, 109285. // #include "mfem.hpp" #include <fstream> #include <iostream> #include "ex33.hpp" using namespace std; using namespace mfem; int main(int argc, char *argv[]) { // 0. Initialize MPI. MPI_Session mpi; int num_procs = mpi.WorldSize(); int myid = mpi.WorldRank(); // 1. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; int num_refs = 3; bool visualization = true; double alpha = 0.5; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree) or -1 for" " isoparametric space."); args.AddOption(&num_refs, "-r", "--refs", "Number of uniform refinements"); args.AddOption(&alpha, "-alpha", "--alpha", "Fractional exponent"); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } if (myid == 0) { args.PrintOptions(cout); } Array<double> coeffs, poles; // 2. Compute the coefficients that define the integer-order PDEs. ComputePartialFractionApproximation(alpha,coeffs,poles); // 3. Read the mesh from the given mesh file. Mesh mesh(mesh_file, 1, 1); int dim = mesh.Dimension(); // 4. Refine the mesh to increase the resolution. for (int i = 0; i < num_refs; i++) { mesh.UniformRefinement(); } ParMesh pmesh(MPI_COMM_WORLD, mesh); mesh.Clear(); // 5. Define a finite element space on the mesh. FiniteElementCollection *fec = new H1_FECollection(order, dim); ParFiniteElementSpace fespace(&pmesh, fec); if (myid == 0) { cout << "Number of finite element unknowns: " << fespace.GetTrueVSize() << endl; } // 6. Determine the list of true (i.e. conforming) essential boundary dofs. Array<int> ess_tdof_list; if (pmesh.bdr_attributes.Size()) { Array<int> ess_bdr(pmesh.bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } // 7. Define diffusion coefficient, load, and solution GridFunction. ConstantCoefficient f(1.0); ConstantCoefficient one(1.0); ParGridFunction u(&fespace); u = 0.; // 8. Prepare for visualization. char vishost[] = "localhost"; int visport = 19916; socketstream xout; socketstream uout; if (visualization) { xout.open(vishost, visport); xout.precision(8); uout.open(vishost, visport); uout.precision(8); } for (int i = 0; i<coeffs.Size(); i++) { // 9. Set up the linear form b(.) for integer-order PDE solve. ParLinearForm b(&fespace); ProductCoefficient cf(coeffs[i], f); b.AddDomainIntegrator(new DomainLFIntegrator(cf)); b.Assemble(); // 10. Define GridFunction for integer-order PDE solve. ParGridFunction x(&fespace); x = 0.0; // 11. Set up the bilinear form a(.,.) for integer-order PDE solve. ParBilinearForm a(&fespace); a.AddDomainIntegrator(new DiffusionIntegrator(one)); ConstantCoefficient c2(-poles[i]); a.AddDomainIntegrator(new MassIntegrator(c2)); a.Assemble(); // 12. Assemble the bilinear form and the corresponding linear system. OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); // 13. Solve the linear system A X = B. HypreBoomerAMG * prec = new HypreBoomerAMG; prec->SetPrintLevel(-1); CGSolver cg(MPI_COMM_WORLD); cg.SetRelTol(1e-12); cg.SetMaxIter(2000); cg.SetPrintLevel(3); cg.SetPreconditioner(*prec); cg.SetOperator(*A); cg.Mult(B, X); delete prec; // 14. Recover the solution as a finite element grid function. a.RecoverFEMSolution(X, b, x); // 15. Accumulate integer-order PDE solutions. u+=x; // 16. Send the solutions by socket to a GLVis server. if (visualization) { xout << "parallel " << num_procs << " " << myid << "\n"; xout << "solution\n" << pmesh << x << flush; uout << "parallel " << num_procs << " " << myid << "\n"; uout << "solution\n" << pmesh << u << flush; } } delete fec; return 0; } <|endoftext|>
<commit_before>// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include <cassert> #include <vector> #include <set> #include <fstream> #include <sstream> #include "llvm/IR/DataLayout.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/Type.h" #include "llvm/IR/TypeBuilder.h" #if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5) #include "llvm/IR/InstIterator.h" #else #include "llvm/Support/InstIterator.h" #endif #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Support/CommandLine.h" using namespace llvm; static cl::opt<std::string> source_name("rename-verifier-funs-source", cl::desc("Specify source filename"), cl::value_desc("filename")); class RenameVerifierFuns : public ModulePass { // every item is (line number, call) std::vector<std::pair<unsigned, CallInst *>> calls_to_replace; std::set<unsigned> lines_nums; std::map<unsigned, std::string> lines; void handleCall(Function& F, CallInst *CI); void mapLines(); void replaceCalls(Module& M); public: static char ID; RenameVerifierFuns() : ModulePass(ID) {} bool runOnFunction(Function &F); // must be module pass, so that we can iterate over // declarations too virtual bool runOnModule(Module &M) { for (auto& F : M) runOnFunction(F); mapLines(); replaceCalls(M); return !calls_to_replace.empty(); } }; bool RenameVerifierFuns::runOnFunction(Function &F) { if (!F.isDeclaration()) return false; StringRef name = F.getName(); if (!name.startswith("__VERIFIER_nondet_")) return false; bool changed = false; //llvm::errs() << "Got __VERIFIER_fun: " << name << "\n"; for (auto I = F.use_begin(), E = F.use_end(); I != E; ++I) { #if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 5)) Value *use = *I; #else Value *use = I->getUser(); #endif if (CallInst *CI = dyn_cast<CallInst>(use)) { handleCall(F, CI); } } return changed; } void RenameVerifierFuns::handleCall(Function& F, CallInst *CI) { const DebugLoc& Loc = CI->getDebugLoc(); if (Loc) { calls_to_replace.emplace_back(Loc.getLine(), CI); lines_nums.insert(Loc.getLine()); } } void RenameVerifierFuns::mapLines() { if (lines_nums.empty()) { assert(calls_to_replace.empty()); return; } std::ifstream file(source_name); if (file.is_open()) { unsigned n = 1; std::string line; while (getline(file,line)) { if (lines_nums.count(n) > 0) lines[n] = std::move(line); ++n; } file.close(); } else { errs() << "Couldn't open file: " << source_name << "\n"; abort(); } assert(lines.size() == lines_nums.size()); } static void replaceCall(Module& M, CallInst *CI, unsigned line, const std::string& var) { std::string parent_name = cast<Function>(CI->getCalledValue()->stripPointerCasts())->getName(); std::string name = parent_name + ":" + var + ":" + std::to_string(line); Function *called_func = CI->getCalledFunction(); Constant *new_func = M.getOrInsertFunction(called_func->getName().str() + "_named", called_func->getAttributes(), called_func->getReturnType(), Type::getInt8PtrTy(M.getContext()), nullptr); assert(new_func); std::vector<Value *> args; Constant *name_const = ConstantDataArray::getString(M.getContext(), name); GlobalVariable *nameG = new GlobalVariable(M, name_const->getType(), true /*constant */, GlobalVariable::PrivateLinkage, name_const); args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(M.getContext()))); CallInst *new_CI = CallInst::Create(new_func, args); SmallVector<std::pair<unsigned, MDNode *>, 8> metadata; CI->getAllMetadata(metadata); // copy the metadata for (auto& md : metadata) new_CI->setMetadata(md.first, md.second); // copy the attributes (like zeroext etc.) new_CI->setAttributes(CI->getAttributes()); new_CI->insertBefore(CI); CI->replaceAllUsesWith(new_CI); CI->eraseFromParent(); } static std::string getName(const std::string& line) { std::istringstream iss(line); std::string sub, var; while (iss >> sub) { if (sub == "=") { break; } var = std::move(sub); } if (!var.empty() && sub == "=") { // check also that after = follows the __VERIFIER_* call iss >> sub; // this may make problems with casting, line: (int) __VERIFIER_nondet_char() // maybe this is not needed? if (sub.compare(0, 18, "__VERIFIER_nondet_") == 0) return var; } return "--"; } void RenameVerifierFuns::replaceCalls(Module& M) { for (auto& pr : calls_to_replace) { unsigned line_num = pr.first; CallInst *CI = pr.second; std::string line = lines[line_num]; assert(!line.empty()); replaceCall(M, CI, line_num, getName(line)); } } static RegisterPass<RenameVerifierFuns> RVF("rename-verifier-funs", "Replace calls to verifier funs with calls to our funs"); char RenameVerifierFuns::ID; <commit_msg>Fix getting parent function name<commit_after>// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include <cassert> #include <vector> #include <set> #include <fstream> #include <sstream> #include "llvm/IR/DataLayout.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/Type.h" #include "llvm/IR/TypeBuilder.h" #if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5) #include "llvm/IR/InstIterator.h" #else #include "llvm/Support/InstIterator.h" #endif #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Support/CommandLine.h" using namespace llvm; static cl::opt<std::string> source_name("rename-verifier-funs-source", cl::desc("Specify source filename"), cl::value_desc("filename")); class RenameVerifierFuns : public ModulePass { // every item is (line number, call) std::vector<std::pair<unsigned, CallInst *>> calls_to_replace; std::set<unsigned> lines_nums; std::map<unsigned, std::string> lines; void handleCall(Function& F, CallInst *CI); void mapLines(); void replaceCalls(Module& M); public: static char ID; RenameVerifierFuns() : ModulePass(ID) {} bool runOnFunction(Function &F); // must be module pass, so that we can iterate over // declarations too virtual bool runOnModule(Module &M) { for (auto& F : M) runOnFunction(F); mapLines(); replaceCalls(M); return !calls_to_replace.empty(); } }; bool RenameVerifierFuns::runOnFunction(Function &F) { if (!F.isDeclaration()) return false; StringRef name = F.getName(); if (!name.startswith("__VERIFIER_nondet_")) return false; bool changed = false; //llvm::errs() << "Got __VERIFIER_fun: " << name << "\n"; for (auto I = F.use_begin(), E = F.use_end(); I != E; ++I) { #if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 5)) Value *use = *I; #else Value *use = I->getUser(); #endif if (CallInst *CI = dyn_cast<CallInst>(use)) { handleCall(F, CI); } } return changed; } void RenameVerifierFuns::handleCall(Function& F, CallInst *CI) { const DebugLoc& Loc = CI->getDebugLoc(); if (Loc) { calls_to_replace.emplace_back(Loc.getLine(), CI); lines_nums.insert(Loc.getLine()); } } void RenameVerifierFuns::mapLines() { if (lines_nums.empty()) { assert(calls_to_replace.empty()); return; } std::ifstream file(source_name); if (file.is_open()) { unsigned n = 1; std::string line; while (getline(file,line)) { if (lines_nums.count(n) > 0) lines[n] = std::move(line); ++n; } file.close(); } else { errs() << "Couldn't open file: " << source_name << "\n"; abort(); } assert(lines.size() == lines_nums.size()); } static void replaceCall(Module& M, CallInst *CI, unsigned line, const std::string& var) { std::string parent_name = cast<Function>(CI->getParent()->getParent())->getName(); std::string name = parent_name + ":" + var + ":" + std::to_string(line); Function *called_func = CI->getCalledFunction(); Constant *new_func = M.getOrInsertFunction(called_func->getName().str() + "_named", called_func->getAttributes(), called_func->getReturnType(), Type::getInt8PtrTy(M.getContext()), nullptr); assert(new_func); std::vector<Value *> args; Constant *name_const = ConstantDataArray::getString(M.getContext(), name); GlobalVariable *nameG = new GlobalVariable(M, name_const->getType(), true /*constant */, GlobalVariable::PrivateLinkage, name_const); args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(M.getContext()))); CallInst *new_CI = CallInst::Create(new_func, args); SmallVector<std::pair<unsigned, MDNode *>, 8> metadata; CI->getAllMetadata(metadata); // copy the metadata for (auto& md : metadata) new_CI->setMetadata(md.first, md.second); // copy the attributes (like zeroext etc.) new_CI->setAttributes(CI->getAttributes()); new_CI->insertBefore(CI); CI->replaceAllUsesWith(new_CI); CI->eraseFromParent(); } static std::string getName(const std::string& line) { std::istringstream iss(line); std::string sub, var; while (iss >> sub) { if (sub == "=") { break; } var = std::move(sub); } if (!var.empty() && sub == "=") { // check also that after = follows the __VERIFIER_* call iss >> sub; // this may make problems with casting, line: (int) __VERIFIER_nondet_char() // maybe this is not needed? if (sub.compare(0, 18, "__VERIFIER_nondet_") == 0) return var; } return "--"; } void RenameVerifierFuns::replaceCalls(Module& M) { for (auto& pr : calls_to_replace) { unsigned line_num = pr.first; CallInst *CI = pr.second; std::string line = lines[line_num]; assert(!line.empty()); replaceCall(M, CI, line_num, getName(line)); } } static RegisterPass<RenameVerifierFuns> RVF("rename-verifier-funs", "Replace calls to verifier funs with calls to our funs"); char RenameVerifierFuns::ID; <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: $Source: /usr/sci/projects/Nektar/cvs/Nektar++/libs/SpatialDomains/SpatialDomains.hpp,v $ // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: // // //////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_SPATIALDOMAINS_SPATIALDOMAINS_H #define NEKTAR_SPATIALDOMAINS_SPATIALDOMAINS_H #include <StdRegions/StdRegions.hpp> #include <LibUtilities/Memory/NekMemoryManager.hpp> #include <LibUtilities/BasicUtils/ErrorUtil.hpp> #include <LibUtilities/Graph.h> namespace Nektar { namespace SpatialDomains { const double kGeomRightAngleTol = 1e-14; enum GeomState { eNotFilled, ePtsFilled }; enum MeshParams { eFieldExpansionOrder, eElementWork, // Don't change below here SIZE_MeshParams }; }; // end of namespace }; // end of namespace #endif //NEKTAR_SPATIALDOMAINS_SPATIALDOMAINS_H // // $Log: SpatialDomains.hpp,v $ // Revision 1.1 2006/05/04 18:59:04 kirby // *** empty log message *** // // Revision 1.4 2006/03/25 00:58:29 jfrazier // Many changes dealing with fundamental structure and reading/writing. // // Revision 1.3 2006/03/13 11:17:03 sherwin // // First compiing version of Demos in SpatialDomains and LocalRegions. However they do not currently seem to execute properly // // Revision 1.2 2006/03/12 14:20:44 sherwin // // First compiling version of SpatialDomains and associated modifications // // Revision 1.1 2006/03/12 11:06:40 sherwin // // First complete copy of code standard code but still not compile tested // // Revision 1.7 2006/03/04 20:26:05 bnelson // Added comments after #endif. // // Revision 1.6 2006/02/19 01:37:34 jfrazier // Initial attempt at bringing into conformance with the coding standard. Still more work to be done. Has not been compiled. // // <commit_msg>*** empty log message ***<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: $Source: /usr/sci/projects/Nektar/cvs/Nektar++/libs/SpatialDomains/SpatialDomains.hpp,v $ // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: // // //////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_SPATIALDOMAINS_SPATIALDOMAINS_H #define NEKTAR_SPATIALDOMAINS_SPATIALDOMAINS_H #include <StdRegions/StdRegions.hpp> #include <LibUtilities/Memory/NekMemoryManager.hpp> #include <LibUtilities/BasicUtils/ErrorUtil.hpp> #include <LibUtilities/Foundations/Graph.h> namespace Nektar { namespace SpatialDomains { const double kGeomRightAngleTol = 1e-14; enum GeomState { eNotFilled, ePtsFilled }; enum MeshParams { eFieldExpansionOrder, eElementWork, // Don't change below here SIZE_MeshParams }; }; // end of namespace }; // end of namespace #endif //NEKTAR_SPATIALDOMAINS_SPATIALDOMAINS_H // // $Log: SpatialDomains.hpp,v $ // Revision 1.2 2006/06/01 13:42:26 kirby // *** empty log message *** // // Revision 1.1 2006/05/04 18:59:04 kirby // *** empty log message *** // // Revision 1.4 2006/03/25 00:58:29 jfrazier // Many changes dealing with fundamental structure and reading/writing. // // Revision 1.3 2006/03/13 11:17:03 sherwin // // First compiing version of Demos in SpatialDomains and LocalRegions. However they do not currently seem to execute properly // // Revision 1.2 2006/03/12 14:20:44 sherwin // // First compiling version of SpatialDomains and associated modifications // // Revision 1.1 2006/03/12 11:06:40 sherwin // // First complete copy of code standard code but still not compile tested // // Revision 1.7 2006/03/04 20:26:05 bnelson // Added comments after #endif. // // Revision 1.6 2006/02/19 01:37:34 jfrazier // Initial attempt at bringing into conformance with the coding standard. Still more work to be done. Has not been compiled. // // <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <list> // explicit list(size_type n); #include <list> #include <cassert> #include "../../../DefaultOnly.h" #include "../../../stack_allocator.h" #include "../../../min_allocator.h" template <class T, class Allocator> void test3(unsigned n, Allocator const &alloc = Allocator()) { #if _LIBCPP_STD_VER > 11 typedef std::list<T, Allocator> C; typedef typename C::const_iterator const_iterator; { C d(n, alloc); assert(d.size() == n); assert(std::distance(d.begin(), d.end()) == n); assert(d.get_allocator() == alloc); } #endif } int main() { { std::list<int> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } { std::list<int, stack_allocator<int, 3> > l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } #if _LIBCPP_STD_VER > 11 { typedef std::list<int, min_allocator<int> > C; C l(3, min_allocator<int> ()); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); C::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); test3<int, min_allocator<int>> (3); } #endif #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { std::list<DefaultOnly> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #if __cplusplus >= 201103L { std::list<int, min_allocator<int>> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int, min_allocator<int>>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { std::list<DefaultOnly, min_allocator<DefaultOnly>> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #endif } <commit_msg>Remove a tab that snuck in<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <list> // explicit list(size_type n); #include <list> #include <cassert> #include "../../../DefaultOnly.h" #include "../../../stack_allocator.h" #include "../../../min_allocator.h" template <class T, class Allocator> void test3(unsigned n, Allocator const &alloc = Allocator()) { #if _LIBCPP_STD_VER > 11 typedef std::list<T, Allocator> C; typedef typename C::const_iterator const_iterator; { C d(n, alloc); assert(d.size() == n); assert(std::distance(d.begin(), d.end()) == n); assert(d.get_allocator() == alloc); } #endif } int main() { { std::list<int> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } { std::list<int, stack_allocator<int, 3> > l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } #if _LIBCPP_STD_VER > 11 { typedef std::list<int, min_allocator<int> > C; C l(3, min_allocator<int> ()); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); C::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); test3<int, min_allocator<int>> (3); } #endif #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { std::list<DefaultOnly> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #if __cplusplus >= 201103L { std::list<int, min_allocator<int>> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int, min_allocator<int>>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { std::list<DefaultOnly, min_allocator<DefaultOnly>> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #endif } <|endoftext|>
<commit_before>#include "cursor.h" #include "page.h" #include "../bloom_filter.h" #include <algorithm> using namespace dariadb; using namespace dariadb::storage; Cursor::Cursor(Page*page, const dariadb::IdArray&ids, dariadb::Time from, dariadb::Time to, dariadb::Flag flag) : link(page), _ids(ids), _from(from), _to(to), _flag(flag) { reset_pos(); } void Cursor::reset_pos() { _is_end = false; _index_end = link->index + link->header->pos_index; _index_it = link->index; } Cursor::~Cursor() { if (link != nullptr) { link->dec_reader(); link = nullptr; } } bool Cursor::is_end()const { return _is_end; } Chunk_Ptr Cursor::readNext() { for (; !_is_end; _index_it++) { if (_index_it == _index_end) { _is_end = true; return nullptr; } if ((_ids.size() != 0) && (std::find(_ids.begin(), _ids.end(), _index_it->info.first.id) == _ids.end())) { continue; } if (!dariadb::bloom_check(_index_it->info.flag_bloom, _flag)) { continue; } if ((dariadb::utils::inInterval(_from, _to, _index_it->info.minTime)) || (dariadb::utils::inInterval(_from, _to, _index_it->info.maxTime))) { Chunk_Ptr c = std::make_shared<Chunk>(_index_it->info, link->chunks + _index_it->offset, link->header->chunk_size); _index_it++; return c; } } return nullptr; } ChuncksList Cursor::readAll() { ChuncksList result; while (!_is_end) { auto c = readNext(); if (c != nullptr) { result.push_back(c); } } return result; }<commit_msg>strange git client.<commit_after>#include "cursor.h" #include "page.h" #include "../bloom_filter.h" #include <algorithm> using namespace dariadb; using namespace dariadb::storage; class Cursor_ListAppend_callback:public Cursor::Callback{ public: ChuncksList*_out; Cursor_ListAppend_callback(ChuncksList*out){ _out=out; } void call(Chunk_Ptr &ptr) override{ _out->push_back(ptr); } }; Cursor::Cursor(Page*page, const dariadb::IdArray&ids, dariadb::Time from, dariadb::Time to, dariadb::Flag flag) : link(page), _ids(ids), _from(from), _to(to), _flag(flag) { reset_pos(); } void Cursor::reset_pos() { _is_end = false; _index_end = link->index + link->header->pos_index; _index_it = link->index; } Cursor::~Cursor() { if (link != nullptr) { link->dec_reader(); link = nullptr; } } bool Cursor::is_end()const { return _is_end; } void Cursor::readNext( Cursor::Callback*cbk) { for (; !_is_end; _index_it++) { if (_index_it == _index_end) { _is_end = true; break; } if ((_ids.size() != 0) && (std::find(_ids.begin(), _ids.end(), _index_it->info.first.id) == _ids.end())) { continue; } if (!dariadb::bloom_check(_index_it->info.flag_bloom, _flag)) { continue; } if ((dariadb::utils::inInterval(_from, _to, _index_it->info.minTime)) || (dariadb::utils::inInterval(_from, _to, _index_it->info.maxTime))) { Chunk_Ptr c = std::make_shared<Chunk>(_index_it->info, link->chunks + _index_it->offset, link->header->chunk_size); cbk->call(c); _index_it++; break; } } } void Cursor::readAll(ChuncksList*output){ std::unique_ptr<Cursor_ListAppend_callback> clbk{new Cursor_ListAppend_callback{output}}; readAll(clbk.get()); } void Cursor::readAll(Callback*cbk) { while (!_is_end) { readNext(cbk); } } <|endoftext|>
<commit_before>#include "ExecutionEngine.h" #include <array> #include <mutex> #include <iostream> #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Host.h> #include <llvm/Support/CommandLine.h> #include "preprocessor/llvm_includes_end.h" #include "Runtime.h" #include "Compiler.h" #include "Optimizer.h" #include "Cache.h" #include "ExecStats.h" #include "Utils.h" #include "BuildInfo.gen.h" namespace dev { namespace eth { namespace jit { namespace { using EntryFuncPtr = ReturnCode(*)(Runtime*); std::string codeHash(i256 const& _hash) { static const auto size = sizeof(_hash); static const auto hexChars = "0123456789abcdef"; std::string str; str.resize(size * 2); auto outIt = str.rbegin(); // reverse for BE auto& arr = *(std::array<byte, size>*)&_hash; for (auto b : arr) { *(outIt++) = hexChars[b & 0xf]; *(outIt++) = hexChars[b >> 4]; } return str; } void printVersion() { std::cout << "Ethereum EVM JIT Compiler (http://github.com/ethereum/evmjit):\n" << " EVMJIT version " << EVMJIT_VERSION << "\n" #ifdef NDEBUG << " Optimized build, " EVMJIT_VERSION_FULL "\n" #else << " DEBUG build, " EVMJIT_VERSION_FULL "\n" #endif << " Built " << __DATE__ << " (" << __TIME__ << ")\n" << std::endl; } namespace cl = llvm::cl; cl::opt<bool> g_optimize{"O", cl::desc{"Optimize"}}; cl::opt<bool> g_cache{"cache", cl::desc{"Cache compiled EVM code on disk"}, cl::init(true)}; cl::opt<bool> g_stats{"st", cl::desc{"Statistics"}}; cl::opt<bool> g_dump{"dump", cl::desc{"Dump LLVM IR module"}}; void parseOptions() { cl::AddExtraVersionPrinter(printVersion); cl::ParseEnvironmentOptions("evmjit", "EVMJIT", "Ethereum EVM JIT Compiler"); } } ReturnCode ExecutionEngine::run(RuntimeData* _data, Env* _env) { static std::once_flag flag; std::call_once(flag, parseOptions); std::unique_ptr<ExecStats> listener{new ExecStats}; listener->stateChanged(ExecState::Started); auto objectCache = g_cache ? Cache::getObjectCache(listener.get()) : nullptr; static std::unique_ptr<llvm::ExecutionEngine> ee; if (!ee) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); auto module = std::unique_ptr<llvm::Module>(new llvm::Module({}, llvm::getGlobalContext())); llvm::EngineBuilder builder(module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); builder.setOptLevel(g_optimize ? llvm::CodeGenOpt::Default : llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ee.reset(builder.create()); if (!CHECK(ee)) return ReturnCode::LLVMConfigError; module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module ee->setObjectCache(objectCache); } static StatsCollector statsCollector; auto mainFuncName = codeHash(_data->codeHash); Runtime runtime(_data, _env); // TODO: I don't know why but it must be created before getFunctionAddress() calls auto entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); if (!entryFuncPtr) { auto module = objectCache ? Cache::getObject(mainFuncName) : nullptr; if (!module) { listener->stateChanged(ExecState::Compilation); assert(_data->code || !_data->codeSize); //TODO: Is it good idea to execute empty code? module = Compiler{{}}.compile(_data->code, _data->code + _data->codeSize, mainFuncName); if (g_optimize) { listener->stateChanged(ExecState::Optimization); optimize(*module); } } if (g_dump) module->dump(); ee->addModule(module.get()); module.release(); listener->stateChanged(ExecState::CodeGen); entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); } if (!CHECK(entryFuncPtr)) return ReturnCode::LLVMLinkError; listener->stateChanged(ExecState::Execution); auto returnCode = entryFuncPtr(&runtime); listener->stateChanged(ExecState::Return); if (returnCode == ReturnCode::Return) { returnData = runtime.getReturnData(); // Save reference to return data std::swap(m_memory, runtime.getMemory()); // Take ownership of memory } listener->stateChanged(ExecState::Finished); if (g_stats) statsCollector.stats.push_back(std::move(listener)); return returnCode; } } } } <commit_msg>Destroy LLVM ManagedStatics<commit_after>#include "ExecutionEngine.h" #include <array> #include <mutex> #include <iostream> #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Host.h> #include <llvm/Support/CommandLine.h> #include <llvm/Support/ManagedStatic.h> #include "preprocessor/llvm_includes_end.h" #include "Runtime.h" #include "Compiler.h" #include "Optimizer.h" #include "Cache.h" #include "ExecStats.h" #include "Utils.h" #include "BuildInfo.gen.h" namespace dev { namespace eth { namespace jit { namespace { using EntryFuncPtr = ReturnCode(*)(Runtime*); std::string codeHash(i256 const& _hash) { static const auto size = sizeof(_hash); static const auto hexChars = "0123456789abcdef"; std::string str; str.resize(size * 2); auto outIt = str.rbegin(); // reverse for BE auto& arr = *(std::array<byte, size>*)&_hash; for (auto b : arr) { *(outIt++) = hexChars[b & 0xf]; *(outIt++) = hexChars[b >> 4]; } return str; } void printVersion() { std::cout << "Ethereum EVM JIT Compiler (http://github.com/ethereum/evmjit):\n" << " EVMJIT version " << EVMJIT_VERSION << "\n" #ifdef NDEBUG << " Optimized build, " EVMJIT_VERSION_FULL "\n" #else << " DEBUG build, " EVMJIT_VERSION_FULL "\n" #endif << " Built " << __DATE__ << " (" << __TIME__ << ")\n" << std::endl; } namespace cl = llvm::cl; cl::opt<bool> g_optimize{"O", cl::desc{"Optimize"}}; cl::opt<bool> g_cache{"cache", cl::desc{"Cache compiled EVM code on disk"}, cl::init(true)}; cl::opt<bool> g_stats{"st", cl::desc{"Statistics"}}; cl::opt<bool> g_dump{"dump", cl::desc{"Dump LLVM IR module"}}; void parseOptions() { static llvm::llvm_shutdown_obj shutdownObj{}; cl::AddExtraVersionPrinter(printVersion); cl::ParseEnvironmentOptions("evmjit", "EVMJIT", "Ethereum EVM JIT Compiler"); } } ReturnCode ExecutionEngine::run(RuntimeData* _data, Env* _env) { static std::once_flag flag; std::call_once(flag, parseOptions); std::unique_ptr<ExecStats> listener{new ExecStats}; listener->stateChanged(ExecState::Started); auto objectCache = g_cache ? Cache::getObjectCache(listener.get()) : nullptr; static std::unique_ptr<llvm::ExecutionEngine> ee; if (!ee) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); auto module = std::unique_ptr<llvm::Module>(new llvm::Module({}, llvm::getGlobalContext())); llvm::EngineBuilder builder(module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); builder.setOptLevel(g_optimize ? llvm::CodeGenOpt::Default : llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ee.reset(builder.create()); if (!CHECK(ee)) return ReturnCode::LLVMConfigError; module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module ee->setObjectCache(objectCache); } static StatsCollector statsCollector; auto mainFuncName = codeHash(_data->codeHash); Runtime runtime(_data, _env); // TODO: I don't know why but it must be created before getFunctionAddress() calls auto entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); if (!entryFuncPtr) { auto module = objectCache ? Cache::getObject(mainFuncName) : nullptr; if (!module) { listener->stateChanged(ExecState::Compilation); assert(_data->code || !_data->codeSize); //TODO: Is it good idea to execute empty code? module = Compiler{{}}.compile(_data->code, _data->code + _data->codeSize, mainFuncName); if (g_optimize) { listener->stateChanged(ExecState::Optimization); optimize(*module); } } if (g_dump) module->dump(); ee->addModule(module.get()); module.release(); listener->stateChanged(ExecState::CodeGen); entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); } if (!CHECK(entryFuncPtr)) return ReturnCode::LLVMLinkError; listener->stateChanged(ExecState::Execution); auto returnCode = entryFuncPtr(&runtime); listener->stateChanged(ExecState::Return); if (returnCode == ReturnCode::Return) { returnData = runtime.getReturnData(); // Save reference to return data std::swap(m_memory, runtime.getMemory()); // Take ownership of memory } listener->stateChanged(ExecState::Finished); if (g_stats) statsCollector.stats.push_back(std::move(listener)); return returnCode; } } } } <|endoftext|>
<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * BSD 3-Clause License /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * Code by Cassius Fiorin - [email protected] http://pinballhomemade.blogspot.com.br * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "PinballSlave.h" #include "PinballObject.h" #include "Pinball.h" #include "HardwareSerial.h" #include "Vector.h" #include "Utils.h" #include "Input.h" #include "DefinesMp3.h" #ifdef DOS #include "PinballMaster.h" #endif // DOS #ifdef ARDUINOLIB #include <Wire.h> PinballSlave *m_PinballSlave = NULL; //-----------------------------------------------------------------------// void receiveMessageFromAnotherArduinoSlave(int howMany) //-----------------------------------------------------------------------// { m_PinballSlave->receiveMessageFromAnotherArduino(howMany); } //-----------------------------------------------------------------------// void SetupWire() //-----------------------------------------------------------------------// { Wire.begin(ADDRESS_SLAVE); // join I2C bus using this address Wire.onReceive(receiveMessageFromAnotherArduinoSlave); // register event to handle requests } #endif // ARDUINOLIB /*---------------------------------------------------------------------*/ // C L A S S /*---------------------------------------------------------------------*/ #ifdef ARDUINOLIB /*---------------------------------------------------------------------*/ PinballSlave::PinballSlave() /*---------------------------------------------------------------------*/ { m_PinballSlave = this; SetupWire(); } /*---------------------------------------------------------------------*/ void PinballSlave::Setup(SFEMP3Shield *MP3player, HardwareSerial *serial) /*---------------------------------------------------------------------*/ { m_serial = serial; m_MP3player = MP3player; playSong(MP3_STARTBUTTONPORT); Init(); } #endif #ifdef DOS /*---------------------------------------------------------------------*/ PinballSlave::PinballSlave(const char *szName, HardwareSerial *serial) : Pinball(szName, serial) /*---------------------------------------------------------------------*/ { m_PinballMaster = NULL; m_Status = StatusPinball::initializing; <<<<<<< HEAD #ifdef DEBUGMESSAGES ======= #ifdef DEBUGMESSAGESCREATION >>>>>>> 100661e6dee3b3d54eb7cb80f222eb79a8c56a8b LogMessage("PinballSlave Constructor"); #endif } #endif /*---------------------------------------------------------------------*/ PinballSlave::~PinballSlave() /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGESCREATION LogMessage("PinballSlave Destructor"); #endif } /*---------------------------------------------------------------------*/ bool PinballSlave::Init() /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGES LogMessage("PinballSlave Init"); #endif m_Status = StatusPinball::waitingmessages; return true; } /*---------------------------------------------------------------------*/ bool PinballSlave::Loop(int value) /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGESLOOP LogMessage("PinballSlave::Loop"); #endif return true; } /*---------------------------------------------------------------------*/ void PinballSlave::DataReceived(char c) /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGES LogMessage("PinballSlave::DataReceived"); #endif switch (c) { case INIT_THEME: { playSong(MP3_THEME); //TODO: } break; } } <commit_msg>fixed merge<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * BSD 3-Clause License /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * Code by Cassius Fiorin - [email protected] http://pinballhomemade.blogspot.com.br * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "PinballSlave.h" #include "PinballObject.h" #include "Pinball.h" #include "HardwareSerial.h" #include "Vector.h" #include "Utils.h" #include "Input.h" #include "DefinesMp3.h" #ifdef DOS #include "PinballMaster.h" #endif // DOS #ifdef ARDUINOLIB #include <Wire.h> PinballSlave *m_PinballSlave = NULL; //-----------------------------------------------------------------------// void receiveMessageFromAnotherArduinoSlave(int howMany) //-----------------------------------------------------------------------// { m_PinballSlave->receiveMessageFromAnotherArduino(howMany); } //-----------------------------------------------------------------------// void SetupWire() //-----------------------------------------------------------------------// { Wire.begin(ADDRESS_SLAVE); // join I2C bus using this address Wire.onReceive(receiveMessageFromAnotherArduinoSlave); // register event to handle requests } #endif // ARDUINOLIB /*---------------------------------------------------------------------*/ // C L A S S /*---------------------------------------------------------------------*/ #ifdef ARDUINOLIB /*---------------------------------------------------------------------*/ PinballSlave::PinballSlave() /*---------------------------------------------------------------------*/ { m_PinballSlave = this; SetupWire(); } /*---------------------------------------------------------------------*/ void PinballSlave::Setup(SFEMP3Shield *MP3player, HardwareSerial *serial) /*---------------------------------------------------------------------*/ { m_serial = serial; m_MP3player = MP3player; playSong(MP3_STARTBUTTONPORT); Init(); } #endif #ifdef DOS /*---------------------------------------------------------------------*/ PinballSlave::PinballSlave(const char *szName, HardwareSerial *serial) : Pinball(szName, serial) /*---------------------------------------------------------------------*/ { m_PinballMaster = NULL; m_Status = StatusPinball::initializing; #ifdef DEBUGMESSAGESCREATION LogMessage("PinballSlave Constructor"); #endif } #endif /*---------------------------------------------------------------------*/ PinballSlave::~PinballSlave() /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGESCREATION LogMessage("PinballSlave Destructor"); #endif } /*---------------------------------------------------------------------*/ bool PinballSlave::Init() /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGES LogMessage("PinballSlave Init"); #endif m_Status = StatusPinball::waitingmessages; return true; } /*---------------------------------------------------------------------*/ bool PinballSlave::Loop(int value) /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGESLOOP LogMessage("PinballSlave::Loop"); #endif return true; } /*---------------------------------------------------------------------*/ void PinballSlave::DataReceived(char c) /*---------------------------------------------------------------------*/ { #ifdef DEBUGMESSAGES LogMessage("PinballSlave::DataReceived"); #endif switch (c) { case INIT_THEME: { playSong(MP3_THEME); //TODO: } break; } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbVcaImageFilter.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" const unsigned int Dimension = 2; typedef double PixelType; typedef double PrecisionType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VCAImageFilter<VectorImageType> VCAFilterType; typedef otb::ImageFileReader<VectorImageType> ReaderType; typedef otb::ImageFileWriter<VectorImageType> WriterType; int otbVCAImageFilterTestHighSNR(int argc, char * argv[]) { const char * inputImage = argv[1]; const char * outputImage = argv[2]; const unsigned int nbEndmembers = atoi(argv[3]); ReaderType::Pointer readerImage = ReaderType::New(); readerImage->SetFileName(inputImage); VCAFilterType::Pointer vca = VCAFilterType::New(); vca->SetNumberOfEndmembers(nbEndmembers); vca->SetInput(readerImage->GetOutput()); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputImage); writer->SetInput(vca->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <commit_msg>TEST: use float<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbVcaImageFilter.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" const unsigned int Dimension = 2; typedef float PixelType; typedef float PrecisionType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VCAImageFilter<VectorImageType> VCAFilterType; typedef otb::ImageFileReader<VectorImageType> ReaderType; typedef otb::ImageFileWriter<VectorImageType> WriterType; int otbVCAImageFilterTestHighSNR(int argc, char * argv[]) { const char * inputImage = argv[1]; const char * outputImage = argv[2]; const unsigned int nbEndmembers = atoi(argv[3]); ReaderType::Pointer readerImage = ReaderType::New(); readerImage->SetFileName(inputImage); VCAFilterType::Pointer vca = VCAFilterType::New(); vca->SetNumberOfEndmembers(nbEndmembers); vca->SetInput(readerImage->GetOutput()); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputImage); writer->SetInput(vca->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of knor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <random> #include <stdexcept> #include "gmeans_coordinator.hpp" #include "gmeans.hpp" #include "io.hpp" #include "clusters.hpp" #include "linalg.hpp" #include "AndersonDarling.hpp" #include "hclust_id_generator.hpp" namespace knor { gmeans_coordinator::gmeans_coordinator(const std::string fn, const size_t nrow, const size_t ncol, const unsigned k, const unsigned max_iters, const unsigned nnodes, const unsigned nthreads, const double* centers, const base::init_t it, const double tolerance, const base::dist_t dt, const unsigned min_clust_size, const short strictness) : xmeans_coordinator(fn, nrow, ncol, k, max_iters, nnodes, nthreads, centers, it, tolerance, dt, min_clust_size), strictness(strictness) { } void gmeans_coordinator::build_thread_state() { // NUMA node affinity binding policy is round-robin unsigned thds_row = nrow / nthreads; for (unsigned thd_id = 0; thd_id < nthreads; thd_id++) { std::pair<unsigned, unsigned> tup = get_rid_len_tup(thd_id); thd_max_row_idx.push_back((thd_id*thds_row) + tup.second); threads.push_back(xmeans::create((thd_id % nnodes), thd_id, tup.first, tup.second, ncol, k, hcltrs, &cluster_assignments[0], fn, _dist_t, cltr_active_vec, partition_dist, nearest_cdist, compute_pdist)); threads[thd_id]->set_parent_cond(&cond); threads[thd_id]->set_parent_pending_threads(&pending_threads); threads[thd_id]->start(WAIT); // Thread puts itself to sleep std::static_pointer_cast<xmeans>(threads[thd_id]) ->set_part_id(&part_id[0]); std::static_pointer_cast<xmeans>(threads[thd_id]) ->set_g_clusters(cltrs); } } void gmeans_coordinator::assemble_ad_vecs(std::unordered_map<unsigned, std::vector<double>>& ad_vecs) { //assert(nearest_cdist.size() == part_id.size() && part_id.size() == nrow); for (size_t i = 0; i < nearest_cdist.size(); i++) { ad_vecs[part_id[i]].push_back(nearest_cdist[i]); } } void gmeans_coordinator::compute_ad_stats( std::unordered_map<unsigned, std::vector<double>>& ad_vecs) { for (auto& kv : ad_vecs) { double score = base::AndersonDarling::compute_statistic(ncol, &kv.second[0]); kv.second.push_back(score); // NOTE: We push the score onto the back } } // NOTE: This modifies hcltrs void gmeans_coordinator::partition_decision() { // Each Anderson Darling (AD) vector represents the vector for which // each cluster gets its AD statistic. std::unordered_map<unsigned, std::vector<double>> ad_vecs; std::vector<double> critical_values; // Populate the AD vectors assemble_ad_vecs(ad_vecs); for (auto& kv : ad_vecs) { base::linalg::scale(&(kv.second)[0], kv.second.size()); } // Compute Critical values base::AndersonDarling::compute_critical_values( ad_vecs.size(), critical_values); // Compute AD statistics compute_ad_stats(ad_vecs); std::vector<size_t> keys; hcltrs.get_keys(keys); // NOTE: We use ad_vecs.back() to store the score std::unordered_map<unsigned, bool> remove_cache; #pragma omp parallel for default(shared) for (size_t i = 0; i < keys.size(); i++) { unsigned pid = keys[i]; auto score = ad_vecs[pid].back(); if (score <= critical_values[strictness]) { #if VERBOSE printf("\nPart: %u will NOT split! score: %.4f <= crit val: %.4f\n", pid, score, critical_values[strictness]); #endif unsigned lid = hcltrs[pid]->get_zeroid(); unsigned rid = hcltrs[pid]->get_oneid(); // Deactivate both lid and rid deactivate(lid); deactivate(rid); // Deactivate pid deactivate(pid); #pragma omp critical { remove_cache[pid] = true; } final_centroids[pid] = std::vector<double>( cltrs->get_mean_rawptr(pid), cltrs->get_mean_rawptr(pid) + ncol); cluster_assignment_counts[pid] = cluster_assignment_counts[lid] + cluster_assignment_counts[rid]; cluster_assignment_counts[lid] = cluster_assignment_counts[rid] = 0; } else { #pragma omp critical { remove_cache[pid] = false; } #if VERBOSE printf("\nPart: %u will split! score: %.4f > crit val: %.4f\n", pid, score, critical_values[strictness]); #endif } } // Assemble cluster membership #pragma omp parallel for default(shared) firstprivate(remove_cache) for (size_t rid = 0; rid < nrow; rid++) { auto pid = part_id[rid]; if (remove_cache[pid]) { // Means that row assignments needs to be reverted to part_id cluster_assignments[rid] = pid; } } for (auto const& kv : remove_cache) { if (kv.second) hcltrs.erase(kv.first); } } void gmeans_coordinator::compute_cluster_diffs() { auto itr = hcltrs.get_iterator(); while (itr.has_next()) { auto kv = itr.next(); auto c = std::static_pointer_cast<base::h_clusters>(kv.second); c->metadata.resize(ncol+1); // +1th index stores the divisor // Compute difference for (size_t i = 0; i < ncol; i++) base::linalg::vdiff(c->get_mean_rawptr(0), c->get_mean_rawptr(1), ncol, c->metadata); // Compute v.dot(v) c->metadata[ncol] = base::linalg::dot(&c->metadata[0], &c->metadata[0], ncol); // NOTE: last element intentionally ignored } } // Main driver base::cluster_t gmeans_coordinator::run( double* allocd_data, const bool numa_opt) { #ifdef PROFILER ProfilerStart("gmeans_coordinator.perf"); #endif build_thread_state(); if (!numa_opt && NULL == allocd_data) { wake4run(ALLOC_DATA); wait4complete(); } else if (allocd_data) { // No NUMA opt set_thread_data_ptr(allocd_data); } struct timeval start, end; gettimeofday(&start , NULL); if (_init_t == kbase::init_t::NONE) _init_t = kbase::init_t::FORGY; run_hinit(); // Initialize clusters // Run loop size_t iter = 0; unsigned curr_nclust = 2; while (true) { // TODO: Do this simultaneously with H_EM step wake4run(MEAN); wait4complete(); combine_partition_means(); compute_pdist = true; for (iter = 0; iter < max_iters; iter++) { #ifndef BIND printf("\nNCLUST: %u, Iteration: %lu\n", curr_nclust, iter); #endif // Now pick between the cluster splits wake4run(H_EM); wait4complete(); update_clusters(); #ifndef BIND printf("\nAssignment counts:\n"); base::sparse_print(cluster_assignment_counts); printf("\n*****************************************************\n"); #endif if (compute_pdist) compute_pdist = false; } compute_cluster_diffs(); wake4run(H_SPLIT); wait4complete(); // Decide on split or not here partition_decision(); if (curr_nclust >= k*2) { #ifndef BIND printf("\n\nCLUSTER SIZE EXIT @ %u!\n", curr_nclust); #endif break; } // Update global state init_splits(); // Initialize possible splits // Break when clusters are inactive due to size if (hcltrs.keyless()) { //assert(steady_state()); // NOTE: Comment when benchmarking #ifndef BIND printf("\n\nSTEADY STATE EXIT!\n"); #endif break; } curr_nclust = hcltrs.keycount()*2 + final_centroids.size(); } #ifdef PROFILER ProfilerStop(); #endif gettimeofday(&end, NULL); #ifndef BIND printf("\n\nAlgorithmic time taken = %.6f sec\n", base::time_diff(start, end)); printf("\n******************************************\n"); #endif #ifndef BIND printf("Final cluster counts: \n"); base::sparse_print(cluster_assignment_counts); //printf("Final centroids\n"); //for (auto const& kv : final_centroids) { //printf("k: %u, v: ", kv.first); base::print(kv.second); //} printf("\n******************************************\n"); #endif #if 0 return base::cluster_t(this->nrow, this->ncol, iter, this->k, &cluster_assignments[0], &cluster_assignment_counts[0], hcltrs->get_means()); #else return base::cluster_t(); // TODO #endif } } <commit_msg>bug: gmeans should use it's own threads<commit_after>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of knor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <random> #include <stdexcept> #include "gmeans_coordinator.hpp" #include "gmeans.hpp" #include "io.hpp" #include "clusters.hpp" #include "linalg.hpp" #include "AndersonDarling.hpp" #include "hclust_id_generator.hpp" namespace knor { gmeans_coordinator::gmeans_coordinator(const std::string fn, const size_t nrow, const size_t ncol, const unsigned k, const unsigned max_iters, const unsigned nnodes, const unsigned nthreads, const double* centers, const base::init_t it, const double tolerance, const base::dist_t dt, const unsigned min_clust_size, const short strictness) : xmeans_coordinator(fn, nrow, ncol, k, max_iters, nnodes, nthreads, centers, it, tolerance, dt, min_clust_size), strictness(strictness) { } void gmeans_coordinator::build_thread_state() { // NUMA node affinity binding policy is round-robin unsigned thds_row = nrow / nthreads; for (unsigned thd_id = 0; thd_id < nthreads; thd_id++) { std::pair<unsigned, unsigned> tup = get_rid_len_tup(thd_id); thd_max_row_idx.push_back((thd_id*thds_row) + tup.second); threads.push_back(gmeans::create((thd_id % nnodes), thd_id, tup.first, tup.second, ncol, k, hcltrs, &cluster_assignments[0], fn, _dist_t, cltr_active_vec, partition_dist, nearest_cdist, compute_pdist)); threads[thd_id]->set_parent_cond(&cond); threads[thd_id]->set_parent_pending_threads(&pending_threads); threads[thd_id]->start(WAIT); // Thread puts itself to sleep std::static_pointer_cast<gmeans>(threads[thd_id]) ->set_part_id(&part_id[0]); std::static_pointer_cast<gmeans>(threads[thd_id]) ->set_g_clusters(cltrs); } } void gmeans_coordinator::assemble_ad_vecs(std::unordered_map<unsigned, std::vector<double>>& ad_vecs) { //assert(nearest_cdist.size() == part_id.size() && part_id.size() == nrow); for (size_t i = 0; i < nearest_cdist.size(); i++) { ad_vecs[part_id[i]].push_back(nearest_cdist[i]); } } void gmeans_coordinator::compute_ad_stats( std::unordered_map<unsigned, std::vector<double>>& ad_vecs) { for (auto& kv : ad_vecs) { double score = base::AndersonDarling::compute_statistic(ncol, &kv.second[0]); kv.second.push_back(score); // NOTE: We push the score onto the back } } // NOTE: This modifies hcltrs void gmeans_coordinator::partition_decision() { // Each Anderson Darling (AD) vector represents the vector for which // each cluster gets its AD statistic. std::unordered_map<unsigned, std::vector<double>> ad_vecs; std::vector<double> critical_values; // Populate the AD vectors assemble_ad_vecs(ad_vecs); for (auto& kv : ad_vecs) { base::linalg::scale(&(kv.second)[0], kv.second.size()); } // Compute Critical values base::AndersonDarling::compute_critical_values( ad_vecs.size(), critical_values); // Compute AD statistics compute_ad_stats(ad_vecs); std::vector<size_t> keys; hcltrs.get_keys(keys); // NOTE: We use ad_vecs.back() to store the score std::unordered_map<unsigned, bool> remove_cache; #pragma omp parallel for default(shared) for (size_t i = 0; i < keys.size(); i++) { unsigned pid = keys[i]; auto score = ad_vecs[pid].back(); if (score <= critical_values[strictness]) { #if VERBOSE printf("\nPart: %u will NOT split! score: %.4f <= crit val: %.4f\n", pid, score, critical_values[strictness]); #endif unsigned lid = hcltrs[pid]->get_zeroid(); unsigned rid = hcltrs[pid]->get_oneid(); // Deactivate both lid and rid deactivate(lid); deactivate(rid); // Deactivate pid deactivate(pid); #pragma omp critical { remove_cache[pid] = true; } final_centroids[pid] = std::vector<double>( cltrs->get_mean_rawptr(pid), cltrs->get_mean_rawptr(pid) + ncol); cluster_assignment_counts[pid] = cluster_assignment_counts[lid] + cluster_assignment_counts[rid]; cluster_assignment_counts[lid] = cluster_assignment_counts[rid] = 0; } else { #pragma omp critical { remove_cache[pid] = false; } #if VERBOSE printf("\nPart: %u will split! score: %.4f > crit val: %.4f\n", pid, score, critical_values[strictness]); #endif } } // Assemble cluster membership #pragma omp parallel for default(shared) firstprivate(remove_cache) for (size_t rid = 0; rid < nrow; rid++) { auto pid = part_id[rid]; if (remove_cache[pid]) { // Means that row assignments needs to be reverted to part_id cluster_assignments[rid] = pid; } } for (auto const& kv : remove_cache) { if (kv.second) hcltrs.erase(kv.first); } } void gmeans_coordinator::compute_cluster_diffs() { auto itr = hcltrs.get_iterator(); while (itr.has_next()) { auto kv = itr.next(); auto c = std::static_pointer_cast<base::h_clusters>(kv.second); c->metadata.resize(ncol+1); // +1th index stores the divisor // Compute difference for (size_t i = 0; i < ncol; i++) base::linalg::vdiff(c->get_mean_rawptr(0), c->get_mean_rawptr(1), ncol, c->metadata); // Compute v.dot(v) c->metadata[ncol] = base::linalg::dot(&c->metadata[0], &c->metadata[0], ncol); // NOTE: last element intentionally ignored } } // Main driver base::cluster_t gmeans_coordinator::run( double* allocd_data, const bool numa_opt) { #ifdef PROFILER ProfilerStart("gmeans_coordinator.perf"); #endif build_thread_state(); if (!numa_opt && NULL == allocd_data) { wake4run(ALLOC_DATA); wait4complete(); } else if (allocd_data) { // No NUMA opt set_thread_data_ptr(allocd_data); } struct timeval start, end; gettimeofday(&start , NULL); if (_init_t == kbase::init_t::NONE) _init_t = kbase::init_t::FORGY; run_hinit(); // Initialize clusters // Run loop size_t iter = 0; unsigned curr_nclust = 2; while (true) { // TODO: Do this simultaneously with H_EM step wake4run(MEAN); wait4complete(); combine_partition_means(); compute_pdist = true; for (iter = 0; iter < max_iters; iter++) { #ifndef BIND printf("\nNCLUST: %u, Iteration: %lu\n", curr_nclust, iter); #endif // Now pick between the cluster splits wake4run(H_EM); wait4complete(); update_clusters(); #ifndef BIND printf("\nAssignment counts:\n"); base::sparse_print(cluster_assignment_counts); printf("\n*****************************************************\n"); #endif if (compute_pdist) compute_pdist = false; } compute_cluster_diffs(); wake4run(H_SPLIT); wait4complete(); // Decide on split or not here partition_decision(); if (curr_nclust >= k*2) { #ifndef BIND printf("\n\nCLUSTER SIZE EXIT @ %u!\n", curr_nclust); #endif break; } // Update global state init_splits(); // Initialize possible splits // Break when clusters are inactive due to size if (hcltrs.keyless()) { //assert(steady_state()); // NOTE: Comment when benchmarking #ifndef BIND printf("\n\nSTEADY STATE EXIT!\n"); #endif break; } curr_nclust = hcltrs.keycount()*2 + final_centroids.size(); } #ifdef PROFILER ProfilerStop(); #endif gettimeofday(&end, NULL); #ifndef BIND printf("\n\nAlgorithmic time taken = %.6f sec\n", base::time_diff(start, end)); printf("\n******************************************\n"); #endif #ifndef BIND printf("Final cluster counts: \n"); base::sparse_print(cluster_assignment_counts); //printf("Final centroids\n"); //for (auto const& kv : final_centroids) { //printf("k: %u, v: ", kv.first); base::print(kv.second); //} printf("\n******************************************\n"); #endif #if 0 return base::cluster_t(this->nrow, this->ncol, iter, this->k, &cluster_assignments[0], &cluster_assignment_counts[0], hcltrs->get_means()); #else return base::cluster_t(); // TODO #endif } } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * FILE * dbtransaction.cxx * * DESCRIPTION * implementation of the pqxx::dbtransaction class. * pqxx::dbtransaction represents a real backend transaction * * Copyright (c) 2004-2005, Jeroen T. Vermeulen <[email protected]> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler.h" #include "pqxx/dbtransaction" using namespace std; pqxx::dbtransaction::dbtransaction(connection_base &C, const PGSTD::string &IsolationString, const PGSTD::string &NName, const PGSTD::string &CName) : transaction_base(C, NName, CName), m_StartCmd() { if (IsolationString != isolation_traits<read_committed>::name()) m_StartCmd = "SET TRANSACTION ISOLATION LEVEL " + IsolationString; } pqxx::dbtransaction::~dbtransaction() { } void pqxx::dbtransaction::start_backend_transaction() { DirectExec("BEGIN", 2); // TODO: Can't we pipeline this to eliminate roundtrip time? if (!m_StartCmd.empty()) DirectExec(m_StartCmd.c_str()); } pqxx::result pqxx::dbtransaction::do_exec(const char Query[]) { try { return DirectExec(Query); } catch (const exception &) { try { abort(); } catch (const exception &) {} throw; } } <commit_msg>Use PGSTD, not std!<commit_after>/*------------------------------------------------------------------------- * * FILE * dbtransaction.cxx * * DESCRIPTION * implementation of the pqxx::dbtransaction class. * pqxx::dbtransaction represents a real backend transaction * * Copyright (c) 2004-2005, Jeroen T. Vermeulen <[email protected]> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler.h" #include "pqxx/dbtransaction" using namespace PGSTD; pqxx::dbtransaction::dbtransaction(connection_base &C, const PGSTD::string &IsolationString, const PGSTD::string &NName, const PGSTD::string &CName) : transaction_base(C, NName, CName), m_StartCmd() { if (IsolationString != isolation_traits<read_committed>::name()) m_StartCmd = "SET TRANSACTION ISOLATION LEVEL " + IsolationString; } pqxx::dbtransaction::~dbtransaction() { } void pqxx::dbtransaction::start_backend_transaction() { DirectExec("BEGIN", 2); // TODO: Can't we pipeline this to eliminate roundtrip time? if (!m_StartCmd.empty()) DirectExec(m_StartCmd.c_str()); } pqxx::result pqxx::dbtransaction::do_exec(const char Query[]) { try { return DirectExec(Query); } catch (const exception &) { try { abort(); } catch (const exception &) {} throw; } } <|endoftext|>
<commit_before>/* ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <iostream> #include <qimessaging/object.hpp> #include <boost/algorithm/string/predicate.hpp> namespace qi { Object::Object() : _meta(new MetaObject()) { advertiseMethod("__metaobject", this, &Object::metaObject); } Object::~Object() { delete _meta; } MetaObject &Object::metaObject() { return *_meta; } MetaMethod::MetaMethod() : _signature("") , _functor(0) , _idx(0) { } MetaMethod::MetaMethod(const std::string &sig, const qi::Functor *functor) : _signature(sig) , _functor(functor) , _idx(0) { } unsigned int Object::xAdvertiseMethod(const std::string& signature, const qi::Functor* functor) { MetaMethod mm(signature, functor); unsigned int idx = _meta->_methodsNumber++; mm._idx = idx; _meta->_methods.push_back(mm); _meta->_methodsNameToIdx[signature] = idx; qiLogVerbose("qi::Object") << "binding method:" << signature; return idx; } void Object::metaCall(unsigned int method, const FunctorParameters &in, qi::FunctorResult out) { if (method > _meta->_methods.size()) { std::stringstream ss; ss << "Can't find methodID: " << method; qi::Buffer buf; qi::DataStream ds(buf); ds << ss.str(); out.setError(buf); return; } MetaMethod *mm = &(_meta->_methods[method]); if (mm->_functor) mm->_functor->call(in, out); } bool Object::xMetaCall(const std::string &signature, const FunctorParameters &in, FunctorResult out) { int methodId = metaObject().methodId(signature); if (methodId < 0) { qiLogError("object") << "cant find method: " << signature; qi::Buffer buf; qi::DataStream ds(buf); std::stringstream ss; ss << "Can't find method: " << signature << std::endl << "Canditate(s):" << std::endl; std::vector<qi::MetaMethod> mml = metaObject().findMethod(qi::signatureSplit(signature)[1]); std::vector<qi::MetaMethod>::iterator it; for (it = mml.begin(); it != mml.end(); ++it) { qi::MetaMethod &mm = *it; ss << " " << mm.signature(); } ds << ss.str(); out.setError(buf); return false; } metaCall(methodId, in, out); return true; } qi::DataStream &operator<<(qi::DataStream &stream, const MetaMethod &meta) { stream << meta._signature; stream << meta._idx; return stream; } qi::DataStream &operator>>(qi::DataStream &stream, MetaMethod &meta) { stream >> meta._signature; stream >> meta._idx; return stream; } qi::DataStream &operator<<(qi::DataStream &stream, const MetaObject &meta) { stream << meta._methodsNameToIdx; stream << meta._methods; stream << meta._methodsNumber; return stream; } qi::DataStream &operator>>(qi::DataStream &stream, MetaObject &meta) { stream >> meta._methodsNameToIdx; stream >> meta._methods; stream >> meta._methodsNumber; return stream; } std::vector<qi::MetaMethod> MetaObject::findMethod(const std::string &name) { std::vector<qi::MetaMethod> ret; std::vector<qi::MetaMethod>::iterator it; std::string cname(name); cname += "::"; for (it = _methods.begin(); it != _methods.end(); ++it) { qi::MetaMethod &mm = *it; if (boost::starts_with(mm.signature(), cname)) ret.push_back(mm); } return ret; } }; <commit_msg>object: better log when a method is not found<commit_after>/* ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <iostream> #include <qimessaging/object.hpp> #include <boost/algorithm/string/predicate.hpp> namespace qi { Object::Object() : _meta(new MetaObject()) { advertiseMethod("__metaobject", this, &Object::metaObject); } Object::~Object() { delete _meta; } MetaObject &Object::metaObject() { return *_meta; } MetaMethod::MetaMethod() : _signature("") , _functor(0) , _idx(0) { } MetaMethod::MetaMethod(const std::string &sig, const qi::Functor *functor) : _signature(sig) , _functor(functor) , _idx(0) { } unsigned int Object::xAdvertiseMethod(const std::string& signature, const qi::Functor* functor) { MetaMethod mm(signature, functor); unsigned int idx = _meta->_methodsNumber++; mm._idx = idx; _meta->_methods.push_back(mm); _meta->_methodsNameToIdx[signature] = idx; qiLogVerbose("qi::Object") << "binding method:" << signature; return idx; } void Object::metaCall(unsigned int method, const FunctorParameters &in, qi::FunctorResult out) { if (method > _meta->_methods.size()) { std::stringstream ss; ss << "Can't find methodID: " << method; qi::Buffer buf; qi::DataStream ds(buf); ds << ss.str(); out.setError(buf); return; } MetaMethod *mm = &(_meta->_methods[method]); if (mm->_functor) mm->_functor->call(in, out); } bool Object::xMetaCall(const std::string &signature, const FunctorParameters &in, FunctorResult out) { int methodId = metaObject().methodId(signature); if (methodId < 0) { qi::Buffer buf; qi::DataStream ds(buf); std::stringstream ss; ss << "Can't find method: " << signature << std::endl << " Candidate(s):" << std::endl; std::vector<qi::MetaMethod> mml = metaObject().findMethod(qi::signatureSplit(signature)[1]); std::vector<qi::MetaMethod>::const_iterator it; for (it = mml.begin(); it != mml.end(); ++it) { const qi::MetaMethod &mm = *it; ss << " " << mm.signature(); } qiLogError("object") << ss.str(); ds << ss.str(); out.setError(buf); return false; } metaCall(methodId, in, out); return true; } qi::DataStream &operator<<(qi::DataStream &stream, const MetaMethod &meta) { stream << meta._signature; stream << meta._idx; return stream; } qi::DataStream &operator>>(qi::DataStream &stream, MetaMethod &meta) { stream >> meta._signature; stream >> meta._idx; return stream; } qi::DataStream &operator<<(qi::DataStream &stream, const MetaObject &meta) { stream << meta._methodsNameToIdx; stream << meta._methods; stream << meta._methodsNumber; return stream; } qi::DataStream &operator>>(qi::DataStream &stream, MetaObject &meta) { stream >> meta._methodsNameToIdx; stream >> meta._methods; stream >> meta._methodsNumber; return stream; } std::vector<qi::MetaMethod> MetaObject::findMethod(const std::string &name) { std::vector<qi::MetaMethod> ret; std::vector<qi::MetaMethod>::iterator it; std::string cname(name); cname += "::"; for (it = _methods.begin(); it != _methods.end(); ++it) { qi::MetaMethod &mm = *it; if (boost::starts_with(mm.signature(), cname)) ret.push_back(mm); } return ret; } }; <|endoftext|>
<commit_before>/* PCA9539 GPIO Expander Library By: OpenROV Date: September 14, 2016 */ #include <Arduino.h> #include <CI2C.h> #include "PCA9539.h" using namespace pca9539; PCA9539::PCA9539( CI2C* i2cInterfaceIn ) : m_i2cAddress( pca9539::PCA9539_ADDRESS ) , m_pI2C( i2cInterfaceIn ) , m_gpioDirection( 0xFF ) //All inputs , m_gpioState( 0x00 ) //All low { } ERetCode PCA9539::Initialize() { Serial.println( "PCA9539.status: INIT" ); m_gpioDirection = 0x00; //All outputs uint8_t value; //Read it auto ret = ReadByte( PCA9539_REGISTER::CONFIG, value ); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } Serial.println(value, HEX); //Write it ret = WriteByte( PCA9539_REGISTER::CONFIG, m_gpioDirection); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Read it ret = ReadByte( PCA9539_REGISTER::CONFIG, value ); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } Serial.println(value, HEX); m_gpioState |= (1 << 5); //Write it ret = WriteByte( PCA9539_REGISTER::OUTPUT, m_gpioState); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } value == HIGH ? _gpioState |= (1 << pin) : _gpioState &= ~(1 << pin); if(HIGH) { value = _gpioState |= (1 << pin); } else { _gpioState &= ~(1 << pin) } /*************************************************************************** PRIVATE FUNCTIONS ***************************************************************************/ int32_t PCA9539::WriteByte( PCA9539_REGISTER addressIn, uint8_t dataIn ) { return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn ); } int32_t PCA9539::ReadByte( PCA9539_REGISTER addressIn, uint8_t &dataOut ) { return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut ); } int32_t PCA9539::ReadNBytes( PCA9539_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn ) { return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn ); } <commit_msg>Huge typo<commit_after>/* PCA9539 GPIO Expander Library By: OpenROV Date: September 14, 2016 */ #include <Arduino.h> #include <CI2C.h> #include "PCA9539.h" using namespace pca9539; PCA9539::PCA9539( CI2C* i2cInterfaceIn ) : m_i2cAddress( pca9539::PCA9539_ADDRESS ) , m_pI2C( i2cInterfaceIn ) , m_gpioDirection( 0xFF ) //All inputs , m_gpioState( 0x00 ) //All low { } ERetCode PCA9539::Initialize() { Serial.println( "PCA9539.status: INIT" ); m_gpioDirection = 0x00; //All outputs uint8_t value; //Read it auto ret = ReadByte( PCA9539_REGISTER::CONFIG, value ); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } Serial.println(value, HEX); //Write it ret = WriteByte( PCA9539_REGISTER::CONFIG, m_gpioDirection); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Read it ret = ReadByte( PCA9539_REGISTER::CONFIG, value ); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } Serial.println(value, HEX); m_gpioState |= (1 << 5); //Write it ret = WriteByte( PCA9539_REGISTER::OUTPUT, m_gpioState); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } // value == HIGH ? _gpioState |= (1 << pin) : _gpioState &= ~(1 << pin); // if(HIGH) // { // value = _gpioState |= (1 << pin); // } // else // { // _gpioState &= ~(1 << pin) // } /*************************************************************************** PRIVATE FUNCTIONS ***************************************************************************/ int32_t PCA9539::WriteByte( PCA9539_REGISTER addressIn, uint8_t dataIn ) { return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn ); } int32_t PCA9539::ReadByte( PCA9539_REGISTER addressIn, uint8_t &dataOut ) { return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut ); } int32_t PCA9539::ReadNBytes( PCA9539_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn ) { return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn ); } <|endoftext|>
<commit_before>/** * ExperimentPackager.cpp * * History: * paul on 1/25/06 - Created. * * Copyright 2006 MIT. All rights reserved. */ #include "ExperimentPackager.h" #include "Utilities.h" #include "LoadingUtilities.h" #include "SystemEventFactory.h" #include <iostream> #include <fstream> #include "PlatformDependentServices.h" #include "boost/filesystem/path.hpp" #include "boost/algorithm/string/replace.hpp" #include <boost/scope_exit.hpp> BEGIN_NAMESPACE_MW Datum ExperimentPackager::packageSingleFile(const Datum &contents, const std::string &filename) { Datum unit(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS_PER_UNIT); Datum name; name.setString(filename.c_str(), filename.length()+1); unit.addElement(M_PACKAGER_FILENAME_STRING, name); unit.addElement(M_PACKAGER_CONTENTS_STRING, contents); return unit; } Datum ExperimentPackager::packageSingleFile(const boost::filesystem::path filepath, const std::string filename) { namespace bf = boost::filesystem; std::ifstream mediaFile; mediaFile.open(filepath.string().c_str(), std::ios::binary); // get length of file: mediaFile.seekg(0, std::ios::end); int length = mediaFile.tellg(); // if the file was never opened if(length <= 0) { mediaFile.close(); Datum undef; return undef; } char * buffer = new char[length]; mediaFile.seekg(0, std::ios::beg); mediaFile.read(buffer, length); mediaFile.close(); Datum bufferData; bufferData.setString(buffer, length); delete [] buffer; return packageSingleFile(bufferData, filename); } Datum ExperimentPackager::packageExperiment(const boost::filesystem::path filename) { namespace bf = boost::filesystem; IncludedFilesParser parser(filename.string()); std::string working_path_string; Datum include_files; try{ parser.parse(false); working_path_string = parser.getWorkingPathString(); include_files = parser.getIncludedFilesManifest(); } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "Experiment packaging failed: %s", e.what()); return Datum(); } Datum eventPayload(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS); { // Use getDocumentData to get the experiment file with any preprocessing and/or // XInclude substitutions already applied std::vector<xmlChar> fileData; parser.getDocumentData(fileData); Datum contents(reinterpret_cast<char *>(&(fileData.front())), fileData.size()); eventPayload.addElement(M_PACKAGER_EXPERIMENT_STRING, packageSingleFile(contents, XMLParser::squashFileName(filename.string()))); } if(include_files.getNElements() >= 1) { Datum mediaFilesPayload(M_LIST, include_files.getNElements()); for(int i=0; i< include_files.getNElements(); ++i) { // DDC there seem to be a lot of unnecessary steps here // simplified hackily for the moment std::string mediaName(include_files.getElement(i).getString()); bf::path mediaPath = expandPath(working_path_string, mediaName); //bf::path mediaPath(include_files.getElement(i).getElement(M_PACKAGER_FULL_NAME).getString()); //std::string mediaName(include_files.getElement(i).getElement(M_PACKAGER_RELATIVE_NAME).getString()); Datum mediaElement = packageSingleFile(mediaPath, mediaName); if(!mediaElement.isUndefined()) { mediaFilesPayload.addElement(mediaElement); } else { merror(M_FILE_MESSAGE_DOMAIN, "Can't find file: %s", mediaPath.string().c_str()); Datum undef; return undef; } } eventPayload.addElement(M_PACKAGER_MEDIA_BUFFERS_STRING, mediaFilesPayload); } return SystemEventFactory::systemEventPackage(M_SYSTEM_DATA_PACKAGE, M_EXPERIMENT_PACKAGE, eventPayload); } IncludedFilesParser::IncludedFilesParser(const std::string &_path) : XMLParser(_path, "MWMediaPackagerTransformation.xsl"), manifest(M_LIST, 1) { } void IncludedFilesParser::parse(bool announce_progress) { // Load the experiment file, applying any preprocessing and/or XInclude substitutions loadFile(); // Look for resource declarations auto xpathObject = evaluateXPathExpression("//resource/@path[string-length() != 0]"); if (xpathObject) { BOOST_SCOPE_EXIT( xpathObject ) { xmlXPathFreeObject(xpathObject); } BOOST_SCOPE_EXIT_END if (xpathObject->type == XPATH_NODESET && xpathObject->nodesetval && xpathObject->nodesetval->nodeNr > 0) { // Found one or more resource declarations, so add the identified files and directories to // the manifest for (int nodeIndex = 0; nodeIndex < xpathObject->nodesetval->nodeNr; nodeIndex++) { auto path = _getContent(xpathObject->nodesetval->nodeTab[nodeIndex]); if (boost::filesystem::is_directory(expandPath(getWorkingPathString(), path))) { addDirectory(path, true); // Recursive } else { manifest.addElement(path); } } // Return without parsing the file. This allows experiments that declare resources to use // run-time expressions in "path" and other attributes that would otherwise need to be // evaluated at parse time. return; } } // No resource declarations found, so parse the experiment (expanding any replicators), and // infer the included files from component attributes XMLParser::parse(announce_progress); } void IncludedFilesParser::addDirectory(const std::string &directoryPath, bool recursive) { std::vector<std::string> filePaths; mw::getFilePaths(getWorkingPathString(), directoryPath, filePaths, recursive); for (const auto &path : filePaths) { manifest.addElement(path); } } void IncludedFilesParser::_processCreateDirective(xmlNode *node) { xmlNode *child = node->children; while (child != NULL) { string name((const char *)(child->name)); if (name == "path") { string filePath = _getContent(child); manifest.addElement(filePath); } else if (name == "directory_path") { string directoryPath = _getContent(child); addDirectory(directoryPath, false); // Not recursive } child = child->next; } } void IncludedFilesParser::_processAnonymousCreateDirective(xmlNode *node) { _processCreateDirective(node); } END_NAMESPACE_MW <commit_msg>In ExperimentPackager::packageSingleFile, don't reject empty files<commit_after>/** * ExperimentPackager.cpp * * History: * paul on 1/25/06 - Created. * * Copyright 2006 MIT. All rights reserved. */ #include "ExperimentPackager.h" #include "Utilities.h" #include "LoadingUtilities.h" #include "SystemEventFactory.h" #include <iostream> #include <fstream> #include "PlatformDependentServices.h" #include "boost/filesystem/path.hpp" #include "boost/algorithm/string/replace.hpp" #include <boost/scope_exit.hpp> BEGIN_NAMESPACE_MW Datum ExperimentPackager::packageSingleFile(const Datum &contents, const std::string &filename) { Datum unit(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS_PER_UNIT); Datum name; name.setString(filename.c_str(), filename.length()+1); unit.addElement(M_PACKAGER_FILENAME_STRING, name); unit.addElement(M_PACKAGER_CONTENTS_STRING, contents); return unit; } Datum ExperimentPackager::packageSingleFile(const boost::filesystem::path filepath, const std::string filename) { namespace bf = boost::filesystem; std::ifstream mediaFile; mediaFile.open(filepath.string().c_str(), std::ios::binary); // get length of file: mediaFile.seekg(0, std::ios::end); int length = mediaFile.tellg(); // if the file was never opened if (length < 0) { mediaFile.close(); Datum undef; return undef; } char * buffer = new char[length]; mediaFile.seekg(0, std::ios::beg); mediaFile.read(buffer, length); mediaFile.close(); Datum bufferData; bufferData.setString(buffer, length); delete [] buffer; return packageSingleFile(bufferData, filename); } Datum ExperimentPackager::packageExperiment(const boost::filesystem::path filename) { namespace bf = boost::filesystem; IncludedFilesParser parser(filename.string()); std::string working_path_string; Datum include_files; try{ parser.parse(false); working_path_string = parser.getWorkingPathString(); include_files = parser.getIncludedFilesManifest(); } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "Experiment packaging failed: %s", e.what()); return Datum(); } Datum eventPayload(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS); { // Use getDocumentData to get the experiment file with any preprocessing and/or // XInclude substitutions already applied std::vector<xmlChar> fileData; parser.getDocumentData(fileData); Datum contents(reinterpret_cast<char *>(&(fileData.front())), fileData.size()); eventPayload.addElement(M_PACKAGER_EXPERIMENT_STRING, packageSingleFile(contents, XMLParser::squashFileName(filename.string()))); } if(include_files.getNElements() >= 1) { Datum mediaFilesPayload(M_LIST, include_files.getNElements()); for(int i=0; i< include_files.getNElements(); ++i) { // DDC there seem to be a lot of unnecessary steps here // simplified hackily for the moment std::string mediaName(include_files.getElement(i).getString()); bf::path mediaPath = expandPath(working_path_string, mediaName); //bf::path mediaPath(include_files.getElement(i).getElement(M_PACKAGER_FULL_NAME).getString()); //std::string mediaName(include_files.getElement(i).getElement(M_PACKAGER_RELATIVE_NAME).getString()); Datum mediaElement = packageSingleFile(mediaPath, mediaName); if(!mediaElement.isUndefined()) { mediaFilesPayload.addElement(mediaElement); } else { merror(M_FILE_MESSAGE_DOMAIN, "Can't find file: %s", mediaPath.string().c_str()); Datum undef; return undef; } } eventPayload.addElement(M_PACKAGER_MEDIA_BUFFERS_STRING, mediaFilesPayload); } return SystemEventFactory::systemEventPackage(M_SYSTEM_DATA_PACKAGE, M_EXPERIMENT_PACKAGE, eventPayload); } IncludedFilesParser::IncludedFilesParser(const std::string &_path) : XMLParser(_path, "MWMediaPackagerTransformation.xsl"), manifest(M_LIST, 1) { } void IncludedFilesParser::parse(bool announce_progress) { // Load the experiment file, applying any preprocessing and/or XInclude substitutions loadFile(); // Look for resource declarations auto xpathObject = evaluateXPathExpression("//resource/@path[string-length() != 0]"); if (xpathObject) { BOOST_SCOPE_EXIT( xpathObject ) { xmlXPathFreeObject(xpathObject); } BOOST_SCOPE_EXIT_END if (xpathObject->type == XPATH_NODESET && xpathObject->nodesetval && xpathObject->nodesetval->nodeNr > 0) { // Found one or more resource declarations, so add the identified files and directories to // the manifest for (int nodeIndex = 0; nodeIndex < xpathObject->nodesetval->nodeNr; nodeIndex++) { auto path = _getContent(xpathObject->nodesetval->nodeTab[nodeIndex]); if (boost::filesystem::is_directory(expandPath(getWorkingPathString(), path))) { addDirectory(path, true); // Recursive } else { manifest.addElement(path); } } // Return without parsing the file. This allows experiments that declare resources to use // run-time expressions in "path" and other attributes that would otherwise need to be // evaluated at parse time. return; } } // No resource declarations found, so parse the experiment (expanding any replicators), and // infer the included files from component attributes XMLParser::parse(announce_progress); } void IncludedFilesParser::addDirectory(const std::string &directoryPath, bool recursive) { std::vector<std::string> filePaths; mw::getFilePaths(getWorkingPathString(), directoryPath, filePaths, recursive); for (const auto &path : filePaths) { manifest.addElement(path); } } void IncludedFilesParser::_processCreateDirective(xmlNode *node) { xmlNode *child = node->children; while (child != NULL) { string name((const char *)(child->name)); if (name == "path") { string filePath = _getContent(child); manifest.addElement(filePath); } else if (name == "directory_path") { string directoryPath = _getContent(child); addDirectory(directoryPath, false); // Not recursive } child = child->next; } } void IncludedFilesParser::_processAnonymousCreateDirective(xmlNode *node) { _processCreateDirective(node); } END_NAMESPACE_MW <|endoftext|>
<commit_before>/* * By: ulises-jeremias * From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3146 * Name: I Can Guess the Data Structure! * Date: 08/09/2017 */ #include <iostream> #include <queue> #include <stack> using namespace std; int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, i, op, v; stack<int> stk; queue<int> q; priority_queue<int> pq; bool is_stack, is_queue, is_priority_queue; while (cin >> n) { while (stk.size()) stk.pop(); while (q.size()) q.pop(); while (pq.size()) pq.pop(); is_stack = is_queue = is_priority_queue = true; for (i = 0; i < n; i++) { cin >> op >> v; if (op == 1) { stk.push(v); q.push(v); pq.push(v); } else { if (stk.size() == 0) { is_stack = is_queue = is_priority_queue = false; } else { if (stk.top() != v) is_stack = false; stk.pop(); if (q.front() != v) is_queue = false; q.pop(); if (pq.top() != v) is_priority_queue = false; pq.pop(); } } } } return 0; } <commit_msg>ICanGuesstheDataStructure! solved<commit_after>/* * By: ulises-jeremias * From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3146 * Name: I Can Guess the Data Structure! * Date: 08/09/2017 */ #include <iostream> #include <queue> #include <stack> using namespace std; int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, i, op, v; stack<int> stk; queue<int> q; priority_queue<int> pq; bool is_stack, is_queue, is_priority_queue; while (cin >> n) { while (stk.size()) stk.pop(); while (q.size()) q.pop(); while (pq.size()) pq.pop(); is_stack = is_queue = is_priority_queue = true; for (i = 0; i < n; i++) { cin >> op >> v; if (op == 1) { stk.push(v); q.push(v); pq.push(v); } else { if (stk.size() == 0) { is_stack = is_queue = is_priority_queue = false; } else { if (stk.top() != v) is_stack = false; stk.pop(); if (q.front() != v) is_queue = false; q.pop(); if (pq.top() != v) is_priority_queue = false; pq.pop(); } } } if (!is_stack && !is_queue && !is_priority_queue) { cout<<"impossible\n"; } else if ((is_stack && is_queue) || (is_stack && is_priority_queue) || (is_queue && is_priority_queue)) { cout<<"not sure\n"; } else if (is_stack) { cout<<"stack\n"; } else if (is_queue) { cout<<"queue\n"; } else { cout<<"priority queue\n"; } } return 0; } <|endoftext|>
<commit_before><commit_msg>[DF][Doc][NFC] Small fixes to DF docs<commit_after><|endoftext|>
<commit_before>/* * tut_xml_reporter.hpp * * ECOS Library. IPT CS R&D CET ECOS Copyright 2008 Nokia * Siemens Networks. All right * * */ #ifndef TUT_XML_REPORTER #define TUT_XML_REPORTER #include <tut/tut.hpp> #include <string> #include <fstream> #include <vector> #include <stdexcept> namespace tut { /** * \brief JUnit XML TUT reporter * @author Lukasz Maszczynski, NSN * @date 11/07/2008 */ class xml_reporter : public tut::callback { protected: typedef std::vector<tut::test_result> TestResults; typedef std::map<std::string, TestResults> TestGroups; TestGroups all_tests; /// holds all test results std::string filename; /// filename base /** * \brief Initializes object * Resets counters and clears all stored test results. */ virtual void init() { ok_count = 0; exceptions_count = 0; failures_count = 0; terminations_count = 0; warnings_count = 0; all_tests.clear(); } /** * \brief Encodes text to XML * XML-reserved characters (e.g. "<") are encoded according to specification * @param text text to be encoded * @return encoded string */ virtual std::string encode(const std::string & text) { std::string out; for (unsigned int i=0; i<text.length(); ++i) { char c = text[i]; switch (c) { case '<': out += "&lt;"; break; case '>': out += "&gt;"; break; case '&': out += "&amp;"; break; case '\'': out += "&apos;"; break; case '"': out += "&quot;"; break; default: out += c; } } return out; } /** * \brief Builds "testcase" XML entity with given parameters * Builds \<testcase\> entity according to given parameters. \<testcase\>-s are part of \<testsuite\>. * @param tr test result to be used as source data * @param failure_type type of failure to be reported ("Assertion" or "Error", empty if test passed) * @param failure_msg failure message to be reported (empty, if test passed) * @return string with \<testcase\> entity */ virtual std::string xml_build_testcase(const tut::test_result & tr, const std::string & failure_type, const std::string & failure_msg, int pid = 0) { using std::endl; using std::string; std::ostringstream out; if (tr.result == test_result::ok) { out << " <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\" />"; } else { string err_msg = encode(failure_msg + tr.message); string tag; // determines tag name: "failure" or "error" if ( tr.result == test_result::fail || tr.result == test_result::warn || tr.result == test_result::ex || tr.result == test_result::ex_ctor ) { tag = "failure"; } else { tag = "error"; } out << " <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\">" << endl; out << " <" << tag << " message=\"" << err_msg << "\"" << " type=\"" << failure_type << "\""; #if defined(TUT_USE_POSIX) if(pid != getpid()) { out << " child=\"" << pid << "\""; } #endif out << ">" << err_msg << "</" << tag << ">" << endl; out << " </testcase>"; } return out.str(); } /** * \brief Builds "testsuite" XML entity * Builds \<testsuite\> XML entity according to given parameters. * @param errors number of errors to be reported * @param failures number of failures to be reported * @param total total number of tests to be reported * @param name test suite name * @param testcases encoded XML string containing testcases * @return string with \<testsuite\> entity */ virtual std::string xml_build_testsuite(int errors, int failures, int total, const std::string & name, const std::string & testcases) { std::ostringstream out; out << "<testsuite errors=\"" << errors << "\" failures=\"" << failures << "\" tests=\"" << total << "\" name=\"" << encode(name) << "\">" << std::endl; out << testcases; out << "</testsuite>"; return out.str(); } public: int ok_count; /// number of passed tests int exceptions_count; /// number of tests that threw exceptions int failures_count; /// number of tests that failed int terminations_count; /// number of tests that would terminate int warnings_count; /// number of tests where destructors threw an exception /** * \brief Default constructor * @param filename base filename * @see setFilenameBase */ xml_reporter(const std::string & _filename = "") { init(); setFilenameBase(_filename); } /** * \brief Sets filename base for output * @param _filename filename base * Example usage: * @code * xml_reporter reporter; * reporter.setFilenameBase("my_xml"); * @endcode * The above code will instruct reporter to create my_xml_1.xml file for the first test group, * my_xml_2.xml file for the second, and so on. */ virtual void setFilenameBase(const std::string & _filename) { if (_filename == "") { filename = "testResult"; } else { if (_filename.length() > 200) { throw(std::runtime_error("Filename too long!")); } filename = _filename; } } /** * \brief Callback function * This function is called before the first test is executed. It initializes counters. */ virtual void run_started() { init(); } /** * \brief Callback function * This function is called when test completes. Counters are updated here, and test results stored. */ virtual void test_completed(const tut::test_result& tr) { // update global statistics switch (tr.result) { case test_result::ok: ok_count++; break; case test_result::fail: case test_result::rethrown: failures_count++; break; case test_result::ex: case test_result::ex_ctor: exceptions_count++; break; case test_result::warn: warnings_count++; break; case test_result::term: terminations_count++; break; } // switch // add test result to results table (all_tests[tr.group]).push_back(tr); } /** * \brief Callback function * This function is called when all tests are completed. It generates XML output * to file(s). File name base can be set with \ref setFilenameBase. */ virtual void run_completed() { using std::endl; using std::string; static int number = 1; // results file sequence number (testResult_<number>.xml) // iterate over all test groups TestGroups::const_iterator tgi; for (tgi = all_tests.begin(); tgi != all_tests.end(); ++tgi) { /* per-group statistics */ int passed = 0; // passed in single group int exceptions = 0; // exceptions in single group int failures = 0; // failures in single group int terminations = 0; // terminations in single group int warnings = 0; // warnings in single group int errors = 0; // errors in single group /* generate output filename */ char fn[256]; sprintf(fn, "%s_%d.xml", filename.c_str(), number++); std::ofstream xmlfile; xmlfile.open(fn, std::ios::in | std::ios::trunc); if (!xmlfile.is_open()) { throw (std::runtime_error("Cannot open file for output")); } /* *********************** header ***************************** */ xmlfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; // output is written to string stream buffer, because JUnit format <testsuite> tag // contains statistics, which aren't known yet std::ostringstream out; // iterate over all test cases in the current test group TestResults::const_iterator tri; for (tri = (*tgi).second.begin(); tri != (*tgi).second.end(); ++tri) { string failure_type; // string describing the failure type string failure_msg; // a string with failure message switch ((*tri).result) { case test_result::ok: passed++; break; case test_result::fail: failure_type = "Assertion"; failure_msg = ""; failures++; break; case test_result::ex: failure_type = "Assertion"; failure_msg = "Thrown exception: " + (*tri).exception_typeid + '\n'; exceptions++; break; case test_result::warn: failure_type = "Assertion"; failure_msg = "Destructor failed.\n"; warnings++; break; case test_result::term: failure_type = "Error"; failure_msg = "Test application terminated abnormally.\n"; terminations++; break; case test_result::ex_ctor: failure_type = "Assertion"; failure_msg = "Constructor has thrown an exception: " + (*tri).exception_typeid + '\n'; exceptions++; break; case test_result::rethrown: failure_type = "Assertion"; failure_msg = "Child failed"; failures++; break; default: failure_type = "Error"; failure_msg = "Unknown test status, this should have never happened. " "You may just have found a BUG in TUT XML reporter, please report it immediately.\n"; errors++; break; } // switch #if defined(TUT_USE_POSIX) out << xml_build_testcase(*tri, failure_type, failure_msg, (*tri).pid) << endl; #else out << xml_build_testcase(*tri, failure_type, failure_msg) << endl; #endif } // iterate over all test cases // calculate per-group statistics int stat_errors = terminations + errors; int stat_failures = failures + warnings + exceptions; int stat_all = stat_errors + stat_failures + passed; xmlfile << xml_build_testsuite(stat_errors, stat_failures, stat_all, (*tgi).first/* name */, out.str()/* testcases */) << endl; xmlfile.close(); } // iterate over all test groups } /** * \brief Returns true, if all tests passed */ virtual bool all_ok() const { return ( (terminations_count + failures_count + warnings_count + exceptions_count) == 0); }; }; } #endif <commit_msg>Added tr::dummy to xml_reporter (thanks [email protected])<commit_after>/* * tut_xml_reporter.hpp * * ECOS Library. IPT CS R&D CET ECOS Copyright 2008 Nokia * Siemens Networks. All right * * */ #ifndef TUT_XML_REPORTER #define TUT_XML_REPORTER #include <tut/tut.hpp> #include <string> #include <fstream> #include <vector> #include <stdexcept> namespace tut { /** * \brief JUnit XML TUT reporter * @author Lukasz Maszczynski, NSN * @date 11/07/2008 */ class xml_reporter : public tut::callback { protected: typedef std::vector<tut::test_result> TestResults; typedef std::map<std::string, TestResults> TestGroups; TestGroups all_tests; /// holds all test results std::string filename; /// filename base /** * \brief Initializes object * Resets counters and clears all stored test results. */ virtual void init() { ok_count = 0; exceptions_count = 0; failures_count = 0; terminations_count = 0; warnings_count = 0; all_tests.clear(); } /** * \brief Encodes text to XML * XML-reserved characters (e.g. "<") are encoded according to specification * @param text text to be encoded * @return encoded string */ virtual std::string encode(const std::string & text) { std::string out; for (unsigned int i=0; i<text.length(); ++i) { char c = text[i]; switch (c) { case '<': out += "&lt;"; break; case '>': out += "&gt;"; break; case '&': out += "&amp;"; break; case '\'': out += "&apos;"; break; case '"': out += "&quot;"; break; default: out += c; } } return out; } /** * \brief Builds "testcase" XML entity with given parameters * Builds \<testcase\> entity according to given parameters. \<testcase\>-s are part of \<testsuite\>. * @param tr test result to be used as source data * @param failure_type type of failure to be reported ("Assertion" or "Error", empty if test passed) * @param failure_msg failure message to be reported (empty, if test passed) * @return string with \<testcase\> entity */ virtual std::string xml_build_testcase(const tut::test_result & tr, const std::string & failure_type, const std::string & failure_msg, int pid = 0) { using std::endl; using std::string; std::ostringstream out; if (tr.result == test_result::ok) { out << " <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\" />"; } else { string err_msg = encode(failure_msg + tr.message); string tag; // determines tag name: "failure" or "error" if ( tr.result == test_result::fail || tr.result == test_result::warn || tr.result == test_result::ex || tr.result == test_result::ex_ctor ) { tag = "failure"; } else { tag = "error"; } out << " <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\">" << endl; out << " <" << tag << " message=\"" << err_msg << "\"" << " type=\"" << failure_type << "\""; #if defined(TUT_USE_POSIX) if(pid != getpid()) { out << " child=\"" << pid << "\""; } #endif out << ">" << err_msg << "</" << tag << ">" << endl; out << " </testcase>"; } return out.str(); } /** * \brief Builds "testsuite" XML entity * Builds \<testsuite\> XML entity according to given parameters. * @param errors number of errors to be reported * @param failures number of failures to be reported * @param total total number of tests to be reported * @param name test suite name * @param testcases encoded XML string containing testcases * @return string with \<testsuite\> entity */ virtual std::string xml_build_testsuite(int errors, int failures, int total, const std::string & name, const std::string & testcases) { std::ostringstream out; out << "<testsuite errors=\"" << errors << "\" failures=\"" << failures << "\" tests=\"" << total << "\" name=\"" << encode(name) << "\">" << std::endl; out << testcases; out << "</testsuite>"; return out.str(); } public: int ok_count; /// number of passed tests int exceptions_count; /// number of tests that threw exceptions int failures_count; /// number of tests that failed int terminations_count; /// number of tests that would terminate int warnings_count; /// number of tests where destructors threw an exception /** * \brief Default constructor * @param filename base filename * @see setFilenameBase */ xml_reporter(const std::string & _filename = "") { init(); setFilenameBase(_filename); } /** * \brief Sets filename base for output * @param _filename filename base * Example usage: * @code * xml_reporter reporter; * reporter.setFilenameBase("my_xml"); * @endcode * The above code will instruct reporter to create my_xml_1.xml file for the first test group, * my_xml_2.xml file for the second, and so on. */ virtual void setFilenameBase(const std::string & _filename) { if (_filename == "") { filename = "testResult"; } else { if (_filename.length() > 200) { throw(std::runtime_error("Filename too long!")); } filename = _filename; } } /** * \brief Callback function * This function is called before the first test is executed. It initializes counters. */ virtual void run_started() { init(); } /** * \brief Callback function * This function is called when test completes. Counters are updated here, and test results stored. */ virtual void test_completed(const tut::test_result& tr) { // update global statistics switch (tr.result) { case test_result::ok: ok_count++; break; case test_result::fail: case test_result::rethrown: failures_count++; break; case test_result::ex: case test_result::ex_ctor: exceptions_count++; break; case test_result::warn: warnings_count++; break; case test_result::term: terminations_count++; break; case tut::test_result::dummy: assert(!"Should never be called"); } // switch // add test result to results table (all_tests[tr.group]).push_back(tr); } /** * \brief Callback function * This function is called when all tests are completed. It generates XML output * to file(s). File name base can be set with \ref setFilenameBase. */ virtual void run_completed() { using std::endl; using std::string; static int number = 1; // results file sequence number (testResult_<number>.xml) // iterate over all test groups TestGroups::const_iterator tgi; for (tgi = all_tests.begin(); tgi != all_tests.end(); ++tgi) { /* per-group statistics */ int passed = 0; // passed in single group int exceptions = 0; // exceptions in single group int failures = 0; // failures in single group int terminations = 0; // terminations in single group int warnings = 0; // warnings in single group int errors = 0; // errors in single group /* generate output filename */ char fn[256]; sprintf(fn, "%s_%d.xml", filename.c_str(), number++); std::ofstream xmlfile; xmlfile.open(fn, std::ios::in | std::ios::trunc); if (!xmlfile.is_open()) { throw (std::runtime_error("Cannot open file for output")); } /* *********************** header ***************************** */ xmlfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; // output is written to string stream buffer, because JUnit format <testsuite> tag // contains statistics, which aren't known yet std::ostringstream out; // iterate over all test cases in the current test group TestResults::const_iterator tri; for (tri = (*tgi).second.begin(); tri != (*tgi).second.end(); ++tri) { string failure_type; // string describing the failure type string failure_msg; // a string with failure message switch ((*tri).result) { case test_result::ok: passed++; break; case test_result::fail: failure_type = "Assertion"; failure_msg = ""; failures++; break; case test_result::ex: failure_type = "Assertion"; failure_msg = "Thrown exception: " + (*tri).exception_typeid + '\n'; exceptions++; break; case test_result::warn: failure_type = "Assertion"; failure_msg = "Destructor failed.\n"; warnings++; break; case test_result::term: failure_type = "Error"; failure_msg = "Test application terminated abnormally.\n"; terminations++; break; case test_result::ex_ctor: failure_type = "Assertion"; failure_msg = "Constructor has thrown an exception: " + (*tri).exception_typeid + '\n'; exceptions++; break; case test_result::rethrown: failure_type = "Assertion"; failure_msg = "Child failed"; failures++; break; default: failure_type = "Error"; failure_msg = "Unknown test status, this should have never happened. " "You may just have found a BUG in TUT XML reporter, please report it immediately.\n"; errors++; break; } // switch #if defined(TUT_USE_POSIX) out << xml_build_testcase(*tri, failure_type, failure_msg, (*tri).pid) << endl; #else out << xml_build_testcase(*tri, failure_type, failure_msg) << endl; #endif } // iterate over all test cases // calculate per-group statistics int stat_errors = terminations + errors; int stat_failures = failures + warnings + exceptions; int stat_all = stat_errors + stat_failures + passed; xmlfile << xml_build_testsuite(stat_errors, stat_failures, stat_all, (*tgi).first/* name */, out.str()/* testcases */) << endl; xmlfile.close(); } // iterate over all test groups } /** * \brief Returns true, if all tests passed */ virtual bool all_ok() const { return ( (terminations_count + failures_count + warnings_count + exceptions_count) == 0); }; }; } #endif <|endoftext|>
<commit_before> // Simple macro showing capabilities of TGSpeedo widget. //Author: Bertrand Bellenot #include "TSystem.h" #include "TGFrame.h" #include "TGWindow.h" #include "TGSpeedo.h" class TGShapedMain : public TGMainFrame { protected: const TGPicture *fBgnd; // picture used as mask TGSpeedo *fSpeedo; // analog meter TTimer *fTimer; // update timer Int_t fActInfo; // actual information value public: TGShapedMain(const TGWindow *p, int w, int h); virtual ~TGShapedMain(); void CloseWindow(); TGSpeedo *GetSpeedo() const { return fSpeedo; } Int_t GetActInfo() const { return fActInfo; } void ToggleInfos(); ClassDef(TGShapedMain, 0) }; // globals TGShapedMain *gMainWindow; TGSpeedo *gSpeedo; Float_t prev_load; Int_t old_memUsage; //______________________________________________________________________________ TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) : TGMainFrame(p, w, h) { // Constructor. fActInfo = 1; fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]"); fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()"); fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()"); Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()"); AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0)); fSpeedo->SetDisplayText("Used RAM", "[MB]"); fTimer = new TTimer(100); fTimer->SetCommand("Update()"); fBgnd = fSpeedo->GetPicture(); gVirtualX->ShapeCombineMask(GetId(), 0, 0, fBgnd->GetMask()); SetBackgroundPixmap(fBgnd->GetPicture()); SetWMSizeHints(fBgnd->GetWidth(), fBgnd->GetHeight(), fBgnd->GetWidth(), fBgnd->GetHeight(), 1, 1); MapSubwindows(); MapWindow(); // To avoid closing the window while TGSpeedo is drawing DontCallClose(); // To avoid closing the window while TGSpeedo is drawing Resize(GetDefaultSize()); // Set fixed size SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1); SetWindowName("ROOT CPU Load Meter"); fTimer->TurnOn(); } //______________________________________________________________________________ void TGShapedMain::ToggleInfos() { // Toggle information displayed in Analog Meter if (fActInfo < 2) fActInfo++; else fActInfo = 0; if (fActInfo == 0) fSpeedo->SetDisplayText("Total RAM", "[MB]"); else if (fActInfo == 1) fSpeedo->SetDisplayText("Used RAM", "[MB]"); else if (fActInfo == 2) fSpeedo->SetDisplayText("Free RAM", "[MB]"); } //______________________________________________________________________________ TGShapedMain::~TGShapedMain() { // Destructor. } //______________________________________________________________________________ void TGShapedMain::CloseWindow() { // Close Window. if (fTimer) fTimer->TurnOff(); delete fTimer; delete fSpeedo; delete this; } void Update() { MemInfo_t memInfo; CpuInfo_t cpuInfo; Float_t act_load = 0.0; Int_t memUsage = 0; prev_load = act_load; old_memUsage = memUsage; // Get CPU informations gSystem->GetCpuInfo(&cpuInfo, 100); // actual CPU load act_load = cpuInfo.fTotal; // Get Memory informations gSystem->GetMemInfo(&memInfo); // choose which value to display if (gMainWindow->GetActInfo() == 0) memUsage = memInfo.fMemTotal; else if (gMainWindow->GetActInfo() == 1) memUsage = memInfo.fMemUsed; else if (gMainWindow->GetActInfo() == 2) memUsage = memInfo.fMemFree; // small threshold to avoid "trembling" needle if (fabs(act_load-prev_load) > 0.9) { gSpeedo->SetScaleValue(act_load, 10); prev_load = act_load; } // update only if value has changed if (memUsage != old_memUsage) { gSpeedo->SetOdoValue(memUsage); old_memUsage = memUsage; } } //______________________________________________________________________________ void CPUMeter() { // Main application. gMainWindow = new TGShapedMain(0, 500, 200); gSpeedo = gMainWindow->GetSpeedo(); // set threshold values gSpeedo->SetThresholds(12.5, 50.0, 87.5); // set threshold colors gSpeedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed); // enable threshold gSpeedo->EnableThreshold(); gSpeedo->SetScaleValue(0.0, 5); // enable peak marker gSpeedo->EnablePeakMark(); } <commit_msg>From Bertrand: Fixed errors reported by valgrind (slc4/ia32) and purify (win32).<commit_after> // Simple macro showing capabilities of TGSpeedo widget. //Author: Bertrand Bellenot #include "TSystem.h" #include "TGFrame.h" #include "TGWindow.h" #include "TGSpeedo.h" class TGShapedMain : public TGMainFrame { protected: const TGPicture *fBgnd; // picture used as mask TGSpeedo *fSpeedo; // analog meter TTimer *fTimer; // update timer Int_t fActInfo; // actual information value public: TGShapedMain(const TGWindow *p, int w, int h); virtual ~TGShapedMain(); void CloseWindow(); TGSpeedo *GetSpeedo() const { return fSpeedo; } Int_t GetActInfo() const { return fActInfo; } void ToggleInfos(); ClassDef(TGShapedMain, 0) }; // globals TGShapedMain *gMainWindow; TGSpeedo *gSpeedo; Float_t prev_load; Int_t old_memUsage; //______________________________________________________________________________ TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) : TGMainFrame(p, w, h) { // Constructor. fActInfo = 1; fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]"); fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()"); fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()"); Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()"); AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0)); fSpeedo->SetDisplayText("Used RAM", "[MB]"); fTimer = new TTimer(100); fTimer->SetCommand("Update()"); fBgnd = fSpeedo->GetPicture(); gVirtualX->ShapeCombineMask(GetId(), 0, 0, fBgnd->GetMask()); SetBackgroundPixmap(fBgnd->GetPicture()); SetWMSizeHints(fBgnd->GetWidth(), fBgnd->GetHeight(), fBgnd->GetWidth(), fBgnd->GetHeight(), 1, 1); MapSubwindows(); MapWindow(); // To avoid closing the window while TGSpeedo is drawing DontCallClose(); // To avoid closing the window while TGSpeedo is drawing Resize(GetDefaultSize()); // Set fixed size SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1); SetWindowName("ROOT CPU Load Meter"); fTimer->TurnOn(); } //______________________________________________________________________________ void TGShapedMain::ToggleInfos() { // Toggle information displayed in Analog Meter if (fActInfo < 2) fActInfo++; else fActInfo = 0; if (fActInfo == 0) fSpeedo->SetDisplayText("Total RAM", "[MB]"); else if (fActInfo == 1) fSpeedo->SetDisplayText("Used RAM", "[MB]"); else if (fActInfo == 2) fSpeedo->SetDisplayText("Free RAM", "[MB]"); } //______________________________________________________________________________ TGShapedMain::~TGShapedMain() { // Destructor. delete fTimer; delete fSpeedo; } //______________________________________________________________________________ void TGShapedMain::CloseWindow() { // Close Window. if (fTimer) fTimer->TurnOff(); DestroyWindow(); } void Update() { MemInfo_t memInfo; CpuInfo_t cpuInfo; Float_t act_load = 0.0; Int_t memUsage = 0; prev_load = act_load; old_memUsage = memUsage; // Get CPU informations gSystem->GetCpuInfo(&cpuInfo, 100); // actual CPU load act_load = cpuInfo.fTotal; // Get Memory informations gSystem->GetMemInfo(&memInfo); // choose which value to display if (gMainWindow->GetActInfo() == 0) memUsage = memInfo.fMemTotal; else if (gMainWindow->GetActInfo() == 1) memUsage = memInfo.fMemUsed; else if (gMainWindow->GetActInfo() == 2) memUsage = memInfo.fMemFree; // small threshold to avoid "trembling" needle if (fabs(act_load-prev_load) > 0.9) { gSpeedo->SetScaleValue(act_load, 10); prev_load = act_load; } // update only if value has changed if (memUsage != old_memUsage) { gSpeedo->SetOdoValue(memUsage); old_memUsage = memUsage; } } //______________________________________________________________________________ void CPUMeter() { // Main application. gMainWindow = new TGShapedMain(0, 500, 200); gSpeedo = gMainWindow->GetSpeedo(); // set threshold values gSpeedo->SetThresholds(12.5, 50.0, 87.5); // set threshold colors gSpeedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed); // enable threshold gSpeedo->EnableThreshold(); gSpeedo->SetScaleValue(0.0, 5); // enable peak marker gSpeedo->EnablePeakMark(); } <|endoftext|>
<commit_before>/* * http://github.com/dusty-nv/jetson-inference */ // #include "gstCamera.h" #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <chrono> #include <jetson-inference/cudaMappedMemory.h> #include <jetson-inference/cudaNormalize.h> #include <jetson-inference/cudaFont.h> #include <jetson-inference/imageNet.h> #define DEFAULT_CAMERA -1 // -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0) using namespace std; bool signal_recieved = false; //void sig_handler(int signo) //{ //if( signo == SIGINT ) //{ //printf("received SIGINT\n"); //signal_recieved = true; //} //} static const std::string OPENCV_WINDOW = "Image post bridge conversion"; static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion"; static const std::string OPENCV_WINDOW3 = "Image post color conversion"; static const std::string OPENCV_WINDOW4 = "Image window"; class ObjectClassifier { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; cv::Mat cv_im; cv_bridge::CvImagePtr cv_ptr; std::chrono::steady_clock::time_point prev; float confidence = 0.0f; //float* bbCPU = NULL; //float* bbCUDA = NULL; //float* confCPU = NULL; //float* confCUDA = NULL; imageNet* net = NULL; //detectNet* net = NULL; //uint32_t maxBoxes = 0; //uint32_t classes = 0; float4* gpu_data = NULL; uint32_t imgWidth; uint32_t imgHeight; size_t imgSize; public: ObjectClassifier(int argc, char** argv ) : it_(nh_) { cout << "start constructor" << endl; // Subscrive to input video feed and publish output video feed image_sub_ = it_.subscribe("/left/image_rect_color", 2, &ObjectClassifier::imageCb, this); cv::namedWindow(OPENCV_WINDOW); cout << "Named a window" << endl; prev = std::chrono::steady_clock::now(); // create imageNet // net = imageNet::Create(prototxt_path.c_str(),model_path.c_str(),NULL,class_labels_path.c_str()); net = imageNet::Create(argc, argv ); /* * create detectNet */ //net = detectNet::Create(argc, argv); //cout << "Created DetectNet" << endl; if( !net ) { printf("obj_detect: failed to initialize imageNet\n"); } //maxBoxes = net->GetMaxBoundingBoxes(); //printf("maximum bounding boxes: %u\n", maxBoxes); //classes = net->GetNumClasses(); ///* //* allocate memory for output bounding boxes and class confidence //*/ //if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) || //!cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) ) //{ //printf("detectnet-console: failed to alloc output memory\n"); //} //cout << "Allocated CUDA mem" << endl; //maxBoxes = net->GetMaxBoundingBoxes(); //printf("maximum bounding boxes: %u\n", maxBoxes); //classes = net->GetNumClasses(); //cout << "Constructor operations complete" << endl; } ~ObjectClassifier() { cv::destroyWindow(OPENCV_WINDOW); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); cv_im = cv_ptr->image; cv_im.convertTo(cv_im,CV_32FC3); // convert color cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // allocate GPU data if necessary if(!gpu_data){ ROS_INFO("first allocation"); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); }else if(imgHeight != cv_im.rows || imgWidth != cv_im.cols){ ROS_INFO("re allocation"); // reallocate for a new image size if necessary CUDA(cudaFree(gpu_data)); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } imgHeight = cv_im.rows; imgWidth = cv_im.cols; imgSize = cv_im.rows*cv_im.cols * sizeof(float4); float4* cpu_data = (float4*)(cv_im.data); // copy to device CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice)); void* imgCUDA = NULL; // classify image const int img_class = net->Classify((float*)gpu_data, imgWidth, imgHeight, &confidence); // find class string std::string class_name; class_name = net->GetClassDesc(img_class); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); float fps = 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(now - prev).count() ; prev = now; char str[256]; sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", fps); cv::setWindowTitle(OPENCV_WINDOW, str); // update image back to original cv_im.convertTo(cv_im,CV_8UC3); cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR); // draw class string cv::putText(cv_im, class_name, cv::Point(60,60), cv::FONT_HERSHEY_PLAIN, 3.0, cv::Scalar(0,0,255),3); // Update GUI Window cv::imshow(OPENCV_WINDOW, cv_im); cv::waitKey(1); } }; int main( int argc, char** argv ) { cout << "starting node" << endl; printf("obj_classifier\n args (%i): ", argc); ros::init(argc, argv, "obj_detector"); ros::NodeHandle nh; for( int i=0; i < argc; i++ ) printf("%i [%s] ", i, argv[i]); printf("\n\n"); ObjectClassifier ic(argc, argv); ros::spin(); return 0; } <commit_msg>change classifier to subscribe to topic coming through on obj_detector<commit_after>/* * http://github.com/dusty-nv/jetson-inference */ // #include "gstCamera.h" #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <chrono> #include <jetson-inference/cudaMappedMemory.h> #include <jetson-inference/cudaNormalize.h> #include <jetson-inference/cudaFont.h> #include <jetson-inference/imageNet.h> #define DEFAULT_CAMERA -1 // -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0) using namespace std; bool signal_recieved = false; //void sig_handler(int signo) //{ //if( signo == SIGINT ) //{ //printf("received SIGINT\n"); //signal_recieved = true; //} //} static const std::string OPENCV_WINDOW = "Image post bridge conversion"; static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion"; static const std::string OPENCV_WINDOW3 = "Image post color conversion"; static const std::string OPENCV_WINDOW4 = "Image window"; class ObjectClassifier { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; cv::Mat cv_im; cv_bridge::CvImagePtr cv_ptr; std::chrono::steady_clock::time_point prev; float confidence = 0.0f; //float* bbCPU = NULL; //float* bbCUDA = NULL; //float* confCPU = NULL; //float* confCUDA = NULL; imageNet* net = NULL; //detectNet* net = NULL; //uint32_t maxBoxes = 0; //uint32_t classes = 0; float4* gpu_data = NULL; uint32_t imgWidth; uint32_t imgHeight; size_t imgSize; public: ObjectClassifier(int argc, char** argv ) : it_(nh_) { cout << "start constructor" << endl; // Subscrive to input video feed and publish output video feed //image_sub_ = it_.subscribe("/left/image_rect_color", 2, //&ObjectClassifier::imageCb, this); image_sub_ = it_.subscribe("/detected_image", 2, &ObjectClassifier::imageCb, this); cv::namedWindow(OPENCV_WINDOW); cout << "Named a window" << endl; prev = std::chrono::steady_clock::now(); // create imageNet // net = imageNet::Create(prototxt_path.c_str(),model_path.c_str(),NULL,class_labels_path.c_str()); net = imageNet::Create(argc, argv ); /* * create detectNet */ //net = detectNet::Create(argc, argv); //cout << "Created DetectNet" << endl; if( !net ) { printf("obj_detect: failed to initialize imageNet\n"); } //maxBoxes = net->GetMaxBoundingBoxes(); //printf("maximum bounding boxes: %u\n", maxBoxes); //classes = net->GetNumClasses(); ///* //* allocate memory for output bounding boxes and class confidence //*/ //if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) || //!cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) ) //{ //printf("detectnet-console: failed to alloc output memory\n"); //} //cout << "Allocated CUDA mem" << endl; //maxBoxes = net->GetMaxBoundingBoxes(); //printf("maximum bounding boxes: %u\n", maxBoxes); //classes = net->GetNumClasses(); //cout << "Constructor operations complete" << endl; } ~ObjectClassifier() { cv::destroyWindow(OPENCV_WINDOW); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); cv_im = cv_ptr->image; cv_im.convertTo(cv_im,CV_32FC3); // convert color cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // allocate GPU data if necessary if(!gpu_data){ ROS_INFO("first allocation"); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); }else if(imgHeight != cv_im.rows || imgWidth != cv_im.cols){ ROS_INFO("re allocation"); // reallocate for a new image size if necessary CUDA(cudaFree(gpu_data)); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } imgHeight = cv_im.rows; imgWidth = cv_im.cols; imgSize = cv_im.rows*cv_im.cols * sizeof(float4); float4* cpu_data = (float4*)(cv_im.data); // copy to device CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice)); void* imgCUDA = NULL; // classify image const int img_class = net->Classify((float*)gpu_data, imgWidth, imgHeight, &confidence); // find class string std::string class_name; class_name = net->GetClassDesc(img_class); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); float fps = 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(now - prev).count() ; prev = now; char str[256]; sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", fps); cv::setWindowTitle(OPENCV_WINDOW, str); // update image back to original cv_im.convertTo(cv_im,CV_8UC3); cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR); // draw class string cv::putText(cv_im, class_name, cv::Point(60,60), cv::FONT_HERSHEY_PLAIN, 3.0, cv::Scalar(0,0,255),3); // Update GUI Window cv::imshow(OPENCV_WINDOW, cv_im); cv::waitKey(1); } }; int main( int argc, char** argv ) { cout << "starting node" << endl; printf("obj_classifier\n args (%i): ", argc); ros::init(argc, argv, "obj_detector"); ros::NodeHandle nh; for( int i=0; i < argc; i++ ) printf("%i [%s] ", i, argv[i]); printf("\n\n"); ObjectClassifier ic(argc, argv); ros::spin(); return 0; } <|endoftext|>
<commit_before>#pragma once #include <af/defines.h> #include <kernel_headers/tile.hpp> #include <cl.hpp> #include <ctx.hpp> #include <traits.hpp> #include <helper.hpp> #include <sstream> #include <string> #include <dispatch.hpp> typedef struct { dim_type dims[4]; } dims_t; using cl::Buffer; using cl::Program; using cl::Kernel; using cl::make_kernel; using cl::EnqueueArgs; using cl::NDRange; using std::string; namespace opencl { namespace kernel { // Kernel Launch Config Values static const dim_type TX = 32; static const dim_type TY = 8; static const dim_type TILEX = 512; static const dim_type TILEY = 32; template<typename T> void tile(Buffer out, const Buffer in, const dim_type *odims, const dim_type *idims, const dim_type *ostrides, const dim_type *istrides, const dim_type offset) { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static Program tileProgs[DeviceManager::MAX_DEVICES]; static Kernel tileKernels[DeviceManager::MAX_DEVICES]; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { Program::Sources setSrc; setSrc.emplace_back(transpose_cl, transpose_cl_len); tileProgs[device] = Program(getContext(), setSrc); std::ostringstream options; options << " -D T=" << dtype_traits<T>::getName() << " -D dim_type=" << dtype_traits<dim_type>::getName() << " -D TILE_DIM=" << TILE_DIM; tileProgs[device].build(options.str().c_str()); tileKernels[device] = Kernel(tileProgs[device], "transpose"); }); auto tileOp = make_kernel<Buffer, const Buffer, const dims_t, const dims_t, const dims_t, const dims_t, const dim_type, const unsigned, const unsigned> (tileKernels[device]); NDRange local(TX, TY, 1); unsigned blocksPerMatX = divup(odims[0], TILEX); unsigned blocksPerMatY = divup(odims[1], TILEY); NDRange global(local[0] * blocksPerMatX * odims[2], local[1] * blocksPerMatY * odims[3], 1); dims_t _odims = {{odims[0], odims[1], odims[2], odims[3]}}; dims_t _idims = {{idims[0], idims[1], idims[2], idims[3]}}; dims_t _ostrides = {{ostrides[0], ostrides[1], ostrides[2], ostrides[3]}}; dims_t _istrides = {{istrides[0], istrides[1], istrides[2], istrides[3]}}; tileOp(EnqueueArgs(getQueue(0), global, local), out, in, _odims, _idims, _ostrides, _istrides, offset, blocksPerMatX, blocksPerMatY); } } } <commit_msg>Fixing copy paste error<commit_after>#pragma once #include <af/defines.h> #include <kernel_headers/tile.hpp> #include <cl.hpp> #include <platform.hpp> #include <traits.hpp> #include <helper.hpp> #include <sstream> #include <string> #include <dispatch.hpp> typedef struct { dim_type dims[4]; } dims_t; using cl::Buffer; using cl::Program; using cl::Kernel; using cl::make_kernel; using cl::EnqueueArgs; using cl::NDRange; using std::string; namespace opencl { namespace kernel { // Kernel Launch Config Values static const dim_type TX = 32; static const dim_type TY = 8; static const dim_type TILEX = 512; static const dim_type TILEY = 32; template<typename T> void tile(Buffer out, const Buffer in, const dim_type *odims, const dim_type *idims, const dim_type *ostrides, const dim_type *istrides, const dim_type offset) { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static Program tileProgs[DeviceManager::MAX_DEVICES]; static Kernel tileKernels[DeviceManager::MAX_DEVICES]; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { Program::Sources setSrc; setSrc.emplace_back(tile_cl, tile_cl_len); tileProgs[device] = Program(getContext(), setSrc); std::ostringstream options; options << " -D T=" << dtype_traits<T>::getName() << " -D dim_type=" << dtype_traits<dim_type>::getName(); tileProgs[device].build(options.str().c_str()); tileKernels[device] = Kernel(tileProgs[device], "tile_kernel"); }); auto tileOp = make_kernel<Buffer, const Buffer, const dims_t, const dims_t, const dims_t, const dims_t, const dim_type, const unsigned, const unsigned> (tileKernels[device]); NDRange local(TX, TY, 1); unsigned blocksPerMatX = divup(odims[0], TILEX); unsigned blocksPerMatY = divup(odims[1], TILEY); NDRange global(local[0] * blocksPerMatX * odims[2], local[1] * blocksPerMatY * odims[3], 1); dims_t _odims = {{odims[0], odims[1], odims[2], odims[3]}}; dims_t _idims = {{idims[0], idims[1], idims[2], idims[3]}}; dims_t _ostrides = {{ostrides[0], ostrides[1], ostrides[2], ostrides[3]}}; dims_t _istrides = {{istrides[0], istrides[1], istrides[2], istrides[3]}}; tileOp(EnqueueArgs(getQueue(), global, local), out, in, _odims, _idims, _ostrides, _istrides, offset, blocksPerMatX, blocksPerMatY); } } } <|endoftext|>