hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
70e7b889c539f5c96bd117e38e3670c378800b0f
1,771
cpp
C++
CK2ToEU4Tests/MapperTests/PrimaryTagMapper/PrimaryTagMapperTests.cpp
Osariusz/CK2ToEU4
a2786f00febb23c63f91b2ff27b788f926e18ea7
[ "MIT" ]
29
2020-04-05T21:27:46.000Z
2021-08-29T20:24:21.000Z
CK2ToEU4Tests/MapperTests/PrimaryTagMapper/PrimaryTagMapperTests.cpp
Osariusz/CK2ToEU4
a2786f00febb23c63f91b2ff27b788f926e18ea7
[ "MIT" ]
66
2020-03-31T00:29:00.000Z
2022-03-02T11:54:24.000Z
CK2ToEU4Tests/MapperTests/PrimaryTagMapper/PrimaryTagMapperTests.cpp
Osariusz/CK2ToEU4
a2786f00febb23c63f91b2ff27b788f926e18ea7
[ "MIT" ]
27
2020-03-30T15:56:24.000Z
2022-02-05T22:54:25.000Z
#include "../../CK2ToEU4/Source/Mappers/PrimaryTagMapper/PrimaryTagMapper.h" #include "gtest/gtest.h" #include <sstream> TEST(Mappers_PrimaryTagMapperTests, CultureTagsDefaultToEmpty) { std::stringstream input; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_TRUE(tagMapper.getCultureTags().empty()); } TEST(Mappers_PrimaryTagMapperTests, CultureTagsCanBeLoaded) { std::stringstream input; input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n"; input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n"; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_EQ(tagMapper.getCultureTags().size(), 4); } TEST(Mappers_PrimaryTagMapperTests, TagMapperReturnsNullOnMiss) { std::stringstream input; input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n"; input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n"; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_FALSE(tagMapper.getPrimaryTagForCulture("culture2")); ASSERT_FALSE(tagMapper.getPrimaryTagForCulture("culture5")); } TEST(Mappers_PrimaryTagMapperTests, TagMapperReturnsTagOnHit) { std::stringstream input; input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n"; input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n"; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture1"), "TAG"); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture3"), "GAT"); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture4"), "GAT"); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture6"), "GOT"); }
37.680851
95
0.730661
Osariusz
70e8a394f69e965052d99400f9b6c850f92adae1
11,805
cpp
C++
SymbolExtractorAndRenamer/lldb/source/Core/DataBufferMemoryMap.cpp
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/lldb/source/Core/DataBufferMemoryMap.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/lldb/source/Core/DataBufferMemoryMap.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//===-- DataBufferMemoryMap.cpp ---------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes #include <fcntl.h> #include <sys/stat.h> #ifdef _WIN32 #include "lldb/Host/windows/windows.h" #else #include <sys/mman.h> #define MAP_EXTRA_HOST_READ_FLAGS 0 #if defined(__APPLE__) //---------------------------------------------------------------------- // Newer versions of MacOSX have a flag that will allow us to read from // binaries whose code signature is invalid without crashing by using // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media // is mapped we can avoid crashing and return zeroes to any pages we try // to read if the media becomes unavailable by using the // MAP_RESILIENT_MEDIA flag. //---------------------------------------------------------------------- #if defined(MAP_RESILIENT_CODESIGN) #undef MAP_EXTRA_HOST_READ_FLAGS #if defined(MAP_RESILIENT_MEDIA) #define MAP_EXTRA_HOST_READ_FLAGS MAP_RESILIENT_CODESIGN | MAP_RESILIENT_MEDIA #else #define MAP_EXTRA_HOST_READ_FLAGS MAP_RESILIENT_CODESIGN #endif #endif // #if defined(MAP_RESILIENT_CODESIGN) #endif // #if defined (__APPLE__) #endif // #else #ifdef _WIN32 // C++ Includes #include <cerrno> #include <climits> // Other libraries and framework includes #include "llvm/Support/MathExtras.h" // Project includes #include "lldb/Core/DataBufferMemoryMap.h" #include "lldb/Core/Error.h" #include "lldb/Core/Log.h" #include "lldb/Host/File.h" #include "lldb/Host/FileSpec.h" #include "lldb/Host/HostInfo.h" using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // Default Constructor //---------------------------------------------------------------------- DataBufferMemoryMap::DataBufferMemoryMap() : m_mmap_addr(nullptr), m_mmap_size(0), m_data(nullptr), m_size(0) {} //---------------------------------------------------------------------- // Virtual destructor since this class inherits from a pure virtual // base class. //---------------------------------------------------------------------- DataBufferMemoryMap::~DataBufferMemoryMap() { Clear(); } //---------------------------------------------------------------------- // Return a pointer to the bytes owned by this object, or nullptr if // the object contains no bytes. //---------------------------------------------------------------------- uint8_t *DataBufferMemoryMap::GetBytes() { return m_data; } //---------------------------------------------------------------------- // Return a const pointer to the bytes owned by this object, or nullptr // if the object contains no bytes. //---------------------------------------------------------------------- const uint8_t *DataBufferMemoryMap::GetBytes() const { return m_data; } //---------------------------------------------------------------------- // Return the number of bytes this object currently contains. //---------------------------------------------------------------------- uint64_t DataBufferMemoryMap::GetByteSize() const { return m_size; } //---------------------------------------------------------------------- // Reverts this object to an empty state by unmapping any memory // that is currently owned. //---------------------------------------------------------------------- void DataBufferMemoryMap::Clear() { if (m_mmap_addr != nullptr) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MMAP)); if (log) log->Printf("DataBufferMemoryMap::Clear() m_mmap_addr = %p, m_mmap_size " "= %" PRIu64 "", (void *)m_mmap_addr, (uint64_t)m_mmap_size); #ifdef _WIN32 UnmapViewOfFile(m_mmap_addr); #else ::munmap((void *)m_mmap_addr, m_mmap_size); #endif m_mmap_addr = nullptr; m_mmap_size = 0; m_data = nullptr; m_size = 0; } } //---------------------------------------------------------------------- // Memory map "length" bytes from "file" starting "offset" // bytes into the file. If "length" is set to SIZE_MAX, then // map as many bytes as possible. // // Returns the number of bytes mapped starting from the requested // offset. //---------------------------------------------------------------------- size_t DataBufferMemoryMap::MemoryMapFromFileSpec(const FileSpec *filespec, lldb::offset_t offset, size_t length, bool writeable) { if (filespec != nullptr) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MMAP)); if (log) { log->Printf("DataBufferMemoryMap::MemoryMapFromFileSpec(file=\"%s\", " "offset=0x%" PRIx64 ", length=0x%" PRIx64 ", writeable=%i", filespec->GetPath().c_str(), offset, (uint64_t)length, writeable); } char path[PATH_MAX]; if (filespec->GetPath(path, sizeof(path))) { uint32_t options = File::eOpenOptionRead; if (writeable) options |= File::eOpenOptionWrite; File file; Error error(file.Open(path, options)); if (error.Success()) { const bool fd_is_file = true; return MemoryMapFromFileDescriptor(file.GetDescriptor(), offset, length, writeable, fd_is_file); } } } // We should only get here if there was an error Clear(); return 0; } #ifdef _WIN32 static size_t win32memmapalignment = 0; void LoadWin32MemMapAlignment() { SYSTEM_INFO data; GetSystemInfo(&data); win32memmapalignment = data.dwAllocationGranularity; } #endif //---------------------------------------------------------------------- // The file descriptor FD is assumed to already be opened as read only // and the STAT structure is assumed to a valid pointer and already // containing valid data from a call to stat(). // // Memory map FILE_LENGTH bytes in FILE starting FILE_OFFSET bytes into // the file. If FILE_LENGTH is set to SIZE_MAX, then map as many bytes // as possible. // // RETURNS // Number of bytes mapped starting from the requested offset. //---------------------------------------------------------------------- size_t DataBufferMemoryMap::MemoryMapFromFileDescriptor(int fd, lldb::offset_t offset, size_t length, bool writeable, bool fd_is_file) { Clear(); if (fd >= 0) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MMAP | LIBLLDB_LOG_VERBOSE)); if (log) { log->Printf("DataBufferMemoryMap::MemoryMapFromFileDescriptor(fd=%i, " "offset=0x%" PRIx64 ", length=0x%" PRIx64 ", writeable=%i, fd_is_file=%i)", fd, offset, (uint64_t)length, writeable, fd_is_file); } #ifdef _WIN32 HANDLE handle = (HANDLE)_get_osfhandle(fd); DWORD file_size_low, file_size_high; file_size_low = GetFileSize(handle, &file_size_high); const lldb::offset_t file_size = llvm::Make_64(file_size_high, file_size_low); const lldb::offset_t max_bytes_available = file_size - offset; const size_t max_bytes_mappable = (size_t)std::min<lldb::offset_t>(SIZE_MAX, max_bytes_available); if (length == SIZE_MAX || length > max_bytes_mappable) { // Cap the length if too much data was requested length = max_bytes_mappable; } if (length > 0) { HANDLE fileMapping = CreateFileMapping( handle, nullptr, writeable ? PAGE_READWRITE : PAGE_READONLY, file_size_high, file_size_low, nullptr); if (fileMapping != nullptr) { if (win32memmapalignment == 0) LoadWin32MemMapAlignment(); lldb::offset_t realoffset = offset; lldb::offset_t delta = 0; if (realoffset % win32memmapalignment != 0) { realoffset = realoffset / win32memmapalignment * win32memmapalignment; delta = offset - realoffset; } LPVOID data = MapViewOfFile(fileMapping, writeable ? FILE_MAP_WRITE : FILE_MAP_READ, 0, realoffset, length + delta); m_mmap_addr = (uint8_t *)data; if (!data) { Error error; error.SetErrorToErrno(); } else { m_data = m_mmap_addr + delta; m_size = length; } CloseHandle(fileMapping); } } #else struct stat stat; if (::fstat(fd, &stat) == 0) { if (S_ISREG(stat.st_mode) && (stat.st_size > static_cast<off_t>(offset))) { const size_t max_bytes_available = stat.st_size - offset; if (length == SIZE_MAX) { length = max_bytes_available; } else if (length > max_bytes_available) { // Cap the length if too much data was requested length = max_bytes_available; } if (length > 0) { int prot = PROT_READ; int flags = MAP_PRIVATE; if (writeable) prot |= PROT_WRITE; else flags |= MAP_EXTRA_HOST_READ_FLAGS; if (fd_is_file) flags |= MAP_FILE; m_mmap_addr = (uint8_t *)::mmap(nullptr, length, prot, flags, fd, offset); Error error; if (m_mmap_addr == (void *)-1) { error.SetErrorToErrno(); if (error.GetError() == EINVAL) { // We may still have a shot at memory mapping if we align things // correctly size_t page_offset = offset % HostInfo::GetPageSize(); if (page_offset != 0) { m_mmap_addr = (uint8_t *)::mmap(nullptr, length + page_offset, prot, flags, fd, offset - page_offset); if (m_mmap_addr == (void *)-1) { // Failed to map file m_mmap_addr = nullptr; } else if (m_mmap_addr != nullptr) { // We recovered and were able to memory map // after we aligned things to page boundaries // Save the actual mmap'ed size m_mmap_size = length + page_offset; // Our data is at an offset into the mapped data m_data = m_mmap_addr + page_offset; // Our pretend size is the size that was requested m_size = length; } } } if (error.GetError() == ENOMEM) { error.SetErrorStringWithFormat("could not allocate %" PRId64 " bytes of memory to mmap in file", (uint64_t)length); } } else { // We were able to map the requested data in one chunk // where our mmap and actual data are the same. m_mmap_size = length; m_data = m_mmap_addr; m_size = length; } if (log) { log->Printf( "DataBufferMemoryMap::MemoryMapFromFileSpec() m_mmap_addr = " "%p, m_mmap_size = %" PRIu64 ", error = %s", (void *)m_mmap_addr, (uint64_t)m_mmap_size, error.AsCString()); } } } } #endif } return GetByteSize(); }
38.327922
80
0.525709
Polidea
70e8aaed399eb428d0b5e4550e3cba3bca905273
2,716
cpp
C++
pseudoSO/src/dispatcher.cpp
LSantos06/PseudoOS
a107dc184b7bed6020c96f5bd74aa464f04012de
[ "MIT" ]
null
null
null
pseudoSO/src/dispatcher.cpp
LSantos06/PseudoOS
a107dc184b7bed6020c96f5bd74aa464f04012de
[ "MIT" ]
1
2017-12-04T13:54:56.000Z
2017-12-04T13:54:56.000Z
pseudoSO/src/dispatcher.cpp
LSantos06/PseudoOS
a107dc184b7bed6020c96f5bd74aa464f04012de
[ "MIT" ]
null
null
null
#include "../include/dispatcher.h" //Funcao de ordenacao para o vetor de processos bool ordena (Processo *proc1, Processo *proc2){ return (proc1->getTempoInicializacao() < proc2->getTempoInicializacao()); } Dispatcher::Dispatcher(vector< Processo* > processosArquivo, Disco *discoArquivo){ tempo_atual = 0; //Atribui para a lista de processos do Dispatcher proximosProcessos = processosArquivo; //Atribui para a estrutura de disco do Dispatcher disco = discoArquivo; //Ordena em ordem crescente de tempo de inicializacao sort(proximosProcessos.begin(), proximosProcessos.end(), ordena); } void Dispatcher::rodaCPU(Processo* processo){ //Diminui tempo do processo em 1 quantum (simula execucao) processo->setTempoProcessador(processo->getTempoProcessador() - 1); cout << "Processo rodando: " << processo->getID() << endl; /************** Acoes a serem simuladas na operacao *********/ //Operacoes de um processo no sistema de arquivos realizarOperacoes(disco, processo->getID(),processo->getPrioridade()); } void Dispatcher::executa(){ FilaGlobal filaGlobal; Processo *processoAtual = nullptr; //Enquanto houver processos para executar while(!filaGlobal.estaoVazias() || !proximosProcessos.empty()){ //Enquanto o tempo atual for igual ao tempo de inicializacao //dos proximos processos a serem inseridos, insere na fila global while(!proximosProcessos.empty() && proximosProcessos.front()->getTempoInicializacao() == tempo_atual){ cout << endl << "dispatcher =>" << endl; proximosProcessos.front()->print(); //Insere elemento na fila filaGlobal.insere(proximosProcessos.front()); //Apaga primeiro elemento proximosProcessos.erase(proximosProcessos.begin()); } //Com elementos devidamente inseridos na fila de prontos, //pode-se escolher 1 da fila global if(!processoAtual && !filaGlobal.estaoVazias()){ processoAtual = filaGlobal.escolhe_processo(); } //Se processo nao for null if(processoAtual){ //Manda pra CPU rodaCPU(processoAtual); if(processoAtual->getTempoProcessador() <= 0){ //TODO: Operacoes de desalocacao de E/S e memoria processoAtual = nullptr; } //Se n tiver acabado e for processo usuario, sofre preempcao else if(processoAtual->eh_usuario()){ filaGlobal.realimenta(processoAtual); processoAtual = nullptr; } } //if processoAtual tempo_atual++; } //while houver processos //Apos fim da execucao, imprimir relatorio de operacoes pros processos relatorioOperacoes(disco); cout << endl << "Mapa de ocupacao do disco:" << endl; //Impressao dos blocos imprimirBlocos(disco); }
34.820513
82
0.701031
LSantos06
70ea05cbd69458cf0478333141d31420a240b899
10,123
cc
C++
src/core/breakpoint/BreakpointManager.cc
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
src/core/breakpoint/BreakpointManager.cc
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
src/core/breakpoint/BreakpointManager.cc
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, 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. */ #include "BreakpointManager.hh" #include "core/breakpoint/BreakpointImpl.hh" #include "core/domain/DomainImpl.hh" #include "core/domain/VcpuImpl.hh" #include <introvirt/core/exception/CommandFailedException.hh> #include <introvirt/util/compiler.hh> #include <log4cxx/logger.h> #include <cassert> #include <stdexcept> namespace introvirt { static InternalBreakpoint* HiddenBreakpoint = nullptr; static thread_local std::shared_ptr<InternalBreakpoint> active_breakpoint = nullptr; static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("introvirt.breakpoint.BreakpointManager")); void InternalBreakpoint::watchpoint_event(Event& event) { if (mapping_.address() != event.mem_access().physical_address().address()) { LOG4CXX_WARN(logger, "Incorrect physical address: " << event.mem_access().physical_address()); } if (event.mem_access().read_violation()) { LOG4CXX_DEBUG(logger, event.task().process_name() << ": Hiding breakpoint from guest at " << mapping_ << " RIP: 0x" << std::hex << event.vcpu().registers().rip()); } if (event.mem_access().write_violation()) { LOG4CXX_DEBUG(logger, event.task().process_name() << ": Guest attempted to write breakpoint memory at " << mapping_); } if (*mapping_ == 0xCC && !nested_bp()) { disable(); HiddenBreakpoint = this; } } void InternalBreakpoint::step_event() { // Re-read the original byte and then restore the breakpoint LOG4CXX_TRACE(logger, "Restoring breakpoint after guest memory access"); original_byte_ = *mapping_; enable(); single_step_.reset(); } void InternalBreakpoint::deliver_breakpoint(Event& event) { // Get a copy of the callback set so that we don't have to hold a lock std::unique_lock lock(mtx_); std::vector<std::shared_ptr<BreakpointImplCallback>> callbacks; callbacks.reserve(breakpoint_list_.size()); for (auto& weakptr : breakpoint_list_) { auto entry = weakptr.lock(); if (entry) callbacks.push_back(entry->callback()); } lock.unlock(); LOG4CXX_DEBUG(logger, "Delivering " << callbacks.size() << " breakpoint callbacks"); for (auto& entry : callbacks) { try { entry->deliver_event(event); } catch (TraceableException& ex) { LOG4CXX_WARN(logger, "Caught exception in deliver_breakpoint(): " << ex); } } } void InternalBreakpoint::add_callback(const std::shared_ptr<BreakpointImpl>& bpimpl) { std::unique_lock lock(mtx_); breakpoint_list_.push_back(bpimpl); if (breakpoint_list_.size() == 1) { enable(); } } bool InternalBreakpoint::remove_expired() { std::unique_lock lock(mtx_); for (auto iter = breakpoint_list_.begin(); iter != breakpoint_list_.end();) { auto& weakptr = *iter; if (weakptr.expired()) { iter = breakpoint_list_.erase(iter); } else { ++iter; } } if (breakpoint_list_.empty()) { disable(); return true; } return false; } InternalBreakpoint::InternalBreakpoint(const guest_phys_ptr<void>& address) : mapping_(static_ptr_cast<uint8_t>(address)), original_byte_(*mapping_) { enable(); // Configure out watchpoint if supported try { #if 0 auto& domain = const_cast<DomainImpl&>(static_cast<const DomainImpl&>(address.domain())); watchpoint_ = domain.create_watchpoint( address, 1, true, true, false, std::bind(&InternalBreakpoint::watchpoint_event, this, std::placeholders::_1)); #endif } catch (CommandFailedException& ex) { // Guest doesn't support watchpoints LOG4CXX_DEBUG(logger, "Failed to create watchpoint for breakpoint: " << ex.what()); } } InternalBreakpoint::~InternalBreakpoint() { disable(); } void BreakpointManager::add_ref(const std::shared_ptr<BreakpointImpl>& breakpoint) { std::lock_guard lock(breakpoints_.mtx_); if (unlikely(interrupted_)) return; std::shared_ptr<InternalBreakpoint> entry; guest_phys_ptr<uint8_t> physical_address = breakpoint->ptr(); // See if we can find it in the breakpoint map auto iter = breakpoints_.map_.find(physical_address.address()); if (iter == breakpoints_.map_.end()) { // Entry doesn't exist, create it entry = std::make_shared<InternalBreakpoint>(physical_address); iter = breakpoints_.map_.emplace(physical_address.address(), std::move(entry)).first; } else { // Entry exists, try to lock it entry = iter->second.lock(); if (!entry) { // Entry has expired, recreate it entry = std::make_shared<InternalBreakpoint>(physical_address); iter = breakpoints_.map_.emplace(physical_address.address(), std::move(entry)).first; } } // Store it with the breakpoint breakpoint->internal_breakpoint(entry); // Register the breakpoint with the internal breakpoint entry->add_callback(breakpoint); } void BreakpointManager::remove_ref(BreakpointImpl& breakpoint) { std::lock_guard lock(breakpoints_.mtx_); if (unlikely(interrupted_)) return; auto entry = breakpoint.internal_breakpoint(); if (entry->remove_expired()) { // The internal breakpoint has no more callbacks and can be erased breakpoints_.map_.erase(breakpoint.ptr().address()); } } bool BreakpointManager::handle_int3_event(Event& event, bool deliver_events) { auto& vcpu = event.vcpu(); auto& regs = vcpu.registers(); guest_ptr<uint8_t> rip(vcpu, regs.rip()); const uint64_t physical_rip = guest_phys_ptr<uint8_t>(rip).address(); if (unlikely(interrupted_)) { return false; } // Find the breakpoint for the event std::unique_lock breakpoints_lock(breakpoints_.mtx_); LOG4CXX_DEBUG(logger, "VCPU " << vcpu.id() << ": INT3 received for " << rip); auto iter = breakpoints_.map_.find(physical_rip); if (unlikely(iter == breakpoints_.map_.end())) { // We don't have a breakpoint for this! // Check to see if there's an actual int3 instruction in place if (*guest_ptr<uint8_t>(rip) == 0xCC) { LOG4CXX_DEBUG(logger, "Injecting unwanted Int3"); vcpu.inject_exception(x86::Exception::INT3); return false; } else { LOG4CXX_DEBUG(logger, "Hit unknown breakpoint. This is probably bad for the guest.") } return false; } // Get our breakpoint entry active_breakpoint = iter->second.lock(); if (unlikely(!active_breakpoint)) { // Maybe all of our breakpoints were removed while we were waiting. // If that's the case, the breakpoint instruction should have already been removed. LOG4CXX_DEBUG(logger, "Failed to lock internal breakpoint from weak_ptr."); return false; } // No longer need to lock on this since we have out internal breakpoint breakpoints_lock.unlock(); // Reinject the exeception if this is a nested Int3 if (active_breakpoint->nested_bp()) vcpu.inject_exception(x86::Exception::INT3); // Run callbacks active_breakpoint->disable(); if (deliver_events) { active_breakpoint->deliver_breakpoint(event); if (active_breakpoint->remove_expired()) { // No one left waiting for this breakpoint. No need for a callback. LOG4CXX_TRACE(logger, "Breakpoing removed, not stepping VCPU " << vcpu.id()); active_breakpoint.reset(); breakpoints_lock.lock(); breakpoints_.map_.erase(physical_rip); return false; } // Check if one of our callbacks changed RIP if (regs.rip() != rip.address()) { // A callback must have changed RIP, just turn the breakpoint back on active_breakpoint.reset(); active_breakpoint->enable(); LOG4CXX_TRACE(logger, "RIP changed, not stepping VCPU " << vcpu.id()); return false; } } // It did not, we need to single step the guest LOG4CXX_DEBUG(logger, "Waiting for BP step on VCPU " << vcpu.id()); return true; } void BreakpointManager::step(Event& event) { if (HiddenBreakpoint != nullptr) { // Unhide the BP HiddenBreakpoint->step_event(); HiddenBreakpoint = nullptr; } // Stepping done, turn the breakpoint back on if (active_breakpoint != nullptr) { active_breakpoint->enable(); active_breakpoint.reset(); LOG4CXX_DEBUG(logger, "BP step on VCPU " << event.vcpu().id()); } } void BreakpointManager::interrupt() { // Clean up and unblock any pending events interrupted_ = true; std::lock_guard lock2(breakpoints_.mtx_); // Disable all breakpoints for (auto& [address, weakptr] : breakpoints_.map_) { auto entry = weakptr.lock(); if (entry) entry->disable(); } } void BreakpointManager::start_injection() { if (active_breakpoint) { active_breakpoint->enable(); } } void BreakpointManager::end_injection() { if (active_breakpoint) { active_breakpoint->disable(); } } BreakpointManager::BreakpointManager() {} BreakpointManager::~BreakpointManager() = default; } // namespace introvirt
33.190164
99
0.648721
IntroVirt
70ea1b0b7d6cb49147134c1c090158164914ec1e
1,061
cpp
C++
USACOContest/2016Feb/Silver/cbarn/cbarn.cpp
UlyssesZh/AlgorithmTraining
a3d3c95cf60f0b73a13d297ef699617a19d0b80e
[ "CC0-1.0" ]
null
null
null
USACOContest/2016Feb/Silver/cbarn/cbarn.cpp
UlyssesZh/AlgorithmTraining
a3d3c95cf60f0b73a13d297ef699617a19d0b80e
[ "CC0-1.0" ]
null
null
null
USACOContest/2016Feb/Silver/cbarn/cbarn.cpp
UlyssesZh/AlgorithmTraining
a3d3c95cf60f0b73a13d297ef699617a19d0b80e
[ "CC0-1.0" ]
null
null
null
#include <cstdio> #include <cstring> char PROG[] = "cbarn"; #include <algorithm> using namespace std; int n; long long x, c[1000]; long long squaresum(long long begin, long long end) { return (end * (end + 1) * (2 * end + 1) - (begin - 1) * begin * (2 * begin - 1)) / 6; } long long endat(int i) { return x + c[i] - 1; } void update(int i) { x = max(0ll, endat(i)); } void init() { scanf("%d", &n); x = 0ll; for (int i = 0; i < n; i++) { scanf("%lld", &c[i]); update(i); } } void pickstart() { for (int i = 0;; i++) { if (!x) { rotate(c, c + i, c + n); break; } update(i); } } long long calc() { long long ret = 0; for (int i = 0; i < n; i++) { ret += squaresum(x, endat(i)); update(i); } return ret; } void actualMain() { init(); pickstart(); printf("%lld\n", calc()); } int main() { int size = sizeof(PROG); char in[size + 3], out[size + 4]; freopen(strcat(strcpy(in, PROG), ".in"), "r", stdin); freopen(strcat(strcpy(out, PROG), ".out"), "w", stdout); actualMain(); fclose(stdin); fclose(stdout); return 0; }
17.683333
57
0.547597
UlyssesZh
70eb371268b94be63aa8e022a1837b2d6bfb77bf
17,204
hpp
C++
libs/boost_1_72_0/boost/type_erasure/tuple.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/type_erasure/tuple.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/type_erasure/tuple.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// Boost.TypeErasure library // // Copyright 2011-2012 Steven Watanabe // // Distributed under the Boost Software License Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // $Id$ #if !defined(BOOST_PP_IS_ITERATING) #ifndef BOOST_TYPE_ERASURE_TUPLE_HPP_INCLUDED #define BOOST_TYPE_ERASURE_TUPLE_HPP_INCLUDED #include <boost/config.hpp> #ifdef BOOST_TYPE_ERASURE_DOXYGEN namespace boost { namespace type_erasure { /** * @ref tuple is a Boost.Fusion Random Access Sequence containing * @ref any "anys". @c Concept specifies the \Concept for each * of the elements. The remaining arguments must be (possibly const * and/or reference qualified) placeholders, which are the * @ref placeholder "placeholders" of the elements. */ template <class Concept, class... T> class tuple { public: /** * Constructs a tuple. Each element of @c args will * be used to initialize the corresponding @ref any member. * The @ref binding for the tuple elements is determined * by mapping the placeholders in @c T to the corresponding * types in @c U. */ template <class... U> explicit tuple(U &&... args); }; /** * Returns the Nth @ref any in the tuple. */ template <int N, class Concept, class... T> any<Concept, TN> &get(tuple<Concept, T...> &arg); /** \overload */ template <int N, class Concept, class... T> const any<Concept, TN> &get(const tuple<Concept, T...> &arg); } // namespace type_erasure } // namespace boost #elif !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && \ !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) #include <boost/fusion/include/category_of.hpp> #include <boost/fusion/include/iterator_facade.hpp> #include <boost/fusion/include/sequence_facade.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/insert.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/map.hpp> #include <boost/type_erasure/any.hpp> #include <boost/type_erasure/config.hpp> #include <boost/type_erasure/static_binding.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> namespace boost { namespace type_erasure { template <class Concept, class... T> struct cons; template <class Concept> struct cons<Concept> { template <class Binding> cons(const Binding &) {} }; template <class Concept, class T0, class... T> struct cons<Concept, T0, T...> { typedef any<Concept, T0> value_type; typedef cons<Concept, T...> rest_type; template <class Binding, class U0, class... U> cons(const Binding &b, U0 &&u0, U &&... u) : value(std::forward<U0>(u0), b), rest(b, std::forward<U>(u)...) {} any<Concept, T0> value; cons<Concept, T...> rest; }; namespace detail { template <int N, class Cons> struct cons_advance { typedef typename cons_advance<N - 1, Cons>::type::rest_type type; static const type &call(const Cons &c) { return cons_advance<N - 1, Cons>::call(c).rest; } }; template <class Cons> struct cons_advance<0, Cons> { typedef Cons type; static const type &call(const Cons &c) { return c; } }; template <class... T> struct make_map; template <class T0, class... T> struct make_map<T0, T...> { typedef typename ::boost::mpl::insert< typename ::boost::type_erasure::detail::make_map<T...>::type, T0>::type type; }; template <> struct make_map<> { typedef ::boost::mpl::map0<> type; }; } // namespace detail /** INTERNAL ONLY */ template <class Tuple, int N> class tuple_iterator : public ::boost::fusion::iterator_facade< tuple_iterator<Tuple, N>, ::boost::fusion::random_access_traversal_tag> { public: typedef ::boost::mpl::int_<N> index; explicit tuple_iterator(Tuple &t_arg) : t(&t_arg) {} template <class It> struct value_of { typedef typename Tuple::template value_at<Tuple, mpl::int_<N>>::type type; }; template <class It> struct deref { typedef typename Tuple::template at<Tuple, mpl::int_<N>>::type type; static type call(It it) { return Tuple::template at<Tuple, mpl::int_<N>>::call(*it.t); } }; template <class It, class M> struct advance { typedef tuple_iterator<Tuple, (It::index::value + M::value)> type; static type call(It it) { return type(*it.t); } }; template <class It> struct next : advance<It, ::boost::mpl::int_<1>> {}; template <class It> struct prior : advance<It, ::boost::mpl::int_<-1>> {}; template <class It1, class It2> struct distance { typedef typename ::boost::mpl::minus<typename It2::index, typename It1::index>::type type; static type call(It1, It2) { return type(); } }; private: Tuple *t; }; template <class Concept, class... T> class tuple : public ::boost::fusion::sequence_facade< ::boost::type_erasure::tuple<Concept, T...>, ::boost::fusion::forward_traversal_tag> { public: template <class... U> explicit tuple(U &&... args) : impl(::boost::type_erasure::make_binding< typename ::boost::type_erasure::detail::make_map< ::boost::mpl::pair< typename ::boost::remove_const< typename ::boost::remove_reference<T>::type>::type, typename ::boost::remove_const< typename ::boost::remove_reference<U>::type>:: type>...>::type>(), std::forward<U>(args)...) {} template <class Seq> struct begin { typedef ::boost::type_erasure::tuple_iterator<Seq, 0> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct end { typedef ::boost::type_erasure::tuple_iterator<Seq, sizeof...(T)> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct size { typedef ::boost::mpl::int_<sizeof...(T)> type; static type call(Seq &seq) { return type(); } }; template <class Seq> struct empty { typedef ::boost::mpl::bool_<sizeof...(T) == 0> type; static type call(Seq &seq) { return type(); } }; template <class Seq, class N> struct at { typedef typename ::boost::type_erasure::detail::cons_advance< N::value, ::boost::type_erasure::cons<Concept, T...>>::type::value_type value_type; typedef typename ::boost::mpl::if_<::boost::is_const<Seq>, const value_type &, value_type &>::type type; static type call(Seq &seq) { return const_cast<type>( ::boost::type_erasure::detail::cons_advance< N::value, ::boost::type_erasure::cons<Concept, T...>>::call(seq.impl) .value); } }; template <class Seq, class N> struct value_at { typedef typename ::boost::type_erasure::detail::cons_advance< N::value, ::boost::type_erasure::cons<Concept, T...>>::type::value_type value_type; }; ::boost::type_erasure::cons<Concept, T...> impl; }; template <int N, class Concept, class... T> typename ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type & get(::boost::type_erasure::tuple<Concept, T...> &t) { return const_cast<typename ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type &>( ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::call(t.impl) .value); } template <int N, class Concept, class... T> const typename ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type & get(const ::boost::type_erasure::tuple<Concept, T...> &t) { return ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::call(t.impl) .value; } } // namespace type_erasure } // namespace boost #else #include <boost/fusion/include/category_of.hpp> #include <boost/fusion/include/iterator_facade.hpp> #include <boost/fusion/include/sequence_facade.hpp> #include <boost/mpl/equal_to.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/minus.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/type_erasure/any.hpp> #include <boost/type_erasure/config.hpp> #include <boost/type_erasure/static_binding.hpp> namespace boost { namespace type_erasure { /** INTERNAL ONLY */ struct na {}; namespace detail { template <int N, class Tuple> struct get_impl; template <class Concept, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T, ::boost::type_erasure::na)> struct tuple_storage; } // namespace detail /** INTERNAL ONLY */ template <class Tuple, int N> class tuple_iterator : public ::boost::fusion::iterator_facade< tuple_iterator<Tuple, N>, ::boost::fusion::random_access_traversal_tag> { public: typedef ::boost::mpl::int_<N> index; explicit tuple_iterator(Tuple &t_arg) : t(&t_arg) {} template <class It> struct value_of { typedef typename ::boost::type_erasure::detail::get_impl< It::index::value, Tuple>::value_type type; }; template <class It> struct deref : ::boost::type_erasure::detail::get_impl<It::index::value, Tuple> { typedef typename ::boost::type_erasure::detail::get_impl<It::index::value, Tuple>::type type; static type call(It it) { return ::boost::type_erasure::detail::get_impl<It::index::value, Tuple>::call(*it.t); } }; template <class It, class M> struct advance { typedef tuple_iterator<Tuple, (It::index::value + M::value)> type; static type call(It it) { return type(*it.t); } }; template <class It> struct next : advance<It, ::boost::mpl::int_<1>> {}; template <class It> struct prior : advance<It, ::boost::mpl::int_<-1>> {}; template <class It1, class It2> struct distance { typedef typename ::boost::mpl::minus<typename It2::index, typename It1::index>::type type; static type call(It1, It2) { return type(); } }; private: Tuple *t; }; /** INTERNAL ONLY */ template <class Derived> struct tuple_base : ::boost::fusion::sequence_facade< Derived, ::boost::fusion::random_access_traversal_tag> { template <class Seq> struct begin { typedef ::boost::type_erasure::tuple_iterator<Seq, 0> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct end { typedef ::boost::type_erasure::tuple_iterator<Seq, Seq::tuple_size::value> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct size { typedef typename Seq::tuple_size type; static type call(Seq &seq) { return type(); } }; template <class Seq> struct empty { typedef typename boost::mpl::equal_to<typename Seq::tuple_size, boost::mpl::int_<0>>::type type; static type call(Seq &seq) { return type(); } }; template <class Seq, class N> struct at : ::boost::type_erasure::detail::get_impl<N::value, Seq> {}; template <class Seq, class N> struct value_at { typedef typename ::boost::type_erasure::detail::get_impl<N::value, Seq>::value_type type; }; }; template <class Concept, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T, ::boost::type_erasure::na)> class tuple; template <int N, class Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T)> typename detail::get_impl<N, tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::type get(tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)> &arg) { return detail::get_impl< N, tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::call(arg); } template <int N, class Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T)> typename detail::get_impl<N, const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::type get(const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)> &arg) { return detail::get_impl< N, const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::call(arg); } /** INTERNAL ONLY */ #define BOOST_PP_FILENAME_1 <boost/type_erasure/tuple.hpp> /** INTERNAL ONLY */ #define BOOST_PP_ITERATION_LIMITS (0, BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE) #include BOOST_PP_ITERATE() } // namespace type_erasure } // namespace boost #endif #endif #else #define N BOOST_PP_ITERATION() #define BOOST_TYPE_ERASURE_TAG_TYPEDEF(z, n, data) \ typedef BOOST_PP_CAT(T, n) BOOST_PP_CAT(tag_type, n); \ typedef typename ::boost::remove_reference<BOOST_PP_CAT(T, n)>::type \ BOOST_PP_CAT(tag, n); #define BOOST_TYPE_ERASURE_PAIR(z, n, data) \ ::boost::mpl::pair<BOOST_PP_CAT(tag, n), BOOST_PP_CAT(U, n)> #define BOOST_TYPE_ERASURE_CONSTRUCT(z, n, data) \ BOOST_PP_CAT(t, n)(BOOST_PP_CAT(u, n), table) #define BOOST_TYPE_ERASURE_TUPLE_MEMBER(z, n, data) \ ::boost::type_erasure::any<Concept, BOOST_PP_CAT(T, n)> BOOST_PP_CAT(t, n); #if N == 1 #define BOOST_TYPE_ERASURE_EXPLICIT explicit #else #define BOOST_TYPE_ERASURE_EXPLICIT #endif namespace detail { template <class Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)> struct tuple_storage #if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE <Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)> #endif { #if N template <class Table BOOST_PP_ENUM_TRAILING_PARAMS(N, class U)> tuple_storage(const Table &table BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, U, &u)) : BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_CONSTRUCT, ~) {} #else template <class Table> explicit tuple_storage(const Table &) {} #endif BOOST_PP_REPEAT(N, BOOST_TYPE_ERASURE_TUPLE_MEMBER, `) }; #if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE template <class Tuple> struct get_impl<N, Tuple> { typedef any<typename Tuple::concept_type, typename Tuple::BOOST_PP_CAT(tag_type, N)> value_type; typedef value_type &type; static type call(Tuple &arg) { return arg.impl.BOOST_PP_CAT(t, N); } }; template <class Tuple> struct get_impl<N, const Tuple> { typedef any<typename Tuple::concept_type, typename Tuple::BOOST_PP_CAT(tag_type, N)> value_type; typedef const value_type &type; static type call(const Tuple &arg) { return arg.impl.BOOST_PP_CAT(t, N); } }; #endif } // namespace detail template <class Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)> class tuple #if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE <Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)> #endif : public tuple_base<tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)>> { typedef Concept concept_type; BOOST_PP_REPEAT(N, BOOST_TYPE_ERASURE_TAG_TYPEDEF, ~) public: typedef ::boost::mpl::int_<N> tuple_size; #if N template <BOOST_PP_ENUM_PARAMS(N, class U)> #endif BOOST_TYPE_ERASURE_EXPLICIT tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, U, &u)) : impl(::boost::type_erasure::make_binding< ::boost::mpl::map<BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_PAIR, ~)>>() BOOST_PP_ENUM_TRAILING_PARAMS(N, u)) { } #if N template <BOOST_PP_ENUM_PARAMS(N, class U)> BOOST_TYPE_ERASURE_EXPLICIT tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, const U, &u)) : impl(::boost::type_erasure::make_binding< ::boost::mpl::map<BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_PAIR, ~)>>() BOOST_PP_ENUM_TRAILING_PARAMS(N, u)) {} #endif private: template <int M, class Tuple> friend struct ::boost::type_erasure::detail::get_impl; ::boost::type_erasure::detail::tuple_storage< Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)> impl; }; #undef BOOST_TYPE_ERASURE_EXPLICIT #undef BOOST_TYPE_ERASURE_TUPLE_MEMBER #undef BOOST_TYPE_ERASURE_CONSTRUCT #undef BOOST_TYPE_ERASURE_PAIR #undef BOOST_TYPE_ERASURE_TAG_TYPEDEF #undef N #endif
35.767152
80
0.659614
henrywarhurst
70ebd377ba8aace3fe88effa5606e07d5717b507
5,419
cpp
C++
src/api/dcps/isocpp/code/org/opensplice/pub/qos/DataWriterQosImpl.cpp
agenihorganization/opensplice
314d3a4538474f2b8e22acffe3c206f4ac38b66b
[ "Apache-2.0" ]
null
null
null
src/api/dcps/isocpp/code/org/opensplice/pub/qos/DataWriterQosImpl.cpp
agenihorganization/opensplice
314d3a4538474f2b8e22acffe3c206f4ac38b66b
[ "Apache-2.0" ]
null
null
null
src/api/dcps/isocpp/code/org/opensplice/pub/qos/DataWriterQosImpl.cpp
agenihorganization/opensplice
314d3a4538474f2b8e22acffe3c206f4ac38b66b
[ "Apache-2.0" ]
null
null
null
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to TO_YEAR PrismTech * Limited, its affiliated companies and licensors. 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. * */ /** * @file */ #include <org/opensplice/pub/qos/DataWriterQosImpl.hpp> namespace org { namespace opensplice { namespace pub { namespace qos { DataWriterQosImpl::DataWriterQosImpl() : strength_(0), lifecycle_(true) { } DataWriterQosImpl::DataWriterQosImpl(const org::opensplice::topic::qos::TopicQosImpl& tqos) : durability_(tqos.policy<dds::core::policy::Durability>()), #ifdef OMG_DDS_PERSISTENCE_SUPPORT durability_service_(tqos.policy<dds::core::policy::DurabilityService>()), #endif deadline_(tqos.policy<dds::core::policy::Deadline>()), budget_(tqos.policy<dds::core::policy::LatencyBudget>()), liveliness_(tqos.policy<dds::core::policy::Liveliness>()), reliability_(tqos.policy<dds::core::policy::Reliability>()), order_(tqos.policy<dds::core::policy::DestinationOrder>()), history_(tqos.policy<dds::core::policy::History>()), resources_(tqos.policy<dds::core::policy::ResourceLimits>()), priority_(tqos.policy<dds::core::policy::TransportPriority>()), lifespan_(tqos.policy<dds::core::policy::Lifespan>()), ownership_(tqos.policy<dds::core::policy::Ownership>()), strength_(0) { } DataWriterQosImpl::DataWriterQosImpl( dds::core::policy::UserData user_data, dds::core::policy::Durability durability, #ifdef OMG_DDS_PERSISTENCE_SUPPORT dds::core::policy::DurabilityService durability_service, #endif // OMG_DDS_PERSISTENCE_SUPPORT dds::core::policy::Deadline deadline, dds::core::policy::LatencyBudget budget, dds::core::policy::Liveliness liveliness, dds::core::policy::Reliability reliability, dds::core::policy::DestinationOrder order, dds::core::policy::History history, dds::core::policy::ResourceLimits resources, dds::core::policy::TransportPriority priority, dds::core::policy::Lifespan lifespan, dds::core::policy::Ownership ownership, #ifdef OMG_DDS_OWNERSHIP_SUPPORT dds::core::policy::OwnershipStrength strength, #endif // OMG_DDS_OWNERSHIP_SUPPORT dds::core::policy::WriterDataLifecycle lifecycle) : user_data_(user_data), durability_(durability), #ifdef OMG_DDS_PERSISTENCE_SUPPORT durability_service_(durability_service), #endif // OMG_DDS_PERSISTENCE_SUPPORT deadline_(deadline), budget_(budget), liveliness_(liveliness), reliability_(reliability), order_(order), history_(history), resources_(resources), priority_(priority), lifespan_(lifespan), ownership_(ownership), strength_(strength), lifecycle_(lifecycle) {} DataWriterQosImpl::~DataWriterQosImpl() { } void DataWriterQosImpl::policy(const dds::core::policy::UserData& user_data) { user_data_ = user_data; } void DataWriterQosImpl::policy(const dds::core::policy::Durability& durability) { durability_ = durability; } #ifdef OMG_DDS_PERSISTENCE_SUPPORT void DataWriterQosImpl::policy(const dds::core::policy::DurabilityService& durability_service) { durability_service_ = durability_service; } #endif // OMG_DDS_PERSISTENCE_SUPPORT void DataWriterQosImpl::policy(const dds::core::policy::Deadline& deadline) { deadline_ = deadline; } void DataWriterQosImpl::policy(const dds::core::policy::LatencyBudget& budget) { budget_ = budget; } void DataWriterQosImpl::policy(const dds::core::policy::Liveliness& liveliness) { liveliness_ = liveliness; } void DataWriterQosImpl::policy(const dds::core::policy::Reliability& reliability) { reliability_ = reliability; } void DataWriterQosImpl::policy(const dds::core::policy::DestinationOrder& order) { order_ = order; } void DataWriterQosImpl::policy(const dds::core::policy::History& history) { history_ = history; } void DataWriterQosImpl::policy(const dds::core::policy::ResourceLimits& resources) { resources_ = resources; } void DataWriterQosImpl::policy(const dds::core::policy::TransportPriority& priority) { priority_ = priority; } void DataWriterQosImpl::policy(const dds::core::policy::Lifespan& lifespan) { lifespan_ = lifespan; } void DataWriterQosImpl::policy(const dds::core::policy::Ownership& ownership) { ownership_ = ownership; } #ifdef OMG_DDS_OWNERSHIP_SUPPORT void DataWriterQosImpl::policy(const dds::core::policy::OwnershipStrength& strength) { strength_ = strength; } #endif // OMG_DDS_OWNERSHIP_SUPPORT void DataWriterQosImpl::policy(const dds::core::policy::WriterDataLifecycle& lifecycle) { lifecycle_ = lifecycle; } } } } }
27.789744
94
0.706772
agenihorganization
70f0557ff129f7473a43940ce69dcfc4b5fd7d63
25,506
hpp
C++
src/netcdf/lpm_netcdf_impl.hpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
src/netcdf/lpm_netcdf_impl.hpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
src/netcdf/lpm_netcdf_impl.hpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
#include "netcdf/lpm_netcdf.hpp" #ifdef LPM_USE_NETCDF #include "util/lpm_string_util.hpp" #include <sstream> namespace Lpm { template <typename Geo> void NcWriter<Geo>::open() { int retval = nc_create(fname.c_str(), NC_NETCDF4 | NC_CLOBBER, &ncid); CHECK_NCERR(retval); text_att_type att = std::make_pair("LPM", "Lagrangian Particle Methods"); define_file_attribute(att); att = std::make_pair("LPM_version", std::string(version())); define_file_attribute(att); att = std::make_pair("LPM_revision", std::string(revision())); define_file_attribute(att); att = std::make_pair("LPM_has_uncommitted_changes", (has_uncomitted_changes() ? "true" : "false")); define_file_attribute(att); } template <typename Geo> void NcWriter<Geo>::define_file_attribute(const text_att_type& att_pair) const { const int att_len = att_pair.second.size(); int retval = nc_put_att_text(ncid, NC_GLOBAL, att_pair.first.c_str(), att_len, att_pair.second.c_str()); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::define_time_dim() { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(time_dimid == NC_EBADID, "time dimension already defined."); int retval = nc_def_dim(ncid, "time", NC_UNLIMITED, &time_dimid); CHECK_NCERR(retval); n_nc_dims++; int varid = NC_EBADID; retval = nc_def_var(ncid, "time", nc_real_type::value, 1, &time_dimid, &varid); CHECK_NCERR(retval); const auto unit_str = ekat::units::to_string(ekat::units::s); retval = nc_put_att_text(ncid, varid, "units", unit_str.size(), unit_str.c_str()); CHECK_NCERR(retval); name_varid_map.emplace("time", varid); add_time_value(0); } template <typename Geo> void NcWriter<Geo>::add_time_value(const Real t) const { const int varid = name_varid_map.at("time"); size_t next_time_idx = 0; int retval = nc_inq_dimlen(ncid, time_dimid, &next_time_idx); CHECK_NCERR(retval); retval = nc_put_var1(ncid, varid, &next_time_idx, &t); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::define_particles_dim(const Index np) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE(particles_dimid != NC_EBADID); int retval = nc_def_dim(ncid, "n_particles", np, &particles_dimid); CHECK_NCERR(retval); n_nc_dims++; } template <typename Geo> void NcWriter<Geo>::define_coord_dim() { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE(coord_dimid == NC_EBADID); int retval = nc_def_dim(ncid, "coord", Geo::ndim, &coord_dimid); CHECK_NCERR(retval); n_nc_dims++; } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::define_scalar_field(const ScalarField<FL>& s) { LPM_ASSERT(ncid != NC_EBADID); LPM_ASSERT(time_dimid != NC_EBADID); int m_ndims = 2; int dimids[2]; dimids[0] = time_dimid; std::string loc_string; switch (FL) { case( ParticleField ) : { LPM_REQUIRE(particles_dimid != NC_EBADID); dimids[1] = particles_dimid; break; } case( VertexField ) : { LPM_REQUIRE(vertices_dimid != NC_EBADID); dimids[1] = vertices_dimid; break; } case( EdgeField ) : { LPM_REQUIRE(edges_dimid != NC_EBADID); dimids[1] = edges_dimid; break; } case( FaceField ) : { LPM_REQUIRE(faces_dimid != NC_EBADID); dimids[1] = faces_dimid; break; } } int varid = NC_EBADID; int retval = nc_def_var(ncid, s.name.c_str(), nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace(s.name, varid); for (auto& md : s.metadata) { retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str()); CHECK_NCERR(retval); } } template <typename Geo> void NcWriter<Geo>::define_edges(const Edges& edges) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(edges_dimid == NC_EBADID, "edges dimension already defined."); LPM_REQUIRE(two_dimid == NC_EBADID); int retval = nc_def_dim(ncid, "edges", edges.nh(), &edges_dimid); CHECK_NCERR(retval); n_nc_dims++; retval = nc_def_dim(ncid, "two", 2, &two_dimid); CHECK_NCERR(retval); n_nc_dims++; const auto nedges = edges.nh(); const auto nmaxedges = edges.n_max(); const auto nleaves = edges._hn_leaves(); int origs_varid = NC_EBADID; int dests_varid = NC_EBADID; int lefts_varid = NC_EBADID; int rights_varid = NC_EBADID; int kids_varid = NC_EBADID; int parents_varid = NC_EBADID; retval = nc_def_var(ncid, "edges.origs", nc_index_type::value, 1, &edges_dimid, &origs_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.origs", origs_varid); retval = nc_put_att(ncid, NC_GLOBAL, "edges.n_max", nc_index_type::value, 1, &nmaxedges); CHECK_NCERR(retval); retval = nc_put_att(ncid, NC_GLOBAL, "edges.n_leaves", nc_index_type::value, 1, &nleaves); CHECK_NCERR(retval); retval = nc_def_var(ncid, "edges.dests", nc_index_type::value, 1, &edges_dimid, &dests_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.dests", dests_varid); retval = nc_def_var(ncid, "edges.lefts", nc_index_type::value, 1, &edges_dimid, &lefts_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.lefts", lefts_varid); retval = nc_def_var(ncid, "edges.rights", nc_index_type::value, 1, &edges_dimid, &rights_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.rights", rights_varid); const int kid_dims[2] = {edges_dimid, two_dimid}; retval = nc_def_var(ncid, "edges.kids", nc_index_type::value, 2, kid_dims, &kids_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.kids", kids_varid); retval = nc_def_var(ncid, "edges.parent", nc_index_type::value, 1, &edges_dimid, &parents_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.parent", parents_varid); const size_t start = 0; const size_t count = nedges; retval = nc_put_vara(ncid, origs_varid, &start, &count, edges._ho.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, dests_varid, &start, &count, edges._hd.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, lefts_varid, &start, &count, edges._hl.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, rights_varid, &start, &count, edges._hr.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, parents_varid, &start, &count, edges._hp.data()); for (size_t i=0; i<nedges; ++i) { for (size_t j=0; j<2; ++j) { const size_t idx[2] = {i,j}; const auto kid_idx = edges.kid_host(i,j); retval = nc_put_var1(ncid, kids_varid, idx, &kid_idx); CHECK_NCERR(retval); } } } template <typename Geo> template <typename FaceType> void NcWriter<Geo>::define_faces(const Faces<FaceType, Geo>& faces) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(faces_dimid == NC_EBADID, "faces dimension already defined."); LPM_REQUIRE(facekind_dimid == NC_EBADID); LPM_REQUIRE(coord_dimid != NC_EBADID); int retval = nc_def_dim(ncid, "faces", faces.nh(), &faces_dimid); CHECK_NCERR(retval); n_nc_dims++; retval = nc_def_dim(ncid, "four", 4, &four_dimid); CHECK_NCERR(retval); n_nc_dims++; retval = nc_def_dim(ncid, "facekind", FaceType::nverts, &facekind_dimid); CHECK_NCERR(retval); n_nc_dims++; const auto nmaxfaces = faces.n_max(); const auto nfaces = faces.nh(); const auto nleaves = faces.n_leaves_host(); int mask_varid = NC_EBADID; int verts_varid = NC_EBADID; int edges_varid = NC_EBADID; int phys_crd_varid = NC_EBADID; int lag_crd_varid = NC_EBADID; int level_varid = NC_EBADID; int parents_varid = NC_EBADID; int kids_varid = NC_EBADID; int area_varid = NC_EBADID; int crd_inds_varid = NC_EBADID; retval = nc_def_var(ncid, "faces.mask", NC_UBYTE, 1, &faces_dimid, &mask_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.mask", mask_varid); const int vert_and_edge_dims[2] = {faces_dimid, facekind_dimid}; retval = nc_def_var(ncid, "faces.vertices", nc_index_type::value, 2, vert_and_edge_dims, &verts_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.vertices", verts_varid); retval = nc_def_var(ncid, "faces.edges", nc_index_type::value, 2, vert_and_edge_dims, &edges_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.edges", edges_varid); retval = nc_def_var(ncid, "faces.crd_inds", nc_index_type::value, 1, &faces_dimid, &crd_inds_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.crd_inds", crd_inds_varid); retval = nc_def_var(ncid, "faces.level", NC_INT, 1, &faces_dimid, &level_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.level", level_varid); retval = nc_def_var(ncid, "faces.parent", nc_index_type::value, 1, &faces_dimid, &parents_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.parent", parents_varid); const int kid_dims[2] = {faces_dimid, four_dimid}; retval = nc_def_var(ncid, "faces.kids", nc_index_type::value, 2, kid_dims, &kids_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.kids", kids_varid); retval = nc_put_att(ncid, NC_GLOBAL, "faces.n_leaves", nc_index_type::value, 1, &nleaves); CHECK_NCERR(retval); retval = nc_put_att(ncid, NC_GLOBAL, "faces.n_max", nc_index_type::value, 1, &nmaxfaces); CHECK_NCERR(retval); const int pcrd_dims[3] = {time_dimid, faces_dimid, coord_dimid}; retval = nc_def_var(ncid, "faces.phys_crds", nc_real_type::value, 3, pcrd_dims, &phys_crd_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.phys_crds", phys_crd_varid); const int lcrd_dims[2] = {faces_dimid, coord_dimid}; retval = nc_def_var(ncid, "faces.lag_crds", nc_real_type::value, 2, lcrd_dims, &lag_crd_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.lag_crds", lag_crd_varid); retval = nc_def_var(ncid, "faces.area", nc_real_type::value, 1, &faces_dimid, &area_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.area", area_varid); const auto area_unit_str = ekat::units::to_string(ekat::units::m * ekat::units::m); retval = nc_put_att_text(ncid, area_varid, "units", area_unit_str.size(), area_unit_str.c_str()); for (size_t i=0; i<nfaces; ++i) { const size_t mask_idx = i; const uint_fast8_t mask_val = (faces._hmask(i) ? 1 : 0); retval = nc_put_var1(ncid, mask_varid, &mask_idx, &mask_val); CHECK_NCERR(retval); for (size_t j=0; j<4; ++j) { const size_t kids_idx[2] = {i,j}; retval = nc_put_var1(ncid, kids_varid, kids_idx, &faces._hostkids(i,j)); CHECK_NCERR(retval); } for (size_t j=0; j<FaceType::nverts; ++j) { const size_t vert_and_edge_idx[2] = {i,j}; retval = nc_put_var1(ncid, verts_varid, vert_and_edge_idx, &faces._hostverts(i,j)); CHECK_NCERR(retval); retval = nc_put_var1(ncid, edges_varid, vert_and_edge_idx, &faces._hostedges(i,j)); } for (size_t j=0; j<Geo::ndim; ++j) { const size_t pcrd_idx[3] = {0, i, j}; const size_t lcrd_idx[2] = {i,j}; const Real pcrd_val = faces.phys_crds->get_crd_component_host(i,j); const Real lcrd_val = faces.lag_crds->get_crd_component_host(i,j); retval = nc_put_var1(ncid, phys_crd_varid, pcrd_idx, &pcrd_val); CHECK_NCERR(retval); retval = nc_put_var1(ncid, lag_crd_varid, lcrd_idx, &lcrd_val); CHECK_NCERR(retval); } } const size_t start = 0; const size_t count = nfaces; retval = nc_put_vara(ncid, crd_inds_varid, &start, &count, faces._host_crd_inds.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, parents_varid, &start, &count, faces._hostparent.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, area_varid, &start, &count, faces._hostarea.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, level_varid, &start, &count, faces._hlevel.data()); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::update_crds(const size_t time_idx, const int varid, const Coords<Geo>& crds) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE(varid != NC_EBADID); LPM_REQUIRE_MSG(time_idx < n_timesteps(), "time variable must be defined before adding timestep data."); for (size_t i=0; i<crds.nh(); ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[3] = {time_idx, i, j}; const Real crd_val = crds.get_crd_component_host(i,j); int retval = nc_put_var1(ncid, varid, idx, &crd_val); CHECK_NCERR(retval); } } } template <typename Geo> template <typename SeedType> void NcWriter<Geo>::define_polymesh(const PolyMesh2d<SeedType>& mesh) { define_vertices(mesh.vertices); define_edges(mesh.edges); define_faces(mesh.faces); int varid = NC_EBADID; int* ignore_me; int retval = nc_def_var(ncid, "base_tree_depth", NC_INT, 0, ignore_me, &varid); CHECK_NCERR(retval); name_varid_map.emplace("base_tree_depth", varid); const auto mesh_id_str = SeedType::id_string(); retval = nc_put_att_text(ncid, NC_GLOBAL, "MeshSeed", mesh_id_str.size(), mesh_id_str.c_str()); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::update_particle_phys_crds(const size_t time_idx, const Coords<Geo>& pcrds) { //TODO after particle class is defined } template <typename Geo> void NcWriter<Geo>::update_vertex_phys_crds(const size_t time_idx, const Vertices<Coords<Geo>>& verts) { update_crds(time_idx, name_varid_map.at("vertices.phys_crds"), *(verts.phys_crds)); } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::put_scalar_field(const size_t time_idx, const ScalarField<FL>& s) { LPM_REQUIRE(time_idx < n_timesteps()); const int varid = name_varid_map.at(s.name); const size_t start[2] = {time_idx, 0}; size_t count[2]; count[0] = 1; switch (FL) { case (ParticleField) : { count[1] = n_particles(); break; } case( VertexField ) : { count[1] = n_vertices(); break; } case( EdgeField ) : { count[1] = n_edges(); break; } case( FaceField ) : { count[1] = n_faces(); break; } } int retval = nc_put_vara(ncid, varid, start, count, s.hview.data()); CHECK_NCERR(retval); } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::put_vector_field(const size_t time_idx, const VectorField<Geo,FL>& v) { LPM_REQUIRE(time_idx < n_timesteps()); const int varid = name_varid_map.at(v.name); Index n_entries; switch (FL) { case (ParticleField) : { n_entries = n_particles(); break; } case( VertexField ) : { n_entries = n_vertices(); break; } case( EdgeField ) : { n_entries = n_edges(); break; } case( FaceField ) : { n_entries = n_faces(); break; } } for (size_t i=0; i<n_entries; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[3] = {time_idx, i, j}; int retval = nc_put_var1(ncid, varid, idx, &v.hview(i,j)); CHECK_NCERR(retval); } } } template <typename Geo> template <typename FaceType> void NcWriter<Geo>::update_face_phys_crds(const size_t time_idx, const Faces<FaceType, Geo>& faces) { update_crds(time_idx, name_varid_map.at("faces.phys_crds"), *(faces.phys_crds)); const size_t start[2] = {time_idx, 0}; const size_t count[2] = {1, faces.nh()}; int retval = nc_put_vara(ncid, name_varid_map.at("faces.area"), start, count, faces._hostarea.data()); } template <typename Geo> void NcWriter<Geo>::define_vertices(const Vertices<Coords<Geo>>& vertices) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(vertices_dimid == NC_EBADID, "vertices dimension already defined."); const Index nverts = vertices.nh(); int retval = nc_def_dim(ncid, "vertices", vertices.nh(), &vertices_dimid); CHECK_NCERR(retval); n_nc_dims++; const auto h_inds = vertices.host_crd_inds(); { int varid = NC_EBADID; retval = nc_def_var(ncid, "vertices.crd_inds", nc_index_type::value, 1, &vertices_dimid, &varid); CHECK_NCERR(retval); name_varid_map.emplace("vertices.crd_inds", varid); size_t start=0; size_t count=nverts; retval = nc_put_vara(ncid, varid, &start, &count, h_inds.data()); CHECK_NCERR(retval); const auto nmaxverts = vertices.n_max(); retval = nc_put_att(ncid, NC_GLOBAL, "vertices.n_max", nc_index_type::value, 1, &nmaxverts); CHECK_NCERR(retval); } { int varid = NC_EBADID; const int m_ndims = 3; const int dimids[3] = {time_dimid, vertices_dimid, coord_dimid}; retval = nc_def_var(ncid, "vertices.phys_crds", nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace("vertices.phys_crds", varid); for (size_t i=0; i<nverts; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[3] = {0, i, j}; const Real crd_val = vertices.phys_crds->get_crd_component_host(h_inds(i),j); retval = nc_put_var1(ncid, varid, idx, &crd_val); CHECK_NCERR(retval); } } } { int varid = NC_EBADID; const int m_ndims = 2; const int dimids[2] = {vertices_dimid, coord_dimid}; retval = nc_def_var(ncid, "vertices.lag_crds", nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace("vertices.lag_crds", varid); for (size_t i=0; i<nverts; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[2] = {i, j}; const Real crd_val = vertices.lag_crds->get_crd_component_host(h_inds(i),j); retval = nc_put_var1(ncid, varid, idx, &crd_val); CHECK_NCERR(retval); } } } { //TODO: If verts are dual... } } template <typename Geo> std::string NcWriter<Geo>::info_string(const int tab_level) const { auto tabstr = indent_string(tab_level); std::ostringstream ss; ss << tabstr << "NcWriter info:\n"; tabstr += "\t"; ss << tabstr << "filename: " << fname << "\n"; ss << tabstr << "ncid: " << ncid << "\n"; ss << tabstr << "n_nc_dims: " << n_nc_dims << "\n"; ss << tabstr << "variables:\n"; for (auto& v : name_varid_map) { ss << "\t" << v.first << "\n"; } return ss.str(); } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::define_vector_field(const VectorField<Geo,FL>& v) { LPM_ASSERT(ncid != NC_EBADID); LPM_ASSERT(time_dimid != NC_EBADID); LPM_ASSERT(coord_dimid != NC_EBADID); int m_ndims = 3; int dimids[3]; dimids[0] = time_dimid; dimids[2] = coord_dimid; switch (FL) { case( ParticleField ) : { LPM_REQUIRE(particles_dimid != NC_EBADID); dimids[1] = particles_dimid; break; } case( VertexField ) : { LPM_REQUIRE(vertices_dimid != NC_EBADID); dimids[1] = vertices_dimid; break; } case( EdgeField ) : { LPM_REQUIRE(edges_dimid != NC_EBADID); dimids[1] = edges_dimid; break; } case( FaceField ) : { LPM_REQUIRE(faces_dimid != NC_EBADID); dimids[1] = faces_dimid; break; } } int varid = NC_EBADID; int retval = nc_def_var(ncid, v.name.c_str(), nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace(v.name, varid); for (auto& md : v.metadata) { retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str()); CHECK_NCERR(retval); } } template <typename Geo> void NcWriter<Geo>::define_single_real_var(const std::string& name, const ekat::units::Units& units, const Real val, const std::vector<text_att_type> metadata) { LPM_ASSERT(ncid != NC_EBADID); int* ignore_me; int varid = NC_EBADID; int retval = nc_def_var(ncid, name.c_str(), nc_real_type::value, 0, ignore_me, &varid); CHECK_NCERR(retval); name_varid_map.emplace(name, varid); const auto unitstr = ekat::units::to_string(units); retval = nc_put_att_text(ncid, varid, "units", unitstr.size(), unitstr.c_str()); for (auto& md : metadata) { retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str()); CHECK_NCERR(retval); } retval = nc_put_var(ncid, varid, &val); } template <typename Geo> void NcWriter<Geo>::close() { int retval = nc_close(ncid); CHECK_NCERR(retval); } template <typename Geo> Index NcWriter<Geo>::n_timesteps() const { size_t nsteps; int retval = nc_inq_dimlen(ncid, time_dimid, &nsteps); CHECK_NCERR(retval); return Index(nsteps); } template <typename Geo> Index NcWriter<Geo>::n_particles() const { size_t np; int retval = nc_inq_dimlen(ncid, particles_dimid, &np); CHECK_NCERR(retval); return Index(np); } template <typename Geo> Index NcWriter<Geo>::n_vertices() const { size_t nverts; int retval = nc_inq_dimlen(ncid, vertices_dimid, &nverts); if (retval == NC_EBADDIM) { nverts = 0; } else { CHECK_NCERR(retval); } return Index(nverts); } template <typename Geo> Index NcWriter<Geo>::n_edges() const { size_t nedges; int retval = nc_inq_dimlen(ncid, edges_dimid, &nedges); if (retval == NC_EBADDIM) { nedges = 0; } else { CHECK_NCERR(retval); } return Index(nedges); } template <typename Geo> Index NcWriter<Geo>::n_faces() const { size_t nfaces; int retval = nc_inq_dimlen(ncid, faces_dimid, &nfaces); if (retval == NC_EBADDIM) { nfaces = 0; } else { CHECK_NCERR(retval); } return Index(nfaces); } template <typename SeedType> std::shared_ptr<PolyMesh2d<SeedType>> PolymeshReader::init_polymesh() { auto result = std::shared_ptr<PolyMesh2d<SeedType>>(new PolyMesh2d<SeedType>(nmaxverts, nmaxedges, nmaxfaces)); fill_vertices(result->vertices); fill_edges(result->edges); fill_faces(result->faces); fill_crds(*(result->vertices.phys_crds), *(result->vertices.lag_crds), *(result->faces.phys_crds), *(result->faces.lag_crds)); result->update_device(); return result; } template <typename Geo> void PolymeshReader::fill_vertices(Vertices<Coords<Geo>>& verts) { LPM_ASSERT(vertices_dimid != NC_EBADID); const Index nverts = n_vertices(); verts._nh() = nverts; auto h_vert_crds = verts.host_crd_inds(); const size_t start = 0; const size_t count = nverts; int retval = nc_get_vara(ncid, name_varid_map.at("vertices.crd_inds"), &start, &count, h_vert_crds.data()); CHECK_NCERR(retval); } template <typename FaceType, typename Geo> void PolymeshReader::fill_faces(Faces<FaceType, Geo>& faces) { LPM_ASSERT(faces_dimid != NC_EBADID); LPM_ASSERT(facekind_dimid != NC_EBADID); size_t nfaceverts; int retval = nc_inq_dimlen(ncid, facekind_dimid, &nfaceverts); CHECK_NCERR(retval); LPM_REQUIRE(nfaceverts == FaceType::nverts); const Index nfaces = n_faces(); Index nleaves; retval = nc_get_att(ncid, NC_GLOBAL, "faces.n_leaves", &nleaves); faces._nh() = nfaces; faces._hn_leaves() = nleaves; { const size_t start = 0; const size_t count = nfaces; retval = nc_get_vara(ncid, name_varid_map.at("faces.crd_inds"), &start, &count, faces._host_crd_inds.data()); CHECK_NCERR(retval); retval = nc_get_vara(ncid, name_varid_map.at("faces.parent"), &start, &count, faces._hostparent.data()); CHECK_NCERR(retval); retval = nc_get_vara(ncid, name_varid_map.at("faces.level"), &start, &count, faces._hlevel.data()); CHECK_NCERR(retval); retval = nc_get_vara(ncid, name_varid_map.at("faces.area"), &start, &count, faces._hostarea.data()); } for (size_t i=0; i<nfaces; ++i) { size_t idx1 = i; uint_fast8_t mask_val; retval = nc_get_var1(ncid, name_varid_map.at("faces.mask"), &idx1, &mask_val); CHECK_NCERR(retval); faces._hmask(i) = (mask_val > 0 ? true : false); for (size_t j=0; j<nfaceverts; ++j) { size_t idx2[2] = {i,j}; retval = nc_get_var1(ncid, name_varid_map.at("faces.vertices"), idx2, &faces._hostverts(i,j)); CHECK_NCERR(retval); retval = nc_get_var1(ncid, name_varid_map.at("faces.edges"), idx2, &faces._hostedges(i,j)); CHECK_NCERR(retval); } for (size_t j=0; j<4; ++j) { size_t idx3[2] = {i,j}; retval = nc_get_var1(ncid, name_varid_map.at("faces.kids"), idx3, &faces._hostkids(i,j)); } } } template <typename Geo> void PolymeshReader::fill_crds(Coords<Geo>& vert_phys_crds, Coords<Geo>& vert_lag_crds, Coords<Geo>& face_phys_crds, Coords<Geo>& face_lag_crds) { const Index nverts = n_vertices(); vert_phys_crds._nh() = nverts; vert_lag_crds._nh() = nverts; const size_t last_time_idx = n_timesteps()-1; for (size_t i=0; i<nverts; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t pidx[3] = {last_time_idx, i,j}; const size_t lidx[2] = {i,j}; Real pcrdval; Real lcrdval; int retval = nc_get_var1(ncid, name_varid_map.at("vertices.phys_crds"), pidx, &pcrdval); CHECK_NCERR(retval); retval = nc_get_var1(ncid, name_varid_map.at("vertices.lag_crds"), lidx, &lcrdval); CHECK_NCERR(retval); vert_phys_crds._hostcrds(i,j) = pcrdval; vert_lag_crds._hostcrds(i,j) = lcrdval; } } const Index nfaces = n_faces(); face_phys_crds._nh() = nfaces; face_lag_crds._nh() = nfaces; for (size_t i=0; i<nfaces; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t pidx[3] = {last_time_idx, i,j}; const size_t lidx[2] = {i,j}; Real pcrdval; Real lcrdval; int retval = nc_get_var1(ncid, name_varid_map.at("faces.phys_crds"), pidx, &pcrdval); CHECK_NCERR(retval); retval = nc_get_var1(ncid, name_varid_map.at("faces.lag_crds"), lidx, &lcrdval); CHECK_NCERR(retval); face_phys_crds._hostcrds(i,j) = pcrdval; face_lag_crds._hostcrds(i,j) = lcrdval; } } } // ETI template class NcWriter<PlaneGeometry>; template class NcWriter<SphereGeometry>; } #endif
34.008
113
0.686231
pbosler
70f3b3aa51b0555247cc9f78af7e11a51239c6a5
4,784
cpp
C++
Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
1
2021-11-20T08:19:27.000Z
2021-11-20T08:19:27.000Z
Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
1
2019-01-09T08:20:18.000Z
2019-01-09T08:20:18.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIntroRegistry.h" #include <berryIConfigurationElement.h> #include <berryIExtension.h> #include "berryIntroDescriptor.h" #include "internal/berryRegistryReader.h" #include "berryWorkbenchPlugin.h" namespace berry { const QString IntroRegistry::TAG_INTRO = "intro"; const QString IntroRegistry::TAG_INTROPRODUCTBINDING = "introProductBinding"; const QString IntroRegistry::ATT_INTROID = "introId"; const QString IntroRegistry::ATT_PRODUCTID = "productId"; QString IntroRegistry::GetIntroForProduct( const QString& targetProductId, const QList<IExtension::Pointer>& extensions) const { for (int i = 0; i < extensions.size(); i++) { QList<IConfigurationElement::Pointer> elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTROPRODUCTBINDING) { QString introId = elements[j]->GetAttribute(ATT_INTROID); QString productId = elements[j]->GetAttribute(ATT_PRODUCTID); if (introId.isEmpty() || productId.isEmpty()) { //TODO IStatus /* IStatus status = new Status( IStatus.ERROR, elements[j].getDeclaringExtension() .getNamespace(), IStatus.ERROR, "introId and productId must be defined.", new IllegalArgumentException()); WorkbenchPlugin.log("Invalid intro binding", status); */ WorkbenchPlugin::Log( elements[j]->GetDeclaringExtension()->GetNamespaceIdentifier() + ": Invalid intro binding. introId and productId must be defined"); continue; } if (targetProductId == productId) { return introId; } } } } return ""; } int IntroRegistry::GetIntroCount() const { return static_cast<int> (GetIntros().size()); } QList<IIntroDescriptor::Pointer> IntroRegistry::GetIntros() const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return QList<IIntroDescriptor::Pointer>(); } QList<IExtension::Pointer> extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QList<IIntroDescriptor::Pointer> list; for (int i = 0; i < extensions.size(); i++) { QList<IConfigurationElement::Pointer> elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTRO) { try { IIntroDescriptor::Pointer descriptor(new IntroDescriptor(elements[j])); list.push_back(descriptor); } catch (const CoreException& e) { // log an error since its not safe to open a dialog here //TODO IStatus WorkbenchPlugin::Log("Unable to create intro descriptor", e); // e.getStatus()); } } } } return list; } IIntroDescriptor::Pointer IntroRegistry::GetIntroForProduct( const QString& targetProductId) const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return IIntroDescriptor::Pointer(); } QList<IExtension::Pointer> extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QString targetIntroId = GetIntroForProduct(targetProductId, extensions); if (targetIntroId.isEmpty()) { return IIntroDescriptor::Pointer(); } IIntroDescriptor::Pointer descriptor; QList<IIntroDescriptor::Pointer> intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { if (intros[i]->GetId() == targetIntroId) { descriptor = intros[i]; break; } } return descriptor; } IIntroDescriptor::Pointer IntroRegistry::GetIntro(const QString& id) const { QList<IIntroDescriptor::Pointer> intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { IIntroDescriptor::Pointer desc = intros[i]; if (desc->GetId() == id) { return desc; } } return IIntroDescriptor::Pointer(); } }
27.653179
90
0.639214
ZP-Hust
70f50b11f65556632c557a92f192e185af562105
10,958
cpp
C++
crypto/CadmiumCrypto.cpp
Acidburn0zzz/NfWebCrypto
0186e3ebde1779419053384983612d7d494e6bcc
[ "Apache-2.0" ]
null
null
null
crypto/CadmiumCrypto.cpp
Acidburn0zzz/NfWebCrypto
0186e3ebde1779419053384983612d7d494e6bcc
[ "Apache-2.0" ]
null
null
null
crypto/CadmiumCrypto.cpp
Acidburn0zzz/NfWebCrypto
0186e3ebde1779419053384983612d7d494e6bcc
[ "Apache-2.0" ]
null
null
null
/* * * Copyright 2013 Netflix, 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. * */ #include "CadmiumCrypto.h" #include <assert.h> #include "CadmiumCryptoImpl.h" using namespace std; namespace cadmium { using namespace base; namespace crypto { namespace //anonymous { map<string, CadmiumCrypto::Algorithm> gStr2AlgTab; void initStr2AlgTab() { gStr2AlgTab["HMAC"] = CadmiumCrypto::HMAC; gStr2AlgTab["AES-CBC"] = CadmiumCrypto::AES_CBC; gStr2AlgTab["AES-CTR"] = CadmiumCrypto::AES_CTR; gStr2AlgTab["AES-GCM"] = CadmiumCrypto::AES_GCM; gStr2AlgTab["RSAES-PKCS1-v1_5"] = CadmiumCrypto::RSAES_PKCS1_V1_5; gStr2AlgTab["RSASSA-PKCS1-v1_5"] = CadmiumCrypto::RSASSA_PKCS1_V1_5; gStr2AlgTab["RSA-OAEP"] = CadmiumCrypto::RSA_OAEP; gStr2AlgTab["SHA-1"] = CadmiumCrypto::SHA1; gStr2AlgTab["SHA-224"] = CadmiumCrypto::SHA224; gStr2AlgTab["SHA-256"] = CadmiumCrypto::SHA256; gStr2AlgTab["SHA-384"] = CadmiumCrypto::SHA384; gStr2AlgTab["SHA-512"] = CadmiumCrypto::SHA512; gStr2AlgTab["AES-KW"] = CadmiumCrypto::AES_KW; gStr2AlgTab["DH"] = CadmiumCrypto::DH; gStr2AlgTab["PBKDF2"] = CadmiumCrypto::PBKDF2; gStr2AlgTab["SYSTEM"] = CadmiumCrypto::SYSTEM; } } // anonymous namespace // CadmiumCrypto is "compiler firewall" in front of CadmiumCryptoImpl CadmiumCrypto::CadmiumCrypto(IDeviceInfo * pDeviceInfo) : impl_(new CadmiumCryptoImpl(pDeviceInfo)) { initStr2AlgTab(); } CadmiumCrypto::~CadmiumCrypto() { } CadErr CadmiumCrypto::init(const Vuc& prngSeed) { return impl_->init(prngSeed); } void CadmiumCrypto::addEntropy(const string& entropyBytes) { impl_->addEntropy(entropyBytes); } CadErr CadmiumCrypto::digest(Algorithm algorithm, const string& data, string& digest) { return impl_->digest(algorithm, data, digest); } CadErr CadmiumCrypto::importKey(KeyFormat format, const string& keyData, const Variant& algVar, bool extractable, const vector<KeyUsage>& keyUsage, uint32_t& keyHandle) { return impl_->importKey(format, keyData, algVar, extractable, keyUsage, keyHandle); } CadErr CadmiumCrypto::exportKey(uint32_t keyHandle, KeyFormat format, string& keyData) { return impl_->exportKey(keyHandle, format, keyData); } CadErr CadmiumCrypto::getKeyInfo(uint32_t keyHandle, KeyType& type, bool& extractable, Variant& algVar, vector<KeyUsage>& usage) const { return impl_->getKeyInfo(keyHandle, type, extractable, algVar, usage); } CadErr CadmiumCrypto::symKeyGen(const Variant& algVar, bool extractable, const vector<KeyUsage> keyUsage, uint32_t &keyHandle) { return impl_->symKeyGen(algVar, extractable, keyUsage, keyHandle); } CadErr CadmiumCrypto::aesCbc(uint32_t keyHandle, const string& ivIn, const string& dataIn, CipherOp cipherOp, string& dataOut) { return impl_->aesCbc(keyHandle, ivIn, dataIn, cipherOp, dataOut); } CadErr CadmiumCrypto::aesGcm(uint32_t keyHandle, const string& ivIn, const string& dataIn, const string& aadIn, uint8_t taglen, CipherOp cipherOp, string& dataOut) { return impl_->aesGcm(keyHandle, ivIn, dataIn, aadIn, taglen, cipherOp, dataOut); } CadErr CadmiumCrypto::rsaCrypt(uint32_t keyHandle, const string& dataIn, CipherOp cipherOp, string& dataOut) { return impl_->rsaCrypt(keyHandle, dataIn, cipherOp, dataOut); } CadErr CadmiumCrypto::hmac(uint32_t keyHandle, Algorithm shaAlgo, KeyUsage opUsage, const string& data, string& hmac) { return impl_->hmac(keyHandle, shaAlgo, opUsage, data, hmac); } CadErr CadmiumCrypto::rsaKeyGen(const Variant& algVar, bool extractable, vector<KeyUsage> keyUsage, uint32_t& pubKeyHandle, uint32_t& privKeyHandle) { return impl_->rsaKeyGen(algVar, extractable, keyUsage, pubKeyHandle, privKeyHandle); } CadErr CadmiumCrypto::rsaSign(uint32_t keyHandle, Algorithm shaAlgo, const string& data, string& sig) { return impl_->rsaSign(keyHandle, shaAlgo, data, sig); } CadErr CadmiumCrypto::rsaVerify(uint32_t keyHandle, Algorithm shaAlgo, const string& data, const string& sig, bool& isVerified) { return impl_->rsaVerify(keyHandle, shaAlgo, data, sig, isVerified); } CadErr CadmiumCrypto::dhKeyGen(const Variant& algVar, bool extractable, vector<KeyUsage> keyUsage, uint32_t& pubKeyHandle, uint32_t& privKeyHandle) { return impl_->dhKeyGen(algVar, extractable, keyUsage, pubKeyHandle, privKeyHandle); } CadErr CadmiumCrypto::dhDerive(uint32_t baseKeyHandle, const string& peerPublicKeyData, const Variant& derivedAlgObj, bool extractable, vector<KeyUsage> keyUsage, uint32_t& keyHandle) { return impl_->dhDerive(baseKeyHandle, peerPublicKeyData, derivedAlgObj, extractable, keyUsage, keyHandle); } CadErr CadmiumCrypto::unwrapJwe(const string& jweData, uint32_t wrappingKeyHandle, const base::Variant& algVar, bool extractable, const vector<KeyUsage>& keyUsage, uint32_t& keyHandle) { return impl_->unwrapJwe(jweData, wrappingKeyHandle, algVar, extractable, keyUsage, keyHandle); } CadErr CadmiumCrypto::wrapJwe(uint32_t toBeWrappedKeyHandle, uint32_t wrappingKeyHandle, const Variant& wrappingAlgoObj, JweEncMethod jweEncMethod, string& wrappedKeyJcs) { return impl_->wrapJwe(toBeWrappedKeyHandle, wrappingKeyHandle, wrappingAlgoObj, jweEncMethod, wrappedKeyJcs); } CadErr CadmiumCrypto::pbkdf2Derive(const string& salt, uint32_t iterations, const base::Variant& prf, const string& password, const base::Variant& derivedAlgObj, bool extractable, const vector<KeyUsage> usage, uint32_t &keyHandle) { return impl_->pbkdf2Derive(salt, iterations, prf, password, derivedAlgObj, extractable, usage, keyHandle); } CadErr CadmiumCrypto::getKeyByName(const string keyName, uint32_t &keyHandle, string& metadata) { return impl_->getKeyByName(keyName, keyHandle, metadata); } CadErr CadmiumCrypto::getDeviceId(string& deviceId) const { return impl_->getDeviceId(deviceId); } CadErr CadmiumCrypto::getSystemKeyHandle(uint32_t& systemKeyHandle) const { return impl_->getSystemKeyHandle(systemKeyHandle); } string toString(CadmiumCrypto::Algorithm algorithm) { switch (algorithm) { case CadmiumCrypto::HMAC: return "HMAC"; case CadmiumCrypto::AES_CBC: return "AES-CBC"; case CadmiumCrypto::AES_GCM: return "AES-GCM"; case CadmiumCrypto::AES_CTR: return "AES-CTR"; case CadmiumCrypto::RSAES_PKCS1_V1_5: return "RSAES-PKCS1-v1_5"; case CadmiumCrypto::RSASSA_PKCS1_V1_5: return "RSASSA-PKCS1-v1_5"; case CadmiumCrypto::RSA_OAEP: return "RSA-OAEP"; case CadmiumCrypto::SHA1: return "SHA-1"; case CadmiumCrypto::SHA224: return "SHA-224"; case CadmiumCrypto::SHA256: return "SHA-256"; case CadmiumCrypto::SHA384: return "SHA-384"; case CadmiumCrypto::SHA512: return "SHA-512"; case CadmiumCrypto::AES_KW: return "AES-KW"; case CadmiumCrypto::DH: return "DH"; case CadmiumCrypto::PBKDF2: return "PBKDF2"; case CadmiumCrypto::SYSTEM: return "SYSTEM"; case CadmiumCrypto::INVALID_ALGORITHM: default: return "invalid"; } } string toString(const vector<CadmiumCrypto::KeyUsage>& kusage) { string output = "[ "; vector<CadmiumCrypto::KeyUsage>::const_iterator it; for (it = kusage.begin(); it != kusage.end(); ++it) output += toString(*it) + " "; output += "]"; return output; } string toString(CadmiumCrypto::KeyType keyType) { switch (keyType) { case CadmiumCrypto::SECRET: return "secret"; break; case CadmiumCrypto::PUBLIC: return "public"; break; case CadmiumCrypto::PRIVATE: return "private"; break; } return "invalid"; } string toString(CadmiumCrypto::KeyUsage keyUsage) { switch (keyUsage) { case CadmiumCrypto::ENCRYPT: return "encrypt"; break; case CadmiumCrypto::DECRYPT: return "decrypt"; break; case CadmiumCrypto::SIGN: return "sign"; break; case CadmiumCrypto::VERIFY: return "verify"; break; case CadmiumCrypto::DERIVE: return "derive"; break; case CadmiumCrypto::WRAP: return "wrap"; break; case CadmiumCrypto::UNWRAP: return "unwrap"; break; } return "invalid"; } string toString(CadmiumCrypto::JweEncMethod jweEncMethod) { switch (jweEncMethod) { case CadmiumCrypto::A128GCM: return "A128GCM"; break; case CadmiumCrypto::A256GCM: return "A256GCM"; break; } return "invalid"; } bool isAlgorithmRsa(CadmiumCrypto::Algorithm algorithm) { return ( algorithm == CadmiumCrypto::RSAES_PKCS1_V1_5 || algorithm == CadmiumCrypto::RSASSA_PKCS1_V1_5 || algorithm == CadmiumCrypto::RSA_OAEP ); } bool isAlgorithmAes(CadmiumCrypto::Algorithm algorithm) { return ( algorithm == CadmiumCrypto::AES_CBC || algorithm == CadmiumCrypto::AES_GCM || algorithm == CadmiumCrypto::AES_CTR || algorithm == CadmiumCrypto::AES_KW ); } bool isAlgorithmHmac(CadmiumCrypto::Algorithm algorithm) { return ( algorithm == CadmiumCrypto::HMAC ); } bool isAlgorithmSha(CadmiumCrypto::Algorithm algorithm) { return ( algorithm == CadmiumCrypto::SHA1 || algorithm == CadmiumCrypto::SHA224 || algorithm == CadmiumCrypto::SHA256 || algorithm == CadmiumCrypto::SHA384 || algorithm == CadmiumCrypto::SHA512 ); } bool isAlgorithmDh(CadmiumCrypto::Algorithm algorithm) { return ( algorithm == CadmiumCrypto::DH ); } bool isAlgorithmPbkdf2(CadmiumCrypto::Algorithm algorithm) { return ( algorithm == CadmiumCrypto::PBKDF2 ); } CadmiumCrypto::Algorithm toAlgorithm(const string& algorithmStr) { assert(gStr2AlgTab.size()); if (!gStr2AlgTab.count(algorithmStr)) return CadmiumCrypto::INVALID_ALGORITHM; return gStr2AlgTab[algorithmStr]; } }} // namespace cadmium::crypto
34.137072
95
0.682059
Acidburn0zzz
70f631eeeaa44d21e18c79b374369fadbb3ccd72
398
hpp
C++
Horista.hpp
vinicassol/PolimorfismoEmpregados
b73a35536c1b6f6acd3cf64d02f71a923174e096
[ "MIT" ]
1
2020-12-29T01:35:03.000Z
2020-12-29T01:35:03.000Z
Horista.hpp
vinicassol/PolimorfismoEmpregados
b73a35536c1b6f6acd3cf64d02f71a923174e096
[ "MIT" ]
null
null
null
Horista.hpp
vinicassol/PolimorfismoEmpregados
b73a35536c1b6f6acd3cf64d02f71a923174e096
[ "MIT" ]
null
null
null
// // Horista.hpp // PolimorfismoEmpregados // // Created by Vini Cassol on 29/05/20. // Copyright © 2020 Vini Cassol. All rights reserved. // #ifndef Horista_hpp #define Horista_hpp #include "Empregado.hpp" class Horista : public Empregado { public: Horista(); double vencimento(); private: double precoHora; double horasTrabalhadas; }; #endif /* Horista_hpp */
14.214286
54
0.673367
vinicassol
70f7688501a0a51d243ec19077826b0657a1e230
32,725
cpp
C++
MNE/inverse/hpiFit/hpifit.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
2
2017-04-20T20:21:16.000Z
2017-04-26T16:30:25.000Z
MNE/inverse/hpiFit/hpifit.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
null
null
null
MNE/inverse/hpiFit/hpifit.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
1
2017-04-23T15:55:31.000Z
2017-04-23T15:55:31.000Z
//============================================================================================================= /** * @file hpifit.cpp * @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date March, 2017 * * @section LICENSE * * Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief HPIFit class defintion. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "hpifit.h" #include <fiff/fiff_dig_point_set.h> #include <utils/ioutils.h> #include <iostream> #include <fiff/fiff_cov.h> #include <fstream> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/SVD> #include <Eigen/Dense> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QFuture> #include <QtConcurrent/QtConcurrent> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace INVERSELIB; using namespace FIFFLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= Eigen::MatrixXd pinv(Eigen::MatrixXd a) { double epsilon = std::numeric_limits<double>::epsilon(); Eigen::JacobiSVD< Eigen::MatrixXd > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV); double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0); return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(),0).matrix().asDiagonal() * svd.matrixU().adjoint(); } /********************************************************************************* * magnetic_dipole leadfield for a magnetic dipole in an infinite medium * The function has been compared with matlab magnetic_dipole and it gives same output *********************************************************************************/ Eigen::MatrixXd magnetic_dipole(Eigen::MatrixXd pos, Eigen::MatrixXd pnt, Eigen::MatrixXd ori) { double u0 = 1e-7; int nchan; Eigen::MatrixXd r, r2, r5, x, y, z, mx, my, mz, Tx, Ty, Tz, lf; nchan = pnt.rows(); // Shift the magnetometers so that the dipole is in the origin pnt.array().col(0) -= pos(0); pnt.array().col(1) -= pos(1); pnt.array().col(2) -= pos(2); r = pnt.array().square().rowwise().sum().sqrt(); r2 = r5 = x = y = z = mx = my = mz = Tx = Ty = Tz = lf = Eigen::MatrixXd::Zero(nchan,3); for(int i = 0;i < nchan;i++) { r2.row(i).array().fill(pow(r(i),2)); r5.row(i).array().fill(pow(r(i),5)); } for(int i = 0;i < nchan;i++) { x.row(i).array().fill(pnt(i,0)); y.row(i).array().fill(pnt(i,1)); z.row(i).array().fill(pnt(i,2)); } mx.col(0).array().fill(1); my.col(1).array().fill(1); mz.col(2).array().fill(1); Tx = 3 * x.cwiseProduct(pnt) - mx.cwiseProduct(r2); Ty = 3 * y.cwiseProduct(pnt) - my.cwiseProduct(r2); Tz = 3 * z.cwiseProduct(pnt) - mz.cwiseProduct(r2); for(int i = 0;i < nchan;i++) { lf(i,0) = Tx.row(i).dot(ori.row(i)); lf(i,1) = Ty.row(i).dot(ori.row(i)); lf(i,2) = Tz.row(i).dot(ori.row(i)); } for(int i = 0;i < nchan;i++) { for(int j = 0;j < 3;j++) { lf(i,j) = u0 * lf(i,j)/(4 * M_PI * r5(i,j)); } } return lf; } /********************************************************************************* * compute_leadfield computes a forward solution for a dipole in a a volume * conductor model. The forward solution is expressed as the leadfield * matrix (Nchan*3), where each column corresponds with the potential or field * distributions on all sensors for one of the x,y,z-orientations of the dipole. * The function has been compared with matlab ft_compute_leadfield and it gives * same output *********************************************************************************/ Eigen::MatrixXd compute_leadfield(const Eigen::MatrixXd& pos, const struct SensorInfo& sensors) { Eigen::MatrixXd pnt, ori, lf; pnt = sensors.coilpos; // position of each coil ori = sensors.coilori; // orientation of each coil lf = magnetic_dipole(pos, pnt, ori); lf = sensors.tra * lf; return lf; } /********************************************************************************* * dipfitError computes the error between measured and model data * and can be used for non-linear fitting of dipole position. * The function has been compared with matlab dipfit_error and it gives * same output *********************************************************************************/ DipFitError dipfitError(const Eigen::MatrixXd& pos, const Eigen::MatrixXd& data, const struct SensorInfo& sensors, const Eigen::MatrixXd& matProjectors) { // Variable Declaration struct DipFitError e; Eigen::MatrixXd lf, dif; // Compute lead field for a magnetic dipole in infinite vacuum lf = compute_leadfield(pos, sensors); e.moment = pinv(lf) * data; //dif = data - lf * e.moment; dif = data - matProjectors * lf * e.moment; e.error = dif.array().square().sum()/data.array().square().sum(); e.numIterations = 0; return e; } /********************************************************************************* * Compare function for sorting *********************************************************************************/ bool compare(HPISortStruct a, HPISortStruct b) { return (a.base_arr < b.base_arr); } /********************************************************************************* * fminsearch Multidimensional unconstrained nonlinear minimization (Nelder-Mead). * X = fminsearch(X0, maxiter, maxfun, display, data, sensors) starts at X0 and * attempts to find a local minimizer *********************************************************************************/ Eigen::MatrixXd fminsearch(const Eigen::MatrixXd& pos, int maxiter, int maxfun, int display, const Eigen::MatrixXd& data, const Eigen::MatrixXd& matProjectors, const struct SensorInfo& sensors, int &simplex_numitr) { double tolx, tolf, rho, chi, psi, sigma, func_evals, usual_delta, zero_term_delta, temp1, temp2; std::string header, how; int n, itercount, prnt; Eigen::MatrixXd onesn, two2np1, one2n, v, y, v1, tempX1, tempX2, xbar, xr, x, xe, xc, xcc, xin, posCopy; std::vector <double> fv, fv1; std::vector <int> idx; DipFitError tempdip, fxr, fxe, fxc, fxcc; //tolx = tolf = 1e-4; // Seok tolx = tolf = 1e-9; switch(display) { case 0: prnt = 0; break; default: prnt = 1; } header = " Iteration Func-count min f(x) Procedure"; posCopy = pos; n = posCopy.cols(); // Initialize parameters rho = 1; chi = 2; psi = 0.5; sigma = 0.5; onesn = Eigen::MatrixXd::Ones(1,n); two2np1 = one2n = Eigen::MatrixXd::Zero(1,n); for(int i = 0;i < n;i++) { two2np1(i) = 1 + i; one2n(i) = i; } v = v1 = Eigen::MatrixXd::Zero(n, n+1); fv.resize(n+1); idx.resize(n+1); fv1.resize(n+1); for(int i = 0;i < n; i++) { v(i,0) = posCopy(i); } tempdip = dipfitError(posCopy, data, sensors, matProjectors); fv[0] = tempdip.error; func_evals = 1; itercount = 0; how = ""; // Continue setting up the initial simplex. // Following improvement suggested by L.Pfeffer at Stanford usual_delta = 0.05; // 5 percent deltas for non-zero terms zero_term_delta = 0.00025; // Even smaller delta for zero elements of x xin = posCopy.transpose(); for(int j = 0;j < n;j++) { y = xin; if(y(j) != 0) { y(j) = (1 + usual_delta) * y(j); } else { y(j) = zero_term_delta; } v.col(j+1).array() = y; posCopy = y.transpose(); tempdip = dipfitError(posCopy, data, sensors, matProjectors); fv[j+1] = tempdip.error; } // Sort elements of fv std::vector<HPISortStruct> vecSortStruct; for (int i = 0; i < fv.size(); i++) { HPISortStruct structTemp; structTemp.base_arr = fv[i]; structTemp.idx = i; vecSortStruct.push_back(structTemp); } sort (vecSortStruct.begin(), vecSortStruct.end(), compare); for (int i = 0; i < vecSortStruct.size(); i++) { idx[i] = vecSortStruct[i].idx; } for (int i = 0;i < n+1;i++) { v1.col(i) = v.col(idx[i]); fv1[i] = fv[idx[i]]; } v = v1;fv = fv1; how = "initial simplex"; itercount = itercount + 1; func_evals = n + 1; tempX1 = Eigen::MatrixXd::Zero(1,n); while ((func_evals < maxfun) && (itercount < maxiter)) { for (int i = 0;i < n;i++) { tempX1(i) = abs(fv[0] - fv[i+1]); } temp1 = tempX1.maxCoeff(); tempX2 = Eigen::MatrixXd::Zero(n,n); for(int i = 0;i < n;i++) { tempX2.col(i) = v.col(i+1) - v.col(0); } tempX2 = tempX2.array().abs(); temp2 = tempX2.maxCoeff(); if((temp1 <= tolf) && (temp2 <= tolx)) { break; } xbar = v.block(0,0,n,n).rowwise().sum(); xbar /= n; xr = (1+rho) * xbar - rho * v.block(0,n,v.rows(),1); x = xr.transpose(); //std::cout << "Iteration Count: " << itercount << ":" << x << std::endl; fxr = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals+1; if (fxr.error < fv[0]) { // Calculate the expansion point xe = (1 + rho * chi) * xbar - rho * chi * v.col(v.cols()-1); x = xe.transpose(); fxe = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals+1; if(fxe.error < fxr.error) { v.col(v.cols()-1) = xe; fv[n] = fxe.error; how = "expand"; } else { v.col(v.cols()-1) = xr; fv[n] = fxr.error; how = "reflect"; } } else { if(fxr.error < fv[n-1]) { v.col(v.cols()-1) = xr; fv[n] = fxr.error; how = "reflect"; } else { // fxr.error >= fv[:,n-1] // Perform contraction if(fxr.error < fv[n]) { // Perform an outside contraction xc = (1 + psi * rho) * xbar - psi * rho * v.col(v.cols()-1); x = xc.transpose(); fxc = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals + 1; if(fxc.error <= fxr.error) { v.col(v.cols()-1) = xc; fv[n] = fxc.error; how = "contract outside"; } else { // perform a shrink how = "shrink"; } } else { xcc = (1 - psi) * xbar + psi * v.col(v.cols()-1); x = xcc.transpose(); fxcc = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals+1; if(fxcc.error < fv[n]) { v.col(v.cols()-1) = xcc; fv[n] = fxcc.error; how = "contract inside"; } else { // perform a shrink how = "shrink"; } } if(how.compare("shrink") == 0) { for(int j = 1;j < n+1;j++) { v.col(j).array() = v.col(0).array() + sigma * (v.col(j).array() - v.col(0).array()); x = v.col(j).array().transpose(); tempdip = dipfitError(x,data, sensors, matProjectors); fv[j] = tempdip.error; } } } } // Sort elements of fv vecSortStruct.clear(); for (int i = 0; i < fv.size(); i++) { HPISortStruct structTemp; structTemp.base_arr = fv[i]; structTemp.idx = i; vecSortStruct.push_back(structTemp); } sort (vecSortStruct.begin(), vecSortStruct.end(), compare); for (int i = 0; i < vecSortStruct.size(); i++) { idx[i] = vecSortStruct[i].idx; } for (int i = 0;i < n+1;i++) { v1.col(i) = v.col(idx[i]); fv1[i] = fv[idx[i]]; } v = v1; fv = fv1; itercount = itercount + 1; } x = v.col(0).transpose(); // Seok simplex_numitr = itercount; return x; } /********************************************************************************* * dipfit function is adapted from Fieldtrip Software. It has been * heavily edited for use with MNE Scan Software *********************************************************************************/ void doDipfitConcurrent(FittingCoilData& lCoilData) { // Initialize variables Eigen::RowVectorXd currentCoil = lCoilData.coilPos; Eigen::VectorXd currentData = lCoilData.sensorData; SensorInfo currentSensors = lCoilData.sensorPos; int display = 0; int maxiter = 500; int simplex_numitr = 0; lCoilData.coilPos = fminsearch(currentCoil, maxiter, 2 * maxiter * currentCoil.cols(), display, currentData, lCoilData.matProjector, currentSensors, simplex_numitr); lCoilData.errorInfo = dipfitError(currentCoil, currentData, currentSensors, lCoilData.matProjector); lCoilData.errorInfo.numIterations = simplex_numitr; } //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= HPIFit::HPIFit() { } //************************************************************************************************************* void HPIFit::fitHPI(const MatrixXd& t_mat, const Eigen::MatrixXd& t_matProjectors, FiffCoordTrans& transDevHead, const QVector<int>& vFreqs, QVector<double>& vGof, FiffDigPointSet& fittedPointSet, FiffInfo::SPtr pFiffInfo, bool bDoDebug, const QString& sHPIResourceDir) { //Check if data was passed if(t_mat.rows() == 0 || t_mat.cols() == 0 ) { std::cout<<std::endl<< "HPIFit::fitHPI - No data passed. Returning."; } //Check if projector was passed if(t_matProjectors.rows() == 0 || t_matProjectors.cols() == 0 ) { std::cout<<std::endl<< "HPIFit::fitHPI - No projector passed. Returning."; } vGof.clear(); struct SensorInfo sensors; struct CoilParam coil; int numCh = pFiffInfo->nchan; int samF = pFiffInfo->sfreq; int samLoc = t_mat.cols(); // minimum samples required to localize numLoc times in a second //Get HPI coils from digitizers and set number of coils int numCoils = 0; QList<FiffDigPoint> lHPIPoints; for(int i = 0; i < pFiffInfo->dig.size(); ++i) { if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) { numCoils++; lHPIPoints.append(pFiffInfo->dig[i]); } } //Set coil frequencies Eigen::VectorXd coilfreq(numCoils); if(vFreqs.size() >= numCoils) { for(int i = 0; i < numCoils; ++i) { coilfreq[i] = vFreqs.at(i); //std::cout<<std::endl << coilfreq[i] << "Hz"; } } else { std::cout<<std::endl<< "HPIFit::fitHPI - Not enough coil frequencies specified. Returning."; return; } // Initialize HPI coils location and moment coil.pos = Eigen::MatrixXd::Zero(numCoils,3); coil.mom = Eigen::MatrixXd::Zero(numCoils,3); coil.dpfiterror = Eigen::VectorXd::Zero(numCoils); coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils); // Generate simulated data Eigen::MatrixXd simsig(samLoc,numCoils*2); Eigen::VectorXd time(samLoc); for (int i = 0; i < samLoc; ++i) { time[i] = i*1.0/samF; } for(int i = 0; i < numCoils; ++i) { for(int j = 0; j < samLoc; ++j) { simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]); simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]); } } // Create digitized HPI coil position matrix Eigen::MatrixXd headHPI(numCoils,3); // check the pFiffInfo->dig information. If dig is empty, set the headHPI is 0; if (lHPIPoints.size() > 0) { for (int i = 0; i < lHPIPoints.size(); ++i) { headHPI(i,0) = lHPIPoints.at(i).r[0]; headHPI(i,1) = lHPIPoints.at(i).r[1]; headHPI(i,2) = lHPIPoints.at(i).r[2]; } } else { for (int i = 0; i < numCoils; ++i) { headHPI(i,0) = 0; headHPI(i,1) = 0; headHPI(i,2) = 0; } } // Get the indices of inner layer channels and exclude bad channels. //TODO: Only supports babymeg and vectorview gradiometeres for hpi fitting. QVector<int> innerind(0); for (int i = 0; i < numCh; ++i) { if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG || pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 || pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 || pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) { // Check if the sensor is bad, if not append to innerind if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) { innerind.append(i); } } } //Create new projector based on the excluded channels, first exclude the rows then the columns MatrixXd matProjectorsRows(innerind.size(),t_matProjectors.cols()); MatrixXd matProjectorsInnerind(innerind.size(),innerind.size()); for (int i = 0; i < matProjectorsRows.rows(); ++i) { matProjectorsRows.row(i) = t_matProjectors.row(innerind.at(i)); } for (int i = 0; i < matProjectorsInnerind.cols(); ++i) { matProjectorsInnerind.col(i) = matProjectorsRows.col(innerind.at(i)); } //UTILSLIB::IOUtils::write_eigen_matrix(matProjectorsInnerind, "matProjectorsInnerind.txt"); //UTILSLIB::IOUtils::write_eigen_matrix(t_matProjectors, "t_matProjectors.txt"); // Initialize inner layer sensors sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3); sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3); sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size()); for(int i = 0; i < innerind.size(); i++) { sensors.coilpos(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.r0[0]; sensors.coilpos(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.r0[1]; sensors.coilpos(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.r0[2]; sensors.coilori(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.ez[0]; sensors.coilori(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.ez[1]; sensors.coilori(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.ez[2]; } Eigen::MatrixXd topo(innerind.size(), numCoils*2); Eigen::MatrixXd amp(innerind.size(), numCoils); Eigen::MatrixXd ampC(innerind.size(), numCoils); // Get the data from inner layer channels Eigen::MatrixXd innerdata(innerind.size(), t_mat.cols()); for(int j = 0; j < innerind.size(); ++j) { innerdata.row(j) << t_mat.row(innerind[j]); } // Calculate topo topo = innerdata * pinv(simsig).transpose(); // topo: # of good inner channel x 8 // Select sine or cosine component depending on the relative size amp = topo.leftCols(numCoils); // amp: # of good inner channel x 4 ampC = topo.rightCols(numCoils); for(int j = 0; j < numCoils; ++j) { float nS = 0.0; float nC = 0.0; for(int i = 0; i < innerind.size(); ++i) { nS += amp(i,j)*amp(i,j); nC += ampC(i,j)*ampC(i,j); } if(nC > nS) { for(int i = 0; i < innerind.size(); ++i) { amp(i,j) = ampC(i,j); } } } //Find good seed point/starting point for the coil position in 3D space //Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index VectorXi chIdcs(numCoils); for (int j = 0; j < numCoils; j++) { double maxVal = 0; int chIdx = 0; for (int i = 0; i < amp.rows(); ++i) { if(abs(amp(i,j)) > maxVal) { maxVal = abs(amp(i,j)); if(chIdx < innerind.size()) { chIdx = innerind.at(i); } } } chIdcs(j) = chIdx; } //Generate seed point by projection the found channel position 3cm inwards Eigen::MatrixXd coilPos = Eigen::MatrixXd::Zero(numCoils,3); for (int j = 0; j < chIdcs.rows(); ++j) { int chIdx = chIdcs(j); if(chIdx < pFiffInfo->chs.size()) { double x = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[0]; double y = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[1]; double z = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[2]; coilPos(j,0) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[0] * 0.03 + x; coilPos(j,1) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[1] * 0.03 + y; coilPos(j,2) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[2] * 0.03 + z; } //std::cout << "HPIFit::fitHPI - Coil " << j << " max value index " << chIdx << std::endl; } coil.pos = coilPos; coil = dipfit(coil, sensors, amp, numCoils, matProjectorsInnerind); Eigen::Matrix4d trans = computeTransformation(headHPI, coil.pos); //Eigen::Matrix4d trans = computeTransformation(coil.pos, headHPI); // Store the final result to fiff info // Set final device/head matrix and its inverse to the fiff info transDevHead.from = 1; transDevHead.to = 4; for(int r = 0; r < 4; ++r) { for(int c = 0; c < 4 ; ++c) { transDevHead.trans(r,c) = trans(r,c); } } // Also store the inverse transDevHead.invtrans = transDevHead.trans.inverse(); //Calculate GOF MatrixXd temp = coil.pos; temp.conservativeResize(coil.pos.rows(),coil.pos.cols()+1); temp.block(0,3,numCoils,1).setOnes(); temp.transposeInPlace(); MatrixXd testPos = trans * temp; MatrixXd diffPos = testPos.block(0,0,3,numCoils) - headHPI.transpose(); for(int i = 0; i < diffPos.cols(); ++i) { vGof.append(diffPos.col(i).norm()); } //Generate final fitted points and store in digitizer set for(int i = 0; i < coil.pos.rows(); ++i) { FiffDigPoint digPoint; digPoint.kind = FIFFV_POINT_EEG; digPoint.ident = i; digPoint.r[0] = coil.pos(i,0); digPoint.r[1] = coil.pos(i,1); digPoint.r[2] = coil.pos(i,2); fittedPointSet << digPoint; } if(bDoDebug) { // DEBUG HPI fitting and write debug results std::cout << std::endl << std::endl << "HPIFit::fitHPI - dpfiterror" << coil.dpfiterror << std::endl << coil.pos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - Initial seed point for HPI coils" << std::endl << coil.pos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - temp" << std::endl << temp << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - testPos" << std::endl << testPos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - Diff fitted - original" << std::endl << diffPos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - dev/head trans" << std::endl << trans << std::endl; QString sTimeStamp = QDateTime::currentDateTime().toString("yyMMdd_hhmmss"); if(!QDir(sHPIResourceDir).exists()) { QDir().mkdir(sHPIResourceDir); } UTILSLIB::IOUtils::write_eigen_matrix(coilPos, QString("%1/%2_coilPosSeed_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString("%1/%2_coilPos_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(headHPI, QString("%1/%2_headHPI_mat").arg(sHPIResourceDir).arg(sTimeStamp)); MatrixXd testPosCut = testPos.transpose();//block(0,0,3,4); UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString("%1/%2_testPos_mat").arg(sHPIResourceDir).arg(sTimeStamp)); MatrixXi idx_mat(chIdcs.rows(),1); idx_mat.col(0) = chIdcs; UTILSLIB::IOUtils::write_eigen_matrix(idx_mat, QString("%1/%2_idx_mat").arg(sHPIResourceDir).arg(sTimeStamp)); MatrixXd coilFreq_mat(coilfreq.rows(),1); coilFreq_mat.col(0) = coilfreq; UTILSLIB::IOUtils::write_eigen_matrix(coilFreq_mat, QString("%1/%2_coilFreq_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(diffPos, QString("%1/%2_diffPos_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(amp, QString("%1/%2_amp_mat").arg(sHPIResourceDir).arg(sTimeStamp)); } } //************************************************************************************************************* CoilParam HPIFit::dipfit(struct CoilParam coil, struct SensorInfo sensors, const Eigen::MatrixXd& data, int numCoils, const Eigen::MatrixXd& t_matProjectors) { //Do this in conncurrent mode //Generate QList structure which can be handled by the QConcurrent framework QList<FittingCoilData> lCoilData; for(qint32 i = 0; i < numCoils; ++i) { FittingCoilData coilData; coilData.coilPos = coil.pos.row(i); coilData.sensorData = data.col(i); coilData.sensorPos = sensors; coilData.matProjector = t_matProjectors; lCoilData.append(coilData); } //Do the concurrent filtering if(!lCoilData.isEmpty()) { //Do sequential for(int l = 0; l < lCoilData.size(); ++l) { doDipfitConcurrent(lCoilData[l]); } // //Do concurrent // QFuture<void> future = QtConcurrent::map(lCoilData, // doDipfitConcurrent); // future.waitForFinished(); //Transform results to final coil information for(qint32 i = 0; i < lCoilData.size(); ++i) { coil.pos.row(i) = lCoilData.at(i).coilPos; coil.mom = lCoilData.at(i).errorInfo.moment.transpose(); coil.dpfiterror(i) = lCoilData.at(i).errorInfo.error; coil.dpfitnumitr(i) = lCoilData.at(i).errorInfo.numIterations; //std::cout<<std::endl<< "HPIFit::dipfit - Itr steps for coil " << i << " =" <<coil.dpfitnumitr(i); } } return coil; } //************************************************************************************************************* Eigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT) { Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q; Eigen::Matrix4d transFinal = Eigen::Matrix4d::Identity(4,4); Eigen::Matrix4d Rot = Eigen::Matrix4d::Zero(4,4); Eigen::Matrix4d Trans = Eigen::Matrix4d::Identity(4,4); double meanx,meany,meanz,normf; for(int i = 0; i < 15; ++i) { // Calcualte mean translation for all points -> centroid of both data sets xdiff = NH.col(0) - BT.col(0); ydiff = NH.col(1) - BT.col(1); zdiff = NH.col(2) - BT.col(2); meanx = xdiff.mean(); meany = ydiff.mean(); meanz = zdiff.mean(); // Apply translation -> bring both data sets to the same center location for (int j = 0; j < BT.rows(); ++j) { BT(j,0) = BT(j,0) + meanx; BT(j,1) = BT(j,1) + meany; BT(j,2) = BT(j,2) + meanz; } // Estimate rotation component C = BT.transpose() * NH; Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV); Q = svd.matrixU() * svd.matrixV().transpose(); //Handle special reflection case if(Q.determinant() < 0) { Q(0,2) = Q(0,2) * -1; Q(1,2) = Q(1,2) * -1; Q(2,2) = Q(2,2) * -1; } // Apply rotation on translated points BT = BT * Q; // Calculate GOF normf = (NH.transpose()-BT.transpose()).norm(); // Store rotation part to transformation matrix Rot(3,3) = 1; for(int j = 0; j < 3; ++j) { for(int k = 0; k < 3; ++k) { Rot(j,k) = Q(k,j); } } // Store translation part to transformation matrix Trans(0,3) = meanx; Trans(1,3) = meany; Trans(2,3) = meanz; // Safe rotation and translation to final matrix for next iteration step transFinal = Rot * Trans * transFinal; } return transFinal; }
35.765027
173
0.507288
13grife37
70f8e531e5af9e2fa3fcc995ffb144de30c83a8d
2,792
hpp
C++
include/crosstex/BC.hpp
Yepoleb/crosstex
02f6da62895c1e14de37f140470b41f0952a4af3
[ "MIT" ]
4
2017-12-24T16:19:29.000Z
2020-02-15T13:40:43.000Z
include/crosstex/BC.hpp
Yepoleb/crosstex
02f6da62895c1e14de37f140470b41f0952a4af3
[ "MIT" ]
null
null
null
include/crosstex/BC.hpp
Yepoleb/crosstex
02f6da62895c1e14de37f140470b41f0952a4af3
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #include <stddef.h> #include "Colors.hpp" #define UNREFERENCED_PARAMETER(name) do { (void)(name); } while (0) namespace Tex { //------------------------------------------------------------------------------------- // Constants //------------------------------------------------------------------------------------- const size_t NUM_PIXELS_PER_BLOCK = 16; enum BC_FLAGS { BC_FLAGS_NONE = 0x0, BC_FLAGS_DITHER_RGB = 0x10000, // Enables dithering for RGB colors for BC1-3 BC_FLAGS_DITHER_A = 0x20000, // Enables dithering for Alpha channel for BC1-3 BC_FLAGS_UNIFORM = 0x40000, // By default, uses perceptual weighting for BC1-3; this flag makes it a uniform weighting BC_FLAGS_USE_3SUBSETS = 0x80000, // By default, BC7 skips mode 0 & 2; this flag adds those modes back BC_FLAGS_FORCE_BC7_MODE6 = 0x100000, // BC7 should only use mode 6; skip other modes }; //------------------------------------------------------------------------------------- // Functions //------------------------------------------------------------------------------------- typedef void (*BC_DECODE)(HDRColorA *pColor, const uint8_t *pBC); typedef void (*BC_ENCODE)(uint8_t *pDXT, const HDRColorA *pColor, uint32_t flags); void DecodeBC1(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC2(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC3(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC4U(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC4S(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC5U(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC5S(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC6HU(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC6HS(HDRColorA *pColor, const uint8_t *pBC); void DecodeBC7(HDRColorA *pColor, const uint8_t *pBC); void EncodeBC1(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); // BC1 may have one additional parameter, so it doesn't match signature of BC_ENCODE above void EncodeBC1(uint8_t *pBC, const HDRColorA *pColor, float threshold, uint32_t flags); void EncodeBC2(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC3(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC4U(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC4S(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC5U(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC5S(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC6HU(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC6HS(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); void EncodeBC7(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags); }; // namespace
44.31746
134
0.653653
Yepoleb
70fc1ccb1df0ebc43bda8ead109ac1b70e7eefe3
5,669
cpp
C++
src/common/commandLine.cpp
salarii/dims
b8008c49edd10a9ca50923b89e3b469c342d9cee
[ "MIT" ]
1
2015-01-22T11:22:19.000Z
2015-01-22T11:22:19.000Z
src/common/commandLine.cpp
salivan-ratcoin-dev-team/dims
b8008c49edd10a9ca50923b89e3b469c342d9cee
[ "MIT" ]
null
null
null
src/common/commandLine.cpp
salivan-ratcoin-dev-team/dims
b8008c49edd10a9ca50923b89e3b469c342d9cee
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 DiMS dev-team // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "rpcclient.h" #include "util.h" #include "json/json_spirit_value.h" #include <openssl/crypto.h> #include "common/commandLine.h" #include <boost/thread.hpp> namespace common { CCommandLine * CCommandLine::ms_instance = NULL; CCommandLine* CCommandLine::getInstance() { if ( !ms_instance ) { ms_instance = new CCommandLine(); }; return ms_instance; } void CCommandLine::reply( CMessageClass::Enum _category, std::string const & _commandResponse ) { std::string comandResponse; switch( _category ) { case CMessageClass::MC_ERROR: comandResponse = "CODE ERROR: "; break; case CMessageClass::MC_DEBUG: comandResponse = "CODE DEBUG: "; break; case CMessageClass::CMD_REQUEST: comandResponse = "COMMAND REQUEST: "; break; case CMessageClass::CMD_REPLY: comandResponse = "COMMAND REPLY: "; break; case CMessageClass::CMD_ERROR: comandResponse = "COMMAND ERROR: "; break; default: break; } addOutputMessage( comandResponse + _commandResponse ); } void CCommandLine::workLoop() { fd_set read_fds; timeval waitTime; waitTime.tv_sec = 0; waitTime.tv_usec = 0; bool promptPrinted = false; while ( 1 ) { if ( !promptPrinted ) { promptPrinted = true; std::cout << "PROMPT > "; std::cout.flush(); } std::string line; FD_ZERO(&read_fds); FD_SET( STDIN_FILENO, &read_fds ); int result = select( FD_SETSIZE, &read_fds, NULL, NULL, &waitTime ); if (result == -1 && errno != EINTR) { assert(!"Error in select"); } else if (result == -1 && errno == EINTR) { assert(!"problem"); } else { if (FD_ISSET(STDIN_FILENO, &read_fds)) { promptPrinted = false; std::getline(std::cin, line); } } if ( !line.empty() ) { request( line ); } boost::lock_guard<boost::mutex> lock( m_lock ); BOOST_FOREACH( std::string const & out, m_outputs ) { std::cout << out << "\n\n"; } m_outputs.clear(); MilliSleep(10); boost::this_thread::interruption_point(); } } bool CCommandLine::parseCommandLine( std::vector<std::string> & _args, const std::string & _strCommand ) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; BOOST_FOREACH( char const & ch, _strCommand ) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if( state == STATE_ARGUMENT ) // Space ends argument { _args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: _args.push_back( curarg ); return true; default: // ERROR to end in one of the other states return false; } } void CCommandLine::request( std::string const & _command ) { std::vector<std::string> args; if( !parseCommandLine( args, _command ) ) { reply( CMessageClass::CMD_ERROR, "Parse error: unbalanced ' or \"" ); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); reply( CMessageClass::CMD_REPLY, strPrint ); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); std::ostringstream errorStream; errorStream << code; reply(CMessageClass::CMD_ERROR, message + " (code " + errorStream.str() + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object reply( CMessageClass::CMD_ERROR, write_string( json_spirit::Value(objError), false) ); } } catch (std::exception& e) { reply( CMessageClass::CMD_ERROR, std::string("Error: ") + e.what()); } } }
23.138776
102
0.66943
salarii
cb0040820ee7e1527e4debb7d8d75d471d79d2fe
919
cpp
C++
templates/Cpp/OpenCV/camera.cpp
koturn/kotemplate
adc2d4b1896b7a0cfde047fea0fa5638d5f61a46
[ "MIT" ]
3
2015-11-08T06:38:11.000Z
2019-03-01T15:47:54.000Z
templates/Cpp/OpenCV/camera.cpp
koturn/kotemplate
adc2d4b1896b7a0cfde047fea0fa5638d5f61a46
[ "MIT" ]
null
null
null
templates/Cpp/OpenCV/camera.cpp
koturn/kotemplate
adc2d4b1896b7a0cfde047fea0fa5638d5f61a46
[ "MIT" ]
1
2015-12-03T19:41:42.000Z
2015-12-03T19:41:42.000Z
/*! * @brief Simple camera program with OpenCV * @author <+AUTHOR+> * @date <+DATE+> * @file <+FILE+> * @version 0.1 */ #include <iostream> #include <opencv/cv.h> #include <opencv/highgui.h> /*! * @brief Entry point of the program * @param [in] argc A number of command-line arguments * @param [in] argv Command line arguments * @return Exit-status */ int main(int argc, char *argv[]) { static const char WINDOW_NAME[] = "<+FILEBASE+>"; static const int WAIT_TIME = 30; static const int CAMERA_NR = 0; cv::VideoCapture camera(CAMERA_NR); if (!camera.isOpened()) { std::cerr << "Unable to open camera device" << std::endl; return EXIT_FAILURE; } cv::Mat frame; cv::namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE); for (int key = cv::waitKey(WAIT_TIME); key < 0; key = cv::waitKey(WAIT_TIME)) { camera >> frame; <+CURSOR+> cv::imshow(WINDOW_NAME, frame); } }
22.975
81
0.639826
koturn
cb0080971d43ed9bdd2cc1c9275497a91e86063d
2,922
hpp
C++
include/mitama/mana/functional/chunkify.hpp
LoliGothick/mitama-mana
32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898
[ "MIT" ]
1
2019-07-25T01:42:22.000Z
2019-07-25T01:42:22.000Z
include/mitama/mana/functional/chunkify.hpp
LoliGothick/mitama-mana
32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898
[ "MIT" ]
null
null
null
include/mitama/mana/functional/chunkify.hpp
LoliGothick/mitama-mana
32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898
[ "MIT" ]
null
null
null
#ifndef MITAMA_MANA_FUNCTIONAL_CHUNKIFY_HPP #define MITAMA_MANA_FUNCTIONAL_CHUNKIFY_HPP #include <mitama/mana/algorithm/chunk.hpp> #include <mitama/mana/algorithm/klisli.hpp> #include <mitama/mana/utility/apply.hpp> #include <mitama/mana/utility/peel.hpp> #include <mitama/mana/type_traits/is_tuple_like.hpp> #include <mitama/mana/meta/repack.hpp> #include <mitama/mana/core/view/view.hpp> #include <tuple> namespace mitama::mana::map_fn { template <std::size_t N> struct chunkify_map_fn { template <class Tuple, std::size_t... Indices> static constexpr auto element_type(Tuple&&, value_list<Indices...>) -> std::tuple<std::tuple_element_t<Indices, Tuple>...>; template <class Tuple> static constexpr std::size_t value = std::tuple_size_v<std::decay_t<Tuple>> / N; template <std::size_t I, class Tuple> using type = decltype(chunkify_map_fn::element_type(std::declval<Tuple>(), mana::iota<I*N, I*N + N>)); template <std::size_t I, class Tuple> static constexpr auto get(Tuple&& t) { return mana::apply([&t](auto... indices){ return std::tuple(std::get<mana::peel(indices)>(t)...); }, mana::iota<I*N, I*N + N>); } }; } namespace mitama::mana { template <std::size_t N> struct chunkify_fn { template <class... Args> auto operator()(Args&&... args) const { return mana::apply([forwarded = std::forward_as_tuple(std::forward<Args>(args)...)](auto... chunk) mutable { return std::tuple{mana::apply([&forwarded](auto... indices) mutable { return std::tuple(std::get<mana::peel(indices)>(forwarded)...); }, mana::peel(chunk))... }; }, mana::chunk<N>(mana::iota<0, sizeof...(Args)>)); } template <class TupleLike, std::enable_if_t<mana::is_tuple_like_v<std::decay_t<TupleLike>>, bool> = false> auto operator()(TupleLike&& t) const { return mana::apply([t](auto... chunk) mutable { return std::tuple{mana::apply([&t](auto... indices) mutable { return std::tuple(std::get<mana::peel(indices)>(t)...); }, mana::peel(chunk))... }; }, mana::chunk<N>(mana::iota<0, std::tuple_size_v<std::decay_t<TupleLike>>>)); } template <class... Args> auto view(Args&&... args) const { return _view<fn::static_, mitama::mana::map_fn::chunkify_map_fn<N>, std::tuple<Args...>>{std::forward<Args>(args)...}; } template <class TupleLike, std::enable_if_t<mana::is_tuple_like_v<std::decay_t<TupleLike>>, bool> = false> auto view(TupleLike&& t) const { return std::apply([](auto&&... args){ return _view<fn::static_, mitama::mana::map_fn::chunkify_map_fn<N>, std::tuple<decltype(args)...>>{std::forward<decltype(args)>(args)...}; }, std::forward<TupleLike>(t)); } }; template <std::size_t N> inline constexpr chunkify_fn<N> chunkify{}; } #endif // !MITAMA_MANA_FUNCTIONAL_CHUNK_HPP
38.96
150
0.644079
LoliGothick
cb022d18789e6e9500f206350d0b5990cd80f4d3
385
cpp
C++
OOPs/TimeUse.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
OOPs/TimeUse.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
OOPs/TimeUse.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
1
2021-10-05T10:09:32.000Z
2021-10-05T10:09:32.000Z
#include <bits/stdc++.h> #include "Time.cpp" using namespace std; int main() { Time t1; t1.setHour(3); t1.setMinutes(34); t1.setSeconds(54); Time t2; t2.setHour(2); t2.setMinutes(24); t2.setSeconds(35); Time t3; t3 = t1.add(t2); t1.print(); t2.print(); t3.print(); Time t4; t4 = t2.subtract(t1); t4.print(); }
14.259259
26
0.532468
Mitushi-23
cb03d9706f54bc8b307bc2c7e23b65b8bfab8851
8,876
cpp
C++
wpimath/src/test/native/cpp/kinematics/MecanumDriveKinematicsTest.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
1
2021-08-06T14:23:33.000Z
2021-08-06T14:23:33.000Z
wpimath/src/test/native/cpp/kinematics/MecanumDriveKinematicsTest.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
2
2020-07-11T23:47:55.000Z
2020-07-16T16:09:06.000Z
wpimath/src/test/native/cpp/kinematics/MecanumDriveKinematicsTest.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
1
2020-07-18T20:47:30.000Z
2020-07-18T20:47:30.000Z
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include <wpi/math> #include "frc/geometry/Translation2d.h" #include "frc/kinematics/MecanumDriveKinematics.h" #include "gtest/gtest.h" #include "units/angular_velocity.h" using namespace frc; class MecanumDriveKinematicsTest : public ::testing::Test { protected: Translation2d m_fl{12_m, 12_m}; Translation2d m_fr{12_m, -12_m}; Translation2d m_bl{-12_m, 12_m}; Translation2d m_br{-12_m, -12_m}; MecanumDriveKinematics kinematics{m_fl, m_fr, m_bl, m_br}; }; TEST_F(MecanumDriveKinematicsTest, StraightLineInverseKinematics) { ChassisSpeeds speeds{5_mps, 0_mps, 0_rad_per_s}; auto moduleStates = kinematics.ToWheelSpeeds(speeds); /* By equation (13.12) of the state-space-guide, the wheel speeds should be as follows: velocities: fl 3.535534 fr 3.535534 rl 3.535534 rr 3.535534 */ EXPECT_NEAR(3.536, moduleStates.frontLeft.to<double>(), 0.1); EXPECT_NEAR(3.536, moduleStates.frontRight.to<double>(), 0.1); EXPECT_NEAR(3.536, moduleStates.rearLeft.to<double>(), 0.1); EXPECT_NEAR(3.536, moduleStates.rearRight.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, StraightLineForwardKinematics) { MecanumDriveWheelSpeeds wheelSpeeds{3.536_mps, 3.536_mps, 3.536_mps, 3.536_mps}; auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds); /* By equation (13.13) of the state-space-guide, the chassis motion from wheel velocities: fl 3.535534 fr 3.535534 rl 3.535534 rr 3.535534 will be [[5][0][0]] */ EXPECT_NEAR(5.0, chassisSpeeds.vx.to<double>(), 0.1); EXPECT_NEAR(0.0, chassisSpeeds.vy.to<double>(), 0.1); EXPECT_NEAR(0.0, chassisSpeeds.omega.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, StrafeInverseKinematics) { ChassisSpeeds speeds{0_mps, 4_mps, 0_rad_per_s}; auto moduleStates = kinematics.ToWheelSpeeds(speeds); /* By equation (13.12) of the state-space-guide, the wheel speeds should be as follows: velocities: fl -2.828427 fr 2.828427 rl 2.828427 rr -2.828427 */ EXPECT_NEAR(-2.828427, moduleStates.frontLeft.to<double>(), 0.1); EXPECT_NEAR(2.828427, moduleStates.frontRight.to<double>(), 0.1); EXPECT_NEAR(2.828427, moduleStates.rearLeft.to<double>(), 0.1); EXPECT_NEAR(-2.828427, moduleStates.rearRight.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, StrafeForwardKinematics) { MecanumDriveWheelSpeeds wheelSpeeds{-2.828427_mps, 2.828427_mps, 2.828427_mps, -2.828427_mps}; auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds); /* By equation (13.13) of the state-space-guide, the chassis motion from wheel velocities: fl 3.535534 fr 3.535534 rl 3.535534 rr 3.535534 will be [[5][0][0]] */ EXPECT_NEAR(0.0, chassisSpeeds.vx.to<double>(), 0.1); EXPECT_NEAR(4.0, chassisSpeeds.vy.to<double>(), 0.1); EXPECT_NEAR(0.0, chassisSpeeds.omega.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, RotationInverseKinematics) { ChassisSpeeds speeds{0_mps, 0_mps, units::radians_per_second_t(2 * wpi::math::pi)}; auto moduleStates = kinematics.ToWheelSpeeds(speeds); /* By equation (13.12) of the state-space-guide, the wheel speeds should be as follows: velocities: fl -106.629191 fr 106.629191 rl -106.629191 rr 106.629191 */ EXPECT_NEAR(-106.62919, moduleStates.frontLeft.to<double>(), 0.1); EXPECT_NEAR(106.62919, moduleStates.frontRight.to<double>(), 0.1); EXPECT_NEAR(-106.62919, moduleStates.rearLeft.to<double>(), 0.1); EXPECT_NEAR(106.62919, moduleStates.rearRight.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, RotationForwardKinematics) { MecanumDriveWheelSpeeds wheelSpeeds{-106.62919_mps, 106.62919_mps, -106.62919_mps, 106.62919_mps}; auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds); /* By equation (13.13) of the state-space-guide, the chassis motion from wheel velocities: fl -106.629191 fr 106.629191 rl -106.629191 rr 106.629191 should be [[0][0][2pi]] */ EXPECT_NEAR(0.0, chassisSpeeds.vx.to<double>(), 0.1); EXPECT_NEAR(0.0, chassisSpeeds.vy.to<double>(), 0.1); EXPECT_NEAR(2 * wpi::math::pi, chassisSpeeds.omega.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, MixedRotationTranslationInverseKinematics) { ChassisSpeeds speeds{2_mps, 3_mps, 1_rad_per_s}; auto moduleStates = kinematics.ToWheelSpeeds(speeds); /* By equation (13.12) of the state-space-guide, the wheel speeds should be as follows: velocities: fl -17.677670 fr 20.506097 rl -13.435029 rr 16.263456 */ EXPECT_NEAR(-17.677670, moduleStates.frontLeft.to<double>(), 0.1); EXPECT_NEAR(20.506097, moduleStates.frontRight.to<double>(), 0.1); EXPECT_NEAR(-13.435, moduleStates.rearLeft.to<double>(), 0.1); EXPECT_NEAR(16.26, moduleStates.rearRight.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, MixedRotationTranslationForwardKinematics) { MecanumDriveWheelSpeeds wheelSpeeds{-17.677670_mps, 20.506097_mps, -13.435_mps, 16.26_mps}; auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds); /* By equation (13.13) of the state-space-guide, the chassis motion from wheel velocities: fl -17.677670 fr 20.506097 rl -13.435029 rr 16.263456 should be [[2][3][1]] */ EXPECT_NEAR(2.0, chassisSpeeds.vx.to<double>(), 0.1); EXPECT_NEAR(3.0, chassisSpeeds.vy.to<double>(), 0.1); EXPECT_NEAR(1.0, chassisSpeeds.omega.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, OffCenterRotationInverseKinematics) { ChassisSpeeds speeds{0_mps, 0_mps, 1_rad_per_s}; auto moduleStates = kinematics.ToWheelSpeeds(speeds, m_fl); /* By equation (13.12) of the state-space-guide, the wheel speeds should be as follows: velocities: fl 0.000000 fr 16.970563 rl -16.970563 rr 33.941125 */ EXPECT_NEAR(0, moduleStates.frontLeft.to<double>(), 0.1); EXPECT_NEAR(16.971, moduleStates.frontRight.to<double>(), 0.1); EXPECT_NEAR(-16.971, moduleStates.rearLeft.to<double>(), 0.1); EXPECT_NEAR(33.941, moduleStates.rearRight.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, OffCenterRotationForwardKinematics) { MecanumDriveWheelSpeeds wheelSpeeds{0_mps, 16.971_mps, -16.971_mps, 33.941_mps}; auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds); /* By equation (13.13) of the state-space-guide, the chassis motion from the wheel velocities should be [[12][-12][1]] */ EXPECT_NEAR(12.0, chassisSpeeds.vx.to<double>(), 0.1); EXPECT_NEAR(-12, chassisSpeeds.vy.to<double>(), 0.1); EXPECT_NEAR(1.0, chassisSpeeds.omega.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, OffCenterTranslationRotationInverseKinematics) { ChassisSpeeds speeds{5_mps, 2_mps, 1_rad_per_s}; auto moduleStates = kinematics.ToWheelSpeeds(speeds, m_fl); /* By equation (13.12) of the state-space-guide, the wheel speeds should be as follows: velocities: fl 2.121320 fr 21.920310 rl -12.020815 rr 36.062446 */ EXPECT_NEAR(2.12, moduleStates.frontLeft.to<double>(), 0.1); EXPECT_NEAR(21.92, moduleStates.frontRight.to<double>(), 0.1); EXPECT_NEAR(-12.02, moduleStates.rearLeft.to<double>(), 0.1); EXPECT_NEAR(36.06, moduleStates.rearRight.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, OffCenterTranslationRotationForwardKinematics) { MecanumDriveWheelSpeeds wheelSpeeds{2.12_mps, 21.92_mps, -12.02_mps, 36.06_mps}; auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds); /* By equation (13.13) of the state-space-guide, the chassis motion from the wheel velocities should be [[17][-10][1]] */ EXPECT_NEAR(17.0, chassisSpeeds.vx.to<double>(), 0.1); EXPECT_NEAR(-10, chassisSpeeds.vy.to<double>(), 0.1); EXPECT_NEAR(1.0, chassisSpeeds.omega.to<double>(), 0.1); } TEST_F(MecanumDriveKinematicsTest, NormalizeTest) { MecanumDriveWheelSpeeds wheelSpeeds{5_mps, 6_mps, 4_mps, 7_mps}; wheelSpeeds.Normalize(5.5_mps); double kFactor = 5.5 / 7.0; EXPECT_NEAR(wheelSpeeds.frontLeft.to<double>(), 5.0 * kFactor, 1E-9); EXPECT_NEAR(wheelSpeeds.frontRight.to<double>(), 6.0 * kFactor, 1E-9); EXPECT_NEAR(wheelSpeeds.rearLeft.to<double>(), 4.0 * kFactor, 1E-9); EXPECT_NEAR(wheelSpeeds.rearRight.to<double>(), 7.0 * kFactor, 1E-9); }
38.424242
80
0.689725
bvisness
cb04e404fbfabf11c460bbdd482e56981214a2a9
70,728
cc
C++
third-party/webscalesqlclient/mysql-5.6/storage/innobase/trx/trx0trx.cc
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
third-party/webscalesqlclient/mysql-5.6/storage/innobase/trx/trx0trx.cc
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
third-party/webscalesqlclient/mysql-5.6/storage/innobase/trx/trx0trx.cc
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/***************************************************************************** Copyright (c) 1996, 2014, Oracle and/or its affiliates. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file trx/trx0trx.cc The transaction Created 3/26/1996 Heikki Tuuri *******************************************************/ #include "trx0trx.h" #ifdef UNIV_NONINL #include "trx0trx.ic" #endif #include "trx0undo.h" #include "trx0rseg.h" #include "log0log.h" #include "que0que.h" #include "lock0lock.h" #include "trx0roll.h" #include "usr0sess.h" #include "read0read.h" #include "srv0srv.h" #include "srv0start.h" #include "btr0sea.h" #include "os0proc.h" #include "trx0xa.h" #include "trx0rec.h" #include "trx0purge.h" #include "ha_prototypes.h" #include "srv0mon.h" #include "ut0vec.h" #include "btr0pcur.h" #include<set> /** Set of table_id */ typedef std::set<table_id_t> table_id_set; /** Dummy session used currently in MySQL interface */ UNIV_INTERN sess_t* trx_dummy_sess = NULL; #ifdef UNIV_PFS_MUTEX /* Key to register the mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t trx_mutex_key; /* Key to register the mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t trx_undo_mutex_key; #endif /* UNIV_PFS_MUTEX */ /*************************************************************//** Set detailed error message for the transaction. */ UNIV_INTERN void trx_set_detailed_error( /*===================*/ trx_t* trx, /*!< in: transaction struct */ const char* msg) /*!< in: detailed error message */ { ut_strlcpy(trx->detailed_error, msg, sizeof(trx->detailed_error)); } /*************************************************************//** Set detailed error message for the transaction from a file. Note that the file is rewinded before reading from it. */ UNIV_INTERN void trx_set_detailed_error_from_file( /*=============================*/ trx_t* trx, /*!< in: transaction struct */ FILE* file) /*!< in: file to read message from */ { os_file_read_string(file, trx->detailed_error, sizeof(trx->detailed_error)); } /*************************************************************** It turns out to be very efficient for all of our trx_t structures to be in contiguous memory; this forced locality results in significant speedups when iterating over the open transactions. We achieve this with trx_t blocks of contiguous memory, each holding TRX_PER_BLOCK trx_t's. As we fill blocks, we allocate new ones. TRX_PER_BLOCK is pretty arbitrary, but you want it to be large (so that all transactions span only a handful of memory regions). */ #define TRX_PER_BLOCK (1024 * 1024 / sizeof(trx_t)) struct trx_block_struct { struct trx_block_struct* next_block; trx_t transactions[TRX_PER_BLOCK]; }; /* A linked list of our transaction blocks. */ static struct trx_block_struct* transaction_blocks = NULL; /* Track the next free transaction (for fast allocation) */ static trx_t *next_free_transaction = NULL; #ifdef UNIV_DEBUG_VALGRIND /********************************************************************//** Frees trx_t pool */ UNIV_INTERN void trx_free_trx_pool() /*==============*/ { trx_t* next; /* Confirm that the list looks OK */ next = next_free_transaction; while (next) { ut_ad(next->magic_n == TRX_FREE_MAGIC_N); next = next->next_free_trx; } next_free_transaction = NULL; while (transaction_blocks) { struct trx_block_struct *next_block = transaction_blocks->next_block; mem_free(transaction_blocks); transaction_blocks = next_block; } } #endif trx_t* trx_allocate() { uint i; trx_t* ret = NULL; mutex_enter(&trx_sys->trx_memory_mutex); /* If we don't have a next_free_transaction -- either because * this is the first allocation or because we are using every * transaction in previous blocks -- allocate a new one, set * all of the trx_t's next_free_trx pointer to the next trx_t * in the block, and set next_free_transaction to be the first * trx_t in the block. */ if (!next_free_transaction) { struct trx_block_struct* block_tmp = static_cast<struct trx_block_struct*>( mem_zalloc(sizeof(struct trx_block_struct))); block_tmp->next_block = transaction_blocks; transaction_blocks = block_tmp; for (i = 0; i < TRX_PER_BLOCK; ++i) { trx_t* next = NULL; if (i < TRX_PER_BLOCK - 1) { next = &(block_tmp->transactions[i + 1]); } block_tmp->transactions[i].next_free_trx = next; block_tmp->transactions[i].magic_n = TRX_FREE_MAGIC_N; } next_free_transaction = &(transaction_blocks->transactions[0]); } ut_a(next_free_transaction->magic_n == TRX_FREE_MAGIC_N); /* We return the next free transaction and remove it from the list. */ ret = next_free_transaction; next_free_transaction = ret->next_free_trx; ret->next_free_trx = NULL; mutex_exit(&trx_sys->trx_memory_mutex); return ret; } void trx_deallocate(trx_t* t) { mutex_enter(&trx_sys->trx_memory_mutex); ut_a(t->magic_n == TRX_MAGIC_N); memset(t, 0, sizeof(trx_t)); /* Place this transaction at the head of our free list. Note * that if somehow this is the last used transaction in a * transaction block, we do not free the block. This is a * wasteful optimization as there are at most a few megabytes of * blocks in an extremely busy system. */ t->next_free_trx = next_free_transaction; t->magic_n = TRX_FREE_MAGIC_N; next_free_transaction = t; mutex_exit(&trx_sys->trx_memory_mutex); } /*************************************************************//** Initialize data structures related to logical-read-ahead. */ void trx_lra_init( /*=============================*/ lra_t* lra) /*!< in: lra structure */ { lra->lra_size = 0; lra->lra_space_id = 0; lra->lra_n_spaces = 0; lra->lra_count_n_spaces = 0; lra->lra_n_pages = 0; lra->lra_n_pages_since = 0; lra->lra_page_no = 0; lra->lra_pages_before_sleep = 0; lra->lra_sleep = 0; lra->lra_tree_height = 0; lra->lra_sort_arr = NULL; lra->lra_ht = NULL; lra->lra_ht1 = NULL; lra->lra_ht2 = NULL; lra->lra_arr1 = NULL; lra->lra_arr2 = NULL; lra->lra_cur = NULL; } /*************************************************************//** Frees data structures related to logical-read-ahead. */ void trx_lra_free( /*=============================*/ lra_t* lra) /*!< in: lra structure */ { if (lra->lra_ht) { ut_a(lra->lra_ht1); ut_a(lra->lra_ht2); ut_a(lra->lra_sort_arr); hash_table_free(lra->lra_ht1); hash_table_free(lra->lra_ht2); btr_pcur_close(lra->lra_cur); ut_free(lra->lra_sort_arr); #ifdef TARGET_OS_LINUX if (cachedev_enabled) { pid_t pid = syscall(SYS_gettid); ioctl(cachedev_fd, FLASHCACHEDELBLACKLIST, &pid); } #endif /* TARGET_OS_LINUX */ } else { ut_a(!lra->lra_ht1); ut_a(!lra->lra_ht2); ut_a(!lra->lra_sort_arr); ut_a(!lra->lra_cur); ut_a(!lra->lra_arr1); ut_a(!lra->lra_arr2); } trx_lra_init(lra); } /*************************************************************//** Creates or frees data structures related to logical-read-ahead. based on the value of lra_size. */ UNIV_INTERN void trx_lra_reset( /*=============================*/ trx_t* trx, /*!< in: transaction */ ulint lra_size, /*!< in: lra_size in MB. If 0, the fields that are releated to logical-read-ahead will be freed if they were initialized. */ ulint lra_pages_before_sleep, /*!< in: The number of node pointer records traversed while holding the index lock before releasing the index lock and sleeping for a short period of time so that the other threads get a chance to x-latch the index lock. */ ulint lra_sleep, /*!< in: Sleep time in milliseconds. */ ulint lra_n_spaces, /*!< in: Number of space switches before lra is disabled. */ bool reset_lra_count_n_spaces) /*!< in: whether to reset lra_count_n_spaces. */ { #ifndef TARGET_OS_LINUX if (lra_size) { ib_logf(IB_LOG_LEVEL_WARN, "Logical read ahead is supported only on linux."); lra_size = 0; } #else /* TARGET_OS_LINUX */ if (!srv_use_native_aio && lra_size) { ib_logf(IB_LOG_LEVEL_WARN, "In order to use logical read ahead please enable " "native aio by setting innodb_use_native_aio=1 in " "my.cnf and restarting the server."); lra_size = 0; } #endif /* TARGET_OS_LINUX */ lra_t* lra = &(trx->lra); if (lra_size == 0) { trx_lra_free(lra); return; } ulint n_pages_max = (lra_size << 20L) / UNIV_ZIP_SIZE_MIN; ulint mem = n_pages_max * (2 * sizeof(ulint) + 2 * sizeof(page_no_holder_t)) + sizeof(btr_pcur_t); lra->lra_size = lra_size; lra->lra_n_spaces = lra_n_spaces; lra->lra_space_id = 0; lra->lra_n_pages = 0; lra->lra_n_pages_since = 0; lra->lra_page_no = 0; lra->lra_pages_before_sleep = lra_pages_before_sleep; lra->lra_sleep = lra_sleep; lra->lra_tree_height = 0; if (reset_lra_count_n_spaces) { lra->lra_count_n_spaces = 0; } if (lra->lra_ht) { ut_a(lra->lra_ht1); ut_a(lra->lra_ht2); ut_a(lra->lra_sort_arr); ut_a(lra->lra_cur); hash_table_clear(lra->lra_ht1); hash_table_clear(lra->lra_ht2); btr_pcur_reset(lra->lra_cur); lra->lra_ht = lra->lra_ht1; #ifdef UNIV_DEBUG /* following resets lra_sort_arr, lra_arr1, lra_arr2, and lra_cursor. */ memset(lra->lra_sort_arr, 0, mem); #endif btr_pcur_init(lra->lra_cur); } else { byte* alloc; ut_a(!lra->lra_ht1); ut_a(!lra->lra_ht2); ut_a(!lra->lra_sort_arr); ut_a(!lra->lra_cur); lra->lra_ht1 = hash_create(16384); lra->lra_ht2 = hash_create(16384); lra->lra_ht = lra->lra_ht1; alloc = (byte*)ut_malloc(mem); #ifdef UNIV_DEBUG memset(alloc, 0, mem); #endif lra->lra_sort_arr = (ulint*)alloc; alloc += 2 * sizeof(ulint) * n_pages_max; lra->lra_arr1 = (page_no_holder_t*) alloc; alloc += sizeof(page_no_holder_t) * n_pages_max; lra->lra_arr2 = (page_no_holder_t*) alloc; alloc += sizeof(page_no_holder_t) * n_pages_max; lra->lra_cur = (btr_pcur_t*) alloc; btr_pcur_init(lra->lra_cur); #ifdef TARGET_OS_LINUX if (cachedev_enabled) { pid_t pid = syscall(SYS_gettid); ioctl(cachedev_fd, FLASHCACHEADDBLACKLIST, &pid); } #endif /* TARGET_OS_LINUX */ } } /****************************************************************//** Creates and initializes a transaction object. It must be explicitly started with trx_start_if_not_started() before using it. The default isolation level is TRX_ISO_REPEATABLE_READ. @return transaction instance, should never be NULL */ static trx_t* trx_create(void) /*============*/ { trx_t* trx; mem_heap_t* heap; ib_alloc_t* heap_alloc; trx = trx_allocate(); mutex_create(trx_mutex_key, &trx->mutex, SYNC_TRX); trx->magic_n = TRX_MAGIC_N; trx->state = TRX_STATE_NOT_STARTED; trx->isolation_level = TRX_ISO_REPEATABLE_READ; trx->no = TRX_ID_MAX; trx->support_xa = TRUE; trx->check_foreigns = TRUE; trx->check_unique_secondary = TRUE; trx->dict_operation = TRX_DICT_OP_NONE; mutex_create(trx_undo_mutex_key, &trx->undo_mutex, SYNC_TRX_UNDO); trx->error_state = DB_SUCCESS; trx->lock.que_state = TRX_QUE_RUNNING; trx->lock.lock_heap = mem_heap_create_typed( 256, MEM_HEAP_FOR_LOCK_HEAP); trx->search_latch_timeout = BTR_SEA_TIMEOUT; trx->always_enter_innodb = FALSE; trx->global_read_view_heap = mem_heap_create(256); trx->xid.formatID = -1; trx->op_info = ""; trx->api_trx = false; trx->api_auto_commit = false; trx->read_write = true; memset(&trx->table_io_perf, 0, sizeof(trx->table_io_perf)); heap = mem_heap_create(sizeof(ib_vector_t) + sizeof(void*) * 8); heap_alloc = ib_heap_allocator_create(heap); /* Remember to free the vector explicitly in trx_free(). */ trx->autoinc_locks = ib_vector_create(heap_alloc, sizeof(void**), 4); /* Remember to free the vector explicitly in trx_free(). */ heap = mem_heap_create(sizeof(ib_vector_t) + sizeof(void*) * 128); heap_alloc = ib_heap_allocator_create(heap); trx->lock.table_locks = ib_vector_create( heap_alloc, sizeof(void**), 32); trx_lra_init(&(trx->lra)); return(trx); } /********************************************************************//** Creates a transaction object for background operations by the master thread. @return own: transaction object */ UNIV_INTERN trx_t* trx_allocate_for_background(void) /*=============================*/ { trx_t* trx; trx = trx_create(); trx->sess = trx_dummy_sess; return(trx); } /********************************************************************//** Creates a transaction object for MySQL. @return own: transaction object */ UNIV_INTERN trx_t* trx_allocate_for_mysql(void) /*========================*/ { trx_t* trx; trx = trx_allocate_for_background(); mutex_enter(&trx_sys->mutex); ut_d(trx->in_mysql_trx_list = TRUE); UT_LIST_ADD_FIRST(mysql_trx_list, trx_sys->mysql_trx_list, trx); mutex_exit(&trx_sys->mutex); return(trx); } /********************************************************************//** Frees a transaction object. */ static void trx_free( /*=====*/ trx_t* trx) /*!< in, own: trx object */ { ut_a(trx->magic_n == TRX_MAGIC_N); ut_ad(!trx->in_ro_trx_list); ut_ad(!trx->in_rw_trx_list); ut_ad(!trx->in_mysql_trx_list); mutex_free(&trx->undo_mutex); if (trx->undo_no_arr != NULL) { trx_undo_arr_free(trx->undo_no_arr); } ut_a(trx->lock.wait_lock == NULL); ut_a(trx->lock.wait_thr == NULL); ut_a(!trx->has_search_latch); ut_a(trx->dict_operation_lock_mode == 0); if (trx->lock.lock_heap) { mem_heap_free(trx->lock.lock_heap); } ut_a(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0); if (trx->global_read_view_heap) { mem_heap_free(trx->global_read_view_heap); } ut_a(ib_vector_is_empty(trx->autoinc_locks)); /* We allocated a dedicated heap for the vector. */ ib_vector_free(trx->autoinc_locks); if (trx->lock.table_locks != NULL) { /* We allocated a dedicated heap for the vector. */ ib_vector_free(trx->lock.table_locks); } mutex_free(&trx->mutex); trx_lra_free(&(trx->lra)); trx_deallocate(trx); } /********************************************************************//** Frees a transaction object of a background operation of the master thread. */ UNIV_INTERN void trx_free_for_background( /*====================*/ trx_t* trx) /*!< in, own: trx object */ { if (trx->declared_to_be_inside_innodb) { ib_logf(IB_LOG_LEVEL_ERROR, "Freeing a trx (%p, " TRX_ID_FMT ") which is declared " "to be processing inside InnoDB", trx, trx->id); trx_print(stderr, trx, 600); putc('\n', stderr); /* This is an error but not a fatal error. We must keep the counters like srv_conc_n_threads accurate. */ srv_conc_force_exit_innodb(trx); } if (trx->n_mysql_tables_in_use != 0 || trx->mysql_n_tables_locked != 0) { ib_logf(IB_LOG_LEVEL_ERROR, "MySQL is freeing a thd though " "trx->n_mysql_tables_in_use is %lu and " "trx->mysql_n_tables_locked is %lu.", (ulong) trx->n_mysql_tables_in_use, (ulong) trx->mysql_n_tables_locked); trx_print(stderr, trx, 600); ut_print_buf(stderr, trx, sizeof(trx_t)); putc('\n', stderr); } ut_a(trx->state == TRX_STATE_NOT_STARTED); ut_a(trx->insert_undo == NULL); ut_a(trx->update_undo == NULL); ut_a(trx->read_view == NULL); trx_free(trx); } /********************************************************************//** At shutdown, frees a transaction object that is in the PREPARED state. */ UNIV_INTERN void trx_free_prepared( /*==============*/ trx_t* trx) /*!< in, own: trx object */ { ut_ad(mutex_own(&trx_sys->mutex)); ut_a(trx_state_eq(trx, TRX_STATE_PREPARED)); ut_a(trx->magic_n == TRX_MAGIC_N); trx_undo_free_prepared(trx); assert_trx_in_rw_list(trx); ut_a(!trx->read_only); UT_LIST_REMOVE(trx_list, trx_sys->rw_trx_list, trx); ut_d(trx->in_rw_trx_list = FALSE); /* Undo trx_resurrect_table_locks(). */ UT_LIST_INIT(trx->lock.trx_locks); trx_free(trx); } /********************************************************************//** Frees a transaction object for MySQL. */ UNIV_INTERN void trx_free_for_mysql( /*===============*/ trx_t* trx) /*!< in, own: trx object */ { mutex_enter(&trx_sys->mutex); ut_ad(trx->in_mysql_trx_list); ut_d(trx->in_mysql_trx_list = FALSE); UT_LIST_REMOVE(mysql_trx_list, trx_sys->mysql_trx_list, trx); ut_ad(trx_sys_validate_trx_list()); mutex_exit(&trx_sys->mutex); trx_free_for_background(trx); } /****************************************************************//** Inserts the trx handle in the trx system trx list in the right position. The list is sorted on the trx id so that the biggest id is at the list start. This function is used at the database startup to insert incomplete transactions to the list. */ static void trx_list_rw_insert_ordered( /*=======================*/ trx_t* trx) /*!< in: trx handle */ { trx_t* trx2; ut_ad(!trx->read_only); ut_d(trx->start_file = __FILE__); ut_d(trx->start_line = __LINE__); ut_a(srv_is_being_started); ut_ad(!trx->in_ro_trx_list); ut_ad(!trx->in_rw_trx_list); ut_ad(trx->state != TRX_STATE_NOT_STARTED); ut_ad(trx->is_recovered); for (trx2 = UT_LIST_GET_FIRST(trx_sys->rw_trx_list); trx2 != NULL; trx2 = UT_LIST_GET_NEXT(trx_list, trx2)) { assert_trx_in_rw_list(trx2); if (trx->id >= trx2->id) { ut_ad(trx->id > trx2->id); break; } } if (trx2 != NULL) { trx2 = UT_LIST_GET_PREV(trx_list, trx2); if (trx2 == NULL) { UT_LIST_ADD_FIRST(trx_list, trx_sys->rw_trx_list, trx); } else { UT_LIST_INSERT_AFTER( trx_list, trx_sys->rw_trx_list, trx2, trx); } } else { UT_LIST_ADD_LAST(trx_list, trx_sys->rw_trx_list, trx); } #ifdef UNIV_DEBUG if (trx->id > trx_sys->rw_max_trx_id) { trx_sys->rw_max_trx_id = trx->id; } #endif /* UNIV_DEBUG */ ut_ad(!trx->in_rw_trx_list); ut_d(trx->in_rw_trx_list = TRUE); } /****************************************************************//** Resurrect the table locks for a resurrected transaction. */ static void trx_resurrect_table_locks( /*======================*/ trx_t* trx, /*!< in/out: transaction */ const trx_undo_t* undo) /*!< in: undo log */ { mtr_t mtr; page_t* undo_page; trx_undo_rec_t* undo_rec; table_id_set tables; ut_ad(undo == trx->insert_undo || undo == trx->update_undo); if (trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY) || undo->empty) { return; } mtr_start(&mtr); /* trx_rseg_mem_create() may have acquired an X-latch on this page, so we cannot acquire an S-latch. */ undo_page = trx_undo_page_get( undo->space, undo->zip_size, undo->top_page_no, &mtr); undo_rec = undo_page + undo->top_offset; do { ulint type; ulint cmpl_info; bool updated_extern; undo_no_t undo_no; table_id_t table_id; page_t* undo_rec_page = page_align(undo_rec); if (undo_rec_page != undo_page) { if (!mtr_memo_release(&mtr, buf_block_align(undo_page), MTR_MEMO_PAGE_X_FIX)) { /* The page of the previous undo_rec should have been latched by trx_undo_page_get() or trx_undo_get_prev_rec(). */ ut_ad(0); } undo_page = undo_rec_page; } trx_undo_rec_get_pars( undo_rec, &type, &cmpl_info, &updated_extern, &undo_no, &table_id); tables.insert(table_id); undo_rec = trx_undo_get_prev_rec( undo_rec, undo->hdr_page_no, undo->hdr_offset, false, &mtr); } while (undo_rec); mtr_commit(&mtr); for (table_id_set::const_iterator i = tables.begin(); i != tables.end(); i++) { if (dict_table_t* table = dict_table_open_on_id( *i, FALSE, DICT_TABLE_OP_LOAD_TABLESPACE)) { if (table->ibd_file_missing || dict_table_is_temporary(table)) { mutex_enter(&dict_sys->mutex); dict_table_close(table, TRUE, FALSE); dict_table_remove_from_cache(table); mutex_exit(&dict_sys->mutex); continue; } lock_table_ix_resurrect(table, trx); DBUG_PRINT("ib_trx", ("resurrect" TRX_ID_FMT " table '%s' IX lock from %s undo", trx->id, table->name, undo == trx->insert_undo ? "insert" : "update")); dict_table_close(table, FALSE, FALSE); } } } /****************************************************************//** Resurrect the transactions that were doing inserts the time of the crash, they need to be undone. @return trx_t instance */ static trx_t* trx_resurrect_insert( /*=================*/ trx_undo_t* undo, /*!< in: entry to UNDO */ trx_rseg_t* rseg) /*!< in: rollback segment */ { trx_t* trx; trx = trx_allocate_for_background(); trx->rseg = rseg; trx->xid = undo->xid; trx->id = undo->trx_id; trx->insert_undo = undo; trx->is_recovered = TRUE; /* This is single-threaded startup code, we do not need the protection of trx->mutex or trx_sys->mutex here. */ if (undo->state != TRX_UNDO_ACTIVE) { /* Prepared transactions are left in the prepared state waiting for a commit or abort decision from MySQL */ if (undo->state == TRX_UNDO_PREPARED) { fprintf(stderr, "InnoDB: Transaction " TRX_ID_FMT " was in the" " XA prepared state.\n", trx->id); if (srv_force_recovery == 0) { trx->state = TRX_STATE_PREPARED; trx_sys->n_prepared_trx++; trx_sys->n_prepared_recovered_trx++; } else { fprintf(stderr, "InnoDB: Since innodb_force_recovery" " > 0, we will rollback it anyway.\n"); trx->state = TRX_STATE_ACTIVE; } } else { trx->state = TRX_STATE_COMMITTED_IN_MEMORY; } /* We give a dummy value for the trx no; this should have no relevance since purge is not interested in committed transaction numbers, unless they are in the history list, in which case it looks the number from the disk based undo log structure */ trx->no = trx->id; } else { trx->state = TRX_STATE_ACTIVE; /* A running transaction always has the number field inited to TRX_ID_MAX */ trx->no = TRX_ID_MAX; } /* trx_start_low() is not called with resurrect, so need to initialize start time here.*/ if (trx->state == TRX_STATE_ACTIVE || trx->state == TRX_STATE_PREPARED) { trx->start_time = ut_time(); } if (undo->dict_operation) { trx_set_dict_operation(trx, TRX_DICT_OP_TABLE); trx->table_id = undo->table_id; } if (!undo->empty) { trx->undo_no = undo->top_undo_no + 1; } return(trx); } /****************************************************************//** Prepared transactions are left in the prepared state waiting for a commit or abort decision from MySQL */ static void trx_resurrect_update_in_prepared_state( /*===================================*/ trx_t* trx, /*!< in,out: transaction */ const trx_undo_t* undo) /*!< in: update UNDO record */ { /* This is single-threaded startup code, we do not need the protection of trx->mutex or trx_sys->mutex here. */ if (undo->state == TRX_UNDO_PREPARED) { fprintf(stderr, "InnoDB: Transaction " TRX_ID_FMT " was in the XA prepared state.\n", trx->id); if (srv_force_recovery == 0) { if (trx_state_eq(trx, TRX_STATE_NOT_STARTED)) { trx_sys->n_prepared_trx++; trx_sys->n_prepared_recovered_trx++; } else { ut_ad(trx_state_eq(trx, TRX_STATE_PREPARED)); } trx->state = TRX_STATE_PREPARED; } else { fprintf(stderr, "InnoDB: Since innodb_force_recovery" " > 0, we will rollback it anyway.\n"); trx->state = TRX_STATE_ACTIVE; } } else { trx->state = TRX_STATE_COMMITTED_IN_MEMORY; } } /****************************************************************//** Resurrect the transactions that were doing updates the time of the crash, they need to be undone. */ static void trx_resurrect_update( /*=================*/ trx_t* trx, /*!< in/out: transaction */ trx_undo_t* undo, /*!< in/out: update UNDO record */ trx_rseg_t* rseg) /*!< in/out: rollback segment */ { trx->rseg = rseg; trx->xid = undo->xid; trx->id = undo->trx_id; trx->update_undo = undo; trx->is_recovered = TRUE; /* This is single-threaded startup code, we do not need the protection of trx->mutex or trx_sys->mutex here. */ if (undo->state != TRX_UNDO_ACTIVE) { trx_resurrect_update_in_prepared_state(trx, undo); /* We give a dummy value for the trx number */ trx->no = trx->id; } else { trx->state = TRX_STATE_ACTIVE; /* A running transaction always has the number field inited to TRX_ID_MAX */ trx->no = TRX_ID_MAX; } /* trx_start_low() is not called with resurrect, so need to initialize start time here.*/ if (trx->state == TRX_STATE_ACTIVE || trx->state == TRX_STATE_PREPARED) { trx->start_time = ut_time(); } if (undo->dict_operation) { trx_set_dict_operation(trx, TRX_DICT_OP_TABLE); trx->table_id = undo->table_id; } if (!undo->empty && undo->top_undo_no >= trx->undo_no) { trx->undo_no = undo->top_undo_no + 1; } } /****************************************************************//** Creates trx objects for transactions and initializes the trx list of trx_sys at database start. Rollback segment and undo log lists must already exist when this function is called, because the lists of transactions to be rolled back or cleaned up are built based on the undo log lists. */ UNIV_INTERN void trx_lists_init_at_db_start(void) /*============================*/ { ulint i; ut_a(srv_is_being_started); UT_LIST_INIT(trx_sys->ro_trx_list); UT_LIST_INIT(trx_sys->rw_trx_list); /* Look from the rollback segments if there exist undo logs for transactions */ for (i = 0; i < TRX_SYS_N_RSEGS; ++i) { trx_undo_t* undo; trx_rseg_t* rseg; rseg = trx_sys->rseg_array[i]; if (rseg == NULL) { continue; } /* Resurrect transactions that were doing inserts. */ for (undo = UT_LIST_GET_FIRST(rseg->insert_undo_list); undo != NULL; undo = UT_LIST_GET_NEXT(undo_list, undo)) { trx_t* trx; trx = trx_resurrect_insert(undo, rseg); trx_list_rw_insert_ordered(trx); trx_resurrect_table_locks(trx, undo); } /* Ressurrect transactions that were doing updates. */ for (undo = UT_LIST_GET_FIRST(rseg->update_undo_list); undo != NULL; undo = UT_LIST_GET_NEXT(undo_list, undo)) { trx_t* trx; ibool trx_created; /* Check the trx_sys->rw_trx_list first. */ mutex_enter(&trx_sys->mutex); trx = trx_get_rw_trx_by_id(undo->trx_id); mutex_exit(&trx_sys->mutex); if (trx == NULL) { trx = trx_allocate_for_background(); trx_created = TRUE; } else { trx_created = FALSE; } trx_resurrect_update(trx, undo, rseg); if (trx_created) { trx_list_rw_insert_ordered(trx); } trx_resurrect_table_locks(trx, undo); } } } /******************************************************************//** Assigns a rollback segment to a transaction in a round-robin fashion. @return assigned rollback segment instance */ static trx_rseg_t* trx_assign_rseg_low( /*================*/ ulong max_undo_logs, /*!< in: maximum number of UNDO logs to use */ ulint n_tablespaces) /*!< in: number of rollback tablespaces */ { ulint i; trx_rseg_t* rseg; static ulint latest_rseg = 0; if (srv_read_only_mode) { ut_a(max_undo_logs == ULONG_UNDEFINED); return(NULL); } /* This breaks true round robin but that should be OK. */ ut_a(max_undo_logs > 0 && max_undo_logs <= TRX_SYS_N_RSEGS); i = latest_rseg++; i %= max_undo_logs; /* Note: The assumption here is that there can't be any gaps in the array. Once we implement more flexible rollback segment management this may not hold. The assertion checks for that case. */ if (trx_sys->rseg_array[0] == NULL) { return(NULL); } /* Skip the system tablespace if we have more than one tablespace defined for rollback segments. We want all UNDO records to be in the non-system tablespaces. */ do { rseg = trx_sys->rseg_array[i]; ut_a(rseg == NULL || i == rseg->id); i = (rseg == NULL) ? 0 : i + 1; } while (rseg == NULL || (rseg->space == 0 && n_tablespaces > 0 && trx_sys->rseg_array[1] != NULL)); return(rseg); } /****************************************************************//** Assign a read-only transaction a rollback-segment, if it is attempting to write to a TEMPORARY table. */ UNIV_INTERN void trx_assign_rseg( /*============*/ trx_t* trx) /*!< A read-only transaction that needs to be assigned a RBS. */ { ut_a(trx->rseg == 0); ut_a(trx->read_only); ut_a(!srv_read_only_mode); ut_a(!trx_is_autocommit_non_locking(trx)); trx->rseg = trx_assign_rseg_low(srv_undo_logs, srv_undo_tablespaces); } /****************************************************************//** Starts a transaction. */ static void trx_start_low( /*==========*/ trx_t* trx) /*!< in: transaction */ { ut_ad(trx->rseg == NULL); ut_ad(trx->start_file != 0); ut_ad(trx->start_line != 0); ut_ad(!trx->is_recovered); ut_ad(trx_state_eq(trx, TRX_STATE_NOT_STARTED)); ut_ad(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0); /* If is primary transaction, should wait during buffer pool resizing. */ if (trx->is_primary && trx->buf_pool_reference == 0) { if (buf_pool_resizing) { if (trx->declared_to_be_inside_innodb) { /* Exit not to block the another active transaction's re-enter */ srv_conc_force_exit_innodb(trx); } DEBUG_SYNC_C("wait_for_buf_pool_resizing"); os_event_wait(buf_pool_resized_event); } /* block resizing buffer pool until set trx->state */ os_inc_counter(server_mutex, buf_pool_referenced); } /* Check whether it is an AUTOCOMMIT SELECT */ trx->auto_commit = (trx->api_trx && trx->api_auto_commit) || thd_trx_is_auto_commit(trx->mysql_thd); trx->read_only = (trx->api_trx && !trx->read_write) || (!trx->ddl && thd_trx_is_read_only(trx->mysql_thd)) || srv_read_only_mode; if (!trx->auto_commit) { ++trx->will_lock; } else if (trx->will_lock == 0) { trx->read_only = TRUE; } if (!trx->read_only) { trx->rseg = trx_assign_rseg_low( srv_undo_logs, srv_undo_tablespaces); } /* The initial value for trx->no: TRX_ID_MAX is used in read_view_open_now: */ trx->no = TRX_ID_MAX; ut_a(ib_vector_is_empty(trx->autoinc_locks)); ut_a(ib_vector_is_empty(trx->lock.table_locks)); mutex_enter(&trx_sys->mutex); /* If this transaction came from trx_allocate_for_mysql(), trx->in_mysql_trx_list would hold. In that case, the trx->state change must be protected by the trx_sys->mutex, so that lock_print_info_all_transactions() will have a consistent view. */ trx->state = TRX_STATE_ACTIVE; trx->id = trx_sys_get_new_trx_id(); ut_ad(!trx->in_rw_trx_list); ut_ad(!trx->in_ro_trx_list); if (trx->read_only) { /* Note: The trx_sys_t::ro_trx_list doesn't really need to be ordered, we should exploit this using a list type that doesn't need a list wide lock to increase concurrency. */ if (!trx_is_autocommit_non_locking(trx)) { UT_LIST_ADD_FIRST(trx_list, trx_sys->ro_trx_list, trx); ut_d(trx->in_ro_trx_list = TRUE); } } else { ut_ad(trx->rseg != NULL || srv_force_recovery >= SRV_FORCE_NO_TRX_UNDO); ut_ad(!trx_is_autocommit_non_locking(trx)); UT_LIST_ADD_FIRST(trx_list, trx_sys->rw_trx_list, trx); ut_d(trx->in_rw_trx_list = TRUE); #ifdef UNIV_DEBUG if (trx->id > trx_sys->rw_max_trx_id) { trx_sys->rw_max_trx_id = trx->id; } #endif /* UNIV_DEBUG */ } ut_ad(trx_sys_validate_trx_list()); mutex_exit(&trx_sys->mutex); if (trx->is_primary && trx->buf_pool_reference == 0) { /* now trx is active and it blocks resizing buffer pool. this atomic operation should work also as write barrier for trx->state. */ os_dec_counter(server_mutex, buf_pool_referenced); } trx->start_time = ut_time(); MONITOR_INC(MONITOR_TRX_ACTIVE); } /****************************************************************//** Set the transaction serialisation number. */ static void trx_serialisation_number_get( /*=========================*/ trx_t* trx) /*!< in: transaction */ { trx_rseg_t* rseg; rseg = trx->rseg; ut_ad(mutex_own(&rseg->mutex)); mutex_enter(&trx_sys->mutex); trx->no = trx_sys_get_new_trx_id(); /* If the rollack segment is not empty then the new trx_t::no can't be less than any trx_t::no already in the rollback segment. User threads only produce events when a rollback segment is empty. */ if (rseg->last_page_no == FIL_NULL) { void* ptr; rseg_queue_t rseg_queue; rseg_queue.rseg = rseg; rseg_queue.trx_no = trx->no; mutex_enter(&purge_sys->bh_mutex); /* This is to reduce the pressure on the trx_sys_t::mutex though in reality it should make very little (read no) difference because this code path is only taken when the rbs is empty. */ mutex_exit(&trx_sys->mutex); ptr = ib_bh_push(purge_sys->ib_bh, &rseg_queue); ut_a(ptr); mutex_exit(&purge_sys->bh_mutex); } else { mutex_exit(&trx_sys->mutex); } } /****************************************************************//** Assign the transaction its history serialisation number and write the update UNDO log record to the assigned rollback segment. */ static __attribute__((nonnull)) void trx_write_serialisation_history( /*============================*/ trx_t* trx, /*!< in/out: transaction */ mtr_t* mtr) /*!< in/out: mini-transaction */ { trx_rseg_t* rseg; rseg = trx->rseg; /* Change the undo log segment states from TRX_UNDO_ACTIVE to some other state: these modifications to the file data structure define the transaction as committed in the file based domain, at the serialization point of the log sequence number lsn obtained below. */ if (trx->update_undo != NULL) { page_t* undo_hdr_page; trx_undo_t* undo = trx->update_undo; /* We have to hold the rseg mutex because update log headers have to be put to the history list in the (serialisation) order of the UNDO trx number. This is required for the purge in-memory data structures too. */ mutex_enter(&rseg->mutex); /* Assign the transaction serialisation number and also update the purge min binary heap if this is the first UNDO log being written to the assigned rollback segment. */ trx_serialisation_number_get(trx); /* It is not necessary to obtain trx->undo_mutex here because only a single OS thread is allowed to do the transaction commit for this transaction. */ undo_hdr_page = trx_undo_set_state_at_finish(undo, mtr); trx_undo_update_cleanup(trx, undo_hdr_page, mtr); } else { mutex_enter(&rseg->mutex); } if (trx->insert_undo != NULL) { trx_undo_set_state_at_finish(trx->insert_undo, mtr); } mutex_exit(&rseg->mutex); MONITOR_INC(MONITOR_TRX_COMMIT_UNDO); srv_n_commit_with_undo++; /* Update the latest MySQL binlog name and offset info in trx sys header if MySQL binlogging is on or the database server is a MySQL replication slave */ if (trx->mysql_log_file_name && trx->mysql_log_file_name[0] != '\0') { trx_sys_update_mysql_binlog_offset( trx->mysql_log_file_name, trx->mysql_log_offset, TRX_SYS_MYSQL_LOG_INFO, mtr, trx->mysql_gtid); trx->mysql_log_file_name = NULL; trx->mysql_gtid = NULL; } } /******************************************************************** Finalize a transaction containing updates for a FTS table. */ static __attribute__((nonnull)) void trx_finalize_for_fts_table( /*=======================*/ fts_trx_table_t* ftt) /* in: FTS trx table */ { fts_t* fts = ftt->table->fts; fts_doc_ids_t* doc_ids = ftt->added_doc_ids; mutex_enter(&fts->bg_threads_mutex); if (fts->fts_status & BG_THREAD_STOP) { /* The table is about to be dropped, no use adding anything to its work queue. */ mutex_exit(&fts->bg_threads_mutex); } else { mem_heap_t* heap; mutex_exit(&fts->bg_threads_mutex); ut_a(fts->add_wq); heap = static_cast<mem_heap_t*>(doc_ids->self_heap->arg); ib_wqueue_add(fts->add_wq, doc_ids, heap); /* fts_trx_table_t no longer owns the list. */ ftt->added_doc_ids = NULL; } } /******************************************************************//** Finalize a transaction containing updates to FTS tables. */ static __attribute__((nonnull)) void trx_finalize_for_fts( /*=================*/ trx_t* trx, /*!< in/out: transaction */ bool is_commit) /*!< in: true if the transaction was committed, false if it was rolled back. */ { if (is_commit) { const ib_rbt_node_t* node; ib_rbt_t* tables; fts_savepoint_t* savepoint; savepoint = static_cast<fts_savepoint_t*>( ib_vector_last(trx->fts_trx->savepoints)); tables = savepoint->tables; for (node = rbt_first(tables); node; node = rbt_next(tables, node)) { fts_trx_table_t** ftt; ftt = rbt_value(fts_trx_table_t*, node); if ((*ftt)->added_doc_ids) { trx_finalize_for_fts_table(*ftt); } } } fts_trx_free(trx->fts_trx); trx->fts_trx = NULL; } /**********************************************************************//** If required, flushes the log to disk based on the value of innodb_flush_log_at_trx_commit. */ static void trx_flush_log_if_needed_low( /*========================*/ lsn_t lsn, /*!< in: lsn up to which logs are to be flushed. */ ibool async) /*!< in: TRUE - don't sync log */ { int flush_log_value = srv_flush_log_at_trx_commit; if (async) { flush_log_value = 2; } switch (flush_log_value) { case 0: /* Do nothing */ break; case 1: { bool sync = srv_unix_file_flush_method != SRV_UNIX_NOSYNC; /* Write the log and optionally flush it to disk */ log_write_up_to(lsn, LOG_WAIT_ONE_GROUP, sync, sync ? LOG_WRITE_FROM_COMMIT_SYNC : LOG_WRITE_FROM_COMMIT_ASYNC ); break; } case 2: /* Write the log but do not flush it to disk */ log_write_up_to(lsn, LOG_WAIT_ONE_GROUP, FALSE, LOG_WRITE_FROM_COMMIT_ASYNC); break; default: ut_error; } } /**********************************************************************//** If required, flushes the log to disk based on the value of innodb_flush_log_at_trx_commit. */ static __attribute__((nonnull)) void trx_flush_log_if_needed( /*====================*/ lsn_t lsn, /*!< in: lsn up to which logs are to be flushed. */ trx_t* trx, /*!< in/out: transaction */ ibool async) /*!< in: TRUE - don't sync log */ { trx->op_info = "flushing log"; trx_flush_log_if_needed_low(lsn, async); trx->op_info = ""; } /****************************************************************//** Commits a transaction in memory. */ static __attribute__((nonnull)) void trx_commit_in_memory( /*=================*/ trx_t* trx, /*!< in/out: transaction */ lsn_t lsn, /*!< in: log sequence number of the mini-transaction commit of trx_write_serialisation_history(), or 0 if the transaction did not modify anything */ ibool for_commit) /*!< in: for rollback when FALSE */ { trx->must_flush_log_later = FALSE; if (trx_is_autocommit_non_locking(trx)) { ut_ad(trx->read_only); ut_a(!trx->is_recovered); ut_ad(trx->rseg == NULL); ut_ad(!trx->in_ro_trx_list); ut_ad(!trx->in_rw_trx_list); /* Note: We are asserting without holding the lock mutex. But that is OK because this transaction is not waiting and cannot be rolled back and no new locks can (or should not) be added becuase it is flagged as a non-locking read-only transaction. */ ut_a(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0); /* This state change is not protected by any mutex, therefore there is an inherent race here around state transition during printouts. We ignore this race for the sake of efficiency. However, the trx_sys_t::mutex will protect the trx_t instance and it cannot be removed from the mysql_trx_list and freed without first acquiring the trx_sys_t::mutex. */ ut_ad(trx_state_eq(trx, TRX_STATE_ACTIVE)); trx->state = TRX_STATE_NOT_STARTED; read_view_remove(trx->global_read_view, false); MONITOR_INC(MONITOR_TRX_NL_RO_COMMIT); if(for_commit) { srv_n_commit_all++; } } else { lock_trx_release_locks(trx); /* Remove the transaction from the list of active transactions now that it no longer holds any user locks. */ ut_ad(trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY)); mutex_enter(&trx_sys->mutex); assert_trx_in_list(trx); if (trx->read_only) { UT_LIST_REMOVE(trx_list, trx_sys->ro_trx_list, trx); ut_d(trx->in_ro_trx_list = FALSE); MONITOR_INC(MONITOR_TRX_RO_COMMIT); if(for_commit) { srv_n_commit_all++; } } else { UT_LIST_REMOVE(trx_list, trx_sys->rw_trx_list, trx); ut_d(trx->in_rw_trx_list = FALSE); MONITOR_INC(MONITOR_TRX_RW_COMMIT); if(for_commit) { srv_n_commit_all++; } } /* If this transaction came from trx_allocate_for_mysql(), trx->in_mysql_trx_list would hold. In that case, the trx->state change must be protected by trx_sys->mutex, so that lock_print_info_all_transactions() will have a consistent view. */ trx->state = TRX_STATE_NOT_STARTED; /* We already own the trx_sys_t::mutex, by doing it here we avoid a potential context switch later. */ read_view_remove(trx->global_read_view, true); ut_ad(trx_sys_validate_trx_list()); mutex_exit(&trx_sys->mutex); } if (trx->global_read_view != NULL) { mem_heap_empty(trx->global_read_view_heap); trx->global_read_view = NULL; } trx->read_view = NULL; if (lsn) { if (trx->insert_undo != NULL) { trx_undo_insert_cleanup(trx); } /* NOTE that we could possibly make a group commit more efficient here: call os_thread_yield here to allow also other trxs to come to commit! */ /*-------------------------------------*/ /* Depending on the my.cnf options, we may now write the log buffer to the log files, making the transaction durable if the OS does not crash. We may also flush the log files to disk, making the transaction durable also at an OS crash or a power outage. The idea in InnoDB's group commit is that a group of transactions gather behind a trx doing a physical disk write to log files, and when that physical write has been completed, one of those transactions does a write which commits the whole group. Note that this group commit will only bring benefit if there are > 2 users in the database. Then at least 2 users can gather behind one doing the physical log write to disk. If we are calling trx_commit() under prepare_commit_mutex, we will delay possible log write and flush to a separate function trx_commit_complete_for_mysql(), which is only called when the thread has released the mutex. This is to make the group commit algorithm to work. Otherwise, the prepare_commit mutex would serialize all commits and prevent a group of transactions from gathering. */ if (trx->flush_log_later) { /* Do nothing yet */ trx->must_flush_log_later = TRUE; } else if (srv_flush_log_at_trx_commit == 0 || thd_requested_durability(trx->mysql_thd) == HA_IGNORE_DURABILITY) { /* Do nothing */ } else { trx_flush_log_if_needed(lsn, trx, false); } trx->commit_lsn = lsn; /* Tell server some activity has happened, since the trx does changes something. Background utility threads like master thread, purge thread or page_cleaner thread might have some work to do. */ srv_active_wake_master_thread(); } /* undo_no is non-zero if we're doing the final commit. */ bool not_rollback = trx->undo_no != 0; /* Free all savepoints, starting from the first. */ trx_named_savept_t* savep = UT_LIST_GET_FIRST(trx->trx_savepoints); trx_roll_savepoints_free(trx, savep); trx->rseg = NULL; trx->undo_no = 0; trx->last_sql_stat_start.least_undo_no = 0; trx->ddl = false; #ifdef UNIV_DEBUG ut_ad(trx->start_file != 0); ut_ad(trx->start_line != 0); trx->start_file = 0; trx->start_line = 0; #endif /* UNIV_DEBUG */ trx->will_lock = 0; trx->read_only = FALSE; trx->auto_commit = FALSE; if (trx->fts_trx) { trx_finalize_for_fts(trx, not_rollback); } ut_ad(trx->lock.wait_thr == NULL); ut_ad(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0); ut_ad(!trx->in_ro_trx_list); ut_ad(!trx->in_rw_trx_list); trx->dict_operation = TRX_DICT_OP_NONE; trx->error_state = DB_SUCCESS; /* trx->in_mysql_trx_list would hold between trx_allocate_for_mysql() and trx_free_for_mysql(). It does not hold for recovered transactions or system transactions. */ } /****************************************************************//** Commits a transaction and a mini-transaction. */ UNIV_INTERN void trx_commit_low( /*===========*/ trx_t* trx, /*!< in/out: transaction */ mtr_t* mtr, /*!< in/out: mini-transaction (will be committed), or NULL if trx made no modifications */ ibool for_commit) /*!< in: for rollback when FALSE */ { lsn_t lsn; assert_trx_nonlocking_or_in_list(trx); ut_ad(!trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY)); ut_ad(!mtr || mtr->state == MTR_ACTIVE); ut_ad(!mtr == !(trx->insert_undo || trx->update_undo)); /* undo_no is non-zero if we're doing the final commit. */ if (trx->fts_trx && trx->undo_no != 0) { dberr_t error; ut_a(!trx_is_autocommit_non_locking(trx)); error = fts_commit(trx); /* FTS-FIXME: Temporarily tolerate DB_DUPLICATE_KEY instead of dying. This is a possible scenario if there is a crash between insert to DELETED table committing and transaction committing. The fix would be able to return error from this function */ if (error != DB_SUCCESS && error != DB_DUPLICATE_KEY) { /* FTS-FIXME: once we can return values from this function, we should do so and signal an error instead of just dying. */ ut_error; } } if (mtr) { trx_write_serialisation_history(trx, mtr); /* The following call commits the mini-transaction, making the whole transaction committed in the file-based world, at this log sequence number. The transaction becomes 'durable' when we write the log to disk, but in the logical sense the commit in the file-based data structures (undo logs etc.) happens here. NOTE that transaction numbers, which are assigned only to transactions with an update undo log, do not necessarily come in exactly the same order as commit lsn's, if the transactions have different rollback segments. To get exactly the same order we should hold the kernel mutex up to this point, adding to the contention of the kernel mutex. However, if a transaction T2 is able to see modifications made by a transaction T1, T2 will always get a bigger transaction number and a bigger commit lsn than T1. */ /*--------------*/ mtr_commit(mtr); /*--------------*/ lsn = mtr->end_lsn; } else { lsn = 0; } trx_commit_in_memory(trx, lsn, for_commit); } /****************************************************************//** Commits a transaction. */ UNIV_INTERN void trx_commit( trx_t* trx, /*!< in/out: transaction */ ibool for_commit) /*!< in: for rollback when FALSE */ { mtr_t local_mtr; mtr_t* mtr; if (trx->insert_undo || trx->update_undo) { mtr = &local_mtr; mtr_start(mtr); } else { mtr = NULL; } trx_commit_low(trx, mtr, for_commit); } /****************************************************************//** Cleans up a transaction at database startup. The cleanup is needed if the transaction already got to the middle of a commit when the database crashed, and we cannot roll it back. */ UNIV_INTERN void trx_cleanup_at_db_startup( /*======================*/ trx_t* trx) /*!< in: transaction */ { ut_ad(trx->is_recovered); if (trx->insert_undo != NULL) { trx_undo_insert_cleanup(trx); } trx->rseg = NULL; trx->undo_no = 0; trx->last_sql_stat_start.least_undo_no = 0; mutex_enter(&trx_sys->mutex); ut_a(!trx->read_only); UT_LIST_REMOVE(trx_list, trx_sys->rw_trx_list, trx); assert_trx_in_rw_list(trx); ut_d(trx->in_rw_trx_list = FALSE); mutex_exit(&trx_sys->mutex); /* Change the transaction state without mutex protection, now that it no longer is in the trx_list. Recovered transactions are never placed in the mysql_trx_list. */ ut_ad(trx->is_recovered); ut_ad(!trx->in_ro_trx_list); ut_ad(!trx->in_rw_trx_list); ut_ad(!trx->in_mysql_trx_list); trx->state = TRX_STATE_NOT_STARTED; } /********************************************************************//** Assigns a read view for a consistent read query. All the consistent reads within the same transaction will get the same read view, which is created when this function is first called for a new started transaction. @return consistent read view */ UNIV_INTERN read_view_t* trx_assign_read_view( /*=================*/ trx_t* trx) /*!< in: active transaction */ { ut_ad(trx->state == TRX_STATE_ACTIVE); if (trx->read_view != NULL) { return(trx->read_view); } if (!trx->read_view) { trx->read_view = read_view_open_now( trx->id, trx->global_read_view_heap); trx->global_read_view = trx->read_view; } return(trx->read_view); } /****************************************************************//** Prepares a transaction for commit/rollback. */ UNIV_INTERN void trx_commit_or_rollback_prepare( /*===========================*/ trx_t* trx) /*!< in/out: transaction */ { /* We are reading trx->state without holding trx_sys->mutex here, because the commit or rollback should be invoked for a running (or recovered prepared) transaction that is associated with the current thread. */ switch (trx->state) { case TRX_STATE_NOT_STARTED: trx_start_low(trx); /* fall through */ case TRX_STATE_ACTIVE: case TRX_STATE_PREPARED: /* If the trx is in a lock wait state, moves the waiting query thread to the suspended state */ if (trx->lock.que_state == TRX_QUE_LOCK_WAIT) { ut_a(trx->lock.wait_thr != NULL); trx->lock.wait_thr->state = QUE_THR_SUSPENDED; trx->lock.wait_thr = NULL; trx->lock.que_state = TRX_QUE_RUNNING; } ut_a(trx->lock.n_active_thrs == 1); return; case TRX_STATE_COMMITTED_IN_MEMORY: break; } ut_error; } /*********************************************************************//** Creates a commit command node struct. @return own: commit node struct */ UNIV_INTERN commit_node_t* trx_commit_node_create( /*===================*/ mem_heap_t* heap) /*!< in: mem heap where created */ { commit_node_t* node; node = static_cast<commit_node_t*>(mem_heap_alloc(heap, sizeof(*node))); node->common.type = QUE_NODE_COMMIT; node->state = COMMIT_NODE_SEND; return(node); } /***********************************************************//** Performs an execution step for a commit type node in a query graph. @return query thread to run next, or NULL */ UNIV_INTERN que_thr_t* trx_commit_step( /*============*/ que_thr_t* thr) /*!< in: query thread */ { commit_node_t* node; node = static_cast<commit_node_t*>(thr->run_node); ut_ad(que_node_get_type(node) == QUE_NODE_COMMIT); if (thr->prev_node == que_node_get_parent(node)) { node->state = COMMIT_NODE_SEND; } if (node->state == COMMIT_NODE_SEND) { trx_t* trx; node->state = COMMIT_NODE_WAIT; trx = thr_get_trx(thr); ut_a(trx->lock.wait_thr == NULL); ut_a(trx->lock.que_state != TRX_QUE_LOCK_WAIT); trx_commit_or_rollback_prepare(trx); trx->lock.que_state = TRX_QUE_COMMITTING; trx_commit(trx, TRUE); ut_ad(trx->lock.wait_thr == NULL); trx->lock.que_state = TRX_QUE_RUNNING; thr = NULL; } else { ut_ad(node->state == COMMIT_NODE_WAIT); node->state = COMMIT_NODE_SEND; thr->run_node = que_node_get_parent(node); } return(thr); } /**********************************************************************//** Does the transaction commit for MySQL. @return DB_SUCCESS or error number */ UNIV_INTERN dberr_t trx_commit_for_mysql( /*=================*/ trx_t* trx) /*!< in/out: transaction */ { /* Because we do not do the commit by sending an Innobase sig to the transaction, we must here make sure that trx has been started. */ ut_a(trx); switch (trx->state) { case TRX_STATE_NOT_STARTED: /* Update the info whether we should skip XA steps that eat CPU time. For the duration of the transaction trx->support_xa is not reread from thd so any changes in the value take effect in the next transaction. This is to avoid a scenario where some undo log records generated by a transaction contain XA information and other undo log records, generated by the same transaction do not. */ trx->support_xa = thd_supports_xa(trx->mysql_thd); ut_d(trx->start_file = __FILE__); ut_d(trx->start_line = __LINE__); trx_start_low(trx); /* fall through */ case TRX_STATE_ACTIVE: case TRX_STATE_PREPARED: trx->op_info = "committing"; trx_commit(trx, TRUE); MONITOR_DEC(MONITOR_TRX_ACTIVE); trx->op_info = ""; return(DB_SUCCESS); case TRX_STATE_COMMITTED_IN_MEMORY: break; } ut_error; return(DB_CORRUPTION); } /**********************************************************************//** If required, flushes the log to disk if we called trx_commit_for_mysql() with trx->flush_log_later == TRUE. */ UNIV_INTERN void trx_commit_complete_for_mysql( /*==========================*/ trx_t* trx, /*!< in/out: transaction */ ibool async) /*!< in: TRUE - don't sync log */ { ut_a(trx); if (!trx->must_flush_log_later || thd_requested_durability(trx->mysql_thd) == HA_IGNORE_DURABILITY) { return; } trx_flush_log_if_needed(trx->commit_lsn, trx, async); trx->must_flush_log_later = FALSE; } /**********************************************************************//** Marks the latest SQL statement ended. */ UNIV_INTERN void trx_mark_sql_stat_end( /*==================*/ trx_t* trx) /*!< in: trx handle */ { ut_a(trx); switch (trx->state) { case TRX_STATE_PREPARED: case TRX_STATE_COMMITTED_IN_MEMORY: break; case TRX_STATE_NOT_STARTED: trx->undo_no = 0; /* fall through */ case TRX_STATE_ACTIVE: trx->last_sql_stat_start.least_undo_no = trx->undo_no; if (trx->fts_trx) { fts_savepoint_laststmt_refresh(trx); } return; } ut_error; } /**********************************************************************//** Prints info about a transaction. Caller must hold trx_sys->mutex. */ UNIV_INTERN void trx_print_low( /*==========*/ FILE* f, /*!< in: output stream */ const trx_t* trx, /*!< in: transaction */ ulint max_query_len, /*!< in: max query length to print, or 0 to use the default max length */ ulint n_rec_locks, /*!< in: lock_number_of_rows_locked(&trx->lock) */ ulint n_trx_locks, /*!< in: length of trx->lock.trx_locks */ ulint heap_size) /*!< in: mem_heap_get_size(trx->lock.lock_heap) */ { ibool newline; const char* op_info; ut_ad(mutex_own(&trx_sys->mutex)); fprintf(f, "TRANSACTION " TRX_ID_FMT, trx->id); /* trx->state cannot change from or to NOT_STARTED while we are holding the trx_sys->mutex. It may change from ACTIVE to PREPARED or COMMITTED. */ switch (trx->state) { case TRX_STATE_NOT_STARTED: fputs(", not started", f); goto state_ok; case TRX_STATE_ACTIVE: fprintf(f, ", ACTIVE %lu sec", (ulong) difftime(time(NULL), trx->start_time)); goto state_ok; case TRX_STATE_PREPARED: fprintf(f, ", ACTIVE (PREPARED) %lu sec", (ulong) difftime(time(NULL), trx->start_time)); goto state_ok; case TRX_STATE_COMMITTED_IN_MEMORY: fputs(", COMMITTED IN MEMORY", f); goto state_ok; } fprintf(f, ", state %lu", (ulong) trx->state); ut_ad(0); state_ok: /* prevent a race condition */ op_info = trx->op_info; if (*op_info) { putc(' ', f); fputs(op_info, f); } if (trx->is_recovered) { fputs(" recovered trx", f); } if (trx->declared_to_be_inside_innodb) { fprintf(f, ", thread declared inside InnoDB %lu", (ulong) trx->n_tickets_to_enter_innodb); } putc('\n', f); if (trx->n_mysql_tables_in_use > 0 || trx->mysql_n_tables_locked > 0) { fprintf(f, "mysql tables in use %lu, locked %lu\n", (ulong) trx->n_mysql_tables_in_use, (ulong) trx->mysql_n_tables_locked); } newline = TRUE; /* trx->lock.que_state of an ACTIVE transaction may change while we are not holding trx->mutex. We perform a dirty read for performance reasons. */ switch (trx->lock.que_state) { case TRX_QUE_RUNNING: newline = FALSE; break; case TRX_QUE_LOCK_WAIT: fputs("LOCK WAIT ", f); break; case TRX_QUE_ROLLING_BACK: fputs("ROLLING BACK ", f); break; case TRX_QUE_COMMITTING: fputs("COMMITTING ", f); break; default: fprintf(f, "que state %lu ", (ulong) trx->lock.que_state); } if (n_trx_locks > 0 || heap_size > 400) { newline = TRUE; fprintf(f, "%lu lock struct(s), heap size %lu," " %lu row lock(s)", (ulong) n_trx_locks, (ulong) heap_size, (ulong) n_rec_locks); } if (trx->has_search_latch) { newline = TRUE; fputs(", holds adaptive hash latch", f); } if (trx->undo_no != 0) { newline = TRUE; fprintf(f, ", undo log entries " TRX_ID_FMT, trx->undo_no); } if (newline) { putc('\n', f); } if (trx->mysql_thd != NULL) { innobase_mysql_print_thd( f, trx->mysql_thd, static_cast<uint>(max_query_len)); } } /**********************************************************************//** Prints info about a transaction. The caller must hold lock_sys->mutex and trx_sys->mutex. When possible, use trx_print() instead. */ UNIV_INTERN void trx_print_latched( /*==============*/ FILE* f, /*!< in: output stream */ const trx_t* trx, /*!< in: transaction */ ulint max_query_len) /*!< in: max query length to print, or 0 to use the default max length */ { ut_ad(lock_mutex_own()); ut_ad(mutex_own(&trx_sys->mutex)); trx_print_low(f, trx, max_query_len, lock_number_of_rows_locked(&trx->lock), UT_LIST_GET_LEN(trx->lock.trx_locks), mem_heap_get_size(trx->lock.lock_heap)); } /**********************************************************************//** Prints info about a transaction. Acquires and releases lock_sys->mutex and trx_sys->mutex. */ UNIV_INTERN void trx_print( /*======*/ FILE* f, /*!< in: output stream */ const trx_t* trx, /*!< in: transaction */ ulint max_query_len) /*!< in: max query length to print, or 0 to use the default max length */ { ulint n_rec_locks; ulint n_trx_locks; ulint heap_size; lock_mutex_enter(); n_rec_locks = lock_number_of_rows_locked(&trx->lock); n_trx_locks = UT_LIST_GET_LEN(trx->lock.trx_locks); heap_size = mem_heap_get_size(trx->lock.lock_heap); lock_mutex_exit(); mutex_enter(&trx_sys->mutex); trx_print_low(f, trx, max_query_len, n_rec_locks, n_trx_locks, heap_size); mutex_exit(&trx_sys->mutex); } #ifdef UNIV_DEBUG /**********************************************************************//** Asserts that a transaction has been started. The caller must hold trx_sys->mutex. @return TRUE if started */ UNIV_INTERN ibool trx_assert_started( /*===============*/ const trx_t* trx) /*!< in: transaction */ { ut_ad(mutex_own(&trx_sys->mutex)); /* Non-locking autocommits should not hold any locks and this function is only called from the locking code. */ assert_trx_in_list(trx); /* trx->state can change from or to NOT_STARTED while we are holding trx_sys->mutex for non-locking autocommit selects but not for other types of transactions. It may change from ACTIVE to PREPARED. Unless we are holding lock_sys->mutex, it may also change to COMMITTED. */ switch (trx->state) { case TRX_STATE_PREPARED: return(TRUE); case TRX_STATE_ACTIVE: case TRX_STATE_COMMITTED_IN_MEMORY: return(TRUE); case TRX_STATE_NOT_STARTED: break; } ut_error; return(FALSE); } #endif /* UNIV_DEBUG */ /*******************************************************************//** Compares the "weight" (or size) of two transactions. Transactions that have edited non-transactional tables are considered heavier than ones that have not. @return TRUE if weight(a) >= weight(b) */ UNIV_INTERN ibool trx_weight_ge( /*==========*/ const trx_t* a, /*!< in: the first transaction to be compared */ const trx_t* b) /*!< in: the second transaction to be compared */ { ibool a_notrans_edit; ibool b_notrans_edit; /* If mysql_thd is NULL for a transaction we assume that it has not edited non-transactional tables. */ a_notrans_edit = a->mysql_thd != NULL && thd_has_edited_nontrans_tables(a->mysql_thd); b_notrans_edit = b->mysql_thd != NULL && thd_has_edited_nontrans_tables(b->mysql_thd); if (a_notrans_edit != b_notrans_edit) { return(a_notrans_edit); } /* Either both had edited non-transactional tables or both had not, we fall back to comparing the number of altered/locked rows. */ #if 0 fprintf(stderr, "%s TRX_WEIGHT(a): %lld+%lu, TRX_WEIGHT(b): %lld+%lu\n", __func__, a->undo_no, UT_LIST_GET_LEN(a->lock.trx_locks), b->undo_no, UT_LIST_GET_LEN(b->lock.trx_locks)); #endif return(TRX_WEIGHT(a) >= TRX_WEIGHT(b)); } /****************************************************************//** Prepares a transaction. */ static void trx_prepare( /*========*/ trx_t* trx, /*!< in/out: transaction */ ibool async) /*!< in: TRUE - don't sync log */ { trx_rseg_t* rseg; lsn_t lsn; mtr_t mtr; rseg = trx->rseg; /* Only fresh user transactions can be prepared. Recovered transactions cannot. */ ut_a(!trx->is_recovered); if (trx->insert_undo != NULL || trx->update_undo != NULL) { mtr_start(&mtr); /* Change the undo log segment states from TRX_UNDO_ACTIVE to TRX_UNDO_PREPARED: these modifications to the file data structure define the transaction as prepared in the file-based world, at the serialization point of lsn. */ mutex_enter(&rseg->mutex); if (trx->insert_undo != NULL) { /* It is not necessary to obtain trx->undo_mutex here because only a single OS thread is allowed to do the transaction prepare for this transaction. */ trx_undo_set_state_at_prepare(trx, trx->insert_undo, &mtr); } if (trx->update_undo) { trx_undo_set_state_at_prepare( trx, trx->update_undo, &mtr); } mutex_exit(&rseg->mutex); /*--------------*/ mtr_commit(&mtr); /* This mtr commit makes the transaction prepared in the file-based world */ /*--------------*/ lsn = mtr.end_lsn; ut_ad(lsn); } else { lsn = 0; } /*--------------------------------------*/ ut_a(trx->state == TRX_STATE_ACTIVE); mutex_enter(&trx_sys->mutex); trx->state = TRX_STATE_PREPARED; trx_sys->n_prepared_trx++; mutex_exit(&trx_sys->mutex); /*--------------------------------------*/ if (lsn) { switch (thd_requested_durability(trx->mysql_thd)) { case HA_IGNORE_DURABILITY: /* We set the HA_IGNORE_DURABILITY during prepare phase of binlog group commit to not flush redo log for every transaction here. So that we can flush prepared records of transactions to redo log in a group right before writing them to binary log during flush stage of binlog group commit. */ thd_store_lsn(trx->mysql_thd, lsn, innobase_get_type()); break; case HA_REGULAR_DURABILITY: /* Depending on the my.cnf options, we may now write the log buffer to the log files, making the prepared state of the transaction durable if the OS does not crash. We may also flush the log files to disk, making the prepared state of the transaction durable also at an OS crash or a power outage. The idea in InnoDB's group prepare is that a group of transactions gather behind a trx doing a physical disk write to log files, and when that physical write has been completed, one of those transactions does a write which prepares the whole group. Note that this group prepare will only bring benefit if there are > 2 users in the database. Then at least 2 users can gather behind one doing the physical log write to disk. We must not be holding any mutexes or latches here. */ trx_flush_log_if_needed(lsn, trx, async); break; } } } /**********************************************************************//** Does the transaction prepare for MySQL. */ UNIV_INTERN void trx_prepare_for_mysql( /*==================*/ trx_t* trx, /*!< in/out: trx handle */ ibool async) /*!< in: TRUE - don't sync log */ { trx_start_if_not_started_xa(trx); trx->op_info = "preparing"; trx_prepare(trx, async); trx->op_info = ""; } /**********************************************************************//** This function is used to find number of prepared transactions and their transaction objects for a recovery. @return number of prepared transactions stored in xid_list */ UNIV_INTERN int trx_recover_for_mysql( /*==================*/ XID* xid_list, /*!< in/out: prepared transactions */ ulint len) /*!< in: number of slots in xid_list */ { const trx_t* trx; ulint count = 0; ut_ad(xid_list); ut_ad(len); /* We should set those transactions which are in the prepared state to the xid_list */ mutex_enter(&trx_sys->mutex); for (trx = UT_LIST_GET_FIRST(trx_sys->rw_trx_list); trx != NULL; trx = UT_LIST_GET_NEXT(trx_list, trx)) { assert_trx_in_rw_list(trx); /* The state of a read-write transaction cannot change from or to NOT_STARTED while we are holding the trx_sys->mutex. It may change to PREPARED, but not if trx->is_recovered. It may also change to COMMITTED. */ if (trx_state_eq(trx, TRX_STATE_PREPARED)) { xid_list[count] = trx->xid; if (count == 0) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Starting recovery for" " XA transactions...\n"); } ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Transaction " TRX_ID_FMT " in" " prepared state after recovery\n", trx->id); ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Transaction contains changes" " to " TRX_ID_FMT " rows\n", trx->undo_no); count++; if (count == len) { break; } } } mutex_exit(&trx_sys->mutex); if (count > 0){ ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: %d transactions in prepared state" " after recovery\n", int (count)); } return(int (count)); } /*******************************************************************//** This function is used to find one X/Open XA distributed transaction which is in the prepared state @return trx on match, the trx->xid will be invalidated; note that the trx may have been committed, unless the caller is holding lock_sys->mutex */ static __attribute__((nonnull, warn_unused_result)) trx_t* trx_get_trx_by_xid_low( /*===================*/ const XID* xid) /*!< in: X/Open XA transaction identifier */ { trx_t* trx; ut_ad(mutex_own(&trx_sys->mutex)); for (trx = UT_LIST_GET_FIRST(trx_sys->rw_trx_list); trx != NULL; trx = UT_LIST_GET_NEXT(trx_list, trx)) { assert_trx_in_rw_list(trx); /* Compare two X/Open XA transaction id's: their length should be the same and binary comparison of gtrid_length+bqual_length bytes should be the same */ if (trx->is_recovered && trx_state_eq(trx, TRX_STATE_PREPARED) && xid->gtrid_length == trx->xid.gtrid_length && xid->bqual_length == trx->xid.bqual_length && memcmp(xid->data, trx->xid.data, xid->gtrid_length + xid->bqual_length) == 0) { /* Invalidate the XID, so that subsequent calls will not find it. */ memset(&trx->xid, 0, sizeof(trx->xid)); trx->xid.formatID = -1; break; } } return(trx); } /*******************************************************************//** This function is used to find one X/Open XA distributed transaction which is in the prepared state @return trx or NULL; on match, the trx->xid will be invalidated; note that the trx may have been committed, unless the caller is holding lock_sys->mutex */ UNIV_INTERN trx_t* trx_get_trx_by_xid( /*===============*/ const XID* xid) /*!< in: X/Open XA transaction identifier */ { trx_t* trx; if (xid == NULL) { return(NULL); } mutex_enter(&trx_sys->mutex); /* Recovered/Resurrected transactions are always only on the trx_sys_t::rw_trx_list. */ trx = trx_get_trx_by_xid_low(xid); mutex_exit(&trx_sys->mutex); return(trx); } /*************************************************************//** Starts the transaction if it is not yet started. */ UNIV_INTERN void trx_start_if_not_started_xa_low( /*============================*/ trx_t* trx) /*!< in: transaction */ { switch (trx->state) { case TRX_STATE_NOT_STARTED: /* Update the info whether we should skip XA steps that eat CPU time. For the duration of the transaction trx->support_xa is not reread from thd so any changes in the value take effect in the next transaction. This is to avoid a scenario where some undo generated by a transaction, has XA stuff, and other undo, generated by the same transaction, doesn't. */ #ifdef XTRABACKUP trx->support_xa = trx->mysql_thd ? thd_supports_xa(trx->mysql_thd) : FALSE; #else /* XTRABACKUP */ trx->support_xa = thd_supports_xa(trx->mysql_thd); #endif /* XTRABACKUP */ trx_start_low(trx); /* fall through */ case TRX_STATE_ACTIVE: return; case TRX_STATE_PREPARED: case TRX_STATE_COMMITTED_IN_MEMORY: break; } ut_error; } /*************************************************************//** Starts the transaction if it is not yet started. */ UNIV_INTERN void trx_start_if_not_started_low( /*=========================*/ trx_t* trx) /*!< in: transaction */ { switch (trx->state) { case TRX_STATE_NOT_STARTED: trx_start_low(trx); /* fall through */ case TRX_STATE_ACTIVE: return; case TRX_STATE_PREPARED: case TRX_STATE_COMMITTED_IN_MEMORY: break; } ut_error; } /*************************************************************//** Starts the transaction for a DDL operation. */ UNIV_INTERN void trx_start_for_ddl_low( /*==================*/ trx_t* trx, /*!< in/out: transaction */ trx_dict_op_t op) /*!< in: dictionary operation type */ { switch (trx->state) { case TRX_STATE_NOT_STARTED: /* Flag this transaction as a dictionary operation, so that the data dictionary will be locked in crash recovery. */ trx_set_dict_operation(trx, op); /* Ensure it is not flagged as an auto-commit-non-locking transation. */ trx->will_lock = 1; trx->ddl = true; trx_start_low(trx); return; case TRX_STATE_ACTIVE: /* We have this start if not started idiom, therefore we can't add stronger checks here. */ trx->ddl = true; ut_ad(trx->dict_operation != TRX_DICT_OP_NONE); ut_ad(trx->will_lock > 0); return; case TRX_STATE_PREPARED: case TRX_STATE_COMMITTED_IN_MEMORY: break; } ut_error; }
26.509745
78
0.655794
hkirsman
cb05949ad8d8d3ac54832173e278edd5826c9bcd
2,868
cpp
C++
src/Program/ViewDisplay2D_3D/Program.ViewDisplay2D_3D.cpp
Robot-Fromage/Lavabo
e6ddc3123f057258a2e9e74c08ecd8d2333c9dd6
[ "MIT" ]
null
null
null
src/Program/ViewDisplay2D_3D/Program.ViewDisplay2D_3D.cpp
Robot-Fromage/Lavabo
e6ddc3123f057258a2e9e74c08ecd8d2333c9dd6
[ "MIT" ]
null
null
null
src/Program/ViewDisplay2D_3D/Program.ViewDisplay2D_3D.cpp
Robot-Fromage/Lavabo
e6ddc3123f057258a2e9e74c08ecd8d2333c9dd6
[ "MIT" ]
null
null
null
/************************************************************************* * * Lavabo *__________________ * * Program.ViewDisplay2D_3D.cpp * * Clement Berthaud - Layl * Please refer to LICENSE.TXT */ #include "Program.ViewDisplay2D_3D.h" #include <QGraphicsItem> #include <QGraphicsProxyWidget> #include "ViewDisplay2D.h" #include "ViewDisplay3D.h" #include "Model3D.h" #include "Shader3D.h" namespace nProgram { namespace nViewDisplay2D_3D { //-------------------------------------------------------------------------------------- //----------------------------------------------------------- Construction / Destruction cProgram_ViewDisplay2D_3D::~cProgram_ViewDisplay2D_3D() { Destroy(); } cProgram_ViewDisplay2D_3D::cProgram_ViewDisplay2D_3D( QWidget* parent ) : tSuperClass( parent ), mViewDisplay2D( NULL ), mViewDisplay3D( NULL ), mProxyViewDisplay3D( NULL ), mModel3D( NULL ), mShader3D( NULL ) { Init(); Build(); Compose(); } //-------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- Event void cProgram_ViewDisplay2D_3D::resizeEvent( QResizeEvent* event ) { tSuperClass::resizeEvent( event ); Compose(); } //-------------------------------------------------------------------------------------- //------------------------------------------------------------------------ GUI utilities void cProgram_ViewDisplay2D_3D::Init() { mViewDisplay2D = new cViewDisplay2D( this ); mViewDisplay3D = new cViewDisplay3D(); mProxyViewDisplay3D = new QGraphicsProxyWidget(); mModel3D = new cModel3D( "resources/obj3d/bunny.obj"); mShader3D = new cShader3D( "resources/shaders/ViewDisplay3D.vert", "resources/shaders/ViewDisplay3D.frag" ); } void cProgram_ViewDisplay2D_3D::Build() { mViewDisplay3D->SetModel3D( mModel3D ); mViewDisplay3D->SetShader3D( mShader3D ); mProxyViewDisplay3D->setWidget( mViewDisplay3D ); mViewDisplay2D->setCenterItem( mProxyViewDisplay3D ); //QObject::connect( mViewDisplay3D, SIGNAL( PaintCompleted() ), mViewDisplay2D, SLOT( update() ) ); } void cProgram_ViewDisplay2D_3D::Compose() { mViewDisplay3D->resize( size() ); mProxyViewDisplay3D->resize( size() ); mViewDisplay2D->resize( size() ); } void cProgram_ViewDisplay2D_3D::Destroy() { delete mViewDisplay2D; } // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // Registry Callback QWidget* RegistryCallback() { return new cProgram_ViewDisplay2D_3D(); } } // namespace nViewDisplay2D_3D } // namespace nProgram
23.129032
112
0.511855
Robot-Fromage
cb09316a90c30dd0cdfd9be6ec24c1760760f3ad
2,592
cpp
C++
src/buffer.cpp
plenluno/libnode
9dea4f2390422e70544186df3f5c032cb4a7db08
[ "BSD-2-Clause", "MIT" ]
255
2015-01-06T15:11:26.000Z
2022-03-30T20:52:58.000Z
src/buffer.cpp
plenluno/libnode
9dea4f2390422e70544186df3f5c032cb4a7db08
[ "BSD-2-Clause", "MIT" ]
2
2018-12-18T22:50:25.000Z
2019-01-09T16:57:11.000Z
src/buffer.cpp
plenluno/libnode
9dea4f2390422e70544186df3f5c032cb4a7db08
[ "BSD-2-Clause", "MIT" ]
36
2015-03-28T03:23:57.000Z
2022-01-16T12:51:30.000Z
// Copyright (c) 2012-2014 Plenluno All rights reserved. #include <libnode/buffer.h> #include <libnode/detail/buffer.h> namespace libj { namespace node { Buffer::Ptr Buffer::create(Size length) { return Ptr(new detail::Buffer<Buffer>(length)); } Buffer::Ptr Buffer::create(const void* data, Size length) { if (!data) return null(); detail::Buffer<Buffer>* buf(new detail::Buffer<Buffer>(length)); const UByte* src = static_cast<const UByte*>(data); UByte* dst = static_cast<UByte*>(const_cast<void*>(buf->data())); std::copy(src, src + length, dst); return Ptr(buf); } Buffer::Ptr Buffer::create(TypedJsArray<UByte>::CPtr array) { if (!array) return null(); Size length = array->length(); detail::Buffer<Buffer>* buf(new detail::Buffer<Buffer>(length)); for (Size i = 0; i < length; i++) { buf->writeUInt8(array->getTyped(i), i); } return Ptr(buf); } template<typename T> static Buffer::Ptr createBuffer(T t, Buffer::Encoding enc) { if (!t) return Buffer::null(); std::string s; switch (enc) { case Buffer::UTF8: s = t->toStdString(); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length()); case Buffer::UTF16BE: s = t->toStdString(String::UTF16BE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 2); // delete the last null character case Buffer::UTF16LE: s = t->toStdString(String::UTF16LE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 2); // delete the last null character case Buffer::UTF32BE: s = t->toStdString(String::UTF32BE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 4); // delete the last null character case Buffer::UTF32LE: s = t->toStdString(String::UTF32LE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 4); // delete the last null character case Buffer::BASE64: return util::base64Decode(t); case Buffer::HEX: return util::hexDecode(t); default: return Buffer::null(); } } Buffer::Ptr Buffer::create(String::CPtr str, Buffer::Encoding enc) { return createBuffer<String::CPtr>(str, enc); } Buffer::Ptr Buffer::create(StringBuilder::CPtr sb, Buffer::Encoding enc) { return createBuffer<StringBuilder::CPtr>(sb, enc); } } // namespace node } // namespace libj
30.857143
74
0.615355
plenluno
cb0ac0e955faa7177b861c492357bb98f501d442
3,698
cc
C++
tests/unittests/test_util.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
2
2016-01-22T03:10:02.000Z
2021-04-21T06:32:11.000Z
tests/unittests/test_util.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
null
null
null
tests/unittests/test_util.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Embedded Framework 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 "tests/unittests/test_util.h" #include "testing/gtest/include/gtest/gtest.h" void TestBinaryEqual(CefRefPtr<CefBinaryValue> val1, CefRefPtr<CefBinaryValue> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); size_t data_size = val1->GetSize(); EXPECT_EQ(data_size, val2->GetSize()); EXPECT_GT(data_size, (size_t)0); char* data1 = new char[data_size+1]; char* data2 = new char[data_size+1]; EXPECT_EQ(data_size, val1->GetData(data1, data_size, 0)); data1[data_size] = 0; EXPECT_EQ(data_size, val2->GetData(data2, data_size, 0)); data2[data_size] = 0; EXPECT_STREQ(data1, data2); delete [] data1; delete [] data2; } void TestDictionaryEqual(CefRefPtr<CefDictionaryValue> val1, CefRefPtr<CefDictionaryValue> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); EXPECT_EQ(val1->GetSize(), val2->GetSize()); CefDictionaryValue::KeyList keys; EXPECT_TRUE(val1->GetKeys(keys)); CefDictionaryValue::KeyList::const_iterator it = keys.begin(); for (; it != keys.end(); ++it) { CefString key = *it; EXPECT_TRUE(val2->HasKey(key)); CefValueType type = val1->GetType(key); EXPECT_EQ(type, val2->GetType(key)); switch (type) { case VTYPE_INVALID: case VTYPE_NULL: break; case VTYPE_BOOL: EXPECT_EQ(val1->GetBool(key), val2->GetBool(key)); break; case VTYPE_INT: EXPECT_EQ(val1->GetInt(key), val2->GetInt(key)); break; case VTYPE_DOUBLE: EXPECT_EQ(val1->GetDouble(key), val2->GetDouble(key)); break; case VTYPE_STRING: EXPECT_EQ(val1->GetString(key), val2->GetString(key)); break; case VTYPE_BINARY: TestBinaryEqual(val1->GetBinary(key), val2->GetBinary(key)); break; case VTYPE_DICTIONARY: TestDictionaryEqual(val1->GetDictionary(key), val2->GetDictionary(key)); break; case VTYPE_LIST: TestListEqual(val1->GetList(key), val2->GetList(key)); break; } } } void TestListEqual(CefRefPtr<CefListValue> val1, CefRefPtr<CefListValue> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); size_t size = val1->GetSize(); EXPECT_EQ(size, val2->GetSize()); for (size_t i = 0; i < size; ++i) { CefValueType type = val1->GetType(i); EXPECT_EQ(type, val2->GetType(i)); switch (type) { case VTYPE_INVALID: case VTYPE_NULL: break; case VTYPE_BOOL: EXPECT_EQ(val1->GetBool(i), val2->GetBool(i)); break; case VTYPE_INT: EXPECT_EQ(val1->GetInt(i), val2->GetInt(i)); break; case VTYPE_DOUBLE: EXPECT_EQ(val1->GetDouble(i), val2->GetDouble(i)); break; case VTYPE_STRING: EXPECT_EQ(val1->GetString(i), val2->GetString(i)); break; case VTYPE_BINARY: TestBinaryEqual(val1->GetBinary(i), val2->GetBinary(i)); break; case VTYPE_DICTIONARY: TestDictionaryEqual(val1->GetDictionary(i), val2->GetDictionary(i)); break; case VTYPE_LIST: TestListEqual(val1->GetList(i), val2->GetList(i)); break; } } } void TestProcessMessageEqual(CefRefPtr<CefProcessMessage> val1, CefRefPtr<CefProcessMessage> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); EXPECT_EQ(val1->GetName(), val2->GetName()); TestListEqual(val1->GetArgumentList(), val2->GetArgumentList()); }
29.11811
80
0.637372
phuy
cb0aeaacb789de549e5f8347b303c573252b58f8
1,658
cpp
C++
Khadas/sample/Face/src/main.cpp
iotbo/TengineKit
b82c3758360ef37cb219d487d3858a4c1b4effe7
[ "Apache-2.0" ]
null
null
null
Khadas/sample/Face/src/main.cpp
iotbo/TengineKit
b82c3758360ef37cb219d487d3858a4c1b4effe7
[ "Apache-2.0" ]
null
null
null
Khadas/sample/Face/src/main.cpp
iotbo/TengineKit
b82c3758360ef37cb219d487d3858a4c1b4effe7
[ "Apache-2.0" ]
null
null
null
#include "manager.hpp" #include <chrono> #include <iostream> #include <memory> #include <opencv2/opencv.hpp> #include <vector> int main(int argc, char **argv) { cv::Mat frame = cv::imread(argv[1]); manager *tm = new manager(); int image_w = frame.cols; int image_h = frame.rows; cv::Mat origin; frame.copyTo(origin); origin = frame.clone(); tm->init(); std::vector<FaceDetectInfo> info; tm->runDetect(origin.data, image_w, image_h, info); std::vector<FaceLandmarkInfo> landmarkinfo; tm->runLandmark2d(origin.data, image_w, image_h, info, landmarkinfo); for (int i = 0; i < info.size(); i++) { float x1 = info[i].face_box.x1; float x2 = info[i].face_box.x2; float y1 = info[i].face_box.y1; float y2 = info[i].face_box.y2; cv::Point pt1(x1 / 160.0f * image_w, y1 / 120.0f * image_h); cv::Point pt2(x2 / 160.0f * image_w, y2 / 120.0f * image_h); cv::rectangle(frame, pt1, pt2, cv::Scalar(255, 0, 0), 2); } for (int j = 0; j < landmarkinfo.size(); j++) { float w = info[j].face_box.x2 - info[j].face_box.x1; float h = info[j].face_box.y2 - info[j].face_box.y1; for (int i = 0; i < 424; i = i + 2) { float point_x = (landmarkinfo[j].landmarks[i] * w * 1.4f - w * 0.2f + info[j].face_box.x1) / 160.0f * image_w; float point_y = (landmarkinfo[j].landmarks[i + 1] * h * 1.4f - h * 0.2f + info[j].face_box.y1) / 120.0f * image_h; cv::Point pt(point_x, point_y); cv::circle(frame, pt, 1, cv::Scalar(255, 0, 0), 1); } } cv::imwrite("FaceOutput.jpg", frame); return 0; }
32.509804
79
0.58082
iotbo
cb0b7dde789b57b4cb63bad8b630a434c245d1d3
1,678
hh
C++
policy-decision-point/ast_preprocessor_visitor.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-06-02T11:50:06.000Z
2018-06-02T11:50:06.000Z
policy-decision-point/ast_preprocessor_visitor.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-01-17T04:16:29.000Z
2018-01-30T09:01:44.000Z
policy-decision-point/ast_preprocessor_visitor.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-11-18T20:31:54.000Z
2018-11-18T20:31:54.000Z
// Copyright 2015-2018 RWTH Aachen University // // 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. #pragma once #include "ast.hh" #include "policy_definition.hh" #include <algorithm> #include <boost/lexical_cast.hpp> //Visitor that preprocesses the AST class AstPreprocessorVisitor : public AstVisitor { public: //the policy definition is used to get the types of IDs, since they are initially unknown after the parsing AstPreprocessorVisitor(const PolicyDefinition &policyDefinition) : policyDefinition(policyDefinition) {} void visit(AstOperation &); void visit(AstConstant &); void visit(AstId &); void visit(AstFunction &); void visit(Ast &); private: const PolicyDefinition &policyDefinition; const static uint64_t maxNumberOfChildren = 2; //fields used to save results of a visit AstValueType resultType; //used for type checking, IDs are replaced with their real value AstOperationType parentType; //used to flip booleans with NOT parent uint64_t nodeCounter; bool flipMeaning; //used to eliminate NOTs by moving them into the relations };
37.288889
115
0.721692
SSICLOPS
cb0c4ae2df7edf3b76f081f073c4eef3bf23221e
1,349
hpp
C++
core/cs_basic_type.hpp
WukongGPU/WukongGPU
7810ecc1328b21230d448c6e64cc6fbd21f3b089
[ "Apache-2.0" ]
6
2017-11-13T02:08:50.000Z
2021-02-21T07:34:31.000Z
core/cs_basic_type.hpp
WukongGPU/WukongGPU
7810ecc1328b21230d448c6e64cc6fbd21f3b089
[ "Apache-2.0" ]
null
null
null
core/cs_basic_type.hpp
WukongGPU/WukongGPU
7810ecc1328b21230d448c6e64cc6fbd21f3b089
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2016 Shanghai Jiao Tong University. * 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. * */ #pragma once #include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> #include <vector> using namespace std; using namespace boost::archive; struct CS_Request { string type; bool use_file; string content; string cid; template <typename Archive> void serialize(Archive &ar, const unsigned int v) { ar &type; ar &use_file; ar &content; } }; struct CS_Reply { string type; string content; int column; vector<int64_t> column_table; vector<int> result_table; string cid; template <typename Archive> void serialize(Archive &ar, const unsigned int v) { ar &type; ar &content; ar &column; ar &column_table; ar &result_table; } };
22.114754
68
0.717569
WukongGPU
cb0cf435add0e49ac330ce3f4cba628c12e9f82f
11,131
cpp
C++
storage/row.cpp
Alchem-Lab/deneva
5201ef12fd8235fea7833709b8bffe45f53877eb
[ "Apache-2.0" ]
88
2017-01-19T03:15:24.000Z
2022-03-30T16:22:19.000Z
storage/row.cpp
Alchem-Lab/deneva
5201ef12fd8235fea7833709b8bffe45f53877eb
[ "Apache-2.0" ]
null
null
null
storage/row.cpp
Alchem-Lab/deneva
5201ef12fd8235fea7833709b8bffe45f53877eb
[ "Apache-2.0" ]
22
2017-01-20T10:22:31.000Z
2022-02-10T18:55:36.000Z
/* Copyright 2016 Massachusetts Institute of Technology 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 "global.h" #include "table.h" #include "catalog.h" #include "row.h" #include "txn.h" #include "row_lock.h" #include "row_ts.h" #include "row_mvcc.h" #include "row_occ.h" #include "row_maat.h" #include "mem_alloc.h" #include "manager.h" #define SIM_FULL_ROW true RC row_t::init(table_t * host_table, uint64_t part_id, uint64_t row_id) { part_info = true; _row_id = row_id; _part_id = part_id; this->table = host_table; Catalog * schema = host_table->get_schema(); tuple_size = schema->get_tuple_size(); #if SIM_FULL_ROW data = (char *) mem_allocator.alloc(sizeof(char) * tuple_size); #else data = (char *) mem_allocator.alloc(sizeof(uint64_t) * 1); #endif return RCOK; } RC row_t::switch_schema(table_t * host_table) { this->table = host_table; return RCOK; } void row_t::init_manager(row_t * row) { #if MODE==NOCC_MODE || MODE==QRY_ONLY_MODE return; #endif DEBUG_M("row_t::init_manager alloc \n"); #if CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE || CC_ALG == CALVIN manager = (Row_lock *) mem_allocator.align_alloc(sizeof(Row_lock)); #elif CC_ALG == TIMESTAMP manager = (Row_ts *) mem_allocator.align_alloc(sizeof(Row_ts)); #elif CC_ALG == MVCC manager = (Row_mvcc *) mem_allocator.align_alloc(sizeof(Row_mvcc)); #elif CC_ALG == OCC manager = (Row_occ *) mem_allocator.align_alloc(sizeof(Row_occ)); #elif CC_ALG == MAAT manager = (Row_maat *) mem_allocator.align_alloc(sizeof(Row_maat)); #endif #if CC_ALG != HSTORE && CC_ALG != HSTORE_SPEC manager->init(this); #endif } table_t * row_t::get_table() { return table; } Catalog * row_t::get_schema() { return get_table()->get_schema(); } const char * row_t::get_table_name() { return get_table()->get_table_name(); }; uint64_t row_t::get_tuple_size() { return get_schema()->get_tuple_size(); } uint64_t row_t::get_field_cnt() { return get_schema()->field_cnt; } void row_t::set_value(int id, void * ptr) { int datasize = get_schema()->get_field_size(id); int pos = get_schema()->get_field_index(id); DEBUG("set_value pos %d datasize %d -- %lx\n",pos,datasize,(uint64_t)this); #if SIM_FULL_ROW memcpy( &data[pos], ptr, datasize); #else char d[tuple_size]; memcpy( &d[pos], ptr, datasize); #endif } void row_t::set_value(int id, void * ptr, int size) { int pos = get_schema()->get_field_index(id); #if SIM_FULL_ROW memcpy( &data[pos], ptr, size); #else char d[tuple_size]; memcpy( &d[pos], ptr, size); #endif } void row_t::set_value(const char * col_name, void * ptr) { uint64_t id = get_schema()->get_field_id(col_name); set_value(id, ptr); } SET_VALUE(uint64_t); SET_VALUE(int64_t); SET_VALUE(double); SET_VALUE(UInt32); SET_VALUE(SInt32); GET_VALUE(uint64_t); GET_VALUE(int64_t); GET_VALUE(double); GET_VALUE(UInt32); GET_VALUE(SInt32); char * row_t::get_value(int id) { int pos __attribute__ ((unused)); pos = get_schema()->get_field_index(id); DEBUG("get_value pos %d -- %lx\n",pos,(uint64_t)this); #if SIM_FULL_ROW return &data[pos]; #else return data; #endif } char * row_t::get_value(char * col_name) { uint64_t pos __attribute__ ((unused)); pos = get_schema()->get_field_index(col_name); #if SIM_FULL_ROW return &data[pos]; #else return data; #endif } char * row_t::get_data() { return data; } void row_t::set_data(char * data) { int tuple_size = get_schema()->get_tuple_size(); #if SIM_FULL_ROW memcpy(this->data, data, tuple_size); #else char d[tuple_size]; memcpy(d, data, tuple_size); #endif } // copy from the src to this void row_t::copy(row_t * src) { assert(src->get_schema() == this->get_schema()); #if SIM_FULL_ROW set_data(src->get_data()); #else char d[tuple_size]; set_data(d); #endif } void row_t::free_row() { DEBUG_M("row_t::free_row free\n"); #if SIM_FULL mem_allocator.free(data, sizeof(char) * get_tuple_size()); #else mem_allocator.free(data, sizeof(uint64_t) * 1); #endif } RC row_t::get_lock(access_t type, TxnManager * txn) { RC rc = RCOK; #if CC_ALG == CALVIN lock_t lt = (type == RD || type == SCAN)? LOCK_SH : LOCK_EX; rc = this->manager->lock_get(lt, txn); #endif return rc; } RC row_t::get_row(access_t type, TxnManager * txn, row_t *& row) { RC rc = RCOK; #if MODE==NOCC_MODE || MODE==QRY_ONLY_MODE row = this; return rc; #endif #if ISOLATION_LEVEL == NOLOCK row = this; return rc; #endif /* #if ISOLATION_LEVEL == READ_UNCOMMITTED if(type == RD) { row = this; return rc; } #endif */ #if CC_ALG == MAAT DEBUG_M("row_t::get_row MAAT alloc \n"); txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t)); txn->cur_row->init(get_table(), get_part_id()); rc = this->manager->access(type,txn); txn->cur_row->copy(this); row = txn->cur_row; assert(rc == RCOK); goto end; #endif #if CC_ALG == WAIT_DIE || CC_ALG == NO_WAIT //uint64_t thd_id = txn->get_thd_id(); lock_t lt = (type == RD || type == SCAN)? LOCK_SH : LOCK_EX; rc = this->manager->lock_get(lt, txn); if (rc == RCOK) { row = this; } else if (rc == Abort) {} else if (rc == WAIT) { ASSERT(CC_ALG == WAIT_DIE); } goto end; #elif CC_ALG == TIMESTAMP || CC_ALG == MVCC //uint64_t thd_id = txn->get_thd_id(); // For TIMESTAMP RD, a new copy of the row will be returned. // for MVCC RD, the version will be returned instead of a copy // So for MVCC RD-WR, the version should be explicitly copied. // row_t * newr = NULL; #if CC_ALG == TIMESTAMP // TIMESTAMP makes a whole copy of the row before reading DEBUG_M("row_t::get_row TIMESTAMP alloc \n"); txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t)); txn->cur_row->init(get_table(), this->get_part_id()); #endif if (type == WR) { rc = this->manager->access(txn, P_REQ, NULL); if (rc != RCOK) goto end; } if ((type == WR && rc == RCOK) || type == RD || type == SCAN) { rc = this->manager->access(txn, R_REQ, NULL); if (rc == RCOK ) { row = txn->cur_row; } else if (rc == WAIT) { rc = WAIT; goto end; } else if (rc == Abort) { } if (rc != Abort) { assert(row->get_data() != NULL); assert(row->get_table() != NULL); assert(row->get_schema() == this->get_schema()); assert(row->get_table_name() != NULL); } } if (rc != Abort && CC_ALG == MVCC && type == WR) { DEBUG_M("row_t::get_row MVCC alloc \n"); row_t * newr = (row_t *) mem_allocator.alloc(sizeof(row_t)); newr->init(this->get_table(), get_part_id()); newr->copy(row); row = newr; } goto end; #elif CC_ALG == OCC // OCC always make a local copy regardless of read or write DEBUG_M("row_t::get_row OCC alloc \n"); txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t)); txn->cur_row->init(get_table(), get_part_id()); rc = this->manager->access(txn, R_REQ); row = txn->cur_row; goto end; #elif CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC || CC_ALG == CALVIN #if CC_ALG == HSTORE_SPEC if(txn_table.spec_mode) { DEBUG_M("row_t::get_row HSTORE_SPEC alloc \n"); txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t)); txn->cur_row->init(get_table(), get_part_id()); rc = this->manager->access(txn, R_REQ); row = txn->cur_row; goto end; } #endif row = this; goto end; #else assert(false); #endif end: return rc; } // Return call for get_row if waiting RC row_t::get_row_post_wait(access_t type, TxnManager * txn, row_t *& row) { RC rc = RCOK; assert(CC_ALG == WAIT_DIE || CC_ALG == MVCC || CC_ALG == TIMESTAMP); #if CC_ALG == WAIT_DIE assert(txn->lock_ready); rc = RCOK; //ts_t endtime = get_sys_clock(); row = this; #elif CC_ALG == MVCC || CC_ALG == TIMESTAMP assert(txn->ts_ready); //INC_STATS(thd_id, time_wait, t2 - t1); row = txn->cur_row; assert(row->get_data() != NULL); assert(row->get_table() != NULL); assert(row->get_schema() == this->get_schema()); assert(row->get_table_name() != NULL); if (CC_ALG == MVCC && type == WR) { DEBUG_M("row_t::get_row_post_wait MVCC alloc \n"); row_t * newr = (row_t *) mem_allocator.alloc(sizeof(row_t)); newr->init(this->get_table(), get_part_id()); newr->copy(row); row = newr; } #endif return rc; } // the "row" is the row read out in get_row(). For locking based CC_ALG, // the "row" is the same as "this". For timestamp based CC_ALG, the // "row" != "this", and the "row" must be freed. // For MVCC, the row will simply serve as a version. The version will be // delete during history cleanup. // For TIMESTAMP, the row will be explicity deleted at the end of access(). // (c.f. row_ts.cpp) void row_t::return_row(RC rc, access_t type, TxnManager * txn, row_t * row) { #if MODE==NOCC_MODE || MODE==QRY_ONLY_MODE return; #endif #if ISOLATION_LEVEL == NOLOCK return; #endif /* #if ISOLATION_LEVEL == READ_UNCOMMITTED if(type == RD) { return; } #endif */ #if CC_ALG == WAIT_DIE || CC_ALG == NO_WAIT || CC_ALG == CALVIN assert (row == NULL || row == this || type == XP); if (CC_ALG != CALVIN && ROLL_BACK && type == XP) {// recover from previous writes. should not happen w/ Calvin this->copy(row); } this->manager->lock_release(txn); #elif CC_ALG == TIMESTAMP || CC_ALG == MVCC // for RD or SCAN or XP, the row should be deleted. // because all WR should be companied by a RD // for MVCC RD, the row is not copied, so no need to free. if (CC_ALG == TIMESTAMP && (type == RD || type == SCAN)) { row->free_row(); DEBUG_M("row_t::return_row TIMESTAMP free \n"); mem_allocator.free(row, sizeof(row_t)); } if (type == XP) { row->free_row(); DEBUG_M("row_t::return_row XP free \n"); mem_allocator.free(row, sizeof(row_t)); this->manager->access(txn, XP_REQ, NULL); } else if (type == WR) { assert (type == WR && row != NULL); assert (row->get_schema() == this->get_schema()); RC rc = this->manager->access(txn, W_REQ, row); assert(rc == RCOK); } #elif CC_ALG == OCC assert (row != NULL); if (type == WR) manager->write( row, txn->get_end_timestamp() ); row->free_row(); DEBUG_M("row_t::return_row OCC free \n"); mem_allocator.free(row, sizeof(row_t)); manager->release(); return; #elif CC_ALG == MAAT assert (row != NULL); if (rc == Abort) { manager->abort(type,txn); } else { manager->commit(type,txn,row); } row->free_row(); DEBUG_M("row_t::return_row Maat free \n"); mem_allocator.free(row, sizeof(row_t)); #elif CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC assert (row != NULL); if (ROLL_BACK && type == XP) {// recover from previous writes. this->copy(row); } return; #else assert(false); #endif }
26.376777
111
0.660677
Alchem-Lab
cb0d492f8289909d70483f319fd2aca06f0184cb
233
hpp
C++
shared/Networking/MpNetworkingEvents.hpp
EnderdracheLP/MultiplayerCore.Quest
fd680fe8eb4dffdd3459059b9058002c3ed24749
[ "MIT" ]
null
null
null
shared/Networking/MpNetworkingEvents.hpp
EnderdracheLP/MultiplayerCore.Quest
fd680fe8eb4dffdd3459059b9058002c3ed24749
[ "MIT" ]
null
null
null
shared/Networking/MpNetworkingEvents.hpp
EnderdracheLP/MultiplayerCore.Quest
fd680fe8eb4dffdd3459059b9058002c3ed24749
[ "MIT" ]
1
2022-03-22T11:36:32.000Z
2022-03-22T11:36:32.000Z
#pragma once #include "../Utils/event.hpp" #include "MpPacketSerializer.hpp" namespace MultiplayerCore::Networking { struct MpNetworkingEvents { static event<Networking::MpPacketSerializer*> RegisterPackets; }; }
19.416667
70
0.729614
EnderdracheLP
cb0d6b53ddd6bc26007aaa873858d9771d92043e
2,069
cpp
C++
dbms/src/Common/isLocalAddress.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Common/isLocalAddress.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Common/isLocalAddress.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, Ltd. // // 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 <Common/isLocalAddress.h> #include <Core/Types.h> #include <Poco/Net/NetworkInterface.h> #include <Poco/Net/SocketAddress.h> #include <Poco/Util/Application.h> #include <cstring> namespace DB { bool isLocalAddress(const Poco::Net::SocketAddress & address) { static auto interfaces = Poco::Net::NetworkInterface::list(); return interfaces.end() != std::find_if(interfaces.begin(), interfaces.end(), [&](const Poco::Net::NetworkInterface & interface) { /** Compare the addresses without taking into account `scope`. * Theoretically, this may not be correct - depends on `route` setting * - through which interface we will actually access the specified address. */ return interface.address().length() == address.host().length() && 0 == memcmp(interface.address().addr(), address.host().addr(), address.host().length()); }); } bool isLocalAddress(const Poco::Net::SocketAddress & address, UInt16 clickhouse_port) { return clickhouse_port == address.port() && isLocalAddress(address); } size_t getHostNameDifference(const std::string & local_hostname, const std::string & host) { size_t hostname_difference = 0; for (size_t i = 0; i < std::min(local_hostname.length(), host.length()); ++i) if (local_hostname[i] != host[i]) ++hostname_difference; return hostname_difference; } } // namespace DB
36.946429
134
0.676655
solotzg
cb0f84695272e739b9209148257672a5b7928f1b
2,115
cpp
C++
src/tensorrt/tests/tests_queue.cpp
LaudateCorpus1/dlcookbook-dlbs
998a44940eb80f534ed682f8ef010e35df6b89a2
[ "Apache-2.0" ]
123
2017-11-28T20:21:24.000Z
2022-03-22T11:21:04.000Z
src/tensorrt/tests/tests_queue.cpp
LaudateCorpus1/dlcookbook-dlbs
998a44940eb80f534ed682f8ef010e35df6b89a2
[ "Apache-2.0" ]
17
2018-01-05T00:05:13.000Z
2020-09-18T05:12:45.000Z
src/tensorrt/tests/tests_queue.cpp
LaudateCorpus1/dlcookbook-dlbs
998a44940eb80f534ed682f8ef010e35df6b89a2
[ "Apache-2.0" ]
48
2018-01-04T20:52:51.000Z
2022-03-06T00:47:17.000Z
#include "core/queues.hpp" #include <chrono> #include <thread> #include <iostream> void client(abstract_queue<int>* queue, long& counter, bool is_provider, int sleep_milliseconds=100); void test_queue(abstract_queue<int>*q, const int num_providers, const size_t num_consumers); int main(int /*argc*/, char** /*argv*/) { std::cout << "Running Infinite Queue" << std::endl; infinite_queue<int> iq(1); test_queue(&iq, 10, 20); std::cout << "Running Thread Safe Queue" << std::endl; thread_safe_queue<int> tsq; test_queue(&tsq, 10, 20); return 0; } void client(abstract_queue<int>* queue, long& counter, bool is_provider, int sleep_milliseconds) { try { while (true) { if (is_provider) { queue->push(1); } else { queue->pop(); } counter ++; std::this_thread::sleep_for(std::chrono::milliseconds(sleep_milliseconds)); } } catch(queue_closed const&) { } } void test_queue(abstract_queue<int>*q, const int num_providers, const size_t num_consumers) { std::vector<std::thread*> providers(num_providers, nullptr), consumers(num_consumers, nullptr); std::vector<long> provider_data(num_providers, 0), consumer_data(num_consumers, 0); for (size_t i=0; i<num_consumers; ++i) consumers[i] = new std::thread(client, std::ref(q), std::ref(consumer_data[i]), false, 100); for (int i=0; i<num_providers; ++i) providers[i] = new std::thread(client, std::ref(q), std::ref(provider_data[i]), true, 120); std::this_thread::sleep_for(std::chrono::milliseconds(3000)); q->close(); for (size_t i=0; i<num_consumers; ++i) { consumers[i] ->join(); delete consumers[i]; std::cout << "Consumer " << i << " updated its counter " << consumer_data[i] << " times." << std::endl; } for (int i=0; i<num_providers; ++i) { providers[i] ->join(); delete providers[i]; std::cout << "Provider " << i << " updated its counter " << provider_data[i] << " times." << std::endl; } }
35.25
111
0.608511
LaudateCorpus1
cb0fa89cbbde76c03257ca2722f09e63f855779a
2,309
cpp
C++
test/cnd_test/cnd_test.cpp
BoostGSoC18/Advanced-Intrusive
30c465125c460e4bc2a9583ce00f0f706ed23e5a
[ "BSL-1.0" ]
3
2018-08-30T18:14:40.000Z
2019-02-22T17:12:44.000Z
test/cnd_test/cnd_test.cpp
BoostGSoC18/Advanced-Intrusive
30c465125c460e4bc2a9583ce00f0f706ed23e5a
[ "BSL-1.0" ]
4
2018-05-31T10:01:25.000Z
2018-07-26T15:14:26.000Z
test/cnd_test/cnd_test.cpp
BoostGSoC18/Advanced-Intrusive
30c465125c460e4bc2a9583ce00f0f706ed23e5a
[ "BSL-1.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #include <iostream> // for std::cout #include <utility> // for std::pair #include <algorithm> // for std::for_each #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/adjacency_matrix.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> using namespace boost; #include "boost/graph/CND/cnd_function.hpp" template<typename Graph> void treesize_vertices(int cur,Graph &graph,bool visited[],int subtree_size[]) { visited[cur] = true; subtree_size[cur] = 1; typedef typename graph_traits<Graph>::adjacency_iterator adj_itr; adj_itr ai,ai_end; for (boost::tie(ai, ai_end) = adjacent_vertices(cur,graph);ai != ai_end; ++ai) { if (!visited[*ai]) { treesize_vertices(*ai,graph,visited,subtree_size); subtree_size[cur]+=subtree_size[*ai]; } } } template<typename Graph> void check_centroid(int cur,Graph &graph,bool visited[],int subtree_size[],int *check) { visited[cur] = true; typedef typename graph_traits<Graph>::adjacency_iterator adj_itr; adj_itr ai,ai_end; for (boost::tie(ai, ai_end) = adjacent_vertices(cur,graph);ai != ai_end; ++ai) { if (!visited[*ai]) { if(subtree_size[*ai]>(subtree_size[cur]/2)) { *check=0; } check_centroid(*ai,graph,visited,subtree_size,check); } } } int main() { int i,n,a,b; scanf("%d",&n); typedef adjacency_list<vecS, vecS, undirectedS> Graph_list; Graph_list graph_list(n); for(i=1;i<n;i++) { scanf("%d %d",&a,&b); add_edge(a,b,graph_list); } pair<Graph_list,int> copy_graph; copy_graph=CND(graph_list,0,n); int root=copy_graph.second; bool visited[1030]; int subtree_size[1030]; for(i=0;i<n;i++) { visited[i]=false; subtree_size[i]=0; } treesize_vertices<Graph_list>(root,copy_graph.first,visited,subtree_size); int check=1; for(i=0;i<n;i++) visited[i]=false; check_centroid<Graph_list>(root,copy_graph.first,visited,subtree_size,&check); if(check) { printf("Success\n"); } return 0; }
28.158537
86
0.614985
BoostGSoC18
cb10bff7cd7288620ab0b1e9f1f7d1e19cfde9ad
381
cpp
C++
C++/C++ I/Lab1/a1p2.cpp
Devang-25/CS-Jacobs
d56a70c13ce3863bcf3140990fab5b634b30a2af
[ "MIT" ]
null
null
null
C++/C++ I/Lab1/a1p2.cpp
Devang-25/CS-Jacobs
d56a70c13ce3863bcf3140990fab5b634b30a2af
[ "MIT" ]
null
null
null
C++/C++ I/Lab1/a1p2.cpp
Devang-25/CS-Jacobs
d56a70c13ce3863bcf3140990fab5b634b30a2af
[ "MIT" ]
null
null
null
/* CH08-320142 Problem 1.2.cpp Digdarshan Kunwar d.kunwar@jacobs-university.de */ #include <iostream> #include <string> using namespace std; int main (int argc, char** argv){ int nr; float val; string s; cin >> nr; cin >> val; cin.get(); getline(cin,s); for (int i=0;i<nr;i++){ cout<< val <<" "<< s<<endl; } return 0; }
13.607143
35
0.548556
Devang-25
cb12fa9353b628206ec24432662579cd5bec6fd5
7,232
cpp
C++
src/core/cpp/scene/SceneUtility.cpp
NeroGames/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
26
2020-09-02T18:14:36.000Z
2022-02-08T18:28:36.000Z
src/core/cpp/scene/SceneUtility.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
14
2020-08-30T01:37:04.000Z
2021-07-19T20:47:29.000Z
src/core/cpp/scene/SceneUtility.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
6
2020-09-02T18:14:57.000Z
2021-12-31T00:32:09.000Z
//////////////////////////////////////////////////////////// // Nero Game Engine // Copyright (c) 2016-2020 Sanou A. K. Landry //////////////////////////////////////////////////////////// ///////////////////////////HEADERS////////////////////////// //NERO #include <Nero/core/cpp/scene/SceneUtility.h> //////////////////////////////////////////////////////////// namespace nero { //////////////////////////////////////////////////////////// //QueryCallback QueryCallback::QueryCallback(const b2Vec2& point) { m_Point = point; m_Fixture = nullptr; } bool QueryCallback::ReportFixture(b2Fixture* fixture) { b2Body* body = fixture->GetBody(); if (body->GetType() == b2_dynamicBody) { bool inside = fixture->TestPoint(m_Point); if (inside) { m_Fixture = fixture; //Clean pointer body = nullptr; //We are done, terminate the query. return false; } } //Clean pointer body = nullptr; //Continue the query. return true; } QueryCallback::~QueryCallback() { m_Fixture = nullptr; } //////////////////////////////////////////////////////////// //SceneSetting SceneSetting::SceneSetting() { hz = 40.0f; viewCenter.Set(0.0f, 0.0f); gravity.Set(0.f, 10.f); velocityIterations = 8; positionIterations = 3; drawAxis = true; drawGrid = true; drawShapes = true; drawJoints = true; drawAABBs = false; drawContactPoints = false; drawContactNormals = false; drawContactImpulse = false; drawFrictionImpulse = false; drawCOMs = false; drawStats = false; drawProfile = false; enableWarmStarting = true; enableContinuous = true; enableSubStepping = false; enableSleep = true; pause = false; singleStep = false; } nlohmann::json SceneSetting::toJson() { nlohmann::json scene_setting; scene_setting["frequency"] = hz; scene_setting["view_center"] = graphics::vectorToJson<b2Vec2>(viewCenter); scene_setting["gravity"] = graphics::vectorToJson<b2Vec2>(gravity); scene_setting["velocity_iterations"] = velocityIterations; scene_setting["position_iterations"] = positionIterations; scene_setting["enable_warm_starting"] = enableWarmStarting; scene_setting["enable_continuous"] = enableContinuous; scene_setting["enable_sub_stepping"] = enableSubStepping; scene_setting["enable_sleep"] = enableSleep; scene_setting["draw_axis"] = drawAxis; scene_setting["draw_grid"] = drawGrid; scene_setting["draw_shapes"] = drawShapes; scene_setting["draw_joints"] = drawJoints; scene_setting["draw_aabbs"] = drawAABBs; scene_setting["draw_contact_points"] = drawContactPoints; scene_setting["draw_contact_normals"] = drawContactNormals; scene_setting["draw_contact_impulse"] = drawContactImpulse; scene_setting["draw_coms"] = drawCOMs; scene_setting["draw_stats"] = drawStats; scene_setting["draw_profile"] = drawProfile; return scene_setting; } SceneSetting SceneSetting::fromJson(nlohmann::json setting) { SceneSetting scene_setting; scene_setting.hz = setting["frequency"]; scene_setting.gravity = graphics::vectorFromJson<b2Vec2>(setting["gravity"]); scene_setting.viewCenter = graphics::vectorFromJson<b2Vec2>(setting["view_center"]); scene_setting.velocityIterations = setting["velocity_iterations"]; scene_setting.positionIterations = setting["position_iterations"]; scene_setting.enableWarmStarting = setting["enable_warm_starting"]; scene_setting.enableContinuous = setting["enable_continuous"]; scene_setting.enableSubStepping = setting["enable_sub_stepping"]; scene_setting.enableSleep = setting["enable_sleep"]; scene_setting.drawAxis = setting["draw_axis"]; scene_setting.drawGrid = setting["draw_grid"]; scene_setting.drawShapes = setting["draw_shapes"]; scene_setting.drawJoints = setting["draw_joints"]; scene_setting.drawAABBs = setting["draw_aabbs"]; scene_setting.drawContactPoints = setting["draw_contact_points"]; scene_setting.drawContactNormals = setting["draw_contact_normals"]; scene_setting.drawContactImpulse = setting["draw_contact_impulse"]; scene_setting.drawCOMs = setting["draw_coms"]; scene_setting.drawStats = setting["draw_stats"]; scene_setting.drawProfile = setting["draw_profile"]; return scene_setting; } //////////////////////////////////////////////////////////// //CameraSetting CameraSetting::CameraSetting() { defaultPosition.x = 0.f; defaultPosition.y = 0.f; defaultRotation = 0.f; defaultZoom = 0.f; position.x = 0.f; position.y = 0.f; rotation = 0.f; zoom = 0.f; }; nlohmann::json CameraSetting::toJson() { nlohmann::json camera_setting; camera_setting["default_position"] = {{"x", defaultPosition.x}, {"y", defaultPosition.y}}; camera_setting["default_rotation"] = defaultRotation; camera_setting["default_zoom"] = defaultZoom; camera_setting["position"] = {{"x", position.x}, {"y", position.y}}; camera_setting["rotation"] = rotation; camera_setting["zoom"] = zoom; return camera_setting; } CameraSetting CameraSetting::fromJson(nlohmann::json setting) { CameraSetting camera_setting; camera_setting.defaultPosition.x = setting["default_position"]["x"]; camera_setting.defaultPosition.y = setting["default_position"]["y"]; camera_setting.defaultRotation = setting["default_rotation"]; camera_setting.defaultZoom = setting["default_zoom"]; camera_setting.position.x = setting["position"]["x"]; camera_setting.position.y = setting["position"]["y"]; camera_setting.rotation = setting["rotation"]; camera_setting.zoom = setting["zoom"]; return camera_setting; } //////////////////////////////////////////////////////////// //Target CameraTarget::CameraTarget() { target = nullptr; offsetLeft = 150.f; offsetRight = 0.f; offsetUp = 250.f; offsetDown = 0.f; followTarget = false; } }
35.106796
98
0.53927
NeroGames
cb157db0e143daed8d54a448b303518d838da3a2
16,835
cpp
C++
libogre/src/input/SDLInputDevice.cpp
sirikata/sirikata
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
[ "BSD-3-Clause" ]
31
2015-01-28T17:01:10.000Z
2021-11-04T08:30:37.000Z
libogre/src/input/SDLInputDevice.cpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
libogre/src/input/SDLInputDevice.cpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
9
2015-08-02T18:39:49.000Z
2019-10-11T10:32:30.000Z
/* Sirikata Input Plugin -- plugins/input * SDLInputDevice.cpp * * Copyright (c) 2009, Patrick Reiter Horn * 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 Sirikata 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 <sirikata/core/util/Standard.hh> #include <sirikata/ogre/input/SDLInputManager.hpp> #include <sirikata/ogre/input/SDLInputDevice.hpp> #include <sirikata/ogre/input/InputEvents.hpp> #include <SDL.h> #include <SDL_video.h> #include <SDL_syswm.h> #include <SDL_events.h> #include <SDL_mouse.h> #include <boost/lexical_cast.hpp> #include <SDL_keysym.h> namespace Sirikata { namespace Input { // HACK: Constant to convert uncalibrated axes to floating point. // We need a way to set calibration values for each axis. SDLMouse::SDLMouse(SDLInputManager *manager, unsigned int which) : mWhich(which) { unsigned int wid,hei; manager->getWindowSize(wid,hei); float maxsize = sqrt((float)(wid*wid+hei*hei)); float drag_deadband (manager->dragDeadBand()); setDragDeadband(2*drag_deadband/maxsize); setName(SDL_GetMouseName(which)); // SDL has no API to query the number of buttons. The exact value doesn't matter. mNumButtons = 5; // left, middle, right, Back, Forward } SDLMouse::~SDLMouse() { } SDLInputManager* SDLMouse::inputManager() { return static_cast<SDLInputManager*>(mManager); } int SDLMouse::getNumButtons() const { return mNumButtons; } std::string SDLMouse::getButtonName(unsigned int button) const { switch (button) { case SDL_BUTTON_LEFT: return "Left Button"; case SDL_BUTTON_MIDDLE: return "Middle Button"; case SDL_BUTTON_RIGHT: return "Right Button"; } { std::ostringstream os; os << "Button " << button; return os.str(); } } void SDLMouse::setRelativeMode(bool enabled) { int oldmouse = SDL_SelectMouse(mWhich); SDL_ShowCursor(enabled? 1 : 0); SDL_SetRelativeMouseMode(mWhich, enabled ? SDL_TRUE : SDL_FALSE); /*#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC CGAssociateMouseAndMouseCursorPosition(!enabled); #endif*/ SDL_SelectMouse(oldmouse); } void SDLMouse::fireMotion(const SDLMousePtr &thisptr, const struct SDL_MouseMotionEvent &event) { unsigned int screenwid, screenhei; inputManager()->getWindowSize(screenwid, screenhei); AxisValue xPctFromCenter = AxisValue::from01(event.x / float(screenwid)); AxisValue yPctFromCenter = AxisValue::from01(1-(event.y / float(screenhei))); bool changedx = (getAxis(AXIS_CURSORX) != xPctFromCenter); bool changedy = (getAxis(AXIS_CURSORY) != yPctFromCenter); if (mRelativeMode) { // negate y axis since coordinates start at bottom-left. float to_axis(inputManager()->relativeMouseToAxis()); fireAxis(thisptr, AXIS_RELX, AxisValue::fromCentered(to_axis*event.xrel)); fireAxis(thisptr, AXIS_RELY, AxisValue::fromCentered(-to_axis*event.yrel)); // drag events still get fired... firePointerMotion(thisptr, event.xrel/float(screenwid), -event.yrel/float(screenhei), event.cursor, event.pressure, event.pressure_min, event.pressure_max); } else { fireAxis(thisptr, AXIS_CURSORX, xPctFromCenter); fireAxis(thisptr, AXIS_CURSORY, yPctFromCenter); if (changedx || changedy) { firePointerMotion(thisptr, xPctFromCenter.getCentered(), yPctFromCenter.getCentered(), event.cursor, event.pressure, event.pressure_min, event.pressure_max); } } if (event.pressure_max) { fireAxis(thisptr, PRESSURE, AxisValue::fromCentered((float)event.pressure / (float)event.pressure_max)); } // "For future use" //fireAxis(CURSORZ, event.z); //fireAxis(TILT, event.pressure); //fireAxis(ROTATION, event.pressure); } void SDLMouse::fireWheel(const SDLMousePtr &thisptr, int xrel, int yrel) { float to_axis (inputManager()->wheelToAxis()); SILOG(input,detailed,"WHEEL: " << xrel << "; " << yrel); fireAxis(thisptr, WHEELX, AxisValue::fromCentered(to_axis*xrel)); fireAxis(thisptr, WHEELY, AxisValue::fromCentered(to_axis*yrel)); } SDLJoystick::SDLJoystick(unsigned int whichDevice) : mWhich(whichDevice) { this->mJoy = SDL_JoystickOpen(whichDevice); if (mJoy == NULL) { // analog joystick? mNumBalls = 0; mNumButtons = 4; mNumHats = 0; mNumGeneralAxes = 4; SILOG(input,error,"Unable to open joystick " << whichDevice << "!"); } else { mNumGeneralAxes = SDL_JoystickNumAxes(mJoy); mNumBalls = SDL_JoystickNumBalls(mJoy); mNumButtons = SDL_JoystickNumButtons(mJoy); mNumHats = SDL_JoystickNumHats(mJoy); mButtonNames.resize(mNumButtons); } } SDLJoystick::~SDLJoystick() { if (mJoy) { SDL_JoystickClose(mJoy); } } SDLInputManager* SDLJoystick::inputManager() { return static_cast<SDLInputManager*>(mManager); } int SDLJoystick::getNumButtons() const { return mNumButtons + HAT_MAX*mNumHats; } unsigned int SDLJoystick::getNumAxes() const { return mNumGeneralAxes + 2*mNumBalls; } std::string SDLJoystick::getAxisName(unsigned int axis) const { if (axis == 0) { return "X"; } else if (axis == 1) { return "Y"; } else if (axis > mNumGeneralAxes) { unsigned int ballaxis = axis - mNumGeneralAxes; unsigned int ballnum = ballaxis/2; const char *axisname = ((ballnum%2) == 0) ? " X" : " Y"; std::ostringstream os; os << "Trackball " << ballnum << axisname; return os.str(); } else { std::ostringstream os; os << "Axis " << axis; return os.str(); } } void SDLJoystick::fireHat(const SDLJoystickPtr &thisptr, unsigned int num, int val) { this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_UP, !!(val & SDL_HAT_UP)); this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_RIGHT, !!(val & SDL_HAT_RIGHT)); this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_DOWN, !!(val & SDL_HAT_DOWN)); this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_LEFT, !!(val & SDL_HAT_LEFT)); } void SDLJoystick::fireBall(const SDLJoystickPtr &thisptr, unsigned int ballNumber, int xrel, int yrel) { float to_axis (inputManager()->joyBallToAxis()); fireAxis(thisptr, mNumGeneralAxes + 2*ballNumber, AxisValue::fromCentered(to_axis*xrel)); fireAxis(thisptr, mNumGeneralAxes + 2*ballNumber + 1, AxisValue::fromCentered(to_axis*yrel)); } std::string SDLJoystick::getButtonName(unsigned int button) const { if (button < mButtonNames.size()) { if (!mButtonNames[button].empty()) { return mButtonNames[button]; } } std::ostringstream os; if (button >= mNumButtons) { int hatbutton = button - mNumButtons; os << "Digital Hat " << (hatbutton/HAT_MAX) << " "; int direction = hatbutton%HAT_MAX; switch (hatbutton) { case HAT_UP: os << "Up"; break; case HAT_DOWN: os << "Up"; break; case HAT_LEFT: os << "Left"; break; case HAT_RIGHT: os << "Right"; break; } return os.str(); } else { os << "Button " << button; return os.str(); } } void SDLJoystick::setButtonName(unsigned int button, std::string name) { if (button < mButtonNames.size()) { mButtonNames[button] = name; } } SDLKeyboard::SDLKeyboard(unsigned int which) : mWhich(which) { if (which == 0) { setName("Primary Keyboard"); } else { std::ostringstream os; os << "Keyboard " << which; setName(os.str()); } } SDLKeyboard::~SDLKeyboard() { } SDLInputManager* SDLKeyboard::inputManager() { return static_cast<SDLInputManager*>(mManager); } std::string SDLKeyboard::getButtonName(unsigned int button) const { const char *keyname = SDL_GetScancodeName((SDL_scancode)button); if (keyname) { return keyname; } else { std::ostringstream ostr; ostr << '#' << button; return ostr.str(); } } static std::map<Input::KeyButton, String> ScancodesToStrings; static std::map<String, Input::KeyButton> StringsToScancodes; static void init_button_conversion_maps(); void ensure_initialized() { static bool initialized = false; if (!initialized) { initialized = true; init_button_conversion_maps(); } } #define INIT_SCANCODE_STRING_MAP(X, STR) \ ScancodesToStrings[SDL_SCANCODE_##X] = #STR; \ StringsToScancodes[#STR] = SDL_SCANCODE_##X static void init_button_conversion_maps() { INIT_SCANCODE_STRING_MAP(A, a); INIT_SCANCODE_STRING_MAP(B, b); INIT_SCANCODE_STRING_MAP(C, c); INIT_SCANCODE_STRING_MAP(D, d); INIT_SCANCODE_STRING_MAP(E, e); INIT_SCANCODE_STRING_MAP(F, f); INIT_SCANCODE_STRING_MAP(G, g); INIT_SCANCODE_STRING_MAP(H, h); INIT_SCANCODE_STRING_MAP(I, i); INIT_SCANCODE_STRING_MAP(J, j); INIT_SCANCODE_STRING_MAP(K, k); INIT_SCANCODE_STRING_MAP(L, l); INIT_SCANCODE_STRING_MAP(M, m); INIT_SCANCODE_STRING_MAP(N, n); INIT_SCANCODE_STRING_MAP(O, o); INIT_SCANCODE_STRING_MAP(P, p); INIT_SCANCODE_STRING_MAP(Q, q); INIT_SCANCODE_STRING_MAP(R, r); INIT_SCANCODE_STRING_MAP(S, s); INIT_SCANCODE_STRING_MAP(T, t); INIT_SCANCODE_STRING_MAP(U, u); INIT_SCANCODE_STRING_MAP(V, v); INIT_SCANCODE_STRING_MAP(W, w); INIT_SCANCODE_STRING_MAP(X, X); INIT_SCANCODE_STRING_MAP(Y, y); INIT_SCANCODE_STRING_MAP(Z, z); INIT_SCANCODE_STRING_MAP(0, 0); INIT_SCANCODE_STRING_MAP(1, 1); INIT_SCANCODE_STRING_MAP(2, 2); INIT_SCANCODE_STRING_MAP(3, 3); INIT_SCANCODE_STRING_MAP(4, 4); INIT_SCANCODE_STRING_MAP(5, 5); INIT_SCANCODE_STRING_MAP(6, 6); INIT_SCANCODE_STRING_MAP(7, 7); INIT_SCANCODE_STRING_MAP(8, 8); INIT_SCANCODE_STRING_MAP(9, 9); INIT_SCANCODE_STRING_MAP(LSHIFT, lshift); INIT_SCANCODE_STRING_MAP(RSHIFT, rshift); INIT_SCANCODE_STRING_MAP(LCTRL, lctrl); INIT_SCANCODE_STRING_MAP(RCTRL, rctrl); INIT_SCANCODE_STRING_MAP(LALT, lalt); INIT_SCANCODE_STRING_MAP(RALT, ralt); INIT_SCANCODE_STRING_MAP(LGUI, lsuper); INIT_SCANCODE_STRING_MAP(RGUI, rsuper); INIT_SCANCODE_STRING_MAP(RETURN, return); INIT_SCANCODE_STRING_MAP(ESCAPE, escape); INIT_SCANCODE_STRING_MAP(BACKSPACE, back); INIT_SCANCODE_STRING_MAP(TAB, tab); INIT_SCANCODE_STRING_MAP(SPACE, space); INIT_SCANCODE_STRING_MAP(MINUS, minus); INIT_SCANCODE_STRING_MAP(EQUALS, equals); INIT_SCANCODE_STRING_MAP(LEFTBRACKET, [); INIT_SCANCODE_STRING_MAP(RIGHTBRACKET, ]); INIT_SCANCODE_STRING_MAP(BACKSLASH, backslash); INIT_SCANCODE_STRING_MAP(SEMICOLON, semicolon); INIT_SCANCODE_STRING_MAP(APOSTROPHE, apostrophe); INIT_SCANCODE_STRING_MAP(GRAVE, OEM_3); INIT_SCANCODE_STRING_MAP(COMMA, comma); INIT_SCANCODE_STRING_MAP(PERIOD, period); INIT_SCANCODE_STRING_MAP(SLASH, OEM_2); INIT_SCANCODE_STRING_MAP(CAPSLOCK, CAPITAL); INIT_SCANCODE_STRING_MAP(F1, F1); INIT_SCANCODE_STRING_MAP(F2, F2); INIT_SCANCODE_STRING_MAP(F3, F3); INIT_SCANCODE_STRING_MAP(F4, F4); INIT_SCANCODE_STRING_MAP(F5, F5); INIT_SCANCODE_STRING_MAP(F6, F6); INIT_SCANCODE_STRING_MAP(F7, F7); INIT_SCANCODE_STRING_MAP(F8, F8); INIT_SCANCODE_STRING_MAP(F9, F9); INIT_SCANCODE_STRING_MAP(F10, F10); INIT_SCANCODE_STRING_MAP(F11, F11); INIT_SCANCODE_STRING_MAP(F12, F12); INIT_SCANCODE_STRING_MAP(PRINTSCREEN, print); INIT_SCANCODE_STRING_MAP(SCROLLLOCK, scroll); INIT_SCANCODE_STRING_MAP(PAUSE, pause); INIT_SCANCODE_STRING_MAP(INSERT, insert); INIT_SCANCODE_STRING_MAP(HOME, home); INIT_SCANCODE_STRING_MAP(PAGEUP, pageup); INIT_SCANCODE_STRING_MAP(DELETE, delete); INIT_SCANCODE_STRING_MAP(END, end); INIT_SCANCODE_STRING_MAP(PAGEDOWN, pagedown); INIT_SCANCODE_STRING_MAP(RIGHT, right); INIT_SCANCODE_STRING_MAP(LEFT, left); INIT_SCANCODE_STRING_MAP(DOWN, down); INIT_SCANCODE_STRING_MAP(UP, up); INIT_SCANCODE_STRING_MAP(KP_0, insert); INIT_SCANCODE_STRING_MAP(KP_1, end); INIT_SCANCODE_STRING_MAP(KP_2, down); INIT_SCANCODE_STRING_MAP(KP_3, next); INIT_SCANCODE_STRING_MAP(KP_4, left); INIT_SCANCODE_STRING_MAP(KP_6, right); INIT_SCANCODE_STRING_MAP(KP_7, home); INIT_SCANCODE_STRING_MAP(KP_8, up); INIT_SCANCODE_STRING_MAP(KP_9, prior); } bool keyIsModifier(Input::KeyButton b) { return (b == SDL_SCANCODE_LSHIFT || b == SDL_SCANCODE_RSHIFT || b == SDL_SCANCODE_LCTRL || b == SDL_SCANCODE_RCTRL || b == SDL_SCANCODE_LALT || b == SDL_SCANCODE_RALT || b == SDL_SCANCODE_LGUI || b == SDL_SCANCODE_RGUI); } String keyButtonString(Input::KeyButton b) { ensure_initialized(); if (ScancodesToStrings.find(b) != ScancodesToStrings.end()) return ScancodesToStrings[b]; return ""; } String keyModifiersString(Input::Modifier m) { if (m == Input::MOD_NONE) return ""; String result; if (m & MOD_SHIFT) { result += "shift"; } if (m & MOD_CTRL) { if (!result.empty()) result += "-"; result += "ctrl"; } if (m & MOD_ALT) { if (!result.empty()) result += "-"; result += "alt"; } if (m & MOD_GUI) { if (!result.empty()) result += "-"; result += "super"; } return result; } String mouseButtonString(Input::MouseButton b) { return boost::lexical_cast<String>(b); } String axisString(Input::AxisIndex i) { return boost::lexical_cast<String>(i); } Input::KeyButton keyButtonFromStrings(std::vector<String>& parts) { ensure_initialized(); assert(!parts.empty()); const String& part = *parts.begin(); Input::KeyButton result = 0; if (StringsToScancodes.find(part) != StringsToScancodes.end()) { result = StringsToScancodes[part]; parts.erase(parts.begin()); } return result; } Input::Modifier keyModifiersFromStrings(std::vector<String>& parts) { bool more = true; Input::Modifier result = Input::MOD_NONE; while(more && !parts.empty()) { const String& val = *parts.begin(); if (val == "shift") result |= Input::MOD_SHIFT; else if (val == "ctrl") result |= Input::MOD_CTRL; else if (val == "alt") result |= Input::MOD_ALT; else if (val == "super") result |= Input::MOD_GUI; else more = false; if (more) // We got something, so we need to remove it parts.erase(parts.begin()); } return result; } Input::MouseButton mouseButtonFromStrings(std::vector<String>& parts) { assert(!parts.empty()); Input::MouseButton result = boost::lexical_cast<Input::MouseButton>(*parts.begin()); parts.erase( parts.begin() ); return result; } Input::AxisIndex axisFromStrings(std::vector<String>& parts) { assert(!parts.empty()); Input::AxisIndex result = boost::lexical_cast<Input::AxisIndex>(*parts.begin()); parts.erase( parts.begin() ); return result; } } }
35.442105
112
0.672943
sirikata
cb172d2b4c13214429f8cc96e65b3f5426edcad6
1,114
cc
C++
matlab_ext/img_video/w1.cc
zaqwes8811/coordinator-tasks
7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a
[ "MIT" ]
null
null
null
matlab_ext/img_video/w1.cc
zaqwes8811/coordinator-tasks
7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a
[ "MIT" ]
15
2015-03-07T12:46:41.000Z
2015-04-11T09:08:36.000Z
matlab_ext/img_video/w1.cc
zaqwes8811/micro-apps
7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a
[ "MIT" ]
null
null
null
#include <opencv/highgui.h> #include <opencv2/opencv.hpp> #include <iostream> #include <string> #include <sstream> using namespace cv; using namespace std; int main() { auto cap = VideoCapture( "../Documents/drop.avi" ); auto frame_counter = 0; // не всегда можно получить cout << "fps:" << cap.get( CV_CAP_PROP_FPS ) << endl; while( cap.isOpened( ) ){ Mat frame; auto success = cap.read( frame ); frame_counter += 1; // If the last frame is reached, reset the capture and the frame_counter if( frame_counter == cap.get( CV_CAP_PROP_FRAME_COUNT ) ){ frame_counter = 0; // Or whatever as long as it is the same as next line cap.set( CV_CAP_PROP_POS_FRAMES, 0 ); } Mat gray; cvtColor( frame, gray, COLOR_BGR2GRAY ); // proc Mat img = gray / 5; circle( img, {100, 150}, 10, 255 ); auto font = FONT_HERSHEY_SIMPLEX; stringstream s; s << frame_counter; string text = "marker:" + s.str(); putText( img, text, {5,200}, font, 0.4, (225),1 ); // play imshow( "frame", img ); if( waitKey(1) >= 0 ) break; } cap.release(); destroyAllWindows(); return 0; }
21.018868
76
0.64632
zaqwes8811
cb174c43dbb3556a123d9d3311e26c54683f224d
538
cpp
C++
Problems/PTA/B1008.cpp
five-5/code
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
[ "Apache-2.0" ]
null
null
null
Problems/PTA/B1008.cpp
five-5/code
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
[ "Apache-2.0" ]
null
null
null
Problems/PTA/B1008.cpp
five-5/code
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
[ "Apache-2.0" ]
null
null
null
#include <iostream> #define maxn 101 int main() { int n, m; int a[maxn]; std::cin >> n >> m; for (int i = 0; i < n; ++i) { std::cin >> a[i]; } m = m % n; if (m == 0) { std::cout << a[0]; for (int i = 1; i < n; ++i) { std::cout << " " << a[i]; } } else { int start = n - m; std::cout << a[start]; for (int i = 1; i < n; ++i) { std::cout << " " << a[(start+i)%n]; } } std::cout << std::endl; return 0; }
19.925926
47
0.343866
five-5
cb17624b674cd3b73a7170b9b5c6b93c77314bf7
432
cpp
C++
ImportantExample/QFindEditDemo/mainwindow.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/QFindEditDemo/mainwindow.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/QFindEditDemo/mainwindow.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
#include "mainwindow.h" #include "qfindedit.h" #include "ui_mainwindow.h" #include <QHBoxLayout> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QFindEdit* edit = new QFindEdit(this); QHBoxLayout *pLayout = new QHBoxLayout(this); pLayout->addWidget(edit); centralWidget()->setLayout(pLayout); } MainWindow::~MainWindow() { delete ui; }
18
49
0.685185
xiaohaijin
0e13c8f5f5d05df5adb873197839765dc4714dad
513
cpp
C++
unittests/NAPI/test_number.cpp
ScriptBox99/microsoft-hermes-windows
c7eb49152bcb5fa6812c3413a80ffc5bb937bb0c
[ "MIT" ]
null
null
null
unittests/NAPI/test_number.cpp
ScriptBox99/microsoft-hermes-windows
c7eb49152bcb5fa6812c3413a80ffc5bb937bb0c
[ "MIT" ]
null
null
null
unittests/NAPI/test_number.cpp
ScriptBox99/microsoft-hermes-windows
c7eb49152bcb5fa6812c3413a80ffc5bb937bb0c
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "napitest.h" #define Init test_number_init #include "js-native-api/test_number/test_number.c" using namespace napitest; TEST_P(NapiTest, test_number) { ExecuteNapi([](NapiTestContext *testContext, napi_env env) { testContext->AddNativeModule( "./build/x86/test_number", [](napi_env env, napi_value exports) { return Init(env, exports); }); testContext->RunTestScript("test_number/test.js"); }); }
27
77
0.717349
ScriptBox99
0e157a9783dc97f2a93951437eef491917042999
540
cpp
C++
Array/Sorting/Insertion Sort/Solution_By_Shourya.cpp
surajshah123/Fork_CPP
c85ec3464382db298f2dbac443f3379dd1c1f4a6
[ "MIT" ]
8
2021-02-14T13:13:27.000Z
2022-01-08T23:58:32.000Z
Array/Sorting/Insertion Sort/Solution_By_Shourya.cpp
surajshah123/Fork_CPP
c85ec3464382db298f2dbac443f3379dd1c1f4a6
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
Array/Sorting/Insertion Sort/Solution_By_Shourya.cpp
surajshah123/Fork_CPP
c85ec3464382db298f2dbac443f3379dd1c1f4a6
[ "MIT" ]
15
2021-03-01T03:54:29.000Z
2021-10-19T18:29:00.000Z
#include <iostream> using namespace std; void insert_sort(int a[], int n){ int temp, k; for (int i = 1; i < n; i++){ k = i; temp = a[k]; for (int j = i - 1; j >= 0; j--){ if (a[j] > temp){ a[k] = a[j]; k--; } } a[k] = temp; } for (int i = 0; i < n; i++){ cout << a[i] << " "; } } int main(){ int n; cin >> n; int a[n]; for (int i = 0; i < n; i++){ cin >> a[i]; } insert_sort(a, n); }
18.62069
41
0.331481
surajshah123
0e15d56105e78a9c42e1d2214c2c580d4caa32ed
53
hpp
C++
src/boost_spirit_home_karma_action_action.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_spirit_home_karma_action_action.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_spirit_home_karma_action_action.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/spirit/home/karma/action/action.hpp>
26.5
52
0.792453
miathedev
0e167340937c0ec900368346616cf65d0432ba4d
315
cpp
C++
src/body.cpp
awinabi/capybara-webkit-0.13.0
84e70bad13e9c137bdf77a2af61bbb7ab7f30a77
[ "MIT" ]
null
null
null
src/body.cpp
awinabi/capybara-webkit-0.13.0
84e70bad13e9c137bdf77a2af61bbb7ab7f30a77
[ "MIT" ]
null
null
null
src/body.cpp
awinabi/capybara-webkit-0.13.0
84e70bad13e9c137bdf77a2af61bbb7ab7f30a77
[ "MIT" ]
null
null
null
#include "Body.h" #include "WebPage.h" #include "WebPageManager.h" Body::Body(WebPageManager *manager, QStringList &arguments, QObject *parent) : SocketCommand(manager, arguments, parent) { } void Body::start() { QString result = page()->currentFrame()->toHtml(); emit finished(new Response(true, result)); }
26.25
122
0.720635
awinabi
0e1a4cee3184b6515c1a98316ffe3ed78f83a706
653
cpp
C++
Voltron/Source/UnitTests/DeskCalculator/Token_tests.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
1
2018-02-09T19:44:51.000Z
2018-02-09T19:44:51.000Z
Voltron/Source/UnitTests/DeskCalculator/Token_tests.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
Voltron/Source/UnitTests/DeskCalculator/Token_tests.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // \file Token_tests.cpp //------------------------------------------------------------------------------ #include "DeskCalculator/Token.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(DeskCalculator) BOOST_AUTO_TEST_SUITE(Token_tests) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ BOOST_AUTO_TEST_CASE(NumberOfBitsInAByteIs8) { BOOST_TEST(true); } BOOST_AUTO_TEST_SUITE_END() // Token_tests BOOST_AUTO_TEST_SUITE_END() // DeskCalculator
34.368421
80
0.415008
ernestyalumni
0e1a5fdac81780d01d59623918dcb530064528d2
17,083
cpp
C++
clang/test/Layout/ms-x86-alias-avoidance-padding.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang/test/Layout/ms-x86-alias-avoidance-padding.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/Layout/ms-x86-alias-avoidance-padding.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple i686-pc-win32 -fms-extensions -fdump-record-layouts -fsyntax-only %s 2>/dev/null \ // RUN: | FileCheck %s --strict-whitespace // RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple x86_64-pc-win32 -fms-extensions -fdump-record-layouts -fsyntax-only %s 2>/dev/null \ // RUN: | FileCheck %s -check-prefix CHECK-X64 --strict-whitespace extern "C" int printf(const char *fmt, ...); __declspec(align(4096)) char buffer[4096]; struct AT {}; struct V : AT { char c; V() { printf("V - this: %d\n", (int)((char*)this - buffer)); } }; struct AT0 { union { struct { int a; AT t; } y; int b; } x; char c; AT0() { printf("AT0 - this: %d\n", (int)((char*)this - buffer)); } }; struct AT1 : V { int a; AT1() { printf("AT1 - this: %d\n", (int)((char*)this - buffer)); } }; struct AT2 { AT0 t; char AT2FieldName0; AT2() { printf("AT2 - this: %d\n", (int)((char*)this - buffer)); printf("AT2 - Fiel: %d\n", (int)((char*)&AT2FieldName0 - buffer)); } }; struct AT3 : AT2, AT1 { AT3() { printf("AT3 - this: %d\n", (int)((char*)this - buffer)); } }; // CHECK-LABEL: 0 | struct AT3{{$}} // CHECK-NEXT: 0 | struct AT2 (base) // CHECK-NEXT: 0 | struct AT0 t // CHECK-NEXT: 0 | union AT0::(unnamed at {{.*}} x // CHECK-NEXT: 0 | struct AT0::(unnamed at {{.*}} y // CHECK-NEXT: 0 | int a // CHECK-NEXT: 4 | struct AT t (empty) // CHECK: 0 | int b // CHECK: 8 | char c // CHECK: 12 | char AT2FieldName0 // CHECK-NEXT: 20 | struct AT1 (base) // CHECK-NEXT: 20 | struct V (base) // CHECK-NEXT: 20 | struct AT (base) (empty) // CHECK-NEXT: 20 | char c // CHECK-NEXT: 24 | int a // CHECK-NEXT: | [sizeof=28, align=4 // CHECK-NEXT: | nvsize=28, nvalign=4] // CHECK-X64-LABEL: 0 | struct AT3{{$}} // CHECK-X64-NEXT: 0 | struct AT2 (base) // CHECK-X64-NEXT: 0 | struct AT0 t // CHECK-X64-NEXT: 0 | union AT0::(unnamed at {{.*}} x // CHECK-X64-NEXT: 0 | struct AT0::(unnamed at {{.*}} y // CHECK-X64-NEXT: 0 | int a // CHECK-X64-NEXT: 4 | struct AT t (empty) // CHECK-X64: 0 | int b // CHECK-X64: 8 | char c // CHECK-X64: 12 | char AT2FieldName0 // CHECK-X64-NEXT: 20 | struct AT1 (base) // CHECK-X64-NEXT: 20 | struct V (base) // CHECK-X64-NEXT: 20 | struct AT (base) (empty) // CHECK-X64-NEXT: 20 | char c // CHECK-X64-NEXT: 24 | int a // CHECK-X64-NEXT: | [sizeof=28, align=4 // CHECK-X64-NEXT: | nvsize=28, nvalign=4] struct BT0 { BT0() { printf("BT0 - this: %d\n", (int)((char*)this - buffer)); } }; struct BT2 : BT0 { char BT2FieldName0; BT2() { printf("BT2 - this: %d\n", (int)((char*)this - buffer)); printf("BT2 - Fiel: %d\n", (int)((char*)&BT2FieldName0 - buffer)); } }; struct BT3 : BT0, BT2 { BT3() { printf("BT3 - this: %d\n", (int)((char*)this - buffer)); } }; // CHECK-LABEL: 0 | struct BT3{{$}} // CHECK-NEXT: 0 | struct BT0 (base) (empty) // CHECK-NEXT: 1 | struct BT2 (base) // CHECK-NEXT: 1 | struct BT0 (base) (empty) // CHECK-NEXT: 1 | char BT2FieldName0 // CHECK-NEXT: | [sizeof=2, align=1 // CHECK-NEXT: | nvsize=2, nvalign=1] // CHECK-X64-LABEL: 0 | struct BT3{{$}} // CHECK-X64-NEXT: 0 | struct BT0 (base) (empty) // CHECK-X64-NEXT: 1 | struct BT2 (base) // CHECK-X64-NEXT: 1 | struct BT0 (base) (empty) // CHECK-X64-NEXT: 1 | char BT2FieldName0 // CHECK-X64-NEXT: | [sizeof=2, align=1 // CHECK-X64-NEXT: | nvsize=2, nvalign=1] struct T0 : AT { T0() { printf("T0 (this) : %d\n", (int)((char*)this - buffer)); } }; struct T1 : T0 { char a; T1() { printf("T1 (this) : %d\n", (int)((char*)this - buffer)); printf("T1 (fiel) : %d\n", (int)((char*)&a - buffer)); } }; struct T2 : AT { char a; T2() { printf("T2 (this) : %d\n", (int)((char*)this - buffer)); printf("T2 (fiel) : %d\n", (int)((char*)&a - buffer)); } }; struct __declspec(align(1)) T3 : virtual T1, virtual T2 { T3() { printf("T3 (this) : %d\n", (int)((char*)this - buffer)); } }; // CHECK-LABEL: 0 | struct T3{{$}} // CHECK-NEXT: 0 | (T3 vbtable pointer) // CHECK-NEXT: 4 | struct T1 (virtual base) // CHECK-NEXT: 4 | struct T0 (base) (empty) // CHECK-NEXT: 4 | struct AT (base) (empty) // CHECK-NEXT: 4 | char a // CHECK-NEXT: 12 | struct T2 (virtual base) // CHECK-NEXT: 12 | struct AT (base) (empty) // CHECK-NEXT: 12 | char a // CHECK-NEXT: | [sizeof=16, align=4 // CHECK-NEXT: | nvsize=4, nvalign=4] // CHECK-X64-LABEL: 0 | struct T3{{$}} // CHECK-X64-NEXT: 0 | (T3 vbtable pointer) // CHECK-X64-NEXT: 8 | struct T1 (virtual base) // CHECK-X64-NEXT: 8 | struct T0 (base) (empty) // CHECK-X64-NEXT: 8 | struct AT (base) (empty) // CHECK-X64-NEXT: 8 | char a // CHECK-X64-NEXT: 16 | struct T2 (virtual base) // CHECK-X64-NEXT: 16 | struct AT (base) (empty) // CHECK-X64-NEXT: 16 | char a // CHECK-X64-NEXT: | [sizeof=24, align=8 // CHECK-X64-NEXT: | nvsize=8, nvalign=8] struct B {}; struct C { int a; }; struct D : B, virtual C { B b; }; struct E : D, B {}; // CHECK-LABEL: 0 | struct E{{$}} // CHECK-NEXT: 0 | struct D (base) // CHECK-NEXT: 4 | struct B (base) (empty) // CHECK-NEXT: 0 | (D vbtable pointer) // CHECK-NEXT: 4 | struct B b (empty) // CHECK: 8 | struct B (base) (empty) // CHECK-NEXT: 8 | struct C (virtual base) // CHECK-NEXT: 8 | int a // CHECK-NEXT: | [sizeof=12, align=4 // CHECK-NEXT: | nvsize=8, nvalign=4] // CHECK-X64-LABEL: 0 | struct E{{$}} // CHECK-X64-NEXT: 0 | struct D (base) // CHECK-X64-NEXT: 8 | struct B (base) (empty) // CHECK-X64-NEXT: 0 | (D vbtable pointer) // CHECK-X64-NEXT: 8 | struct B b (empty) // CHECK-X64: 16 | struct B (base) (empty) // CHECK-X64-NEXT: 16 | struct C (virtual base) // CHECK-X64-NEXT: 16 | int a // CHECK-X64-NEXT: | [sizeof=24, align=8 // CHECK-X64-NEXT: | nvsize=16, nvalign=8] struct F : virtual D, virtual B {}; // CHECK-LABEL: 0 | struct F{{$}} // CHECK-NEXT: 0 | (F vbtable pointer) // CHECK-NEXT: 4 | struct C (virtual base) // CHECK-NEXT: 4 | int a // CHECK-NEXT: 8 | struct D (virtual base) // CHECK-NEXT: 12 | struct B (base) (empty) // CHECK-NEXT: 8 | (D vbtable pointer) // CHECK-NEXT: 12 | struct B b (empty) // CHECK: 16 | struct B (virtual base) (empty) // CHECK-NEXT: | [sizeof=16, align=4 // CHECK-NEXT: | nvsize=4, nvalign=4] // CHECK-X64-LABEL: 0 | struct F{{$}} // CHECK-X64-NEXT: 0 | (F vbtable pointer) // CHECK-X64-NEXT: 8 | struct C (virtual base) // CHECK-X64-NEXT: 8 | int a // CHECK-X64-NEXT: 16 | struct D (virtual base) // CHECK-X64-NEXT: 24 | struct B (base) (empty) // CHECK-X64-NEXT: 16 | (D vbtable pointer) // CHECK-X64-NEXT: 24 | struct B b (empty) // CHECK-X64: 32 | struct B (virtual base) (empty) // CHECK-X64-NEXT: | [sizeof=32, align=8 // CHECK-X64-NEXT: | nvsize=8, nvalign=8] struct JC0 { JC0() { printf("JC0 : %d\n", (int)((char*)this - buffer)); } }; struct JC1 : JC0 { virtual void f() {} JC1() { printf("JC1 : %d\n", (int)((char*)this - buffer)); } }; struct JC2 : JC1 { JC2() { printf("JC2 : %d\n", (int)((char*)this - buffer)); } }; struct JC4 : JC1, JC2 { JC4() { printf("JC4 : %d\n", (int)((char*)this - buffer)); } }; // CHECK-LABEL: 0 | struct JC4{{$}} // CHECK-NEXT: 0 | struct JC1 (primary base) // CHECK-NEXT: 0 | (JC1 vftable pointer) // CHECK-NEXT: 4 | struct JC0 (base) (empty) // CHECK-NEXT: 8 | struct JC2 (base) // CHECK-NEXT: 8 | struct JC1 (primary base) // CHECK-NEXT: 8 | (JC1 vftable pointer) // CHECK-NEXT: 12 | struct JC0 (base) (empty) // CHECK-NEXT: | [sizeof=12, align=4 // CHECK-NEXT: | nvsize=12, nvalign=4] // CHECK-X64-LABEL: 0 | struct JC4{{$}} // CHECK-X64-NEXT: 0 | struct JC1 (primary base) // CHECK-X64-NEXT: 0 | (JC1 vftable pointer) // CHECK-X64-NEXT: 8 | struct JC0 (base) (empty) // CHECK-X64-NEXT: 16 | struct JC2 (base) // CHECK-X64-NEXT: 16 | struct JC1 (primary base) // CHECK-X64-NEXT: 16 | (JC1 vftable pointer) // CHECK-X64-NEXT: 24 | struct JC0 (base) (empty) // CHECK-X64-NEXT: | [sizeof=24, align=8 // CHECK-X64-NEXT: | nvsize=24, nvalign=8] struct RA {}; struct RB { char c; }; struct RV {}; struct RW { char c; }; struct RY { RY() { printf("%Id\n", (char*)this - buffer); } }; struct RX0 : RB, RA {}; struct RX1 : RA, RB {}; struct RX2 : RA { char a; }; struct RX3 : RA { RB a; }; struct RX4 { RA a; char b; }; struct RX5 { RA a; RB b; }; struct RX6 : virtual RV { RB a; }; struct RX7 : virtual RW { RA a; }; struct RX8 : RA, virtual RW {}; struct RZ0 : RX0, RY {}; // CHECK-LABEL: 0 | struct RZ0{{$}} // CHECK-NEXT: 0 | struct RX0 (base) // CHECK-NEXT: 0 | struct RB (base) // CHECK-NEXT: 0 | char c // CHECK-NEXT: 1 | struct RA (base) (empty) // CHECK-NEXT: 2 | struct RY (base) (empty) // CHECK-NEXT: | [sizeof=2, align=1 // CHECK-NEXT: | nvsize=2, nvalign=1] // CHECK-X64-LABEL: 0 | struct RZ0{{$}} // CHECK-X64-NEXT: 0 | struct RX0 (base) // CHECK-X64-NEXT: 0 | struct RB (base) // CHECK-X64-NEXT: 0 | char c // CHECK-X64-NEXT: 1 | struct RA (base) (empty) // CHECK-X64-NEXT: 2 | struct RY (base) (empty) // CHECK-X64-NEXT: | [sizeof=2, align=1 // CHECK-X64-NEXT: | nvsize=2, nvalign=1] struct RZ1 : RX1, RY {}; // CHECK-LABEL: 0 | struct RZ1{{$}} // CHECK-NEXT: 0 | struct RX1 (base) // CHECK-NEXT: 0 | struct RA (base) (empty) // CHECK-NEXT: 0 | struct RB (base) // CHECK-NEXT: 0 | char c // CHECK-NEXT: 1 | struct RY (base) (empty) // CHECK-NEXT: | [sizeof=1, align=1 // CHECK-NEXT: | nvsize=1, nvalign=1] // CHECK-X64-LABEL: 0 | struct RZ1{{$}} // CHECK-X64-NEXT: 0 | struct RX1 (base) // CHECK-X64-NEXT: 0 | struct RA (base) (empty) // CHECK-X64-NEXT: 0 | struct RB (base) // CHECK-X64-NEXT: 0 | char c // CHECK-X64-NEXT: 1 | struct RY (base) (empty) // CHECK-X64-NEXT: | [sizeof=1, align=1 // CHECK-X64-NEXT: | nvsize=1, nvalign=1] struct RZ2 : RX2, RY {}; // CHECK-LABEL: 0 | struct RZ2{{$}} // CHECK-NEXT: 0 | struct RX2 (base) // CHECK-NEXT: 0 | struct RA (base) (empty) // CHECK-NEXT: 0 | char a // CHECK-NEXT: 2 | struct RY (base) (empty) // CHECK-NEXT: | [sizeof=2, align=1 // CHECK-NEXT: | nvsize=2, nvalign=1] // CHECK-X64-LABEL: 0 | struct RZ2{{$}} // CHECK-X64-NEXT: 0 | struct RX2 (base) // CHECK-X64-NEXT: 0 | struct RA (base) (empty) // CHECK-X64-NEXT: 0 | char a // CHECK-X64-NEXT: 2 | struct RY (base) (empty) // CHECK-X64-NEXT: | [sizeof=2, align=1 // CHECK-X64-NEXT: | nvsize=2, nvalign=1] struct RZ3 : RX3, RY {}; // CHECK-LABEL: 0 | struct RZ3{{$}} // CHECK-NEXT: 0 | struct RX3 (base) // CHECK-NEXT: 0 | struct RA (base) (empty) // CHECK-NEXT: 0 | struct RB a // CHECK-NEXT: 0 | char c // CHECK-NEXT: 1 | struct RY (base) (empty) // CHECK-NEXT: | [sizeof=1, align=1 // CHECK-NEXT: | nvsize=1, nvalign=1] // CHECK-X64-LABEL: 0 | struct RZ3{{$}} // CHECK-X64-NEXT: 0 | struct RX3 (base) // CHECK-X64-NEXT: 0 | struct RA (base) (empty) // CHECK-X64-NEXT: 0 | struct RB a // CHECK-X64-NEXT: 0 | char c // CHECK-X64-NEXT: 1 | struct RY (base) (empty) // CHECK-X64-NEXT: | [sizeof=1, align=1 // CHECK-X64-NEXT: | nvsize=1, nvalign=1] struct RZ4 : RX4, RY {}; // CHECK-LABEL: 0 | struct RZ4{{$}} // CHECK-NEXT: 0 | struct RX4 (base) // CHECK-NEXT: 0 | struct RA a (empty) // CHECK-NEXT: 1 | char b // CHECK-NEXT: 3 | struct RY (base) (empty) // CHECK-NEXT: | [sizeof=3, align=1 // CHECK-NEXT: | nvsize=3, nvalign=1] // CHECK-X64-LABEL: 0 | struct RZ4{{$}} // CHECK-X64-NEXT: 0 | struct RX4 (base) // CHECK-X64-NEXT: 0 | struct RA a (empty) // CHECK-X64-NEXT: 1 | char b // CHECK-X64-NEXT: 3 | struct RY (base) (empty) // CHECK-X64-NEXT: | [sizeof=3, align=1 // CHECK-X64-NEXT: | nvsize=3, nvalign=1] struct RZ5 : RX5, RY {}; // CHECK-LABEL: 0 | struct RZ5{{$}} // CHECK-NEXT: 0 | struct RX5 (base) // CHECK-NEXT: 0 | struct RA a (empty) // CHECK-NEXT: 1 | struct RB b // CHECK-NEXT: 1 | char c // CHECK-NEXT: 2 | struct RY (base) (empty) // CHECK-NEXT: | [sizeof=2, align=1 // CHECK-NEXT: | nvsize=2, nvalign=1] // CHECK-X64-LABEL: 0 | struct RZ5{{$}} // CHECK-X64-NEXT: 0 | struct RX5 (base) // CHECK-X64-NEXT: 0 | struct RA a (empty) // CHECK-X64-NEXT: 1 | struct RB b // CHECK-X64-NEXT: 1 | char c // CHECK-X64-NEXT: 2 | struct RY (base) (empty) // CHECK-X64-NEXT: | [sizeof=2, align=1 // CHECK-X64-NEXT: | nvsize=2, nvalign=1] struct RZ6 : RX6, RY {}; // CHECK-LABEL: 0 | struct RZ6{{$}} // CHECK-NEXT: 0 | struct RX6 (base) // CHECK-NEXT: 0 | (RX6 vbtable pointer) // CHECK-NEXT: 4 | struct RB a // CHECK-NEXT: 4 | char c // CHECK-NEXT: 9 | struct RY (base) (empty) // CHECK-NEXT: 12 | struct RV (virtual base) (empty) // CHECK-NEXT: | [sizeof=12, align=4 // CHECK-NEXT: | nvsize=12, nvalign=4] // CHECK-X64-LABEL: 0 | struct RZ6{{$}} // CHECK-X64-NEXT: 0 | struct RX6 (base) // CHECK-X64-NEXT: 0 | (RX6 vbtable pointer) // CHECK-X64-NEXT: 8 | struct RB a // CHECK-X64-NEXT: 8 | char c // CHECK-X64-NEXT: 17 | struct RY (base) (empty) // CHECK-X64-NEXT: 24 | struct RV (virtual base) (empty) // CHECK-X64-NEXT: | [sizeof=24, align=8 // CHECK-X64-NEXT: | nvsize=24, nvalign=8] struct RZ7 : RX7, RY {}; // CHECK-LABEL: 0 | struct RZ7{{$}} // CHECK-NEXT: 0 | struct RX7 (base) // CHECK-NEXT: 0 | (RX7 vbtable pointer) // CHECK-NEXT: 4 | struct RA a (empty) // CHECK-NEXT: 8 | struct RY (base) (empty) // CHECK-NEXT: 8 | struct RW (virtual base) // CHECK-NEXT: 8 | char c // CHECK-NEXT: | [sizeof=9, align=4 // CHECK-NEXT: | nvsize=8, nvalign=4] // CHECK-X64-LABEL: 0 | struct RZ7{{$}} // CHECK-X64-NEXT: 0 | struct RX7 (base) // CHECK-X64-NEXT: 0 | (RX7 vbtable pointer) // CHECK-X64-NEXT: 8 | struct RA a (empty) // CHECK-X64-NEXT: 16 | struct RY (base) (empty) // CHECK-X64-NEXT: 16 | struct RW (virtual base) // CHECK-X64-NEXT: 16 | char c // CHECK-X64-NEXT: | [sizeof=24, align=8 // CHECK-X64-NEXT: | nvsize=16, nvalign=8] struct RZ8 : RX8, RY {}; // CHECK-LABEL: 0 | struct RZ8{{$}} // CHECK-NEXT: 0 | struct RX8 (base) // CHECK-NEXT: 4 | struct RA (base) (empty) // CHECK-NEXT: 0 | (RX8 vbtable pointer) // CHECK-NEXT: 4 | struct RY (base) (empty) // CHECK-NEXT: 4 | struct RW (virtual base) // CHECK-NEXT: 4 | char c // CHECK-NEXT: | [sizeof=5, align=4 // CHECK-NEXT: | nvsize=4, nvalign=4] // CHECK-X64-LABEL: 0 | struct RZ8{{$}} // CHECK-X64-NEXT: 0 | struct RX8 (base) // CHECK-X64-NEXT: 8 | struct RA (base) (empty) // CHECK-X64-NEXT: 0 | (RX8 vbtable pointer) // CHECK-X64-NEXT: 8 | struct RY (base) (empty) // CHECK-X64-NEXT: 8 | struct RW (virtual base) // CHECK-X64-NEXT: 8 | char c // CHECK-X64-NEXT: | [sizeof=16, align=8 // CHECK-X64-NEXT: | nvsize=8, nvalign=8] struct JA {}; struct JB {}; struct JC : JA { virtual void f() {} }; struct JD : virtual JB, virtual JC { virtual void f() {} JD() {} }; // CHECK-LABEL: 0 | struct JD{{$}} // CHECK-NEXT: 0 | (JD vbtable pointer) // CHECK-NEXT: 4 | struct JB (virtual base) (empty) // CHECK-NEXT: 4 | (vtordisp for vbase JC) // CHECK-NEXT: 8 | struct JC (virtual base) // CHECK-NEXT: 8 | (JC vftable pointer) // CHECK-NEXT: 12 | struct JA (base) (empty) // CHECK-NEXT: | [sizeof=12, align=4 // CHECK-NEXT: | nvsize=4, nvalign=4] // CHECK-X64-LABEL: 0 | struct JD{{$}} // CHECK-X64-NEXT: 0 | (JD vbtable pointer) // CHECK-X64-NEXT: 8 | struct JB (virtual base) (empty) // CHECK-X64-NEXT: 12 | (vtordisp for vbase JC) // CHECK-X64-NEXT: 16 | struct JC (virtual base) // CHECK-X64-NEXT: 16 | (JC vftable pointer) // CHECK-X64-NEXT: 24 | struct JA (base) (empty) // CHECK-X64-NEXT: | [sizeof=24, align=8 // CHECK-X64-NEXT: | nvsize=8, nvalign=8] int a[ sizeof(AT3) + sizeof(BT3) + sizeof(T3) + sizeof(E) + sizeof(F) + sizeof(JC4) + sizeof(RZ0) + sizeof(RZ1) + sizeof(RZ2) + sizeof(RZ3) + sizeof(RZ4) + sizeof(RZ5) + sizeof(RZ6) + sizeof(RZ7) + sizeof(RZ8) + sizeof(JD) + 0];
36.040084
137
0.545162
mkinsner
0e1cd4dfd145316d3d09108749e51e5356a31259
2,220
hh
C++
src/include/syntax/source.hh
awfeequdng/px_cppgo
5a102fce4c919ce93af247deb68241480374bf01
[ "MIT" ]
null
null
null
src/include/syntax/source.hh
awfeequdng/px_cppgo
5a102fce4c919ce93af247deb68241480374bf01
[ "MIT" ]
null
null
null
src/include/syntax/source.hh
awfeequdng/px_cppgo
5a102fce4c919ce93af247deb68241480374bf01
[ "MIT" ]
null
null
null
#pragma once #include "common/types.hh" #include "common/utf8/rune.hh" #include "common/hex_formatter.hh" #include <vector> #include <string> #include <iostream> #include <tuple> #include <fstream> template <typename T> std::vector<T> slice(std::vector<T>& v, std::size_t low, std::size_t high = -1) { std::vector<T> vec; if (high == -1) { std::copy(v.begin() + low, v.end(), std::back_inserter(vec)); } else { std::copy(v.begin() + low, v.begin() + high, std::back_inserter(vec)); } return vec; } namespace syntax { int64_t nextSize(int64_t size); typedef void (*err_handler)(uint line, uint col, std::string msg); // The source buffer is accessed using three indices b (begin), // r (read), and e (end): // // - If b >= 0, it points to the beginning of a segment of most // recently read characters (typically a Go literal). // // - r points to the byte immediately following the most recently // read character ch, which starts at r-chw. // // - e points to the byte immediately following the last byte that // was read into the buffer. // // The buffer content is terminated at buf[e] with the sentinel // character utf8.RuneSelf. This makes it possible to test for // the common case of ASCII characters with a single 'if' (see // nextch method). // // +------ content in use -------+ // v v // buf [...read...|...segment...|ch|...unread...|s|...free...] // ^ ^ ^ ^ // | | | | // b r-chw r e // // Invariant: -1 <= b < r <= e < len(buf) && buf[e] == sentinel struct source { std::ifstream _ifs; err_handler _errh{}; std::string _buf; int64_t _b; int64_t _r; int64_t _e; int _line; int _col; common::utf8::rune_t _ch; int _chw; void init(std::string file, err_handler errh); std::pair<int, int> pos(); void error(std::string msg); void start(); void stop(); // std::string segment() { return slice(buf, b, r - chw); } std::string segment(); void rewind(); void nextch(); void fill(); }; } // namespace syntax
25.813953
81
0.569369
awfeequdng
0e1cfe242aa6f0b92124df6d11ada3782f41ea01
5,531
cpp
C++
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
//<Snippet1> #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; public ref class ListViewInsertionMarkExample: public Form { private: ListView^ myListView; public: //<Snippet2> ListViewInsertionMarkExample() { // Initialize myListView. myListView = gcnew ListView; myListView->Dock = DockStyle::Fill; myListView->View = View::LargeIcon; myListView->MultiSelect = false; myListView->ListViewItemSorter = gcnew ListViewIndexComparer; // Initialize the insertion mark. myListView->InsertionMark->Color = Color::Green; // Add items to myListView. myListView->Items->Add( "zero" ); myListView->Items->Add( "one" ); myListView->Items->Add( "two" ); myListView->Items->Add( "three" ); myListView->Items->Add( "four" ); myListView->Items->Add( "five" ); // Initialize the drag-and-drop operation when running // under Windows XP or a later operating system. if ( System::Environment::OSVersion->Version->Major > 5 || (System::Environment::OSVersion->Version->Major == 5 && System::Environment::OSVersion->Version->Minor >= 1) ) { myListView->AllowDrop = true; myListView->ItemDrag += gcnew ItemDragEventHandler( this, &ListViewInsertionMarkExample::myListView_ItemDrag ); myListView->DragEnter += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragEnter ); myListView->DragOver += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragOver ); myListView->DragLeave += gcnew EventHandler( this, &ListViewInsertionMarkExample::myListView_DragLeave ); myListView->DragDrop += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragDrop ); } // Initialize the form. this->Text = "ListView Insertion Mark Example"; this->Controls->Add( myListView ); } private: //</Snippet2> // Starts the drag-and-drop operation when an item is dragged. void myListView_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e ) { myListView->DoDragDrop( e->Item, DragDropEffects::Move ); } // Sets the target drop effect. void myListView_DragEnter( Object^ /*sender*/, DragEventArgs^ e ) { e->Effect = e->AllowedEffect; } //<Snippet3> // Moves the insertion mark as the item is dragged. void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e ) { // Retrieve the client coordinates of the mouse pointer. Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) ); // Retrieve the index of the item closest to the mouse pointer. int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint ); // Confirm that the mouse pointer is not over the dragged item. if ( targetIndex > -1 ) { // Determine whether the mouse pointer is to the left or // the right of the midpoint of the closest item and set // the InsertionMark.AppearsAfterItem property accordingly. Rectangle itemBounds = myListView->GetItemRect( targetIndex ); if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) ) { myListView->InsertionMark->AppearsAfterItem = true; } else { myListView->InsertionMark->AppearsAfterItem = false; } } // Set the location of the insertion mark. If the mouse is // over the dragged item, the targetIndex value is -1 and // the insertion mark disappears. myListView->InsertionMark->Index = targetIndex; } //</Snippet3> // Removes the insertion mark when the mouse leaves the control. void myListView_DragLeave( Object^ /*sender*/, EventArgs^ /*e*/ ) { myListView->InsertionMark->Index = -1; } // Moves the item to the location of the insertion mark. void myListView_DragDrop( Object^ /*sender*/, DragEventArgs^ e ) { // Retrieve the index of the insertion mark; int targetIndex = myListView->InsertionMark->Index; // If the insertion mark is not visible, exit the method. if ( targetIndex == -1 ) { return; } // If the insertion mark is to the right of the item with // the corresponding index, increment the target index. if ( myListView->InsertionMark->AppearsAfterItem ) { targetIndex++; } // Retrieve the dragged item. ListViewItem^ draggedItem = dynamic_cast<ListViewItem^>(e->Data->GetData( ListViewItem::typeid )); // Insert a copy of the dragged item at the target index. // A copy must be inserted before the original item is removed // to preserve item index values. myListView->Items->Insert( targetIndex, dynamic_cast<ListViewItem^>(draggedItem->Clone()) ); // Remove the original copy of the dragged item. myListView->Items->Remove( draggedItem ); } // Sorts ListViewItem objects by index. ref class ListViewIndexComparer: public System::Collections::IComparer { public: virtual int Compare( Object^ x, Object^ y ) { return (dynamic_cast<ListViewItem^>(x))->Index - (dynamic_cast<ListViewItem^>(y))->Index; } }; }; [STAThread] int main() { Application::EnableVisualStyles(); Application::Run( gcnew ListViewInsertionMarkExample ); } //</Snippet1>
34.354037
175
0.661906
BohdanMosiyuk
0e1fc7dc1299325d1821fba77b7ef0f674214da3
6,326
cpp
C++
estacaocarregamento.cpp
luisdecker/Modelsim16.1
d664d23e5fb9a25db16f8a45e2f1bf954e838c6e
[ "Apache-2.0" ]
null
null
null
estacaocarregamento.cpp
luisdecker/Modelsim16.1
d664d23e5fb9a25db16f8a45e2f1bf954e838c6e
[ "Apache-2.0" ]
null
null
null
estacaocarregamento.cpp
luisdecker/Modelsim16.1
d664d23e5fb9a25db16f8a45e2f1bf954e838c6e
[ "Apache-2.0" ]
null
null
null
#include "estacaocarregamento.h" /*=============================================== Construtores ===============================================*/ EstacaoCarregamento::EstacaoCarregamento() { tempoMinimoFila = Relogio(); tempoMaximoFila = Relogio(); minimoEntidadesNaFila = 0; maximoEntidadesNaFila = 0; distTC = new RN::Constante( 1.0 ); } //=============================================== EstacaoCarregamento::EstacaoCarregamento( RN::Distribuicao *distribuicaoProbabilidadeTC ) { tempoMinimoFila = Relogio(); tempoMaximoFila = Relogio(); minimoEntidadesNaFila = 0; maximoEntidadesNaFila = 0; distTC = distribuicaoProbabilidadeTC; } /*=============================================== Eventos principais ===============================================*/ Evento *EstacaoCarregamento::enfileirarCaminhao( Caminhao *caminhao, Relogio horaAtual ) { std::cout << "[Enfileirando caminhão carga]"<<std::endl; Evento *eventoCarga; if( temEstacaoLivre() ) { eventoCarga = new Evento( Evento::carga,horaAtual,caminhao ); atualizaTemposFila( Relogio() ); return eventoCarga; } eventoCarga = new Evento( Evento::carga,proximoTempoLivre,caminhao ); Relogio tempoEmFila( proximoTempoLivre ); std::cout <<">Carregamento ocupado " << horaAtual.getSegundosSimulacao()<< " - " << proximoTempoLivre.getSegundosSimulacao()<<std::endl; tempoEmFila -= horaAtual; atualizaTemposFila( tempoEmFila ); aumentaNumeroNaFila(); return eventoCarga; } //=============================================== Evento *EstacaoCarregamento::carregarCaminhao( Caminhao *caminhao, Relogio horaAtual ) { std::cout << "[Carregando caminhão]"<<std::endl; int plataformaOcupando; diminuiNumeroNaFila(); //Verifica qual plataforma está livre plataformaOcupando = plataformaLivre(); livre[plataformaOcupando-1] = false;//ocupa a plataforma caminhaoOcupandoPlataforma[plataformaOcupando-1] = caminhao;//Seta o caminhao que está ocupando essa plataforma int TC = distTC->gerarVariavelAleatoria();//Gera o TC std::cout<<"[TC = " << TC<< "]" << std::endl; tempoTotalOcupacaoPlataforma[plataformaOcupando-1] += TC;//Aumenta o tempo total de ocupação desta plataforma Relogio fimCarga( horaAtual ); Relogio relTC = Relogio(); relTC.adicionaSegundos( TC ); fimCarga << relTC; horaLiberacaoPlataforma[plataformaOcupando-1] = fimCarga; if( horaLiberacaoPlataforma[0] < horaLiberacaoPlataforma[1] ) { proximoTempoLivre = horaLiberacaoPlataforma[0]; } else { proximoTempoLivre = horaLiberacaoPlataforma[1]; } jaUtilizada [plataformaOcupando-1] = true; std::cout << "[Fim da carga "<< fimCarga.getSegundosSimulacao()<< "][Proximo Livre " << proximoTempoLivre.getSegundosSimulacao()<<"]" << std::endl; return new Evento( Evento::chegadaPesagem,fimCarga,caminhao ); } //=============================================== void EstacaoCarregamento::retirarCaminhao( Caminhao *caminhao ) { std::cout << "[Retirando caminhão carregamento]"<<std::endl; int plataformaRetirada; if( *caminhaoOcupandoPlataforma[0]==*caminhao ) { plataformaRetirada = 1; } else { plataformaRetirada = 2; } livre[plataformaRetirada-1] = true; } /*=============================================== Funções auxiliares (private) ===============================================*/ bool EstacaoCarregamento::plataformasVirgens() { if( !jaUtilizada[0] )return true; if( !jaUtilizada[1] )return true; return false; } //=============================================== int EstacaoCarregamento::plataformaLivre() { if( livre[0] ) { return 1; } else { return 2; } } //=============================================== void EstacaoCarregamento::modificarDistribuicaoTC( RN::Distribuicao *dist ) { this->distTC = dist; } //=============================================== bool EstacaoCarregamento::temEstacaoLivre() { return livre[0] || livre[1]; } //=============================================== void EstacaoCarregamento::atualizaTemposFila( Relogio tempoFila ) { Relogio zero = Relogio(); if ( tempoFila == zero ) { temposDeFila.push_back( Relogio( tempoFila ) ); return; } //Atualiza a lista de tempos de fila temposDeFila.push_back( Relogio( tempoFila ) ); //Atualiza o tempo mínimo em fila if( tempoFila < tempoMinimoFila ) { tempoMinimoFila = tempoFila; } //Atualiza o tempo máximo em fila if ( tempoMaximoFila < tempoFila ) { tempoMaximoFila = tempoFila; } } //=============================================== void EstacaoCarregamento::aumentaNumeroNaFila() { numeroEntidadesEnfileiradas++; totalEntidadesEnfileiradas++; somaFila.push_back( numeroEntidadesEnfileiradas ); if( maximoEntidadesNaFila < numeroEntidadesEnfileiradas ) { maximoEntidadesNaFila = numeroEntidadesEnfileiradas; } } //=============================================== void EstacaoCarregamento::diminuiNumeroNaFila() { if( numeroEntidadesEnfileiradas >0 ) numeroEntidadesEnfileiradas--; somaFila.push_back( numeroEntidadesEnfileiradas ); if( minimoEntidadesNaFila > numeroEntidadesEnfileiradas ) { minimoEntidadesNaFila = numeroEntidadesEnfileiradas; } } //=============================================== double EstacaoCarregamento::mediaFila() { if( somaFila.empty() ) return 0; int somaTotal = 0; for( int numeroEmFila : somaFila ) { //std::cout << "Media carregamento: somando " << numeroEmFila << std::endl; somaTotal += numeroEmFila; } return ( double )somaTotal / somaFila.size(); } //=============================================== void EstacaoCarregamento::atualizaEstatisticasTempoFila() { //Organiza os tempos de fila if( temposDeFila.size()==0 ) {tempoMinimoFila = Relogio(); tempoMaximoFila=Relogio(); return;} tempoMinimoFila = *std::max_element( temposDeFila.begin(),temposDeFila.end() ); tempoMaximoFila = *std::min_element( temposDeFila.begin(),temposDeFila.end() ); } //=============================================== double EstacaoCarregamento::getMediaTempoFila() { if( temposDeFila.size()>0 ) { int somaTemposFila; for( Relogio tempoEmFila: temposDeFila ) { somaTemposFila += tempoEmFila.getSegundosSimulacao(); } return ( double ) somaTemposFila / ( double ) temposDeFila.size(); } return 0; }
36.356322
151
0.619033
luisdecker
0e243f5773f04ce8d2effa8dcdb92cb77df9b806
718
cpp
C++
POO/arquivos-livro/03/C++/cadastro02.cpp
ell3a/estudos-python
09808a462aa3e73ad433501acb11f62217548af8
[ "MIT" ]
null
null
null
POO/arquivos-livro/03/C++/cadastro02.cpp
ell3a/estudos-python
09808a462aa3e73ad433501acb11f62217548af8
[ "MIT" ]
null
null
null
POO/arquivos-livro/03/C++/cadastro02.cpp
ell3a/estudos-python
09808a462aa3e73ad433501acb11f62217548af8
[ "MIT" ]
null
null
null
/* Programa: cadastro02 Arquivo: cadastro02.cpp */ #include <iostream> #include "parametros.h" using namespace std; struct Pessoa { string nome; int idade; char sexo; } ; int main() { Pessoa cadastro[N]; int x; // Variável de controle for ( x = 0; x < N ; x++) { cout << "Digite o nome: "; cin >> cadastro[x].nome; cout << "Digite a idade: "; cin >> cadastro[x].idade; cout << "Digite o sexo (m para masculino, f para feminino): "; cin >> cadastro[x].sexo; } for ( x = 0; x < N ; x++) { cout << cadastro[x].nome << " - "<< cadastro[x].idade ; cout << " - "<< cadastro[x].sexo << endl; } return 0; }
19.944444
70
0.511142
ell3a
0e25c89f5d72ccf90a1ca9e2cc44047455978236
25,528
cc
C++
intern/opencolorio/ocio_impl.cc
gunslingster/CSC581-assignement1
39012146e142bf400c7140d90ecfd27c45b589ca
[ "Naumen", "Condor-1.1", "MS-PL" ]
39
2020-05-26T15:21:14.000Z
2022-03-24T04:46:31.000Z
intern/opencolorio/ocio_impl.cc
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
7
2020-05-11T14:04:54.000Z
2020-06-03T15:00:20.000Z
intern/opencolorio/ocio_impl.cc
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
14
2019-06-21T12:14:23.000Z
2021-08-25T14:57:06.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2012 Blender Foundation. * All rights reserved. */ #include <iostream> #include <math.h> #include <sstream> #include <string.h> #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4251 4275) #endif #include <OpenColorIO/OpenColorIO.h> #ifdef _MSC_VER # pragma warning(pop) #endif using namespace OCIO_NAMESPACE; #include "MEM_guardedalloc.h" #include "BLI_math_color.h" #include "ocio_impl.h" #if !defined(WITH_ASSERT_ABORT) # define OCIO_abort() #else # include <stdlib.h> # define OCIO_abort() abort() #endif #if defined(_MSC_VER) # define __func__ __FUNCTION__ #endif /* NOTE: This is because OCIO 1.1.0 has a bug which makes default * display to be the one which is first alphabetically. * * Fix has been submitted as a patch * https://github.com/imageworks/OpenColorIO/pull/638 * * For until then we use first usable display instead. */ #define DEFAULT_DISPLAY_WORKAROUND #ifdef DEFAULT_DISPLAY_WORKAROUND # include <algorithm> # include <map> # include <mutex> # include <set> # include <string> # include <vector> using std::map; using std::set; using std::string; using std::vector; #endif static void OCIO_reportError(const char *err) { std::cerr << "OpenColorIO Error: " << err << std::endl; OCIO_abort(); } static void OCIO_reportException(Exception &exception) { OCIO_reportError(exception.what()); } OCIO_ConstConfigRcPtr *OCIOImpl::getCurrentConfig(void) { ConstConfigRcPtr *config = OBJECT_GUARDED_NEW(ConstConfigRcPtr); try { *config = GetCurrentConfig(); if (*config) return (OCIO_ConstConfigRcPtr *)config; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(config, ConstConfigRcPtr); return NULL; } void OCIOImpl::setCurrentConfig(const OCIO_ConstConfigRcPtr *config) { try { SetCurrentConfig(*(ConstConfigRcPtr *)config); } catch (Exception &exception) { OCIO_reportException(exception); } } OCIO_ConstConfigRcPtr *OCIOImpl::configCreateFromEnv(void) { ConstConfigRcPtr *config = OBJECT_GUARDED_NEW(ConstConfigRcPtr); try { *config = Config::CreateFromEnv(); if (*config) return (OCIO_ConstConfigRcPtr *)config; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(config, ConstConfigRcPtr); return NULL; } OCIO_ConstConfigRcPtr *OCIOImpl::configCreateFromFile(const char *filename) { ConstConfigRcPtr *config = OBJECT_GUARDED_NEW(ConstConfigRcPtr); try { *config = Config::CreateFromFile(filename); if (*config) return (OCIO_ConstConfigRcPtr *)config; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(config, ConstConfigRcPtr); return NULL; } void OCIOImpl::configRelease(OCIO_ConstConfigRcPtr *config) { OBJECT_GUARDED_DELETE((ConstConfigRcPtr *)config, ConstConfigRcPtr); } int OCIOImpl::configGetNumColorSpaces(OCIO_ConstConfigRcPtr *config) { try { return (*(ConstConfigRcPtr *)config)->getNumColorSpaces(); } catch (Exception &exception) { OCIO_reportException(exception); } return 0; } const char *OCIOImpl::configGetColorSpaceNameByIndex(OCIO_ConstConfigRcPtr *config, int index) { try { return (*(ConstConfigRcPtr *)config)->getColorSpaceNameByIndex(index); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } OCIO_ConstColorSpaceRcPtr *OCIOImpl::configGetColorSpace(OCIO_ConstConfigRcPtr *config, const char *name) { ConstColorSpaceRcPtr *cs = OBJECT_GUARDED_NEW(ConstColorSpaceRcPtr); try { *cs = (*(ConstConfigRcPtr *)config)->getColorSpace(name); if (*cs) return (OCIO_ConstColorSpaceRcPtr *)cs; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(cs, ConstColorSpaceRcPtr); return NULL; } int OCIOImpl::configGetIndexForColorSpace(OCIO_ConstConfigRcPtr *config, const char *name) { try { return (*(ConstConfigRcPtr *)config)->getIndexForColorSpace(name); } catch (Exception &exception) { OCIO_reportException(exception); } return -1; } const char *OCIOImpl::configGetDefaultDisplay(OCIO_ConstConfigRcPtr *config) { #ifdef DEFAULT_DISPLAY_WORKAROUND if (getenv("OCIO_ACTIVE_DISPLAYS") == NULL) { const char *active_displays = (*(ConstConfigRcPtr *)config)->getActiveDisplays(); if (active_displays[0] != '\0') { const char *separator_pos = strchr(active_displays, ','); if (separator_pos == NULL) { return active_displays; } static std::string active_display; /* NOTE: Configuration is shared and is never changed during * runtime, so we only guarantee two threads don't initialize at the * same. */ static std::mutex mutex; mutex.lock(); if (active_display.empty()) { active_display = active_displays; active_display[separator_pos - active_displays] = '\0'; } mutex.unlock(); return active_display.c_str(); } } #endif try { return (*(ConstConfigRcPtr *)config)->getDefaultDisplay(); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } int OCIOImpl::configGetNumDisplays(OCIO_ConstConfigRcPtr *config) { try { return (*(ConstConfigRcPtr *)config)->getNumDisplays(); } catch (Exception &exception) { OCIO_reportException(exception); } return 0; } const char *OCIOImpl::configGetDisplay(OCIO_ConstConfigRcPtr *config, int index) { try { return (*(ConstConfigRcPtr *)config)->getDisplay(index); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } #ifdef DEFAULT_DISPLAY_WORKAROUND namespace { void splitStringEnvStyle(vector<string> *tokens, const string &str) { tokens->clear(); const int len = str.length(); int token_start = 0, token_length = 0; for (int i = 0; i < len; ++i) { const char ch = str[i]; if (ch != ',' && ch != ':') { /* Append non-separator char to a token. */ ++token_length; } else { /* Append current token to the list (if any). */ if (token_length > 0) { string token = str.substr(token_start, token_length); tokens->push_back(token); } /* Re-set token pointers. */ token_start = i + 1; token_length = 0; } } /* Append token which might be at the end of the string. */ if (token_length != 0) { string token = str.substr(token_start, token_length); tokens->push_back(token); } } string stringToLower(const string &str) { string lower = str; std::transform(lower.begin(), lower.end(), lower.begin(), tolower); return lower; } } // namespace #endif const char *OCIOImpl::configGetDefaultView(OCIO_ConstConfigRcPtr *config, const char *display) { #ifdef DEFAULT_DISPLAY_WORKAROUND /* NOTE: We assume that first active view always exists for a default * display. */ if (getenv("OCIO_ACTIVE_VIEWS") == NULL) { ConstConfigRcPtr config_ptr = *((ConstConfigRcPtr *)config); const char *active_views_encoded = config_ptr->getActiveViews(); if (active_views_encoded[0] != '\0') { const string display_lower = stringToLower(display); static map<string, string> default_display_views; static std::mutex mutex; mutex.lock(); /* Check if the view is already known. */ map<string, string>::const_iterator it = default_display_views.find(display_lower); if (it != default_display_views.end()) { mutex.unlock(); return it->second.c_str(); } /* Active views. */ vector<string> active_views; splitStringEnvStyle(&active_views, active_views_encoded); /* Get all views supported by tge display. */ set<string> display_views; const int num_display_views = config_ptr->getNumViews(display); for (int view_index = 0; view_index < num_display_views; ++view_index) { const char *view = config_ptr->getView(display, view_index); display_views.insert(stringToLower(view)); } /* Get first view which is supported by tge display. */ for (const string &view : active_views) { const string view_lower = stringToLower(view); if (display_views.find(view_lower) != display_views.end()) { default_display_views[display_lower] = view; mutex.unlock(); return default_display_views[display_lower].c_str(); } } mutex.unlock(); } } #endif try { return (*(ConstConfigRcPtr *)config)->getDefaultView(display); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } int OCIOImpl::configGetNumViews(OCIO_ConstConfigRcPtr *config, const char *display) { try { return (*(ConstConfigRcPtr *)config)->getNumViews(display); } catch (Exception &exception) { OCIO_reportException(exception); } return 0; } const char *OCIOImpl::configGetView(OCIO_ConstConfigRcPtr *config, const char *display, int index) { try { return (*(ConstConfigRcPtr *)config)->getView(display, index); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } const char *OCIOImpl::configGetDisplayColorSpaceName(OCIO_ConstConfigRcPtr *config, const char *display, const char *view) { try { return (*(ConstConfigRcPtr *)config)->getDisplayColorSpaceName(display, view); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } void OCIOImpl::configGetDefaultLumaCoefs(OCIO_ConstConfigRcPtr *config, float *rgb) { try { (*(ConstConfigRcPtr *)config)->getDefaultLumaCoefs(rgb); } catch (Exception &exception) { OCIO_reportException(exception); } } void OCIOImpl::configGetXYZtoRGB(OCIO_ConstConfigRcPtr *config_, float xyz_to_rgb[3][3]) { ConstConfigRcPtr config = (*(ConstConfigRcPtr *)config_); /* Default to ITU-BT.709 in case no appropriate transform found. */ memcpy(xyz_to_rgb, OCIO_XYZ_TO_LINEAR_SRGB, sizeof(OCIO_XYZ_TO_LINEAR_SRGB)); /* Auto estimate from XYZ and scene_linear roles, assumed to be a linear transform. */ if (config->hasRole("XYZ") && config->hasRole("scene_linear")) { ConstProcessorRcPtr to_rgb_processor = config->getProcessor("XYZ", "scene_linear"); if (to_rgb_processor) { xyz_to_rgb[0][0] = 1.0f; xyz_to_rgb[0][1] = 0.0f; xyz_to_rgb[0][2] = 0.0f; xyz_to_rgb[1][0] = 0.0f; xyz_to_rgb[1][1] = 1.0f; xyz_to_rgb[1][2] = 0.0f; xyz_to_rgb[2][0] = 0.0f; xyz_to_rgb[2][1] = 0.0f; xyz_to_rgb[2][2] = 1.0f; to_rgb_processor->applyRGB(xyz_to_rgb[0]); to_rgb_processor->applyRGB(xyz_to_rgb[1]); to_rgb_processor->applyRGB(xyz_to_rgb[2]); } } } int OCIOImpl::configGetNumLooks(OCIO_ConstConfigRcPtr *config) { try { return (*(ConstConfigRcPtr *)config)->getNumLooks(); } catch (Exception &exception) { OCIO_reportException(exception); } return 0; } const char *OCIOImpl::configGetLookNameByIndex(OCIO_ConstConfigRcPtr *config, int index) { try { return (*(ConstConfigRcPtr *)config)->getLookNameByIndex(index); } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } OCIO_ConstLookRcPtr *OCIOImpl::configGetLook(OCIO_ConstConfigRcPtr *config, const char *name) { ConstLookRcPtr *look = OBJECT_GUARDED_NEW(ConstLookRcPtr); try { *look = (*(ConstConfigRcPtr *)config)->getLook(name); if (*look) return (OCIO_ConstLookRcPtr *)look; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(look, ConstLookRcPtr); return NULL; } const char *OCIOImpl::lookGetProcessSpace(OCIO_ConstLookRcPtr *look) { return (*(ConstLookRcPtr *)look)->getProcessSpace(); } void OCIOImpl::lookRelease(OCIO_ConstLookRcPtr *look) { OBJECT_GUARDED_DELETE((ConstLookRcPtr *)look, ConstLookRcPtr); } int OCIOImpl::colorSpaceIsInvertible(OCIO_ConstColorSpaceRcPtr *cs_) { ConstColorSpaceRcPtr *cs = (ConstColorSpaceRcPtr *)cs_; const char *family = (*cs)->getFamily(); if (!strcmp(family, "rrt") || !strcmp(family, "display")) { /* assume display and rrt transformations are not invertible in fact some of them could be, * but it doesn't make much sense to allow use them as invertible. */ return false; } if ((*cs)->isData()) { /* data color spaces don't have transformation at all */ return true; } if ((*cs)->getTransform(COLORSPACE_DIR_TO_REFERENCE)) { /* if there's defined transform to reference space, * color space could be converted to scene linear. */ return true; } return true; } int OCIOImpl::colorSpaceIsData(OCIO_ConstColorSpaceRcPtr *cs) { return (*(ConstColorSpaceRcPtr *)cs)->isData(); } static float compare_floats(float a, float b, float abs_diff, int ulp_diff) { /* Returns true if the absolute difference is smaller than abs_diff (for numbers near zero) * or their relative difference is less than ulp_diff ULPs. Based on: * https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ */ if (fabsf(a - b) < abs_diff) { return true; } if ((a < 0.0f) != (b < 0.0f)) { return false; } return (abs((*(int *)&a) - (*(int *)&b)) < ulp_diff); } void OCIOImpl::colorSpaceIsBuiltin(OCIO_ConstConfigRcPtr *config_, OCIO_ConstColorSpaceRcPtr *cs_, bool &is_scene_linear, bool &is_srgb) { ConstConfigRcPtr *config = (ConstConfigRcPtr *)config_; ConstColorSpaceRcPtr *cs = (ConstColorSpaceRcPtr *)cs_; ConstProcessorRcPtr processor; try { processor = (*config)->getProcessor((*cs)->getName(), "scene_linear"); } catch (Exception &) { /* Silently ignore if no conversion possible, then it's not scene linear or sRGB. */ is_scene_linear = false; is_srgb = false; return; } is_scene_linear = true; is_srgb = true; for (int i = 0; i < 256; i++) { float v = i / 255.0f; float cR[3] = {v, 0, 0}; float cG[3] = {0, v, 0}; float cB[3] = {0, 0, v}; float cW[3] = {v, v, v}; processor->applyRGB(cR); processor->applyRGB(cG); processor->applyRGB(cB); processor->applyRGB(cW); /* Make sure that there is no channel crosstalk. */ if (fabsf(cR[1]) > 1e-5f || fabsf(cR[2]) > 1e-5f || fabsf(cG[0]) > 1e-5f || fabsf(cG[2]) > 1e-5f || fabsf(cB[0]) > 1e-5f || fabsf(cB[1]) > 1e-5f) { is_scene_linear = false; is_srgb = false; break; } /* Make sure that the three primaries combine linearly. */ if (!compare_floats(cR[0], cW[0], 1e-6f, 64) || !compare_floats(cG[1], cW[1], 1e-6f, 64) || !compare_floats(cB[2], cW[2], 1e-6f, 64)) { is_scene_linear = false; is_srgb = false; break; } /* Make sure that the three channels behave identically. */ if (!compare_floats(cW[0], cW[1], 1e-6f, 64) || !compare_floats(cW[1], cW[2], 1e-6f, 64)) { is_scene_linear = false; is_srgb = false; break; } float out_v = (cW[0] + cW[1] + cW[2]) * (1.0f / 3.0f); if (!compare_floats(v, out_v, 1e-6f, 64)) { is_scene_linear = false; } if (!compare_floats(srgb_to_linearrgb(v), out_v, 1e-6f, 64)) { is_srgb = false; } } } void OCIOImpl::colorSpaceRelease(OCIO_ConstColorSpaceRcPtr *cs) { OBJECT_GUARDED_DELETE((ConstColorSpaceRcPtr *)cs, ConstColorSpaceRcPtr); } OCIO_ConstProcessorRcPtr *OCIOImpl::configGetProcessorWithNames(OCIO_ConstConfigRcPtr *config, const char *srcName, const char *dstName) { ConstProcessorRcPtr *p = OBJECT_GUARDED_NEW(ConstProcessorRcPtr); try { *p = (*(ConstConfigRcPtr *)config)->getProcessor(srcName, dstName); if (*p) return (OCIO_ConstProcessorRcPtr *)p; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(p, ConstProcessorRcPtr); return 0; } OCIO_ConstProcessorRcPtr *OCIOImpl::configGetProcessor(OCIO_ConstConfigRcPtr *config, OCIO_ConstTransformRcPtr *transform) { ConstProcessorRcPtr *p = OBJECT_GUARDED_NEW(ConstProcessorRcPtr); try { *p = (*(ConstConfigRcPtr *)config)->getProcessor(*(ConstTransformRcPtr *)transform); if (*p) return (OCIO_ConstProcessorRcPtr *)p; } catch (Exception &exception) { OCIO_reportException(exception); } OBJECT_GUARDED_DELETE(p, ConstProcessorRcPtr); return NULL; } void OCIOImpl::processorApply(OCIO_ConstProcessorRcPtr *processor, OCIO_PackedImageDesc *img) { try { (*(ConstProcessorRcPtr *)processor)->apply(*(PackedImageDesc *)img); } catch (Exception &exception) { OCIO_reportException(exception); } } void OCIOImpl::processorApply_predivide(OCIO_ConstProcessorRcPtr *processor, OCIO_PackedImageDesc *img_) { try { PackedImageDesc *img = (PackedImageDesc *)img_; int channels = img->getNumChannels(); if (channels == 4) { float *pixels = img->getData(); int width = img->getWidth(); int height = img->getHeight(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float *pixel = pixels + 4 * (y * width + x); processorApplyRGBA_predivide(processor, pixel); } } } else { (*(ConstProcessorRcPtr *)processor)->apply(*img); } } catch (Exception &exception) { OCIO_reportException(exception); } } void OCIOImpl::processorApplyRGB(OCIO_ConstProcessorRcPtr *processor, float *pixel) { (*(ConstProcessorRcPtr *)processor)->applyRGB(pixel); } void OCIOImpl::processorApplyRGBA(OCIO_ConstProcessorRcPtr *processor, float *pixel) { (*(ConstProcessorRcPtr *)processor)->applyRGBA(pixel); } void OCIOImpl::processorApplyRGBA_predivide(OCIO_ConstProcessorRcPtr *processor, float *pixel) { if (pixel[3] == 1.0f || pixel[3] == 0.0f) { (*(ConstProcessorRcPtr *)processor)->applyRGBA(pixel); } else { float alpha, inv_alpha; alpha = pixel[3]; inv_alpha = 1.0f / alpha; pixel[0] *= inv_alpha; pixel[1] *= inv_alpha; pixel[2] *= inv_alpha; (*(ConstProcessorRcPtr *)processor)->applyRGBA(pixel); pixel[0] *= alpha; pixel[1] *= alpha; pixel[2] *= alpha; } } void OCIOImpl::processorRelease(OCIO_ConstProcessorRcPtr *p) { OBJECT_GUARDED_DELETE(p, ConstProcessorRcPtr); } const char *OCIOImpl::colorSpaceGetName(OCIO_ConstColorSpaceRcPtr *cs) { return (*(ConstColorSpaceRcPtr *)cs)->getName(); } const char *OCIOImpl::colorSpaceGetDescription(OCIO_ConstColorSpaceRcPtr *cs) { return (*(ConstColorSpaceRcPtr *)cs)->getDescription(); } const char *OCIOImpl::colorSpaceGetFamily(OCIO_ConstColorSpaceRcPtr *cs) { return (*(ConstColorSpaceRcPtr *)cs)->getFamily(); } OCIO_DisplayTransformRcPtr *OCIOImpl::createDisplayTransform(void) { DisplayTransformRcPtr *dt = OBJECT_GUARDED_NEW(DisplayTransformRcPtr); *dt = DisplayTransform::Create(); return (OCIO_DisplayTransformRcPtr *)dt; } void OCIOImpl::displayTransformSetInputColorSpaceName(OCIO_DisplayTransformRcPtr *dt, const char *name) { (*(DisplayTransformRcPtr *)dt)->setInputColorSpaceName(name); } void OCIOImpl::displayTransformSetDisplay(OCIO_DisplayTransformRcPtr *dt, const char *name) { (*(DisplayTransformRcPtr *)dt)->setDisplay(name); } void OCIOImpl::displayTransformSetView(OCIO_DisplayTransformRcPtr *dt, const char *name) { (*(DisplayTransformRcPtr *)dt)->setView(name); } void OCIOImpl::displayTransformSetDisplayCC(OCIO_DisplayTransformRcPtr *dt, OCIO_ConstTransformRcPtr *t) { (*(DisplayTransformRcPtr *)dt)->setDisplayCC(*(ConstTransformRcPtr *)t); } void OCIOImpl::displayTransformSetLinearCC(OCIO_DisplayTransformRcPtr *dt, OCIO_ConstTransformRcPtr *t) { (*(DisplayTransformRcPtr *)dt)->setLinearCC(*(ConstTransformRcPtr *)t); } void OCIOImpl::displayTransformSetLooksOverride(OCIO_DisplayTransformRcPtr *dt, const char *looks) { (*(DisplayTransformRcPtr *)dt)->setLooksOverride(looks); } void OCIOImpl::displayTransformSetLooksOverrideEnabled(OCIO_DisplayTransformRcPtr *dt, bool enabled) { (*(DisplayTransformRcPtr *)dt)->setLooksOverrideEnabled(enabled); } void OCIOImpl::displayTransformRelease(OCIO_DisplayTransformRcPtr *dt) { OBJECT_GUARDED_DELETE((DisplayTransformRcPtr *)dt, DisplayTransformRcPtr); } OCIO_PackedImageDesc *OCIOImpl::createOCIO_PackedImageDesc(float *data, long width, long height, long numChannels, long chanStrideBytes, long xStrideBytes, long yStrideBytes) { try { void *mem = MEM_mallocN(sizeof(PackedImageDesc), __func__); PackedImageDesc *id = new (mem) PackedImageDesc( data, width, height, numChannels, chanStrideBytes, xStrideBytes, yStrideBytes); return (OCIO_PackedImageDesc *)id; } catch (Exception &exception) { OCIO_reportException(exception); } return NULL; } void OCIOImpl::OCIO_PackedImageDescRelease(OCIO_PackedImageDesc *id) { OBJECT_GUARDED_DELETE((PackedImageDesc *)id, PackedImageDesc); } OCIO_GroupTransformRcPtr *OCIOImpl::createGroupTransform(void) { GroupTransformRcPtr *gt = OBJECT_GUARDED_NEW(GroupTransformRcPtr); *gt = GroupTransform::Create(); return (OCIO_GroupTransformRcPtr *)gt; } void OCIOImpl::groupTransformSetDirection(OCIO_GroupTransformRcPtr *gt, const bool forward) { TransformDirection dir = forward ? TRANSFORM_DIR_FORWARD : TRANSFORM_DIR_INVERSE; (*(GroupTransformRcPtr *)gt)->setDirection(dir); } void OCIOImpl::groupTransformPushBack(OCIO_GroupTransformRcPtr *gt, OCIO_ConstTransformRcPtr *tr) { (*(GroupTransformRcPtr *)gt)->push_back(*(ConstTransformRcPtr *)tr); } void OCIOImpl::groupTransformRelease(OCIO_GroupTransformRcPtr *gt) { OBJECT_GUARDED_DELETE((GroupTransformRcPtr *)gt, GroupTransformRcPtr); } OCIO_ColorSpaceTransformRcPtr *OCIOImpl::createColorSpaceTransform(void) { ColorSpaceTransformRcPtr *ct = OBJECT_GUARDED_NEW(ColorSpaceTransformRcPtr); *ct = ColorSpaceTransform::Create(); (*ct)->setDirection(TRANSFORM_DIR_FORWARD); return (OCIO_ColorSpaceTransformRcPtr *)ct; } void OCIOImpl::colorSpaceTransformSetSrc(OCIO_ColorSpaceTransformRcPtr *ct, const char *name) { (*(ColorSpaceTransformRcPtr *)ct)->setSrc(name); } void OCIOImpl::colorSpaceTransformRelease(OCIO_ColorSpaceTransformRcPtr *ct) { OBJECT_GUARDED_DELETE((ColorSpaceTransformRcPtr *)ct, ColorSpaceTransformRcPtr); } OCIO_ExponentTransformRcPtr *OCIOImpl::createExponentTransform(void) { ExponentTransformRcPtr *et = OBJECT_GUARDED_NEW(ExponentTransformRcPtr); *et = ExponentTransform::Create(); return (OCIO_ExponentTransformRcPtr *)et; } void OCIOImpl::exponentTransformSetValue(OCIO_ExponentTransformRcPtr *et, const float *exponent) { (*(ExponentTransformRcPtr *)et)->setValue(exponent); } void OCIOImpl::exponentTransformRelease(OCIO_ExponentTransformRcPtr *et) { OBJECT_GUARDED_DELETE((ExponentTransformRcPtr *)et, ExponentTransformRcPtr); } OCIO_MatrixTransformRcPtr *OCIOImpl::createMatrixTransform(void) { MatrixTransformRcPtr *mt = OBJECT_GUARDED_NEW(MatrixTransformRcPtr); *mt = MatrixTransform::Create(); return (OCIO_MatrixTransformRcPtr *)mt; } void OCIOImpl::matrixTransformSetValue(OCIO_MatrixTransformRcPtr *mt, const float *m44, const float *offset4) { (*(MatrixTransformRcPtr *)mt)->setValue(m44, offset4); } void OCIOImpl::matrixTransformRelease(OCIO_MatrixTransformRcPtr *mt) { OBJECT_GUARDED_DELETE((MatrixTransformRcPtr *)mt, MatrixTransformRcPtr); } void OCIOImpl::matrixTransformScale(float *m44, float *offset4, const float *scale4f) { MatrixTransform::Scale(m44, offset4, scale4f); } const char *OCIOImpl::getVersionString(void) { return GetVersion(); } int OCIOImpl::getVersionHex(void) { return GetVersionHex(); }
27.627706
99
0.67663
gunslingster
0e28d45fe9ef7e6f7b94113c3263bd28888fa736
25,820
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/dex/DexFileVerifier.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/dex/DexFileVerifier.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/dex/DexFileVerifier.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/server/pm/dex/DexFileVerifier.h" #include <zlib.h> namespace Elastos { namespace Droid { namespace Server { namespace Pm { namespace Dex { static uint32_t MapTypeToBitMask(uint32_t map_type) { switch (map_type) { case DexFile::kDexTypeHeaderItem: return 1 << 0; case DexFile::kDexTypeStringIdItem: return 1 << 1; case DexFile::kDexTypeTypeIdItem: return 1 << 2; case DexFile::kDexTypeProtoIdItem: return 1 << 3; case DexFile::kDexTypeFieldIdItem: return 1 << 4; case DexFile::kDexTypeMethodIdItem: return 1 << 5; case DexFile::kDexTypeClassDefItem: return 1 << 6; case DexFile::kDexTypeMapList: return 1 << 7; case DexFile::kDexTypeTypeList: return 1 << 8; case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9; case DexFile::kDexTypeAnnotationSetItem: return 1 << 10; case DexFile::kDexTypeClassDataItem: return 1 << 11; case DexFile::kDexTypeCodeItem: return 1 << 12; case DexFile::kDexTypeStringDataItem: return 1 << 13; case DexFile::kDexTypeDebugInfoItem: return 1 << 14; case DexFile::kDexTypeAnnotationItem: return 1 << 15; case DexFile::kDexTypeEncodedArrayItem: return 1 << 16; case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17; } return 0; } static bool IsDataSectionType(uint32_t map_type) { switch (map_type) { case DexFile::kDexTypeHeaderItem: case DexFile::kDexTypeStringIdItem: case DexFile::kDexTypeTypeIdItem: case DexFile::kDexTypeProtoIdItem: case DexFile::kDexTypeFieldIdItem: case DexFile::kDexTypeMethodIdItem: case DexFile::kDexTypeClassDefItem: return FALSE; } return TRUE; } Boolean DexFileVerifier::Verify( /* [in] */ const DexFile* dex_file, /* [in] */ const Byte* begin, /* [in] */ size_t size, /* [in] */ const char* location, /* [out] */ String* error_msg) { AutoPtr<DexFileVerifier> verifier = new DexFileVerifier(dex_file, begin, size, location); if (!verifier->Verify()) { *error_msg = verifier->FailureReason(); return FALSE; } return TRUE; } Boolean DexFileVerifier::CheckListSize( /* [in] */ const void* start, /* [in] */ size_t count, /* [in] */ size_t elem_size, /* [in] */ const char* label) { // Check that size is not 0. assert(elem_size != 0U); const byte* range_start = reinterpret_cast<const byte*>(start); const byte* file_start = reinterpret_cast<const byte*>(mBegin); // Check for overflow. uintptr_t max = 0 - 1; size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start); size_t max_count = available_bytes_till_end_of_mem / elem_size; if (max_count < count) { ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label, static_cast<size_t>(range_start - file_start), count, elem_size); return FALSE; } const byte* range_end = range_start + count * elem_size; const byte* file_end = file_start + mSize; if ((range_start < file_start) || (range_end > file_end)) { // Note: these two tests are enough as we make sure above that there's no overflow. ErrorStringPrintf("Bad range for %s: %zx to %zx", label, static_cast<size_t>(range_start - file_start), static_cast<size_t>(range_end - file_start)); return FALSE; } return TRUE; } Boolean DexFileVerifier::CheckValidOffsetAndSize( /* [in] */ uint32_t offset, /* [in] */ uint32_t size, /* [in] */ const char* label) { if (size == 0) { if (offset != 0) { ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label); return FALSE; } } if (mSize <= offset) { ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, mSize, label); return FALSE; } return TRUE; } Boolean DexFileVerifier::CheckHeader() { // Check file size from the header. uint32_t expected_size = mHeader->mFileSize; if (mSize != expected_size) { ErrorStringPrintf("Bad file size (%zd, expected %ud)", mSize, expected_size); return FALSE; } // Compute and verify the checksum in the header. uint32_t adler_checksum = adler32(0L, Z_NULL, 0); const uint32_t non_sum = sizeof(mHeader->mMagic) + sizeof(mHeader->mChecksum); const byte* non_sum_ptr = reinterpret_cast<const byte*>(mHeader) + non_sum; adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum); if (adler_checksum != mHeader->mChecksum) { ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, mHeader->mChecksum); return FALSE; } // Check the contents of the header. if (mHeader->mEndianTag != DexFile::sDexEndianConstant) { ErrorStringPrintf("Unexpected endian_tag: %x", mHeader->mEndianTag); return FALSE; } if (mHeader->mHeaderSize != sizeof(DexFile::Header)) { ErrorStringPrintf("Bad header size: %ud", mHeader->mHeaderSize); return FALSE; } // Check that all offsets are inside the file. Boolean result = CheckValidOffsetAndSize(mHeader->mLinkOff, mHeader->mLinkSize, "link") && CheckValidOffsetAndSize(mHeader->mMapOff, mHeader->mMapOff, "map") && CheckValidOffsetAndSize(mHeader->mStringIdsOff, mHeader->mStringIdsSize, "string-ids") && CheckValidOffsetAndSize(mHeader->mTypeIdsOff, mHeader->mTypeIdsSize, "type-ids") && CheckValidOffsetAndSize(mHeader->mProtoIdsOff, mHeader->mProtoIdsSize, "proto-ids") && CheckValidOffsetAndSize(mHeader->mFieldIdsOff, mHeader->mFieldIdsSize, "field-ids") && CheckValidOffsetAndSize(mHeader->mMethodIdsOff, mHeader->mMethodIdsSize, "method-ids") && CheckValidOffsetAndSize(mHeader->mClassDefsOff, mHeader->mClassDefsSize, "class-defs") && CheckValidOffsetAndSize(mHeader->mDataOff, mHeader->mDataSize, "data"); return result; } Boolean DexFileVerifier::CheckMap() { const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(mBegin + mHeader->mMapOff); // Check that map list content is available. if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) { return FALSE; } const DexFile::MapItem* item = map->mList; uint32_t count = map->mSize; uint32_t last_offset = 0; uint32_t data_item_count = 0; uint32_t data_items_left = mHeader->mDataSize; uint32_t used_bits = 0; // Sanity check the size of the map list. if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) { return FALSE; } // Check the items listed in the map. for (uint32_t i = 0; i < count; i++) { if (last_offset >= item->mOffset && i != 0) { ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->mOffset); return FALSE; } if (item->mOffset >= mHeader->mFileSize) { ErrorStringPrintf("Map item after end of file: %x, size %x", item->mOffset, mHeader->mFileSize); return FALSE; } if (IsDataSectionType(item->mType)) { uint32_t icount = item->mSize; if (icount > data_items_left) { ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount); return FALSE; } data_items_left -= icount; data_item_count += icount; } uint32_t bit = MapTypeToBitMask(item->mType); if (bit == 0) { ErrorStringPrintf("Unknown map section type %x", item->mType); return FALSE; } if ((used_bits & bit) != 0) { ErrorStringPrintf("Duplicate map section of type %x", item->mType); return FALSE; } used_bits |= bit; last_offset = item->mOffset; item++; } // Check for missing sections in the map. if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0) { ErrorStringPrintf("Map is missing header entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0) { ErrorStringPrintf("Map is missing map_list entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 && ((mHeader->mStringIdsOff != 0) || (mHeader->mStringIdsSize != 0))) { ErrorStringPrintf("Map is missing string_ids entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 && ((mHeader->mTypeIdsOff != 0) || (mHeader->mTypeIdsSize != 0))) { ErrorStringPrintf("Map is missing type_ids entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 && ((mHeader->mProtoIdsOff != 0) || (mHeader->mProtoIdsSize != 0))) { ErrorStringPrintf("Map is missing proto_ids entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 && ((mHeader->mFieldIdsOff != 0) || (mHeader->mFieldIdsSize != 0))) { ErrorStringPrintf("Map is missing field_ids entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 && ((mHeader->mMethodIdsOff != 0) || (mHeader->mMethodIdsSize != 0))) { ErrorStringPrintf("Map is missing method_ids entry"); return FALSE; } if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 && ((mHeader->mClassDefsOff != 0) || (mHeader->mClassDefsSize != 0))) { ErrorStringPrintf("Map is missing class_defs entry"); return FALSE; } return TRUE; } Boolean DexFileVerifier::CheckPadding( /* [in] */ size_t offset, /* [in] */ uint32_t aligned_offset) { if (offset < aligned_offset) { if (!CheckListSize(mBegin + offset, aligned_offset - offset, sizeof(byte), "section")) { return FALSE; } while (offset < aligned_offset) { if (*mPtr != '\0') { ErrorStringPrintf("Non-zero padding %x before section start at %zx", *mPtr, offset); return FALSE; } mPtr++; offset++; } } return TRUE; } Boolean DexFileVerifier::CheckIntraSectionIterate( /* [in] */ size_t offset, /* [in] */ uint32_t section_count, /* [in] */ uint16_t type) { // Get the right alignment mask for the type of section. size_t alignment_mask; switch (type) { case DexFile::kDexTypeClassDataItem: case DexFile::kDexTypeStringDataItem: case DexFile::kDexTypeDebugInfoItem: case DexFile::kDexTypeAnnotationItem: case DexFile::kDexTypeEncodedArrayItem: alignment_mask = sizeof(uint8_t) - 1; break; default: alignment_mask = sizeof(uint32_t) - 1; break; } // // Iterate through the items in the section. // for (uint32_t i = 0; i < section_count; i++) { // size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask; // // Check the padding between items. // if (!CheckPadding(offset, aligned_offset)) { // return FALSE; // } // // Check depending on the section type. // switch (type) { // case DexFile::kDexTypeStringIdItem: { // if (!CheckListSize(mPtr, 1, sizeof(DexFile::StringId), "string_ids")) { // return FALSE; // } // mPtr += sizeof(DexFile::StringId); // break; // } // case DexFile::kDexTypeTypeIdItem: { // if (!CheckListSize(mPtr, 1, sizeof(DexFile::TypeId), "type_ids")) { // return FALSE; // } // mPtr += sizeof(DexFile::TypeId); // break; // } // case DexFile::kDexTypeProtoIdItem: { // if (!CheckListSize(mPtr, 1, sizeof(DexFile::ProtoId), "proto_ids")) { // return FALSE; // } // mPtr += sizeof(DexFile::ProtoId); // break; // } // case DexFile::kDexTypeFieldIdItem: { // if (!CheckListSize(mPtr, 1, sizeof(DexFile::FieldId), "field_ids")) { // return FALSE; // } // mPtr += sizeof(DexFile::FieldId); // break; // } // case DexFile::kDexTypeMethodIdItem: { // if (!CheckListSize(mPtr, 1, sizeof(DexFile::MethodId), "method_ids")) { // return FALSE; // } // mPtr += sizeof(DexFile::MethodId); // break; // } // case DexFile::kDexTypeClassDefItem: { // if (!CheckListSize(mPtr, 1, sizeof(DexFile::ClassDef), "class_defs")) { // return FALSE; // } // mPtr += sizeof(DexFile::ClassDef); // break; // } // case DexFile::kDexTypeTypeList: { // if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &mPtr)) { // return FALSE; // } // break; // } // case DexFile::kDexTypeAnnotationSetRefList: { // if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &mPtr)) { // return FALSE; // } // break; // } // case DexFile::kDexTypeAnnotationSetItem: { // if (!CheckList(sizeof(uint32_t), "annotation_set_item", &mPtr)) { // return FALSE; // } // break; // } // case DexFile::kDexTypeClassDataItem: { // if (!CheckIntraClassDataItem()) { // return FALSE; // } // break; // } // case DexFile::kDexTypeCodeItem: { // if (!CheckIntraCodeItem()) { // return FALSE; // } // break; // } // case DexFile::kDexTypeStringDataItem: { // if (!CheckIntraStringDataItem()) { // return FALSE; // } // break; // } // case DexFile::kDexTypeDebugInfoItem: { // if (!CheckIntraDebugInfoItem()) { // return FALSE; // } // break; // } // case DexFile::kDexTypeAnnotationItem: { // if (!CheckIntraAnnotationItem()) { // return FALSE; // } // break; // } // case DexFile::kDexTypeEncodedArrayItem: { // if (!CheckEncodedArray()) { // return FALSE; // } // break; // } // case DexFile::kDexTypeAnnotationsDirectoryItem: { // if (!CheckIntraAnnotationsDirectoryItem()) { // return FALSE; // } // break; // } // default: // ErrorStringPrintf("Unknown map item type %x", type); // return FALSE; // } // if (IsDataSectionType(type)) { // offset_to_type_map_.Put(aligned_offset, type); // } // aligned_offset = mPtr - begin_; // if (aligned_offset > size_) { // ErrorStringPrintf("Item %d at ends out of bounds", i); // return FALSE; // } // offset = aligned_offset; // } return TRUE; } Boolean DexFileVerifier::CheckIntraIdSection( /* [in] */ size_t offset, /* [in] */ uint32_t count, /* [in] */ uint16_t type) { uint32_t expected_offset; uint32_t expected_size; // Get the expected offset and size from the header. switch (type) { case DexFile::kDexTypeStringIdItem: expected_offset = mHeader->mStringIdsOff; expected_size = mHeader->mStringIdsSize; break; case DexFile::kDexTypeTypeIdItem: expected_offset = mHeader->mTypeIdsOff; expected_size = mHeader->mTypeIdsSize; break; case DexFile::kDexTypeProtoIdItem: expected_offset = mHeader->mProtoIdsOff; expected_size = mHeader->mProtoIdsSize; break; case DexFile::kDexTypeFieldIdItem: expected_offset = mHeader->mFieldIdsOff; expected_size = mHeader->mFieldIdsSize; break; case DexFile::kDexTypeMethodIdItem: expected_offset = mHeader->mMethodIdsOff; expected_size = mHeader->mMethodIdsSize; break; case DexFile::kDexTypeClassDefItem: expected_offset = mHeader->mClassDefsOff; expected_size = mHeader->mClassDefsSize; break; default: ErrorStringPrintf("Bad type for id section: %x", type); return FALSE; } // Check that the offset and size are what were expected from the header. if (offset != expected_offset) { ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset); return FALSE; } if (count != expected_size) { ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size); return FALSE; } return CheckIntraSectionIterate(offset, count, type); } Boolean DexFileVerifier::CheckIntraDataSection( /* [in] */ size_t offset, /* [in] */ uint32_t count, /* [in] */ uint16_t type) { size_t data_start = mHeader->mDataOff; size_t data_end = data_start + mHeader->mDataSize; // Sanity check the offset of the section. if ((offset < data_start) || (offset > data_end)) { ErrorStringPrintf("Bad offset for data subsection: %zx", offset); return false; } if (!CheckIntraSectionIterate(offset, count, type)) { return FALSE; } size_t next_offset = mPtr - mBegin; if (next_offset > data_end) { ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset); return FALSE; } return TRUE; } Boolean DexFileVerifier::CheckIntraSection() { const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(mBegin + mHeader->mMapOff); const DexFile::MapItem* item = map->mList; uint32_t count = map->mSize; size_t offset = 0; mPtr = mBegin; // Check the items listed in the map. while (count--) { uint32_t section_offset = item->mOffset; uint32_t section_count = item->mSize; uint16_t type = item->mType; // Check for padding and overlap between items. if (!CheckPadding(offset, section_offset)) { return FALSE; } else if (offset > section_offset) { ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset); return FALSE; } // Check each item based on its type. switch (type) { case DexFile::kDexTypeHeaderItem: if (section_count != 1) { ErrorStringPrintf("Multiple header items"); return FALSE; } if (section_offset != 0) { ErrorStringPrintf("Header at %x, not at start of file", section_offset); return FALSE; } mPtr = mBegin + mHeader->mHeaderSize; offset = mHeader->mHeaderSize; break; case DexFile::kDexTypeStringIdItem: case DexFile::kDexTypeTypeIdItem: case DexFile::kDexTypeProtoIdItem: case DexFile::kDexTypeFieldIdItem: case DexFile::kDexTypeMethodIdItem: case DexFile::kDexTypeClassDefItem: if (!CheckIntraIdSection(section_offset, section_count, type)) { return FALSE; } offset = mPtr - mBegin; break; case DexFile::kDexTypeMapList: if (section_count != 1) { ErrorStringPrintf("Multiple map list items"); return FALSE; } if (section_offset != mHeader->mMapOff) { ErrorStringPrintf("Map not at header-defined offset: %x, expected %x", section_offset, mHeader->mMapOff); return FALSE; } mPtr += sizeof(uint32_t) + (map->mSize * sizeof(DexFile::MapItem)); offset = section_offset + sizeof(uint32_t) + (map->mSize * sizeof(DexFile::MapItem)); break; case DexFile::kDexTypeTypeList: case DexFile::kDexTypeAnnotationSetRefList: case DexFile::kDexTypeAnnotationSetItem: case DexFile::kDexTypeClassDataItem: case DexFile::kDexTypeCodeItem: case DexFile::kDexTypeStringDataItem: case DexFile::kDexTypeDebugInfoItem: case DexFile::kDexTypeAnnotationItem: case DexFile::kDexTypeEncodedArrayItem: case DexFile::kDexTypeAnnotationsDirectoryItem: if (!CheckIntraDataSection(section_offset, section_count, type)) { return FALSE; } offset = mPtr - mBegin; break; default: ErrorStringPrintf("Unknown map item type %x", type); return FALSE; } item++; } return TRUE; } Boolean DexFileVerifier::CheckInterSection() { const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(mBegin + mHeader->mMapOff); const DexFile::MapItem* item = map->mList; uint32_t count = map->mSize; // Cross check the items listed in the map. while (count--) { uint32_t section_offset = item->mOffset; uint32_t section_count = item->mSize; uint16_t type = item->mType; switch (type) { case DexFile::kDexTypeHeaderItem: case DexFile::kDexTypeMapList: case DexFile::kDexTypeTypeList: case DexFile::kDexTypeCodeItem: case DexFile::kDexTypeStringDataItem: case DexFile::kDexTypeDebugInfoItem: case DexFile::kDexTypeAnnotationItem: case DexFile::kDexTypeEncodedArrayItem: break; case DexFile::kDexTypeStringIdItem: case DexFile::kDexTypeTypeIdItem: case DexFile::kDexTypeProtoIdItem: case DexFile::kDexTypeFieldIdItem: case DexFile::kDexTypeMethodIdItem: case DexFile::kDexTypeClassDefItem: case DexFile::kDexTypeAnnotationSetRefList: case DexFile::kDexTypeAnnotationSetItem: case DexFile::kDexTypeClassDataItem: case DexFile::kDexTypeAnnotationsDirectoryItem: { // TODO: // if (!CheckInterSectionIterate(section_offset, section_count, type)) { // return FALSE; // } break; } default: ErrorStringPrintf("Unknown map item type %x", type); return FALSE; } item++; } return TRUE; } Boolean DexFileVerifier::Verify() { // Check the header. if (!CheckHeader()) { return FALSE; } // Check the map section. if (!CheckMap()) { return FALSE; } // Check structure within remaining sections. if (!CheckIntraSection()) { return FALSE; } // Check references from one section to another. if (!CheckInterSection()) { return FALSE; } return TRUE; } void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); mFailureReason = ""; mFailureReason.AppendFormat("Failure to verify dex file '%s': ", mLocation); mFailureReason.AppendFormat(fmt, ap); va_end(ap); } } // namespace Dex } // namespace Pm } // namespace Server } // namespace Droid } // namespace Elastos
36.264045
109
0.561813
jingcao80
0e28eec7659ff2ce90bc80232ef7550bed9d317d
144,164
cxx
C++
base/efiutil/efilib/src/usa/fatsachk.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/efiutil/efilib/src/usa/fatsachk.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/efiutil/efilib/src/usa/fatsachk.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1991-2001 Microsoft Corporation Module Name: fatsachk.cxx --*/ #include <pch.cxx> #include "bitvect.hxx" #include "error.hxx" #include "rtmsg.h" #include "ifsentry.hxx" // Timeinfo is full of windows stuff. #if !defined( _AUTOCHECK_ ) && !defined( _SETUP_LOADER_ ) && !defined( _EFICHECK_ ) #include "timeinfo.hxx" #endif #define UCHAR_SP ' ' typedef struct _VISIT_DIR *PVISIT_DIR; typedef struct _VISIT_DIR { PVISIT_DIR Next; PWSTRING Path; ULONG Cluster; } VISIT_DIR; #if !defined( _EFICHECK_ ) extern "C" { #include <stdio.h> } #endif extern VOID InsertSeparators( LPCWSTR OutWNumber, char * InANumber, ULONG Width ); VOID dofmsg( IN PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) { if (*NeedErrorsMessage) { Message->Set(MSG_CORRECTIONS_WILL_NOT_BE_WRITTEN, NORMAL_MESSAGE, TEXT_MESSAGE); Message->Display(); *NeedErrorsMessage = FALSE; } } BOOLEAN CheckAndFixFileName( PVOID DirEntry, PBOOLEAN Changes ) { PUCHAR p = (PUCHAR)DirEntry; #if 1 // // Should not correct case error within file name because // different language build translates differently. On a // dual boot machine containing build of two different languages, // the chkdsk from one build may not like what the second build // put onto the disk. // return TRUE; #else memcpy(backup_copy, p, 11); first_char_replaced = (0x5 == p[0]); if (first_char_replaced) p[0] = 0xe5; ntstatus = RtlOemToUnicodeN(unicode_string, sizeof(unicode_string), &unicode_string_length, (PCHAR)p, 11); if (!NT_SUCCESS(ntstatus)) { DebugPrintTrace(("UFAT: Error in RtlOemToUnicodeN, 0x%x\n", ntstatus)); memcpy(p, backup_copy, 11); return FALSE; } ntstatus = RtlUpcaseUnicodeToOemN((PCHAR)p, 11, NULL, unicode_string, unicode_string_length); if (!NT_SUCCESS(ntstatus)) { DebugPrintTrace(("UFAT: Error in RtlUpcaseUnicodeToOemN, 0x%x\n", ntstatus)); memcpy(p, backup_copy, 11); return FALSE; } if (first_char_replaced) { if (0xe5 == p[0]) { p[0] = 0x5; } else { DebugPrintTrace(("UFAT: First byte changed to 0x%x unexpectedly\n", p[0])); memcpy(p, backup_copy, 11); return FALSE; } } *Changes = (memcmp(p, backup_copy, 11) != 0); return TRUE; #endif } BOOLEAN IsFileNameMatch( PFATDIR Dir, UCHAR FatType, ULONG CurrentIndex, ULONG MatchingIndexCount, PULONG MatchingIndexArray ) { ULONG j; for (j = 0; j < MatchingIndexCount; j++) { FAT_DIRENT fd; ULONG indx = MatchingIndexArray[j]; if (!fd.Initialize(Dir->GetDirEntry(indx), FatType) || fd.IsVolumeLabel()) { continue; } if (!memcmp(Dir->GetDirEntry(indx), Dir->GetDirEntry(CurrentIndex), 11)) { return TRUE; // there is a match } } return FALSE; // no match } BOOLEAN RenameFileName( PULONG Positions, PVOID DirEntry ) { PUCHAR p = (PUCHAR)DirEntry; INT i; if (*Positions == 0) { // if first rename // find out the first char in the extension that is real for (i = 10; i > 7; i--) if (p[i] != UCHAR_SP) break; if (i >= 7 && i < 10) { // fill the unused extension space with dashes for (i++; i < 10; i++) p[i] = '-'; } *Positions = 1; if (p[10] != '0') { p[10] = '0'; // the last char of the extension gets a zero return TRUE; } } // extension chars are all in use now // check to see if renaming is already in progress for (i=10; i>=0; i--) { if (!(*Positions & (1 << (10-i)))) { *Positions |= (1 << (10-i)); if (p[i] != '0') { p[i] = '0'; return TRUE; } } if (p[i] >= '0' && p[i] < '9') { p[i]++; return TRUE; } else if (p[i] == '9') { p[i] = '0'; } } // if we get here that means we have exhausted all possible name // shouldn't be as there are more combination than the max number // of files that can be in a FAT directory (65536) return FALSE; } BOOLEAN PushVisitDir( IN OUT PVISIT_DIR *VisitDirStack, IN ULONG Cluster, IN PWSTRING DirectoryPath ) { PVISIT_DIR visit_dir; visit_dir = (PVISIT_DIR)MALLOC( sizeof( VISIT_DIR ) ); if( visit_dir == NULL ){ return FALSE; } visit_dir->Path = DirectoryPath; visit_dir->Cluster = Cluster; visit_dir->Next = *VisitDirStack; *VisitDirStack = visit_dir; return TRUE; } BOOLEAN PopVisitDir( IN OUT PVISIT_DIR *VisitDirStack, OUT PULONG Cluster OPTIONAL, OUT PWSTRING *DirectoryPath OPTIONAL ) { PVISIT_DIR visit_dir; visit_dir = *VisitDirStack; if( visit_dir == NULL ){ return FALSE; } *VisitDirStack = visit_dir->Next; if( ARGUMENT_PRESENT( Cluster ) ){ *Cluster = visit_dir->Cluster; } if( ARGUMENT_PRESENT( DirectoryPath ) ){ *DirectoryPath = visit_dir->Path; } FREE( visit_dir ); return TRUE; } STATIC VOID EraseAssociatedLongName( PFATDIR Dir, INT FirstLongEntry, INT ShortEntry ) { FAT_DIRENT dirent; for (int j = FirstLongEntry; j < ShortEntry; ++j) { dirent.Initialize(Dir->GetDirEntry(j)); dirent.SetErased(); } } STATIC BOOLEAN IsString8Dot3( PCWSTRING s ) /*++ Routine Description: This routine is used to ensure that lfn's legally correspond to their short names. The given string is examined to see if it is a legal fat 8.3 name. Arguments: s -- lfn to examine. Return Value: TRUE - The string is a legal 8.3 name. FALSE - Not legal. --*/ { USHORT i; BOOLEAN extension_present = FALSE; WCHAR c; // // The name can't be more than 12 characters (including a single dot). // if (s->QueryChCount() > 12) { return FALSE; } for (i = 0; i < s->QueryChCount(); ++i) { c = s->QueryChAt(i); #if 0 if (!FsRtlIsAnsiCharLegalFat(c, FALSE)) { return FALSE; } #endif if (c == '.') { // // We stepped onto a period. We require the following things: // // - it can't be the first character // - there can be only one // - there can't be more than 3 characters following it // - the previous character can't be a space // if (i == 0 || extension_present || s->QueryChCount() - (i + 1) > 3 || s->QueryChAt(i - 1) == ' ') { return FALSE; } extension_present = TRUE; } // // The base part of the name can't be more than 8 characters long. // if (i >= 8 && !extension_present) { return FALSE; } } // // The name cannot end in a space or a period. // if (c == ' ' || c == '.') { return FALSE; } return TRUE; } STATIC PMESSAGE _pvfMessage = NULL; STATIC BOOLEAN _Verbose = FALSE; VOID FreeSpaceInBitmap( IN ULONG StartingCluster, IN PCFAT Fat, IN OUT PBITVECTOR FatBitMap ); BOOLEAN FAT_SA::VerifyAndFix( IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN ULONG Flags, IN ULONG LogFileSize, OUT PULONG ExitStatus, IN PCWSTRING DriveLetter ) /*++ Routine Description: This routine verifies the FAT superarea and if neccessary fixes it to a correct state. Arguments: FixLevel - Supplies the level of fixes that may be performed on the disk. Message - Supplies an outlet for messages. Flags - Supplies flags to control the behavior of chkdsk (see ulib\inc\ifsserv.hxx for details) LogFileSize - ignored ExitStatus - Returns an indication of the result of the check DriveLetter - For autocheck, supplies the letter of the volume being checked Return Value: FALSE - Failure. TRUE - Success. --*/ { FAT_DIRENT eadent; ULONG cluster_size; ULONG ea_clus_num; USHORT num_eas, save_num_eas; PEA_INFO ea_infos; ULONG cluster_count; HMEM ea_header_mem; EA_HEADER ea_header; BOOLEAN changes = FALSE; BITVECTOR fat_bitmap; FATCHK_REPORT report; PUSHORT p; VOLID volid; ULONG free_count, bad_count, total_count; BOOLEAN fmsg; DSTRING label; DSTRING eafilename; DSTRING eafilepath; BOOLEAN tmp_bool; ULONG tmp_ulong; DSTRING date; DSTRING time; UCHAR dirty_byte, media_byte; BOOLEAN Verbose = (BOOLEAN)(Flags & CHKDSK_VERBOSE); BOOLEAN OnlyIfDirty = (BOOLEAN)(Flags & CHKDSK_CHECK_IF_DIRTY); BOOLEAN EnableUpgrade = (BOOLEAN)(Flags & CHKDSK_ENABLE_UPGRADE); BOOLEAN EnableDowngrade = (BOOLEAN)(Flags & CHKDSK_DOWNGRADE); BOOLEAN RecoverFree = (BOOLEAN)(Flags & CHKDSK_RECOVER_FREE_SPACE); BOOLEAN RecoverAlloc = (BOOLEAN)(Flags & CHKDSK_RECOVER_ALLOC_SPACE); _pvfMessage = Message; _Verbose = Verbose; memset(&report, 0, sizeof(FATCHK_REPORT)); if (NULL == ExitStatus) { ExitStatus = &report.ExitStatus; } report.ExitStatus = CHKDSK_EXIT_SUCCESS; *ExitStatus = CHKDSK_EXIT_COULD_NOT_CHK; fmsg = TRUE; if (FixLevel != CheckOnly) { fmsg = FALSE; } if (EnableUpgrade || EnableDowngrade) { Message->Set(MSG_CHK_CANNOT_UPGRADE_DOWNGRADE_FAT); Message->Display(); _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // // Check to see if the dirty bit is set. // dirty_byte = QueryVolumeFlags(); if (OnlyIfDirty) { if ((dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE)) == 0) { Message->Set(MSG_CHK_VOLUME_CLEAN); Message->Display(); Message->SetLoggingEnabled(FALSE); *ExitStatus = CHKDSK_EXIT_SUCCESS; _Verbose = FALSE; _pvfMessage = NULL; return TRUE; } // We need to re-initialize the fatsa object to include the whole // super area if (!Initialize(_drive, Message, TRUE)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); *ExitStatus = CHKDSK_EXIT_COULD_NOT_CHK; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (!Read(Message)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); *ExitStatus = CHKDSK_EXIT_COULD_NOT_CHK; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // If the second bit of the dirty byte is set then // also perform a full recovery of the free and allocated // space. if (dirty_byte & FAT_BPB_RESERVED_TEST_SURFACE) { RecoverFree = TRUE; RecoverAlloc = TRUE; } } // // NOTE that this check must follow the above "if (OnlyIfDirty)" because in the // OnlyIfDirty case only the first part of the FAT_SA object is in memory // until the above if gets executed. // if (QueryLength() <= SecPerBoot()) { Message->Set(MSG_NOT_FAT); Message->Display(); _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // // The volume is not clean, so if we're autochecking we want to // make sure that we're printing real messages on the console // instead of just dots. // #if defined(_AUTOCHECK_) if (Message->SetDotsOnly(FALSE)) { Message->SetLoggingEnabled(FALSE); if (NULL != DriveLetter) { Message->Set(MSG_CHK_RUNNING); Message->Display("%W", DriveLetter); } Message->Set(MSG_FILE_SYSTEM_TYPE); Message->Display("%s", _ft == LARGE32 ? "FAT32" : "FAT"); Message->SetLoggingEnabled(); } if (Message->IsInAutoChk()) { ULONG timeout; if (!VOL_LIODPDRV::QueryAutochkTimeOut(&timeout)) { timeout = AUTOCHK_TIMEOUT; } if (timeout > MAX_AUTOCHK_TIMEOUT_VALUE) timeout = AUTOCHK_TIMEOUT; if (timeout != 0) { if (dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE)) Message->Set(MSG_CHK_AUTOCHK_SKIP_WARNING); else Message->Set(MSG_CHK_USER_AUTOCHK_SKIP_WARNING); Message->Display(); if (Message->IsKeyPressed(MSG_CHK_ABORT_AUTOCHK, timeout)) { Message->SetLoggingEnabled(FALSE); Message->Set(MSG_CHK_AUTOCHK_ABORTED); Message->Display(); *ExitStatus = CHKDSK_EXIT_SUCCESS; return TRUE; } else { Message->Set(MSG_CHK_AUTOCHK_RESUMED); Message->Display(); } } else if ((dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE))) { Message->Set(MSG_CHK_VOLUME_IS_DIRTY); Message->Display(); } } else { DebugAssert(Message->IsInSetup()); if (dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE)) { Message->Set(MSG_CHK_VOLUME_IS_DIRTY); Message->Display(); } } #endif // _AUTOCHECK_ // // The BPB's Media Byte must be in the set accepted // by the file system. // media_byte = QueryMediaByte(); #if defined(FE_SB) && defined(_X86_) if ((media_byte != 0x00) && /* FMR */ (media_byte != 0x01) && /* FMR */ (media_byte != 0xf0) && #else if ((media_byte != 0xf0) && #endif (media_byte != 0xf8) && (media_byte != 0xf9) && #if defined(FE_SB) && defined(_X86_) (media_byte != 0xfa) && /* FMR */ (media_byte != 0xfb) && /* FMR */ #endif (media_byte != 0xfc) && (media_byte != 0xfd) && (media_byte != 0xfe) && (media_byte != 0xff)) { SetMediaByte(_drive->QueryMediaByte()); } // First print out the label and volume serial number. // We won't bother printing this message under autocheck. #if !defined( _AUTOCHECK_ ) && !defined( _SETUP_LOADER_ ) && !defined( _EFICHECK_ ) TIMEINFO timeinfo; if ((QueryLabel(&label, &timeinfo) || label.Initialize("")) && label.QueryChCount() && timeinfo.QueryDate(&date) && timeinfo.QueryTime(&time)) { Message->Set(MSG_VOLUME_LABEL_AND_DATE); Message->Display("%W%W%W", &label, &date, &time); } #else #if defined(_EFICHECK_) if (QueryLabel(&label) && label.QueryChCount() > 0) { Message->Set(MSG_VOLUME_LABEL_AND_DATE); // date is !!not!! displayed for EFI, since timeinfo is not implemented. Message->Display("%W", &label); } #endif #endif // !_AUTOCHECK_ && !_SETUP_LOADER_ if (volid = QueryVolId()) { p = (PUSHORT) &volid; Message->Set(MSG_VOLUME_SERIAL_NUMBER); Message->Display("%04X%04X", p[1], p[0]); } // Validate the FAT. if (_dirF32 == NULL) _fat->Scrub(&changes); if (changes) { dofmsg(Message, &fmsg); Message->Set(MSG_CHK_ERRORS_IN_FAT); Message->Display(); } // // Make sure that the media type in the BPB is the same as at // the beginning of the FAT. // if (QueryMediaByte() != _fat->QueryMediaByte()) { #if defined(FE_SB) // MO & OEM FAT Support BOOLEAN bPrintError = TRUE; #if defined(_X86_) if (IsPC98_N()) { // PC98 Nov.01.1994 // to help the early NEC DOS if(_drive->QueryMediaType() == FixedMedia && QueryMediaByte() == 0xf8 && _fat->QueryMediaByte() == 0xfe) { bPrintError = FALSE; } } #endif if (bPrintError == TRUE && (_drive->QueryMediaType() == F3_128Mb_512 || _drive->QueryMediaType() == F3_230Mb_512 )) { // We won't to recognized as illegal in following case. // // Some OpticalDisk might have 0xf0 as media in BPB, but it also has 0xF8 in FAT. // if (QueryMediaByte() == 0xf0 && _fat->QueryMediaByte() == 0xf8) { bPrintError = FALSE; } } if( bPrintError ) { #endif dofmsg(Message, &fmsg); Message->Set(MSG_PROBABLE_NON_DOS_DISK); Message->Display(); if (!Message->IsYesResponse(FALSE)) { report.ExitStatus = CHKDSK_EXIT_SUCCESS; _Verbose = FALSE; _pvfMessage = NULL; return TRUE; } #if defined(FE_SB) // REAL_FAT_SA::Create():Optical disk support // // Here is a table of Optical Disk (MO) format on OEM DOS. // // 128MB | NEC | IBM | Fujitsu | // -----------+-------+-------+---------+ // BPB.Media | 0xF0 | 0xF0 | 0xF0 | // -----------+-------+-------+---------+ // FAT.DiskID | 0xF0 | 0xF8 | 0xF8 | // -----------+-------+-------+---------+ // // 230MB | NEC | IBM | Fujitsu | // -----------+-------+-------+---------+ // BPB.Media | 0xF0 | 0xF0 | 0xF0 | // -----------+-------+-------+---------+ // FAT.DiskID | 0xF8 | 0xF8 | 0xF8 | // -----------+-------+-------+---------+ // // We will take NEC's way.... if (_drive->QueryMediaType() == F3_230Mb_512) { DebugAssert(QueryMediaByte() == (UCHAR) 0xF0); _fat->SetEarlyEntries((UCHAR) 0xF8); } else { _fat->SetEarlyEntries(QueryMediaByte()); } } #else _fat->SetEarlyEntries(QueryMediaByte()); #endif } // Compute the cluster size and the number of clusters on disk. cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster(); cluster_count = QueryClusterCount(); // No EAs have been detected yet. ea_infos = NULL; num_eas = 0; // Create an EA file name string. if (!eafilename.Initialize("EA DATA. SF") || !eafilepath.Initialize("\\EA DATA. SF")) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // // This bitmap will be reinitialized before 'WalkDirectoryTree'. // Its contents will be ignored until then. // if (!fat_bitmap.Initialize(cluster_count)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // If there is an EA file on disk then... // FAT32 volume does not support EA. if (_dir != NULL && // <-- If this is not a FAT32 volume. eadent.Initialize(_dir->SearchForDirEntry(&eafilename), FAT_TYPE_EAS_OKAY)) { // Validate the EA file directory entry. if (!ValidateDirent(&eadent, &eafilepath, FixLevel, FALSE, Message, &fmsg, &fat_bitmap, &tmp_bool, &tmp_ulong, ExitStatus)) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // If the EA file directory entry was valid then... // FATDIR::SearchForDirEntry will not return an erased dirent, but whatever... if (!eadent.IsErased()) { // The EA file should not have an EA handle. if (eadent.QueryEaHandle()) { dofmsg(Message, &fmsg); Message->Set(MSG_CHK_EAFILE_HAS_HANDLE); Message->Display(); eadent.SetEaHandle(0); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } // Compute the EA file's starting cluster. ea_clus_num = eadent.QueryStartingCluster(); // // Perform any log operations recorded at the beginning // of the EA file. // if (!PerformEaLogOperations(ea_clus_num, FixLevel, Message, &fmsg)) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // // Validate the EA file's EA sets and return an array of // information about them. // ea_infos = RecoverEaSets(ea_clus_num, &num_eas, FixLevel, Message, &fmsg); // // If there are no valid EAs in the EA file then erase // the EA file. // if (!ea_infos) { if (num_eas) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } eadent.SetErased(); dofmsg(Message, &fmsg); Message->Set(MSG_CHK_EMPTY_EA_FILE); Message->Display(); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } } } // Initialize FAT bitmap to be used in detection of cross-links. if (!fat_bitmap.Initialize(cluster_count)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (!CheckSectorHeapAllocation(FixLevel, Message, &fmsg)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (!VerifyFatExtensions(FixLevel, Message, &fmsg)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // // Should probably add another function to perform the following task. // if (_dirF32 != NULL) { if (!VerifyAndFixFat32RootDir( &fat_bitmap, Message, &report, &fmsg)) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } } // Validate all of the files on the disk. save_num_eas = num_eas; if (!WalkDirectoryTree(ea_infos, &num_eas, &fat_bitmap, &report, FixLevel, RecoverAlloc, Message, Verbose, &fmsg)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (save_num_eas != num_eas && ea_infos) { if (!EraseEaHandle(ea_infos, num_eas, save_num_eas, FixLevel, Message)) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (!num_eas) { delete [] ea_infos; ea_infos = NULL; // // Note that the following two steps cause the EA file chain to get recovered // as a lost cluster chain since all this does is erase the dirent, not the // cluster chain. // eadent.SetErased(); FreeSpaceInBitmap(eadent.QueryStartingCluster(), _fat, &fat_bitmap); dofmsg(Message, &fmsg); Message->Set(MSG_CHK_EMPTY_EA_FILE); Message->Display(); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } } // If there are EAs on the disk then... if (ea_infos) { // Remove all unused EAs from EA file. if (!PurgeEaFile(ea_infos, num_eas, &fat_bitmap, FixLevel, Message, &fmsg)) { // DELETE( ea_infos ); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // Rebuild header portion of EA file. if (!ea_header_mem.Initialize() || !RebuildEaHeader(&ea_clus_num, ea_infos, num_eas, &ea_header_mem, &ea_header, &fat_bitmap, FixLevel, Message, &fmsg)) { // DELETE( ea_infos ); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (ea_clus_num) { eadent.SetStartingCluster(ea_clus_num); eadent.SetFileSize(cluster_size* _fat->QueryLengthOfChain(ea_clus_num)); } else { dofmsg(Message, &fmsg); Message->Set(MSG_CHK_EMPTY_EA_FILE); Message->Display(); // // Note that the following two steps cause the EA file chain to get recovered // as a lost cluster chain since all this does is erase the dirent, not the // cluster chain. // eadent.SetErased(); FreeSpaceInBitmap(eadent.QueryStartingCluster(), _fat, &fat_bitmap); } *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } // // If WalkDirectoryTree deleted any files, we need to sync the // FAT_EXTENSIONS up with the FAT again. // if (!VerifyFatExtensions(FixLevel, Message, &fmsg)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } if (!RecoverOrphans(&fat_bitmap, FixLevel, Message, &fmsg, &report, &changes)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // // RecoverOrphans may have cleared faulty entries from the FAT, // and now we need to sync the FAT_EXTENSIONS again. // if (!VerifyFatExtensions(FixLevel, Message, &fmsg)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // If requested, validate all of the free space on the volume. if (RecoverFree && !RecoverFreeSpace(Message)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } total_count = cluster_count - FirstDiskCluster; if (changes) { report.ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } *ExitStatus = report.ExitStatus; switch (*ExitStatus) { case CHKDSK_EXIT_SUCCESS: Message->DisplayMsg(MSG_CHK_NO_PROBLEM_FOUND); break; case CHKDSK_EXIT_ERRS_FIXED: Message->DisplayMsg((FixLevel != CheckOnly) ? MSG_CHK_ERRORS_FIXED : MSG_CHK_NEED_F_PARAMETER); break; case CHKDSK_EXIT_COULD_NOT_CHK: // case CHKDSK_EXIT_ERRS_NOT_FIXED: // case CHKDSK_EXIT_COULD_NOT_FIX: Message->DisplayMsg(MSG_CHK_ERRORS_NOT_FIXED); break; } BIG_INT temp_big_int; ULONG temp_ulong; MSGID message_id; BOOLEAN KSize; DSTRING wdNum1; char wdAstr[14]; DSTRING wdNum2; if (!wdNum1.Initialize(" ") || !wdNum2.Initialize(" ") ) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } temp_big_int = cluster_size; temp_big_int = temp_big_int * total_count; // NOTE: The magic number 4095MB comes from Win9x's GUI SCANDISK utility if (temp_big_int.GetHighPart() || (temp_big_int.GetLowPart() > (4095ul*1024ul*1024ul))) { temp_ulong = (temp_big_int / 1024ul).GetLowPart(); message_id = MSG_TOTAL_KILOBYTES; KSize = TRUE; } else { temp_ulong = temp_big_int.GetLowPart(); message_id = MSG_TOTAL_DISK_SPACE; KSize = FALSE; } Message->Set(message_id); sprintf(wdAstr, "%u", temp_ulong); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); if (report.HiddenEntriesCount) { temp_big_int = cluster_size; temp_big_int = temp_big_int * report.HiddenClusters; if (KSize) { temp_ulong = (temp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_HIDDEN_FILES; } else { temp_ulong = temp_big_int.GetLowPart(); message_id = MSG_HIDDEN_FILES; } Message->Set(message_id); sprintf(wdAstr, "%u", temp_ulong); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); sprintf(wdAstr, "%d", report.HiddenEntriesCount); InsertSeparators(wdNum2.GetWSTR(),wdAstr, 0); Message->Display("%ws%ws", wdNum1.GetWSTR(), wdNum2.GetWSTR()); } if (report.DirEntriesCount) { temp_big_int = cluster_size; temp_big_int = temp_big_int * report.DirClusters; if (KSize) { temp_ulong = (temp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_DIRECTORIES; } else { temp_ulong = temp_big_int.GetLowPart(); message_id = MSG_DIRECTORIES; } Message->Set(message_id); sprintf(wdAstr, "%u", temp_ulong); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); sprintf(wdAstr, "%d", report.DirEntriesCount); InsertSeparators(wdNum2.GetWSTR(),wdAstr, 0); Message->Display("%ws%ws", wdNum1.GetWSTR(), wdNum2.GetWSTR()); } if (report.FileEntriesCount) { temp_big_int = cluster_size; temp_big_int = temp_big_int * report.FileClusters; if (KSize) { temp_ulong = (temp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_USER_FILES; } else { temp_ulong = temp_big_int.GetLowPart(); message_id = MSG_USER_FILES; } Message->Set(message_id); sprintf(wdAstr, "%u", temp_ulong); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); sprintf(wdAstr, "%d", report.FileEntriesCount); InsertSeparators(wdNum2.GetWSTR(),wdAstr, 0); Message->Display("%ws%ws", wdNum1.GetWSTR(), wdNum2.GetWSTR()); } if (bad_count = _fat->QueryBadClusters()) { temp_big_int = bad_count; temp_big_int = temp_big_int * cluster_size; if (KSize) { temp_ulong = (temp_big_int / 1024ul).GetLowPart(); message_id = MSG_CHK_NTFS_BAD_SECTORS_REPORT_IN_KB; } else { temp_ulong = temp_big_int.GetLowPart(); message_id = MSG_BAD_SECTORS; } Message->Set(message_id); sprintf(wdAstr, "%u", temp_ulong); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); } if (ea_infos) { Message->Set(MSG_CHK_EA_SIZE); sprintf(wdAstr, "%u", cluster_size*_fat->QueryLengthOfChain(ea_clus_num)); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); } free_count = _fat->QueryFreeClusters(); temp_big_int = free_count; temp_big_int = temp_big_int * cluster_size; if (KSize) { temp_ulong = (temp_big_int / 1024ul).GetLowPart(); message_id = MSG_AVAILABLE_KILOBYTES; } else { temp_ulong = temp_big_int.GetLowPart(); message_id = MSG_AVAILABLE_DISK_SPACE; } Message->Set(message_id); sprintf(wdAstr, "%u", temp_ulong); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); Message->Set(MSG_ALLOCATION_UNIT_SIZE); sprintf(wdAstr, "%u", cluster_size); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); Message->Set(MSG_TOTAL_ALLOCATION_UNITS); sprintf(wdAstr, "%u", total_count); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); Message->Set(MSG_AVAILABLE_ALLOCATION_UNITS); sprintf(wdAstr, "%u", free_count); InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13); Message->Display("%ws", wdNum1.GetWSTR()); if (FixLevel != CheckOnly && ea_infos && !ea_header.Write()) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // Clear the dirty bit. // if( RecoverAlloc ) { SetVolumeFlags(FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE, TRUE); } else { SetVolumeFlags(FAT_BPB_RESERVED_DIRTY, TRUE); } if (FixLevel != CheckOnly && !Write(Message)) { // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } // DELETE(ea_infos); delete [] ea_infos; ea_infos = NULL; _Verbose = FALSE; _pvfMessage = NULL; return TRUE; } BOOLEAN FAT_SA::VerifyAndFixFat32RootDir ( IN OUT PBITVECTOR FatBitMap, IN PMESSAGE Message, IN OUT PFATCHK_REPORT Report, IN OUT PBOOLEAN NeedErrorMessage ) /*++ Routine Description: This routine verifies the FAT32 root directory which is not an integral part of the super area buffer. The method employed to verify and fix the root directory is very similar to the one used to verify and fix regular directory structure. Arguments: BitVector - Supplies a bit map for cross/bad links detection. The whole map should be zeroed when it is passed in this method. Message - Supplies an outlet for messages. Report - Supplies the fat chkdsk report structures for storing the actions performed by this method. NeedErrorsMessage - Supplies whether or not an error has occurred under check only conditions. Return Values: TRUE - Success. FALSE - Failed. --*/ { BOOLEAN crosslink_detected = FALSE; BOOLEAN changes_made = FALSE; ULONG starting_cluster; ULONG dummy; starting_cluster = QueryFat32RootDirStartingCluster(); _fat->ScrubChain( starting_cluster, FatBitMap, &changes_made, &crosslink_detected, &dummy ); // // Root dir is the only component marked in the // bitmap so far. // DebugAssert(!crosslink_detected); if (changes_made) { dofmsg(Message, NeedErrorMessage); Message->Set(MSG_BAD_LINK); Message->Display("%s", "\\"); Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; // // We have to reinitialized the root directory. // if (!_hmem_F32->Initialize() || !_dirF32->Initialize( _hmem_F32, _drive, this, _fat, starting_cluster)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } // // Force a re-reading of the root directory. // We don't care if it fails, subsequent code can fix that. // _dirF32->Read(); } // // Validate the readability of the root chain // // // We don't want replacement clusters becuase the replacement given // by RecoverChain will be zeroed which, according to the spec., means // it contains the end of the directory structure and WalkDirectoryTree // will just go ahead and erase all the 'good' directory entries that comes // after the replaced cluster. Not a really nice thing to do to the root // directory IMHO. // if(!RecoverChain(&starting_cluster, &changes_made, 0, FALSE)){ dofmsg(Message, NeedErrorMessage); Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (changes_made) { if ( starting_cluster ) { if ( starting_cluster != _dirF32->QueryStartingCluster() ) { SetFat32RootDirStartingCluster( starting_cluster ); } // // Should reinitialize the root directory // if (!_hmem_F32->Initialize() || !_dirF32->Initialize( _hmem_F32, _drive, this, _fat, starting_cluster)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else { if(!RelocateNewFat32RootDirectory( Report, FatBitMap, Message )) { return FALSE; } } // // Reread the root directory // if (!_dirF32->Read()) { // // Shouldn't fail. // DebugAbort("Failed to read the FAT32 root directory despite all the fixing.\n"); } dofmsg(Message, NeedErrorMessage); Message->Set(MSG_CHK_NTFS_CORRECTING_ERROR_IN_DIRECTORY); Message->Display("%s", "\\"); // // Erasing the root will totally destroy the disk // so we just leave it partially corrupted and // hopefully WalkDirectoryTree will be able to fix it. // Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } return TRUE; } BOOLEAN FAT_SA::RelocateNewFat32RootDirectory ( IN OUT PFATCHK_REPORT Report, IN OUT PBITVECTOR FatBitMap, IN PMESSAGE Message ) /*++ Routine Description: This routine relocates a FAT32 root directory Arguments: Report - Supplies the fat chkdsk report structure for storing the fix status. FatBitMap - Supplies a pointer to the bit map for cross-link detection. Message - Supplies an outlet for messages. Return Values: TRUE - Success. FALSE - Failed. --*/ { SECRUN root_secrun; // Allocate one cluster for the // new root directory. ULONG root_clus; // New cluster number of the // root directory ULONG cluster_size;// Number of sectors in a cluster. ULONG starting_data_lbn; ULONG sector_size; starting_data_lbn = QueryStartDataLbn(); cluster_size = QuerySectorsPerCluster(); sector_size = _drive->QuerySectorSize(); for (;;) { root_clus = _fat->AllocChain(1, NULL); if (!root_clus) { // // The disk is full, we have no choice but to bail out. // Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE); Message->Display(); return FALSE; } if ( !_hmem_F32->Initialize() || !root_secrun.Initialize( _hmem_F32, _drive, QuerySectorFromCluster(root_clus, NULL), cluster_size)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } memset(root_secrun.GetBuf(), 0, cluster_size * sector_size); if (root_secrun.Write() && root_secrun.Read()) { SetFat32RootDirStartingCluster(root_clus); // // Set the bit for the new root in the bit map. // FatBitMap->SetBit(root_clus); // // Reinitialize the FAT32 root directory // if ( !_hmem_F32->Initialize() || !_dirF32->Initialize( _hmem_F32, _drive, this, _fat, root_clus)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; return TRUE; } else { _fat->SetClusterBad(root_clus); } } DebugPrintTrace(("FAT_SA::RelocateNewFat32RootDirectory: This line should not be reached.\n")); return FALSE; } BOOLEAN FAT_SA::PerformEaLogOperations( IN ULONG EaFileCn, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine reads the EA file log from the disk and then performs any logged operations specified. Arguments: EaFileCn - Supplies the first cluster of the EA file. FixLevel - Supplies the fix level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not an error has occurred under check only conditions. Return Value: FALSE - Failure. TRUE - Success. --*/ { HMEM hmem; EA_HEADER ea_header; PEA_FILE_HEADER pea_header; ULONG cluster_size; ULONG num_clus; cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster(); num_clus = sizeof(EA_FILE_HEADER) + BaseTableSize*sizeof(USHORT); if (num_clus%cluster_size) { num_clus = (num_clus/cluster_size + 1); } else { num_clus = (num_clus/cluster_size); } if (!hmem.Initialize() || !ea_header.Initialize(&hmem, _drive, this, _fat, EaFileCn, num_clus) || !(pea_header = ea_header.GetEaFileHeader())) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!ea_header.Read()) { Message->Set(MSG_CHK_CANT_CHECK_EA_LOG); Message->Display(); return TRUE; } if (pea_header->Signature != HeaderSignature || pea_header->FormatType || pea_header->LogType) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_BAD_LOG, NORMAL_MESSAGE, TEXT_MESSAGE); Message->Display(); if (Message->IsYesResponse(TRUE)) { pea_header->Signature = HeaderSignature; pea_header->Cluster1 = 0; pea_header->Cluster2 = 0; pea_header->Cluster3 = 0; if (FixLevel != CheckOnly) { ea_header.Write(); } return TRUE; } else { return FALSE; } } if (pea_header->Cluster1) { if (_fat->IsInRange(pea_header->Cluster1) && _fat->IsInRange(pea_header->NewCValue1)) { _fat->SetEntry(pea_header->Cluster1, pea_header->NewCValue1); } else { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_ERROR_IN_LOG); Message->Display(); } } if (pea_header->Cluster2) { if (_fat->IsInRange(pea_header->Cluster2) && _fat->IsInRange(pea_header->NewCValue2)) { _fat->SetEntry(pea_header->Cluster2, pea_header->NewCValue2); } else { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_ERROR_IN_LOG); Message->Display(); } } if (pea_header->Cluster3) { if (_fat->IsInRange(pea_header->Cluster3) && _fat->IsInRange(pea_header->NewCValue3)) { _fat->SetEntry(pea_header->Cluster3, pea_header->NewCValue3); } else { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_ERROR_IN_LOG); Message->Display(); } } return TRUE; } PEA_INFO FAT_SA::RecoverEaSets( IN ULONG EaFileCn, OUT PUSHORT NumEas, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine validates and if necessary recovers the EA file. Arguments: EaFileCn - Supplies the cluster number for the EA file. NumEas - Returns the number of EA sets in the EA file. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not an error has occurred under check only conditions. Return Value: An allocated array containing 'NumberOfEaSets' entries documenting important information about the EA sets. If there are no EAs then 'NumberOfEaSets' is returned as 0 and NULL is returned. If there is an error then NULL will be returned with a non-zero 'NumberOfEaSets'. --*/ { PEA_INFO ea_infos; ULONG clus, prev; USHORT num_eas; ULONG i; ULONG length; DebugAssert(NumEas); *NumEas = 1; length = _fat->QueryLengthOfChain(EaFileCn); ea_infos = NEW EA_INFO[length]; if (!ea_infos) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return NULL; } memset(ea_infos, 0, length*sizeof(EA_INFO)); // // Scan file for EA sets and validate them while updating the // array. // num_eas = 0; prev = EaFileCn; while (!_fat->IsEndOfChain(prev)) { clus = VerifyAndFixEaSet(prev, &ea_infos[num_eas], FixLevel, Message, NeedErrorsMessage); if (clus) { num_eas++; } else { clus = _fat->QueryEntry(prev); } prev = clus; } if (!num_eas) { // All the ea sets are unused, the ea file is // effectively empty. // Should use array delete instead. // DELETE( ea_infos ); delete [] ea_infos; // Free the cluster chain occupied by the ea file // so subsequent checking and fixing will not // complain about the lost chain in the ea file. _fat->FreeChain(EaFileCn); ea_infos = NULL; *NumEas = 0; return NULL; } // Go through and remove unused portions of the EA file. for (i = 0; i < (USHORT)(num_eas - 1); i++) { if (ea_infos[i].LastCn != ea_infos[i + 1].PreceedingCn) { _fat->RemoveChain(ea_infos[i].LastCn, ea_infos[i + 1].PreceedingCn); dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_UNUSED_EA_PORTION); Message->Display(); ea_infos[i + 1].PreceedingCn = ea_infos[i].LastCn; } } if (!_fat->IsEndOfChain(ea_infos[num_eas - 1].LastCn)) { _fat->SetEndOfChain(ea_infos[num_eas - 1].LastCn); dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_UNUSED_EA_PORTION); Message->Display(); } // Sort the EAs in the EA file. if (!EaSort(ea_infos, num_eas, Message, NeedErrorsMessage)) { return NULL; } *NumEas = num_eas; return ea_infos; } ULONG FAT_SA::VerifyAndFixEaSet( IN ULONG PreceedingCluster, OUT PEA_INFO EaInfo, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine attempts to identify the clusters following the 'PreceedingCluster' as an EA set. If this routine does not recognize these clusters as an EA set then it will return 0. Otherwise, it will return the last cluster of the validated EA set. Changes may be made to the clusters if they are recognized as an EA set with errors. Arguments: PreceedingCluster - Supplies the cluster preceeding the EA set cluster. Info - Returns information about the EA set. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not errors have occurred under check only conditions. Return Value: The cluster number of the last cluster in the EA set or 0. --*/ { HMEM hmem; EA_SET easet; ULONG clus; PEA_HDR eahdr; LONG i; ULONG j; ULONG need_count; LONG total_size; LONG size; ULONG length; BOOLEAN need_write; PEA pea; BOOLEAN more; ULONG chain_length; clus = _fat->QueryEntry(PreceedingCluster); chain_length = _fat->QueryLengthOfChain(clus); length = 1; need_write = FALSE; if (!hmem.Initialize() || !easet.Initialize(&hmem, _drive, this, _fat, clus, length) || !(eahdr = easet.GetEaSetHeader())) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return 0; } if (!easet.Read()) { return 0; } if (!easet.VerifySignature()) { return 0; } need_count = 0; total_size = 4; for (i = 0; ; i++) { for (j = 0; !(pea = easet.GetEa(i, &size, &more)) && more && length + j < chain_length; ) { j++; if (!hmem.Initialize() || !easet.Initialize(&hmem, _drive, this, _fat, clus, length + j)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return 0; } if (!easet.Read()) { return 0; } } if (pea) { length += j; } else { break; } total_size += size; if (pea->Flag & NeedFlag) { need_count++; } } if (!i) { return 0; } if (total_size != eahdr->TotalSize) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_EASET_SIZE); Message->Display("%d", clus); eahdr->TotalSize = total_size; need_write = TRUE; } if (need_count != eahdr->NeedCount) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_EASET_NEED_COUNT); Message->Display("%d", clus); eahdr->NeedCount = need_count; need_write = TRUE; } EaInfo->OwnHandle = eahdr->OwnHandle; EaInfo->PreceedingCn = PreceedingCluster; EaInfo->LastCn = _fat->QueryNthCluster(PreceedingCluster, length); memcpy(EaInfo->OwnerFileName, eahdr->OwnerFileName, 14); EaInfo->UsedCount = 0; if (need_write) { if (FixLevel != CheckOnly && !easet.Write()) { return 0; } } return EaInfo->LastCn; } BOOLEAN FAT_SA::EaSort( IN OUT PEA_INFO EaInfos, IN ULONG NumEas, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine sorts the EaInfos array by 'OwnHandle' into ascending order. It also edits the FAT with the changes in the EAs order. Arguments: EaInfos - Supplies the array of EA_INFOs to sort. NumEas - Supplies the number of elements in the array. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not errors have occurred under check only conditions. Return Value: FALSE - Failure. TRUE - Success. --*/ { BOOLEAN done; EA_INFO tmp; ULONG clus; ULONG i; BOOLEAN change; done = FALSE; change = FALSE; while (!done) { done = TRUE; for (i = 0; i < NumEas - 1; i++) { if (EaInfos[i].OwnHandle > EaInfos[i + 1].OwnHandle) { done = FALSE; clus = _fat->RemoveChain(EaInfos[i + 1].PreceedingCn, EaInfos[i + 1].LastCn); _fat->InsertChain(clus, EaInfos[i + 1].LastCn, EaInfos[i].PreceedingCn); EaInfos[i + 1].PreceedingCn = EaInfos[i].PreceedingCn; EaInfos[i].PreceedingCn = EaInfos[i + 1].LastCn; if (i + 2 < NumEas) { EaInfos[i + 2].PreceedingCn = EaInfos[i].LastCn; } change = TRUE; tmp = EaInfos[i]; EaInfos[i] = EaInfos[i + 1]; EaInfos[i + 1] = tmp; } } } if (change) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_UNORDERED_EA_SETS); Message->Display(); } return TRUE; } BOOLEAN FAT_SA::RebuildEaHeader( IN OUT PULONG StartingCluster, IN OUT PEA_INFO EaInfos, IN ULONG NumEas, IN OUT PMEM EaHeaderMem, OUT PEA_HEADER EaHeader, IN OUT PBITVECTOR FatBitMap, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine rebuilds the header and tables of the EA file base on the information in the 'EaInfos' array. The header log is set to zero, and the header itself is relocated if any of the clusters are bad. The starting cluster may be relocated if there are bad clusters. Arguments: StartingCluster - Supplies the first cluster of the EA file. EaInfos - Supplies an array containing information for every EA set. NumberOfEas - Supplies the total number of EA sets. EaHeaderMem - Supplies the memory for the EA header. EaHeader - Returns the EA header. FatBitMap - Supplies the cross-links bitmap. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not errors have occurred under check only conditions. Return Value: FALSE - Failure. TRUE - Success. --*/ { ULONG length; ULONG cluster_size; ULONG actual_length; ULONG new_chain; ULONG last_cluster; BOOLEAN changes; LONG i, j, k; PEA_MAP_TBL table; PEA_FILE_HEADER header; LONG tmp; BOOLEAN empty_ea_file; ULONG clus; // Compute the number of clusters necessary for the header portion of // the EA file. length = sizeof(EA_FILE_HEADER) + BaseTableSize*sizeof(USHORT) + EaInfos[NumEas - 1].OwnHandle*sizeof(USHORT); cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster(); if (length%cluster_size) { length = length/cluster_size + 1; } else { length = length/cluster_size; } // // Make sure that the header contains enough clusters to accomodate // the size of the offset table. // last_cluster = EaInfos[0].PreceedingCn; actual_length = _fat->QueryLengthOfChain(*StartingCluster, last_cluster); if (length > actual_length) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_NEED_MORE_HEADER_SPACE); Message->Display(); new_chain = _fat->AllocChain((length - actual_length), &last_cluster); if (!new_chain) { Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE); Message->Display(); return FALSE; } if (IsCompressed() && !AllocSectorsForChain(new_chain)) { _fat->FreeChain(new_chain); Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE); Message->Display(); return FALSE; } for (clus = new_chain; !_fat->IsEndOfChain(clus); clus = _fat->QueryEntry(clus)) { FatBitMap->SetBit(clus); } FatBitMap->SetBit(clus); _fat->InsertChain(new_chain, last_cluster, EaInfos[0].PreceedingCn); EaInfos[0].PreceedingCn = last_cluster; } else if (length < actual_length) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_UNUSED_EA_PORTION); Message->Display(); last_cluster = _fat->QueryNthCluster(*StartingCluster, length - 1); clus = _fat->RemoveChain(last_cluster, EaInfos[0].PreceedingCn); EaInfos[0].PreceedingCn = last_cluster; for (; !_fat->IsEndOfChain(clus); clus = _fat->QueryEntry(clus)) { FatBitMap->ResetBit(clus); } FatBitMap->ResetBit(clus); } // Verify the cluster chain containing the header. changes = FALSE; if (FixLevel != CheckOnly && !RecoverChain(StartingCluster, &changes, last_cluster, TRUE)) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE); Message->Display(); return FALSE; } if (changes) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_RELOCATED_EA_HEADER); Message->Display(); } // Compute the tables. if (!EaHeader->Initialize(EaHeaderMem, _drive, this, _fat, *StartingCluster, (USHORT) length) || !(table = EaHeader->GetMapTable()) || !(header = EaHeader->GetEaFileHeader())) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!EaHeader->Read()) { if (FixLevel == CheckOnly) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_RELOCATED_EA_HEADER); Message->Display(); } else { return FALSE; } } // Set the log in the header to zero. header->Signature = HeaderSignature; header->FormatType = 0; header->LogType = 0; header->Cluster1 = 0; header->NewCValue1 = 0; header->Cluster2 = 0; header->NewCValue2 = 0; header->Cluster3 = 0; header->NewCValue3 = 0; header->Handle = 0; header->NewHOffset = 0; // Reconcile the tables with the EaInfo information. changes = FALSE; for (i = 0; i < BaseTableSize; i++) { table->BaseTab[i] = 0; } j = 0; empty_ea_file = TRUE; for (i = 0; i < (LONG) NumEas; i++) { if (EaInfos[i].UsedCount != 1) { continue; } empty_ea_file = FALSE; for (; j < (LONG) EaInfos[i].OwnHandle; j++) { if (table->OffTab[j] != InvalidHandle) { table->OffTab[j] = InvalidHandle; changes = TRUE; } } length = _fat->QueryLengthOfChain(*StartingCluster, EaInfos[i].PreceedingCn); for (k = j>>7; k >= 0 && !table->BaseTab[k]; k--) { table->BaseTab[k] = (USHORT) length; } tmp = length - table->BaseTab[j>>7]; if ((LONG)table->OffTab[j] != tmp) { table->OffTab[j] = (USHORT) tmp; changes = TRUE; } j++; } if (empty_ea_file) { for (clus = *StartingCluster; !_fat->IsEndOfChain(clus); clus = _fat->QueryEntry(clus)) { FatBitMap->ResetBit(clus); } FatBitMap->ResetBit(clus); *StartingCluster = 0; return TRUE; } tmp = _fat->QueryLengthOfChain(*StartingCluster); for (k = ((j - 1)>>7) + 1; k < BaseTableSize; k++) { table->BaseTab[k] = (USHORT) tmp; } for (; j < (LONG) EaHeader->QueryOffTabSize(); j++) { if (table->OffTab[j] != InvalidHandle) { table->OffTab[j] = InvalidHandle; changes = TRUE; } } if (changes) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_ERROR_IN_EA_HEADER); Message->Display(); } return TRUE; } VOID FreeSpaceInBitmap( IN ULONG StartingCluster, IN PCFAT Fat, IN OUT PBITVECTOR FatBitMap ) { if (!StartingCluster) { return; } while (!Fat->IsEndOfChain(StartingCluster)) { FatBitMap->ResetBit(StartingCluster); StartingCluster = Fat->QueryEntry(StartingCluster); } FatBitMap->ResetBit(StartingCluster); } ULONG ComputeFileNameHashValue( IN PVOID FileName ) { ULONG h; BYTE i; PUCHAR p; p = (PUCHAR) FileName; h = 0; for (i=0; i<11; i++) { h = (h << 2) ^ p[i]; } for (i=0; i<2; i++) { h = (h << 2) ^ p[i]; } return h; } STATIC ULONG _Twinkle = 0; STATIC LONG64 _LastTwnkTime = 0; STATIC ULONG _LastPercent = 0xFFFFFFFF; BOOLEAN DisplayTwnkPercent( ULONG percent ) { BIG_INT currenttime; #if !defined( _EFICHECK_ ) NtQuerySystemTime((_LARGE_INTEGER *)&currenttime); #else EfiQuerySystemTime((_LARGE_INTEGER *)&currenttime); #endif // The above clock counts in 1/10,000ths of a second if((percent != _LastPercent) || ((currenttime.GetQuadPart() - _LastTwnkTime) >= (6 * 100 * 10000))) { if(percent > 100) { percent = 100; } if((_Twinkle > 5) || _Verbose) { _Twinkle = 0; } if(_Verbose && (percent == _LastPercent)) { return TRUE; } _LastPercent = percent; _LastTwnkTime = currenttime.GetQuadPart(); if(_pvfMessage) { STR dots[6]; dots[5] = '\0'; dots[4] = ' '; dots[3] = ' '; dots[2] = ' '; dots[1] = ' '; dots[0] = ' '; switch(_Twinkle) { case 5: default: dots[4] = '.'; case 4: dots[3] = '.'; case 3: dots[2] = '.'; case 2: dots[1] = '.'; case 1: dots[0] = '.'; case 0: ; } if(!_Verbose) { _Twinkle++; } _pvfMessage->Set(MSG_PERCENT_COMPLETE2); if (!_pvfMessage->Display("%d%s", percent, &dots[0])) { return FALSE; } if(_Verbose) { _pvfMessage->Set(MSG_BLANK_LINE); _pvfMessage->Display(); } } } return TRUE; } VOID DoTwinkle( VOID ) { DisplayTwnkPercent(_LastPercent); return; } VOID DoInsufMemory( VOID ) { if(_pvfMessage) { _pvfMessage->Set(MSG_CHK_NO_MEMORY); _pvfMessage->Display(); } return; } BOOLEAN FAT_SA::WalkDirectoryTree( IN OUT PEA_INFO EaInfos, IN OUT PUSHORT NumEas, IN OUT PBITVECTOR FatBitMap, OUT PFATCHK_REPORT Report, IN FIX_LEVEL FixLevel, IN BOOLEAN RecoverAlloc, IN OUT PMESSAGE Message, IN BOOLEAN Verbose, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine walks all of the files on the volume by traversing the directory tree. In doing so it validates all of the directory entries on the disk. It also verifies the proper chaining of all file cluster chains. This routine also validates the integrity of the EA handles for all of the directory entries on the disk. The FatBitMap is used to find and eliminate cross-links in the file system. Arguments: EaInfos - Supplies the EA information. NumEas - Supplies the number of EA sets. FatBitMap - Supplies a bit map marking all of the clusters currently in use. Report - Returns a FAT CHKDSK report on the files of the disk. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages. Verbose - Supplies whether or not to be verbose. NeedErrorsMessage - Supplies whether or not errors have occurred under check only conditions. Return Value: FALSE - Failure. TRUE - Success. --*/ { PVISIT_DIR visit_list; ULONG current_dir; PFATDIR dir; FILEDIR filedir; FAT_DIRENT dirent; ULONG i, j; ULONG clus, next; DSTRING file_path; PWSTRING new_path; PWSTRING current_path; ULONG new_dir; DSTRING filename; DSTRING long_name; HMEM hmem; CLUSTER_CHAIN cluster; ULONG new_chain; ULONG cluster_size; ULONG length; DSTRING backslash; DSTRING eafilename; DSTRING eafilename_path; DSTRING tmp_string; BOOLEAN cross_link_detected; ULONG cross_link_prevclus; HMEM tmphmem; FILEDIR tmpfiledir; FAT_DIRENT tmpdirent1; FAT_DIRENT tmpdirent2; BOOLEAN non_zero_dirents; HASH_INDEX file_name_hash_table; ULONG hash_value; PULONG matching_index_array; ULONG matching_index_count; BOOLEAN has_long_entry = FALSE; UCHAR chksum; BOOLEAN broke; ULONG first_long_entry; FAT_DIRENT dirent2; ULONG percent; ULONG allocated_clusters; BOOLEAN processing_ea_file; ULONG old_clus; ULONG new_clus; UCHAR FatType; USHORT numEasLeft = *NumEas; DEBUG((D_INFO, (CHAR8*)"Sizeof(INT) %x\n", sizeof(INT))); // find no clue for the following assert // DebugAssert(sizeof(PUCHAR) <= sizeof(INT)); DebugAssert(sizeof(USHORT) <= sizeof(INT)); DebugAssert(sizeof(ULONG ) <= sizeof(INT)); visit_list = NULL; cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster(); if (!backslash.Initialize("\\") || !eafilename.Initialize("EA DATA. SF") || !eafilename_path.Initialize("\\EA DATA. SF")) { return FALSE; } if (!(current_path = NEW DSTRING) || !current_path->Initialize(&backslash)) { return FALSE; } if (!PushVisitDir( &visit_list, 0, current_path )) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } Message->Set(MSG_CHK_CHECKING_FILES); Message->Display(); percent = 0; if(!DisplayTwnkPercent(percent)) { return FALSE; } for (; PopVisitDir( &visit_list, &current_dir, &current_path ); DELETE( current_path )) { DoTwinkle(); has_long_entry = FALSE; if (current_dir) { if (!hmem.Initialize() || !filedir.Initialize(&hmem, _drive, this, _fat, current_dir)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!filedir.Read()) { Message->Set(MSG_BAD_DIR_READ); Message->Display(); return FALSE; } dir = &filedir; } else { if ( _dir ) { dir = _dir; FatType = FAT_TYPE_EAS_OKAY; } else { dir = _dirF32; FatType = FAT_TYPE_FAT32; } } if (!file_name_hash_table.Initialize(dir->QueryNumberOfEntries(), 10)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } for (i = (current_dir ? 2 : 0); ; i++) { if (!dirent.Initialize(dir->GetDirEntry(i), FatType) || dirent.IsEndOfDirectory()) { if (has_long_entry) { // // There was an orphaned lfn at the end of the // directory. Erase it now. // Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_BAD_LONG_NAME); Message->Display( "%W", current_path ); EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } // // This code must make sure that all other directory // entries are end of directory entries. // non_zero_dirents = FALSE; for (; dirent.Initialize(dir->GetDirEntry(i),FatType); i++) { if (!dirent.IsEndOfDirectory()) { non_zero_dirents = TRUE; dirent.SetEndOfDirectory(); } } if (non_zero_dirents) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_TRAILING_DIRENTS); Message->Display("%W", current_path); Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } break; } if (dirent.IsErased()) { if (has_long_entry) { // // The preceding lfn is orphaned. Remove it. // Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_BAD_LONG_NAME); Message->Display( "%W", current_path ); EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } continue; } if (dirent.IsLongEntry()) { // skip long name entries; come back to them later if (has_long_entry) { // already amid long entry continue; } // first long entry has_long_entry = TRUE; first_long_entry = i; continue; } dirent.QueryName(&filename); if (has_long_entry) { DSTRING lfn; // // The current entry is short, and we've just finished // skipping the associated long entry. Look back through // the long entries, make sure they're okay. // broke = FALSE; chksum = dirent.QueryChecksum(); for (j = i - 1; j >= first_long_entry; j--) { dirent2.Initialize(dir->GetDirEntry(j),FatType); if (!dirent2.IsLongNameEntry()) { continue; } broke = (dirent2.QueryLongOrdinal() != i - j) || (dirent2.QueryChecksum() != chksum) || (LOUSHORT(dirent2.QueryStartingCluster()) != 0); broke = broke || !dirent2.IsWellTerminatedLongNameEntry(); if (broke || dirent2.IsLastLongEntry()) { break; } } broke = broke || (!dirent2.IsLastLongEntry()); #if 0 // We'll elide this code because Win95 isn't this strict and we // don't want to delete all their lfn's. if (!broke && dir->QueryLongName(i, &lfn)) { broke = !dirent.NameHasTilde() && (dirent.NameHasExtendedChars() || 0 != filename.Stricmp(&lfn)) && !IsString8Dot3(&lfn); } #endif if (broke) { Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; // // Erase all the long name entries. // dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_BAD_LONG_NAME); Message->Display( "%W", current_path ); EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } // // Fall into code to check short name. // } DoTwinkle(); dirent.QueryName(&filename); if (!file_path.Initialize(current_path)) { return FALSE; } if (current_dir) { if (!file_path.Strcat(&backslash)) { return FALSE; } } if (dir->QueryLongName(i, &long_name) && long_name.QueryChCount() != 0) { if (!file_path.Strcat(&long_name)) { return FALSE; } } else { if (!file_path.Strcat(&filename)) { return FALSE; } } if (Verbose && !dirent.IsVolumeLabel()) { Message->Set(MSG_CHK_FILENAME); Message->Display("%W", &file_path); } if (!ValidateDirent(&dirent, &file_path, FixLevel, RecoverAlloc, Message, NeedErrorsMessage, FatBitMap, &cross_link_detected, &cross_link_prevclus, &Report->ExitStatus)) { return FALSE; } DoTwinkle(); if (dirent.IsErased()) { // // ValidateDirent erased this entry, presumably because it's // hosed. Remove corresponding long name, if any. // if (has_long_entry) { EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } continue; } // // Analyze for duplicate names // if (!dirent.IsVolumeLabel()) { BOOLEAN renamed = FALSE; ULONG renaming_positions = 0; FAT_DIRENT temp_dirent; DSTRING new_filename; BOOLEAN changes = FALSE; if (!CheckAndFixFileName(dir->GetDirEntry(i), &changes)) { Message->Set(MSG_CHK_UNHANDLED_INVALID_NAME); Message->Display("%W%W", &filename, current_path); } for (;;) { hash_value = ComputeFileNameHashValue(dir->GetDirEntry(i)); if (!file_name_hash_table.QueryAndAdd(hash_value, i, &matching_index_array, &matching_index_count)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } DebugAssert(matching_index_count >= 1); matching_index_count--; if (matching_index_count && IsFileNameMatch(dir, FatType, i, matching_index_count, matching_index_array)) { file_name_hash_table.RemoveLastEntry(hash_value, i); Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; renamed = TRUE; if (!RenameFileName(&renaming_positions, dir->GetDirEntry(i))) { if (!temp_dirent.Initialize(dir->GetDirEntry(i), FatType)) { if (!new_filename.Initialize(TEXT("????????.???"))) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else temp_dirent.QueryName(&new_filename); // bugbug: should have return code dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_RENAMING_FAILURE); Message->Display("%W%W%W", &filename, current_path, &new_filename); if (!filename.Initialize(&new_filename)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!file_path.Initialize(current_path)) { return FALSE; } if (current_dir) { if (!file_path.Strcat(&backslash)) { return FALSE; } } if (dir->QueryLongName(i, &long_name) && long_name.QueryChCount() != 0) { if (!file_path.Strcat(&long_name)) { return FALSE; } } else { if (!file_path.Strcat(&new_filename)) { return FALSE; } } break; // done } } else if (renamed) { if (!temp_dirent.Initialize(dir->GetDirEntry(i), FatType)) { if (!new_filename.Initialize(TEXT("????????.???"))) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else temp_dirent.QueryName(&new_filename); // bugbug: should have return code Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_RENAMED_REPEATED_ENTRY); Message->Display("%W%W%W", &filename, current_path, &new_filename); if (!filename.Initialize(&new_filename)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!file_path.Initialize(current_path)) { return FALSE; } if (current_dir) { if (!file_path.Strcat(&backslash)) { return FALSE; } } if (dir->QueryLongName(i, &long_name) && long_name.QueryChCount() != 0) { if (!file_path.Strcat(&long_name)) { return FALSE; } } else { if (!file_path.Strcat(&new_filename)) { return FALSE; } } break; // no more conflict, done } else if (changes) { Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_INVALID_NAME_CORRECTED); Message->Display("%W%W", &filename, current_path); break; // done } else break; // done as there is no name conflict DoTwinkle(); } } DoTwinkle(); // // Analyze for cross-links. // if (cross_link_detected) { // CROSSLINK !! Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; // Identify cross linked cluster. clus = cross_link_prevclus; next = cross_link_prevclus ? _fat->QueryEntry(cross_link_prevclus) : dirent.QueryStartingCluster(); dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CROSS_LINK); Message->Display("%W%d", &file_path, next); processing_ea_file = (eafilename_path == file_path); if (dirent.IsDirectory()) { DebugAssert(!processing_ea_file); Message->Set(MSG_CHK_DIR_TRUNC); Message->Display(); if (clus) { _fat->SetEndOfChain(clus); } else { dirent.SetErased(); if (has_long_entry) { EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } continue; } } else { if (!CopyClusters(next, &new_chain, FatBitMap, FixLevel, Message)) { return FALSE; } if (new_chain) { Message->Set(MSG_CHK_CROSS_LINK_COPY); Message->Display(); if (processing_ea_file) { USHORT j; old_clus = next; new_clus = new_chain; for(;;) { for (j=0; j<*NumEas; j++) { if (EaInfos[j].PreceedingCn == old_clus) { EaInfos[j].PreceedingCn = new_clus; } else if (EaInfos[j].LastCn == old_clus) { EaInfos[j].LastCn = new_clus; } } if (_fat->IsEndOfChain(new_clus) || _fat->IsEndOfChain(old_clus)) { DebugAssert(_fat->IsEndOfChain(new_clus) && _fat->IsEndOfChain(old_clus)); break; } old_clus = _fat->QueryEntry(old_clus); new_clus = _fat->QueryEntry(new_clus); } } if (clus) { _fat->SetEntry(clus, new_chain); } else { dirent.SetStartingCluster(new_chain); } } else { Message->Set(MSG_CHK_CROSS_LINK_TRUNC); Message->Display(); if (clus) { if (processing_ea_file) { USHORT j; old_clus = next; for(;;) { for (j=0; j<*NumEas; j++) { if (EaInfos[j].LastCn == old_clus) { numEasLeft = j; break; } } if (_fat->IsEndOfChain(old_clus)) break; old_clus = _fat->QueryEntry(old_clus); } } _fat->SetEndOfChain(clus); dirent.SetFileSize( cluster_size*_fat->QueryLengthOfChain( dirent.QueryStartingCluster())); } else { numEasLeft = 0; dirent.SetErased(); if (has_long_entry) { EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } } } } } DoTwinkle(); if (!ValidateEaHandle(&dirent, current_dir, i, EaInfos, *NumEas, &file_path, FixLevel, Message, NeedErrorsMessage)) { return FALSE; } DoTwinkle(); // // Do special stuff if the current entry is a directory. // if (dirent.IsDirectory()) { new_dir = dirent.QueryStartingCluster(); // // Validate the integrity of the directory. // // Very first make sure it actually has a valid starting clus (check for 0) if(!(_fat->IsInRange(new_dir))) { if (dirent.IsDot() || dirent.IsDotDot()) { // If this happens on the . or .. entry just ignore it as it will // get fixed up later. continue; } Message->Set(MSG_CHK_ERROR_IN_DIR); Message->Display("%W", &file_path); Message->Set(MSG_CHK_CONVERT_DIR_TO_FILE, NORMAL_MESSAGE, TEXT_MESSAGE); Message->Display(); if (Message->IsYesResponse(TRUE)) { dirent.ResetDirectory(); dirent.SetStartingCluster(0); dirent.SetFileSize(0); } continue; } // Read the directory. if (!tmphmem.Initialize() || !tmpfiledir.Initialize(&tmphmem, _drive, this, _fat, new_dir) || !tmpfiledir.Read()) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } // Check the . and .. entries. if (!tmpdirent1.Initialize(tmpfiledir.GetDirEntry(0),FatType) || !tmpdirent2.Initialize(tmpfiledir.GetDirEntry(1),FatType)) { DebugAbort("GetDirEntry of 0 and 1 failed!"); return FALSE; } if (!tmpdirent1.IsDot() || !tmpdirent2.IsDotDot() || !tmpdirent1.IsDirectory() || !tmpdirent2.IsDirectory()) { Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_ERROR_IN_DIR); Message->Display("%W", &file_path); Message->Set(MSG_CHK_CONVERT_DIR_TO_FILE, NORMAL_MESSAGE, TEXT_MESSAGE); Message->Display(); if (Message->IsYesResponse(TRUE)) { dirent.ResetDirectory(); dirent.SetFileSize( _fat->QueryLengthOfChain(new_dir)* cluster_size); } else { FreeSpaceInBitmap(dirent.QueryStartingCluster(), _fat, FatBitMap); dirent.SetErased(); if (has_long_entry) { EraseAssociatedLongName(dir, first_long_entry, i); has_long_entry = FALSE; } continue; } } else { // Directory looks valid. if (tmpdirent1.QueryStartingCluster() != new_dir || tmpdirent2.QueryStartingCluster() != current_dir || tmpdirent1.QueryFileSize() || tmpdirent2.QueryFileSize()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_ERRORS_IN_DIR_CORR); Message->Display("%W", &file_path); Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED; tmpdirent1.SetStartingCluster(new_dir); tmpdirent2.SetStartingCluster(current_dir); tmpdirent1.SetFileSize(0); tmpdirent2.SetFileSize(0); if (FixLevel != CheckOnly && !tmpfiledir.Write()) { DebugAbort("Could not write tmp file dir."); return FALSE; } } // Add the directory to the list of directories // to validate. if (!(new_path = NEW DSTRING) || !new_path->Initialize(&file_path)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!PushVisitDir( &visit_list, new_dir, new_path )) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } } // // Generate report stats. // if (current_dir || !(filename == eafilename)) { length = _fat->QueryLengthOfChain(dirent.QueryStartingCluster()); if (dirent.IsHidden()) { Report->HiddenEntriesCount++; Report->HiddenClusters += length; } else if (dirent.IsDirectory()) { Report->DirEntriesCount++; Report->DirClusters += length; } else if (!dirent.IsVolumeLabel()) { Report->FileEntriesCount++; Report->FileClusters += length; } } allocated_clusters = _fat->QueryAllocatedClusterCount(); if (0 == allocated_clusters) { allocated_clusters++; // Prevent divide by 0 } percent = (Report->HiddenClusters + Report->DirClusters + Report->FileClusters) * 100 / allocated_clusters; if(!DisplayTwnkPercent(percent)) { return FALSE; } has_long_entry = FALSE; } file_name_hash_table.DumpHashTable(); #if 0 // // The following line should be moved to REAL_FAT_SA::Write. // // // The placement of the following line actually touches upon // the philosophical dilemma of what makes a superarea a superarea. // In the good old FAT16/12 days when the root directory is a fixed size // structure and sitting right next to the fat and boot sector, it kind // of makes sense to define the superarea as a run of sectors including the // the root directory. But now that the FAT32 root directory is defined // as a cluster chain, is the superarea still an area (or a run of sectors // as a matter of fact) by including the FAT32 root directory?(Rhetorical // question) Hence I can sort of understand why the following line // is placed where it is originally (but this is an incomplete job // considering the fact that the FAT32 root directory is still part of // the superarea object). So in order to honor the fine tradition of // totally embedding the root directory into the superarea, I have decided // to move the following line to the Write method of the FAT superarea // object. The proper way out of this dilemma is to define the superarea // as a persistent object which is not necessarily a contagious run of // sectors. (I think I get a little bit carried away.) // if((_dirF32) && !(current_dir)) { //root directory fix if (FixLevel != CheckOnly && !_dirF32->Write()) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } } #endif if (current_dir) { if (FixLevel != CheckOnly && !filedir.Write()) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } } } percent = 100; if(!DisplayTwnkPercent(percent)) { _Verbose = FALSE; _pvfMessage = NULL; return FALSE; } Message->Set(MSG_CHK_DONE_CHECKING); Message->Display(); *NumEas = numEasLeft; _Verbose = FALSE; _pvfMessage = NULL; return TRUE; } BOOLEAN FAT_SA::ValidateDirent( IN OUT PFAT_DIRENT Dirent, IN PCWSTRING FilePath, IN FIX_LEVEL FixLevel, IN BOOLEAN RecoverAlloc, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage, IN OUT PBITVECTOR FatBitMap, OUT PBOOLEAN CrossLinkDetected, OUT PULONG CrossLinkPreviousCluster, OUT PULONG ExitStatus ) /*++ Routine Description: This routine verifies that all components of a directory entry are correct. If the time stamps are invalid then they will be corrected to the current time. If the filename is invalid then the directory entry will be marked as deleted. If the cluster number is out of disk range then the directory entry will be marked as deleted. Otherwise, the cluster chain will be validated and the length of the cluster chain will be compared against the file size. If there is a difference then the file size will be corrected. If there are any strange errors then FALSE will be returned. Arguments: Dirent - Supplies the directory entry to validate. FilePath - Supplies the full path name for the directory entry. RecoverAlloc - Supplies whether or not to recover all allocated space on the volume. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not an error has occurred during check only mode. FatBitMap - Supplies a bitmap marking in use all known clusters. CrossLinkDetected - Returns TRUE if the file is cross-linked with another. CrossLinkPreviousCluster - Returns the cluster previous to the cross-linked one. Return Value: FALSE - Failure. TRUE - Success. --*/ { ULONG start_clus; BOOLEAN changes; ULONG length; ULONG min_file_size; ULONG max_file_size; ULONG clus; BIG_INT tmp_big_int; ULONG file_size; ULONG cluster_size; BOOLEAN recover_status; DebugAssert(CrossLinkDetected); DebugAssert(CrossLinkPreviousCluster); *CrossLinkDetected = FALSE; if (Dirent->IsErased()) { return TRUE; } cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster(); // Don't validate names or time stamps anymore. #if 0 if (!Dirent->IsValidName()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_INVALID_NAME); Message->Display("%W", FilePath); Dirent->SetErased(); return TRUE; } if (!Dirent->IsValidTimeStamp()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_INVALID_TIME_STAMP); Message->Display("%W", FilePath); if (!Dirent->SetTimeStamp()) { return FALSE; } } #endif if (Dirent->IsDirectory() && Dirent->QueryFileSize()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_DIR_HAS_FILESIZE); Message->Display("%W", FilePath); Dirent->SetFileSize( 0 ); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } if ((start_clus = Dirent->QueryStartingCluster()) != 0 ) { if (!_fat->IsInRange(start_clus) || _fat->IsClusterFree(start_clus)) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_FIRST_UNIT); Message->Display("%W", FilePath); Dirent->SetErased(); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; return TRUE; } if (Dirent->IsDirectory() || RecoverAlloc) { _fat->ScrubChain(start_clus, &changes); if (changes) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_LINK); Message->Display("%W", FilePath); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } // // Validate the readability of the directory or file // in the case that 'RecoverAlloc' is TRUE. // if (Dirent->IsDirectory()) { if (!(recover_status = RecoverChain(&start_clus, &changes))) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else if (FixLevel != CheckOnly) { // If we check the recover status for directory, why shouldn't we check // the recover status for file also? (I added the following check.) if (!(recover_status = RecoverChain(&start_clus, &changes, 0, TRUE))) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else { recover_status = TRUE; changes = FALSE; } if (changes) { *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; dofmsg(Message, NeedErrorsMessage); if (Dirent->IsDirectory()) { if (!start_clus) { Message->Set(MSG_CHK_BAD_DIR); Message->Display("%W", FilePath); Dirent->SetErased(); return TRUE; } else { Message->Set(MSG_CHK_BAD_CLUSTERS_IN_DIR); Message->Display("%W", FilePath); Dirent->SetStartingCluster(start_clus); } } else { // In the file case, since we're replacing bad clusters // with new ones, start_clus cannot be zero. DebugAssert(start_clus); if (recover_status) { Message->Set(MSG_CHK_BAD_CLUSTERS_IN_FILE_SUCCESS); Message->Display("%W", FilePath); } else { Message->Set(MSG_CHK_BAD_CLUSTERS_IN_FILE_FAILURE); Message->Display(); } Dirent->SetStartingCluster(start_clus); } } } _fat->ScrubChain(start_clus, FatBitMap, &changes, CrossLinkDetected, CrossLinkPreviousCluster); if (changes) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_LINK); Message->Display("%W", FilePath); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } // Note here that we know here that start_clus != 0 so length will be // at least 1. tmp_big_int = length = _fat->QueryLengthOfChain(start_clus); tmp_big_int = tmp_big_int * cluster_size; if (tmp_big_int.GetHighPart()) { if ((tmp_big_int.GetHighPart() != 1) || tmp_big_int.GetLowPart()) { // // Cluster chain is > 4GB in size, error. Max allowed is 4GB worth // of clusters. Note that since cluster size is a power of 2 (since // sec/clus and sector_size are both powers of 2) we KNOW that cluster_size // evenly divides 4GB. // clus = start_clus; tmp_big_int = cluster_size; while(tmp_big_int.GetHighPart() == 0) { clus = _fat->QueryEntry(clus); tmp_big_int += cluster_size; } _fat->SetEndOfChain(clus); // This message is not exactly correct, but saying that the file size // is messed up is not totally unreasonable.......... dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_FILE_SIZE); Message->Display("%W", FilePath); Dirent->SetFileSize(0xFFFFFFFF); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } max_file_size = 0xFFFFFFFF; min_file_size = (0xFFFFFFFF - cluster_size) + 2; } else { max_file_size = tmp_big_int.GetLowPart(); min_file_size = (max_file_size - cluster_size) + 1; } if (( file_size = Dirent->QueryFileSize()) != 0 ) { if (file_size < min_file_size || file_size > max_file_size) { // // Note that no message is displayed if the // file size is less than the allocation--it // is just silently corrected. // if (file_size > max_file_size) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_FILE_SIZE); Message->Display("%W", FilePath); } Dirent->SetFileSize(max_file_size); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } } else { if (!Dirent->IsDirectory()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_FILE_SIZE); Message->Display("%W", FilePath); Dirent->SetFileSize(max_file_size); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } } } else { if (Dirent->IsDirectory() && !Dirent->IsDotDot()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_LINK); Message->Display("%W", FilePath); Dirent->SetErased(); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; return TRUE; } if (Dirent->QueryFileSize()) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_BAD_FILE_SIZE); Message->Display("%W", FilePath); Dirent->SetFileSize(0); *ExitStatus = CHKDSK_EXIT_ERRS_FIXED; } } return TRUE; } BOOLEAN FAT_SA::EraseEaHandle( IN PEA_INFO EaInfos, IN USHORT NumEasLeft, IN USHORT NumEas, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message ) /*++ Routine Description: This routine erases the EA handle that references ea set beyond the number of ea sets that should be left. Arguments: EaInfos - Supplies the list of current EA information. NumEasLeft - Supplies the number of EA sets that should be in EaInfos. NumEas - Supplies the total number of EA sets. FixLevel - Supplies the fix up level. Message - Supplies an outlet for messages. Return Value: FALSE - Failure. TRUE - Success. --*/ { HMEM hmem; FILEDIR filedir; FAT_DIRENT other_dirent; USHORT i; for (i=NumEasLeft; i<NumEas; i++) { if (EaInfos[i].UserFileEntryCn) { if (!hmem.Initialize() || !filedir.Initialize(&hmem, _drive, this, _fat, EaInfos[i].UserFileEntryCn) || !filedir.Read() || !other_dirent.Initialize(filedir.GetDirEntry( EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else { if (!other_dirent.Initialize(_dir->GetDirEntry( // Default _dir works because FAT 32 won't have EA's on it to validate EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) { return FALSE; } } // // Do not follow an EA link to an LFN entry. Zeroing the EA handle in an LFN entry // destroys name data. The link is probably just invalid // if (!other_dirent.IsLongNameEntry()) { other_dirent.SetEaHandle(0); if (EaInfos[i].UserFileEntryCn && FixLevel != CheckOnly && !filedir.Write()) { return FALSE; } } } return TRUE; } BOOLEAN FAT_SA::ValidateEaHandle( IN OUT PFAT_DIRENT Dirent, IN ULONG DirClusterNumber, IN ULONG DirEntryNumber, IN OUT PEA_INFO EaInfos, IN USHORT NumEas, IN PCWSTRING FilePath, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine validates the EA handle in the directory entry 'Dirent'. It ensures that it references an actual EA set. It also ensures that it is the only directory entry which references the EA set. If several entries try to reference the same EA set then ties will be broken based on the 'OwnerFileName' entry in the EA set. Arguments: Dirent - Supplies the directory entry to validate. DirClusterNumber - Supplies the cluster number of the directory containing the dirent. DirEntryNumber - Supplies the position of the directory entry in the directory. EaInfos - Supplies the list of current EA information. NumEas - Supplies the number of EA sets. FilePath - Supplies the full path name for the directory entry. FixLevel - Supplies the fix up level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not an error has occurred during check only mode. Return Value: FALSE - Failure. TRUE - Success. --*/ { ULONG i; USHORT handle; DSTRING wfilename; STR filename[14]; BOOLEAN remove_other_handle; HMEM hmem; FILEDIR filedir; FAT_DIRENT other_dirent; if (!(handle = Dirent->QueryEaHandle())) { return TRUE; } // The above should exclude any FAT 32 drive. if (!EaInfos) { NumEas = 0; } for (i = 0; i < NumEas; i++) { if (handle == EaInfos[i].OwnHandle) { break; } } if (i == NumEas) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_UNRECOG_EA_HANDLE); Message->Display("%W", FilePath); Dirent->SetEaHandle(0); return TRUE; } if (EaInfos[i].UsedCount >= 2) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_SHARED_EA); Message->Display("%W", FilePath); Dirent->SetEaHandle(0); return TRUE; } Dirent->QueryName(&wfilename); if (!wfilename.QuerySTR( 0, TO_END, filename, 14)) { return FALSE; } if (EaInfos[i].UsedCount == 0) { memcpy(EaInfos[i].UserFileName, filename, 14); EaInfos[i].UserFileEntryCn = DirClusterNumber; EaInfos[i].UserFileEntryNumber = DirEntryNumber; EaInfos[i].UsedCount = 1; return TRUE; } // UsedCount == 1. remove_other_handle = FALSE; if (!strcmp(filename, EaInfos[i].OwnerFileName)) { remove_other_handle = TRUE; if (!strcmp(EaInfos[i].UserFileName, EaInfos[i].OwnerFileName)) { EaInfos[i].UsedCount = 2; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_SHARED_EA); Message->Display("%W", FilePath); Dirent->SetEaHandle(0); } } else { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_SHARED_EA); Message->Display("%W", FilePath); Dirent->SetEaHandle(0); if (strcmp(EaInfos[i].UserFileName, EaInfos[i].OwnerFileName)) { EaInfos[i].UsedCount = 2; remove_other_handle = TRUE; } } if (remove_other_handle) { if (EaInfos[i].UserFileEntryCn) { if (!hmem.Initialize() || !filedir.Initialize(&hmem, _drive, this, _fat, EaInfos[i].UserFileEntryCn) || !filedir.Read() || !other_dirent.Initialize(filedir.GetDirEntry( EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } } else { if (!other_dirent.Initialize(_dir->GetDirEntry( // Default _dir works because FAT 32 won't have EA's on it to validate EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) { return FALSE; } } dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_SHARED_EA); Message->Display("%W", FilePath); // // Do not follow an EA link to an LFN entry. Zeroing the EA handle in an LFN entry // destroys name data. The link is probably just invalid // if (!other_dirent.IsLongNameEntry()) { other_dirent.SetEaHandle(0); if (EaInfos[i].UserFileEntryCn && FixLevel != CheckOnly && !filedir.Write()) { return FALSE; } } strcpy(EaInfos[i].UserFileName, filename); EaInfos[i].UserFileEntryCn = DirClusterNumber; EaInfos[i].UserFileEntryNumber = DirEntryNumber; } return TRUE; } BOOLEAN FAT_SA::CopyClusters( IN ULONG SourceChain, OUT PULONG DestChain, IN OUT PBITVECTOR FatBitMap, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message ) /*++ Routine Description: This routine copies the cluster chain beginning at 'SourceChain' to a free portion of the disk. The beginning of the copied chain will be returned in 'DestChain'. If there isn't enough free space on the disk to copy the chain then 'DestChain' will return 0. Arguments: SourceChain - Supplies the chain to copy. DestChain - Returns the copy of the chain. FatBitMap - Supplies the orphan and cross-link bitmap. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages Return Value: FALSE - Failure. TRUE - Success. --*/ { HMEM hmem; CLUSTER_CHAIN cluster; ULONG src, dst; BOOLEAN changes; ULONG clus; if (!hmem.Initialize()) { return FALSE; } if (!(*DestChain = _fat->AllocChain( _fat->QueryLengthOfChain(SourceChain)))) { return TRUE; } changes = FALSE; if (FixLevel != CheckOnly && !RecoverChain(DestChain, &changes, 0, TRUE)) { if (*DestChain) { _fat->FreeChain(*DestChain); } *DestChain = 0; return TRUE; } if (IsCompressed() && !AllocSectorsForChain(*DestChain)) { _fat->FreeChain(*DestChain); *DestChain = 0; return TRUE; } // Mark the new chain as "used" in the FAT bitmap. for (clus = *DestChain; !_fat->IsEndOfChain(clus); clus = _fat->QueryEntry(clus)) { FatBitMap->SetBit(clus); } FatBitMap->SetBit(clus); src = SourceChain; dst = *DestChain; for (;;) { if (!cluster.Initialize(&hmem, _drive, this, _fat, src, 1)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } cluster.Read(); if (!cluster.Initialize(&hmem, _drive, this, _fat, dst, 1)) { return FALSE; } if (FixLevel != CheckOnly && !cluster.Write()) { return FALSE; } if (_fat->IsEndOfChain(src)) { break; } src = _fat->QueryEntry(src); dst = _fat->QueryEntry(dst); } return TRUE; } BOOLEAN FAT_SA::PurgeEaFile( IN PEA_INFO EaInfos, IN USHORT NumEas, IN OUT PBITVECTOR FatBitMap, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage ) /*++ Routine Description: This routine is executed after the directory tree is walked. Stored, in the EaInfos array, is information concerning which EAs get used and by how many files. If an EA set is not used, or is used by more than one file, then this routine will eliminate it from the EA file. Arguments: EaInfos - Supplies an array of EA information. NumEas - Supplies the number of EA sets. FatBitMap - Supplies the FAT cross-link detection bitmap. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not an error has occured in check only mode. Return Value: FALSE - Failure. TRUE - Success. --*/ { LONG i; EA_SET easet; HMEM hmem; PEA_HDR eahdr; ULONG clus; if (!hmem.Initialize()) { return FALSE; } for (i = NumEas - 1; i >= 0; i--) { if (EaInfos[i].UsedCount != 1) { dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_UNUSED_EA_SET); Message->Display("%d", EaInfos[i].OwnHandle); // Mark the FAT entries of the removed chain as "not claimed", // for the purposes of orphan recovery. for (clus = _fat->QueryEntry(EaInfos[i].PreceedingCn); clus != EaInfos[i].LastCn; clus = _fat->QueryEntry(clus)) { FatBitMap->ResetBit(clus); } FatBitMap->ResetBit(clus); // // Remove the unused EA chain from the EA file. Here we also // have to examine subsequent EaInfos; we may have to modify // several PreceedingCn entries if several adjacent EA chains // have been removed. // _fat->RemoveChain(EaInfos[i].PreceedingCn, EaInfos[i].LastCn); for (LONG j = i + 2; j < NumEas; j++) { if (EaInfos[j].PreceedingCn == EaInfos[i + 1].PreceedingCn) { EaInfos[j].PreceedingCn = EaInfos[i].PreceedingCn; } else { break; } } EaInfos[i + 1].PreceedingCn = EaInfos[i].PreceedingCn; } else if (strcmp(EaInfos[i].OwnerFileName, EaInfos[i].UserFileName)) { if (!easet.Initialize(&hmem, _drive, this, _fat, _fat->QueryEntry(EaInfos[i].PreceedingCn), 1) || !easet.Read() || !(eahdr = easet.GetEaSetHeader())) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_NEW_OWNER_NAME); Message->Display("%d%s%s", EaInfos[i].OwnHandle, eahdr->OwnerFileName, EaInfos[i].UserFileName); memcpy(eahdr->OwnerFileName, EaInfos[i].UserFileName, 14); if (FixLevel != CheckOnly && !easet.Write()) { return FALSE; } } } return TRUE; } BOOLEAN FAT_SA::RecoverOrphans( IN OUT PBITVECTOR FatBitMap, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message, IN OUT PBOOLEAN NeedErrorsMessage, IN OUT PFATCHK_REPORT Report, OUT PBOOLEAN Changes ) /*++ Routine Description: This routine examines the file system for cluster chains which are not claimed by any file. These 'orphans' will then be recovered in a subdirectory of the root or removed from the system. Arguments: FatBitMap - Supplies a bit map marking all currently used clusters. FixLevel - Supplies the CHKDSK fix level. Message - Supplies an outlet for messages. NeedErrorsMessage - Supplies whether or not an error has occured in check only mode. Return Value: FALSE - Failure. TRUE - Success. --*/ { // // Why the below define placing an artificial limit on the number of orphans? // 1.) The format for the file names is "FILE%04d.CHK" starting at 0 so we can // do only 0-9999 before generating a duplicate file name. // 2.) Since CHKDSK recovers all of the orphans into a single directory this prevents // it from making a directory with a HUGE file count in it (which is a performance // issue). // #if defined( _AUTOCHECK_ ) || defined( _EFICHECK_ ) // Due to memory constraints, the maximum number of orphans to // recover is less for Autochk than for run-time Chkdsk. // // BUG BUG this is the old setting for this, the above comment makes no // sense because there is no in memory allocation that I can find // which is effected by this setting. This may have been a HACK fix // for an overflow of the memory heap (which is fatal when there // is no paging file). This problem no longer exists because of // the paging memory heap tracking that has been added to AUTOCHK. // ARR // // CONST ULONG maximum_orphans = 1000; // CONST ULONG maximum_orphans = 10000; #else CONST ULONG maximum_orphans = 10000; #endif ULONG i; ULONG clus; BOOLEAN changes; HMEM hmem; FILEDIR found_dir; STR found_name[14]; DSTRING wfound_name; STR filename[14]; FAT_DIRENT dirent; ULONG found_cluster; ULONG orphan_count; ULONG orphan_rec_clus_cnt; ULONG cluster_size; ULONG found_length; ULONG next; PUCHAR orphan_track; ULONG cluster_count; ULONG num_orphans; ULONG num_orphan_clusters; DSTRING tmp_string; BITVECTOR tmp_bitvector; BOOLEAN tmp_bool; ULONG tmp_ulong; BIG_INT tmp_big_int; MSGID message_id; BOOLEAN KSize; cluster_count = QueryClusterCount(); if (!(orphan_track = NEW UCHAR[cluster_count])) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } memset(orphan_track, 0, cluster_count); if (!tmp_bitvector.Initialize(cluster_count)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster(); num_orphans = 0; num_orphan_clusters = 0; for (i = FirstDiskCluster; _fat->IsInRange(i); i++) { if (!_fat->IsClusterFree(i) && !FatBitMap->IsBitSet(i) && !_fat->IsClusterBad(i) && !_fat->IsClusterReserved(i)) { num_orphans++; tmp_bitvector.ResetAll(); _fat->ScrubChain(i, &tmp_bitvector, &changes, &tmp_bool, &tmp_ulong); if (changes) { *Changes = TRUE; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_BAD_LINKS_IN_ORPHANS); Message->Display("%d", i); } num_orphan_clusters++; clus = i; while (!_fat->IsEndOfChain(clus)) { next = _fat->QueryEntry(clus); if (orphan_track[next] == 1) { num_orphans--; orphan_track[next] = 2; break; } if (FatBitMap->IsBitSet(next)) { // CROSSLINK !! *Changes = TRUE; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CHK_CROSS_LINKED_ORPHAN); Message->Display("%d", clus); _fat->SetEndOfChain(clus); break; } num_orphan_clusters++; FatBitMap->SetBit(next); orphan_track[next] = 2; clus = next; } FatBitMap->SetBit(i); orphan_track[i] = 1; } } // Now scan through the secondary pointers in search of orphans. changes = FALSE; for (i = FirstDiskCluster; _fat->IsInRange(i); i++) { if (orphan_track[i]) { changes = TRUE; break; } } if (!changes) { // No orphans to recover. return TRUE; } // Compute whether reporting size in bytes or kilobytes // // NOTE: The magic number 4095MB comes from Win9x's GUI SCANDISK utility // tmp_ulong = cluster_count - FirstDiskCluster; tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * tmp_ulong; if (tmp_big_int.GetHighPart() || (tmp_big_int.GetLowPart() > (4095ul*1024ul*1024ul))) { KSize = TRUE; } else { KSize = FALSE; } *Changes = TRUE; dofmsg(Message, NeedErrorsMessage); Message->Set(MSG_CONVERT_LOST_CHAINS, NORMAL_MESSAGE, TEXT_MESSAGE); Message->Display(); if (!Message->IsYesResponse(TRUE)) { if (FixLevel != CheckOnly) { for (i = FirstDiskCluster; _fat->IsInRange(i); i++) { if (orphan_track[i] == 1) { _fat->FreeChain(i); } } if (KSize) { message_id = MSG_KILOBYTES_FREED; } else { message_id = MSG_BYTES_FREED; } } else { if (KSize) { message_id = MSG_KILOBYTES_WOULD_BE_FREED; } else { message_id = MSG_BYTES_WOULD_BE_FREED; } } tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * num_orphan_clusters; if (KSize) { tmp_ulong = (tmp_big_int / 1024ul).GetLowPart(); } else { tmp_ulong = tmp_big_int.GetLowPart(); } Message->Set(message_id); Message->Display("%d", tmp_ulong); return TRUE; } // Set up for orphan recovery. // Establish "FOUND.XXX" directory. for (i = 0; i < 1000; i++) { sprintf(found_name, "FOUND.%03d", i); if (!wfound_name.Initialize(found_name)) { return FALSE; } if (_dir && !_dir->SearchForDirEntry(&wfound_name)) { break; } else if (_dirF32 && !_dirF32->SearchForDirEntry(&wfound_name)) { break; } } if (i == 1000) { tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * num_orphan_clusters; if (KSize) { tmp_ulong = (tmp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES; } else { tmp_ulong = tmp_big_int.GetLowPart(); message_id = MSG_WOULD_BE_RECOVERED_FILES; } Message->Set(message_id); Message->Display("%d%d", tmp_ulong, num_orphans); return TRUE; } found_length = ((min(num_orphans,maximum_orphans)*BytesPerDirent - 1)/cluster_size + 1); if (!(found_cluster = _fat->AllocChain(found_length)) && !(found_cluster = _fat->AllocChain(found_length = 1))) { Message->Set(MSG_ORPHAN_DISK_SPACE); Message->Display(); tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * num_orphan_clusters; if (KSize) { tmp_ulong = (tmp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES; } else { tmp_ulong = tmp_big_int.GetLowPart(); message_id = MSG_WOULD_BE_RECOVERED_FILES; } Message->Set(message_id); Message->Display("%d%d", tmp_ulong, num_orphans); return TRUE; } // Check the chain. changes = FALSE; if (FixLevel != CheckOnly && !RecoverChain(&found_cluster, &changes, 0, TRUE)) { Message->Set(MSG_ORPHAN_DISK_SPACE); Message->Display(); Message->Set(MSG_WOULD_BE_RECOVERED_FILES); Message->Display("%d%d", cluster_size*num_orphan_clusters, num_orphans); return TRUE; } if (!hmem.Initialize() || !found_dir.Initialize(&hmem, _drive, this, _fat, found_cluster)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); DebugAbort( "Initialization failed" ); return FALSE; } // Allocate space for the cluster chain in the sector heap (fat_db) if (IsCompressed() && !AllocSectorsForChain(found_cluster)) { _fat->FreeChain(found_cluster); Message->Set(MSG_ORPHAN_DISK_SPACE); Message->Display(); return TRUE; } memset(hmem.GetBuf(), 0, (UINT) hmem.QuerySize()); PFATDIR _fat_dir; UCHAR FatType; if (_dir) { _fat_dir = _dir; FatType = FAT_TYPE_EAS_OKAY; } else { _fat_dir = _dirF32; FatType = FAT_TYPE_FAT32; } if (!dirent.Initialize(_fat_dir->GetFreeDirEntry(),FatType)) { Message->Set(MSG_NO_ROOM_IN_ROOT); Message->Display(); Message->Set(MSG_WOULD_BE_RECOVERED_FILES); Message->Display("%d%d", cluster_size*num_orphan_clusters, num_orphans); return TRUE; } dirent.Clear(); if (!dirent.SetName(&wfound_name)) { return FALSE; } dirent.SetDirectory(); if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() || !dirent.SetLastAccessTime()) { return FALSE; } dirent.SetStartingCluster(found_cluster); if(_dirF32) { if (FixLevel != CheckOnly && !_dirF32->Write()) { return FALSE; } } if (!dirent.Initialize(found_dir.GetDirEntry(0),FatType)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } dirent.Clear(); if (!tmp_string.Initialize(".")) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!dirent.SetName(&tmp_string)) { return FALSE; } dirent.SetDirectory(); if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() || !dirent.SetLastAccessTime()) { return FALSE; } dirent.SetStartingCluster(found_cluster); if (!dirent.Initialize(found_dir.GetDirEntry(1),FatType)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } dirent.Clear(); if (!tmp_string.Initialize("..")) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } if (!dirent.SetName(&tmp_string)) { return FALSE; } dirent.SetDirectory(); if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() || !dirent.SetLastAccessTime()) { return FALSE; } dirent.SetStartingCluster(0); // OK, now let's recover those orphans. orphan_rec_clus_cnt = orphan_count = 0; for (i = FirstDiskCluster; _fat->IsInRange(i); i++) { if (orphan_track[i] != 1) { continue; } if (orphan_count == maximum_orphans) { Message->Set(MSG_TOO_MANY_ORPHANS); Message->Display(); break; } if (!dirent.Initialize(found_dir.GetFreeDirEntry(), FatType)) { if (_fat->ReAllocChain(found_cluster, ++found_length) != found_length) { Message->Set(MSG_ORPHAN_DISK_SPACE); Message->Display(); tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * num_orphan_clusters; if (KSize) { tmp_ulong = (tmp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES; } else { tmp_ulong = tmp_big_int.GetLowPart(); message_id = MSG_WOULD_BE_RECOVERED_FILES; } Message->Set(message_id); Message->Display("%d%d", tmp_ulong, num_orphans); break; } //XXX: FATDB: need to get sectors for found_cluster + realloc. changes = FALSE; if (FixLevel != CheckOnly && !RecoverChain(&found_cluster, &changes, 0, TRUE)) { Message->Set(MSG_ORPHAN_DISK_SPACE); Message->Display(); tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * num_orphan_clusters; if (KSize) { tmp_ulong = (tmp_big_int / 1024ul).GetLowPart(); message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES; } else { tmp_ulong = tmp_big_int.GetLowPart(); message_id = MSG_WOULD_BE_RECOVERED_FILES; } Message->Set(message_id); Message->Display("%d%d", tmp_ulong, num_orphans); return TRUE; } if (FixLevel != CheckOnly && !found_dir.Write()) { return FALSE; } if (!hmem.Initialize() || !found_dir.Initialize(&hmem, _drive, this, _fat, found_cluster) || !found_dir.Read()) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); Message->Set(MSG_WOULD_BE_RECOVERED_FILES); Message->Display("%d%d", cluster_size*num_orphan_clusters, num_orphans); return TRUE; } if (!dirent.Initialize(found_dir.GetDirEntry(2 + orphan_count), FatType)) { return FALSE; } dirent.SetEndOfDirectory(); if (!dirent.Initialize(found_dir.GetFreeDirEntry(),FatType)) { return FALSE; } } sprintf(filename, "FILE%04d.CHK", orphan_count); if (!tmp_string.Initialize(filename)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); return FALSE; } dirent.Clear(); if (!dirent.SetName(&tmp_string)) { return FALSE; } if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() || !dirent.SetLastAccessTime()) { return FALSE; } dirent.SetStartingCluster(i); dirent.SetFileSize(cluster_size*_fat->QueryLengthOfChain(i)); orphan_count++; orphan_rec_clus_cnt += _fat->QueryLengthOfChain(i); } // Set all dirents past the orphan count to end of directory. for (i = 2 + orphan_count; dirent.Initialize(found_dir.GetDirEntry(i),FatType); i++) { dirent.SetEndOfDirectory(); } if (FixLevel != CheckOnly && !found_dir.Write()) { return FALSE; } if(FixLevel == CheckOnly) { if (KSize) { message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES; } else { message_id = MSG_WOULD_BE_RECOVERED_FILES; } } else { if (KSize) { message_id = MSG_KILOBYTES_IN_RECOVERED_FILES; } else { message_id = MSG_RECOVERED_FILES; } // Add the recovered data to the report totals Report->FileClusters += orphan_rec_clus_cnt; Report->FileEntriesCount += orphan_count; Report->DirClusters += found_length; Report->DirEntriesCount++; } tmp_big_int = cluster_size; tmp_big_int = tmp_big_int * num_orphan_clusters; if (KSize) { tmp_ulong = (tmp_big_int / 1024ul).GetLowPart(); } else { tmp_ulong = tmp_big_int.GetLowPart(); } Message->Set(message_id); Message->Display("%d%d", tmp_ulong, num_orphans); return TRUE; } BOOLEAN FAT_SA::AllocSectorsForChain( ULONG ChainHead ) /*++ Routine Description: When VerifyAndFix needs to allocate a cluster chain in order to create a new directory (such as \FOUND.000), it also needs to allocate space in the sector heap for data blocks for those clusters. This routine does that. Arguments: ChainHead - a cluster chain; data blocks are allocated for each cluster in this chain. Return Value: TRUE - Success. FALSE - Failure - not enough disk space --*/ { ULONG clus; ULONG next; clus = ChainHead; for (;;) { if (!AllocateClusterData(clus, (UCHAR)QuerySectorsPerCluster(), FALSE, (UCHAR)QuerySectorsPerCluster())) { break; } if (_fat->IsEndOfChain(clus)) { return TRUE; } clus = _fat->QueryEntry(clus); } // Error: not enough disk space. XXX // Free the sectors we already allocated while (ChainHead != clus) { FreeClusterData(ChainHead); next = _fat->QueryEntry(ChainHead); _fat->SetClusterFree(ChainHead); ChainHead = next; } return FALSE; } #if defined( _SETUP_LOADER_ ) BOOLEAN FAT_SA::RecoverFreeSpace( IN OUT PMESSAGE Message ) { return TRUE; } #else // _SETUP_LOADER_ not defined BOOLEAN FAT_SA::RecoverFreeSpace( IN OUT PMESSAGE Message ) /*++ Routine Description: This routine checks all of the space marked free in the FAT for bad clusters. If any clusters are bad they are marked bad in the FAT. Arguments: Message - Supplies an outlet for messages. Return Value: FALSE - Failure. TRUE - Success. --*/ { ULONG clus, length, max_length; ULONG start_sector, num_sectors, i; NUMBER_SET bad_sectors; LBN lbn; ULONG percent_complete; ULONG num_checked, total_to_check; Message->Set(MSG_CHK_RECOVERING_FREE_SPACE, PROGRESS_MESSAGE); Message->Display(); _pvfMessage = Message; percent_complete = 0; if(!DisplayTwnkPercent(percent_complete)) { _pvfMessage = NULL; return FALSE; } num_checked = 0; total_to_check = _fat->QueryFreeClusters(); max_length = QueryClusterCount()/20 + 1; for (clus = FirstDiskCluster; _fat->IsInRange(clus); clus++) { for (length = 0; _fat->IsInRange(clus + length) && _fat->IsClusterFree(clus + length) && length < max_length; length++) { } if (length) { start_sector = QueryStartDataLbn() + (clus - FirstDiskCluster)*QuerySectorsPerCluster(); num_sectors = length*QuerySectorsPerCluster(); if (!bad_sectors.Initialize() || !_drive->Verify(start_sector, num_sectors, &bad_sectors)) { Message->Set(MSG_CHK_NO_MEMORY); Message->Display(); _pvfMessage = NULL; return FALSE; } for (i = 0; i < bad_sectors.QueryCardinality(); i++) { lbn = bad_sectors.QueryNumber(i).GetLowPart(); _fat->SetClusterBad(((lbn - QueryStartDataLbn())/ QuerySectorsPerCluster()) + FirstDiskCluster ); } clus += length - 1; num_checked += length; if (100*num_checked/total_to_check > percent_complete) { percent_complete = 100*num_checked/total_to_check; } if (!DisplayTwnkPercent(percent_complete)) { _pvfMessage = NULL; return FALSE; } } } percent_complete = 100; if(!DisplayTwnkPercent(percent_complete)) { _pvfMessage = NULL; return FALSE; } Message->Set(MSG_CHK_DONE_RECOVERING_FREE_SPACE, PROGRESS_MESSAGE); Message->Display(); _pvfMessage = NULL; return TRUE; } #endif // _SETUP_LOADER_
30.204065
122
0.505008
npocmaka
0e29b84f026b3e180267054aae52b43a0e3814a4
4,921
cc
C++
src/ui/scenic/lib/scheduling/delegating_frame_scheduler.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/ui/scenic/lib/scheduling/delegating_frame_scheduler.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/ui/scenic/lib/scheduling/delegating_frame_scheduler.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 "src/ui/scenic/lib/scheduling/delegating_frame_scheduler.h" #include "src/lib/fxl/logging.h" #include "src/ui/scenic/lib/scheduling/id.h" namespace scheduling { DelegatingFrameScheduler::DelegatingFrameScheduler( std::shared_ptr<FrameScheduler> frame_scheduler) { if (frame_scheduler) { SetFrameScheduler(frame_scheduler); } } void DelegatingFrameScheduler::SetFrameRenderer(fxl::WeakPtr<FrameRenderer> frame_renderer) { CallWhenFrameSchedulerAvailable( [frame_renderer = frame_renderer](FrameScheduler* frame_scheduler) { frame_scheduler->SetFrameRenderer(frame_renderer); }); }; void DelegatingFrameScheduler::AddSessionUpdater(fxl::WeakPtr<SessionUpdater> session_updater) { CallWhenFrameSchedulerAvailable( [session_updater = session_updater](FrameScheduler* frame_scheduler) { frame_scheduler->AddSessionUpdater(session_updater); }); }; void DelegatingFrameScheduler::SetRenderContinuously(bool render_continuously) { CallWhenFrameSchedulerAvailable([render_continuously](FrameScheduler* frame_scheduler) { frame_scheduler->SetRenderContinuously(render_continuously); }); } PresentId DelegatingFrameScheduler::RegisterPresent( SessionId session_id, std::variant<OnPresentedCallback, Present2Info> present_information, std::vector<zx::event> release_fences, PresentId present_id) { // Assuming we never have several levels of delegating frame schedulers |present_id| should never // be set. FXL_CHECK(present_id == kInvalidPresentId); present_id = scheduling::GetNextPresentId(); CallWhenFrameSchedulerAvailable([session_id, present_information = std::move(present_information), release_fences = std::move(release_fences), present_id](FrameScheduler* frame_scheduler) mutable { frame_scheduler->RegisterPresent(session_id, std::move(present_information), std::move(release_fences), present_id); }); return present_id; } void DelegatingFrameScheduler::SetOnUpdateFailedCallbackForSession( SessionId session_id, FrameScheduler::OnSessionUpdateFailedCallback update_failed_callback) { CallWhenFrameSchedulerAvailable([session_id, callback = std::move(update_failed_callback)]( FrameScheduler* frame_scheduler) mutable { frame_scheduler->SetOnUpdateFailedCallbackForSession(session_id, std::move(callback)); }); } void DelegatingFrameScheduler::ScheduleUpdateForSession(zx::time presentation_time, SchedulingIdPair id_pair) { CallWhenFrameSchedulerAvailable([presentation_time, id_pair](FrameScheduler* frame_scheduler) { frame_scheduler->ScheduleUpdateForSession(presentation_time, id_pair); }); } void DelegatingFrameScheduler::GetFuturePresentationInfos( zx::duration requested_prediction_span, GetFuturePresentationInfosCallback callback) { FXL_DCHECK(callback); CallWhenFrameSchedulerAvailable([requested_prediction_span, callback = std::move(callback)]( FrameScheduler* frame_scheduler) mutable { frame_scheduler->GetFuturePresentationInfos(requested_prediction_span, std::move(callback)); }); } void DelegatingFrameScheduler::SetOnFramePresentedCallbackForSession( SessionId session, OnFramePresentedCallback callback) { if (callback) { CallWhenFrameSchedulerAvailable( [session, callback = std::move(callback)](FrameScheduler* frame_scheduler) mutable { frame_scheduler->SetOnFramePresentedCallbackForSession(session, std::move(callback)); }); } } void DelegatingFrameScheduler::RemoveSession(SessionId session_id) { CallWhenFrameSchedulerAvailable([session_id](FrameScheduler* frame_scheduler) { frame_scheduler->RemoveSession(session_id); }); } void DelegatingFrameScheduler::CallWhenFrameSchedulerAvailable( OnFrameSchedulerAvailableCallback callback) { if (frame_scheduler_) { callback(frame_scheduler_.get()); } else { call_when_frame_scheduler_available_callbacks_.push_back(std::move(callback)); } } void DelegatingFrameScheduler::SetFrameScheduler( const std::shared_ptr<FrameScheduler>& frame_scheduler) { if (frame_scheduler_) { FXL_LOG(ERROR) << "DelegatingFrameScheduler can only be set once."; return; } if (!frame_scheduler) { FXL_LOG(ERROR) << "DelegatingFrameScheduler cannot be set to a null value."; return; } frame_scheduler_ = frame_scheduler; for (auto& callback : call_when_frame_scheduler_available_callbacks_) { callback(frame_scheduler_.get()); } call_when_frame_scheduler_available_callbacks_.clear(); } } // namespace scheduling
40.336066
100
0.751473
casey
0e29f093b5e8e8bdd82feb66c1a8e7d67c0e2a89
3,267
cpp
C++
dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
1
2019-02-06T19:12:41.000Z
2019-02-06T19:12:41.000Z
dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
null
null
null
dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzCore/Serialization/SerializeContext.h> #include "EMotionFXConfig.h" #include "BlendTreeConnection.h" #include <MCore/Source/IDGenerator.h> #include "AnimGraphNode.h" #include "AnimGraph.h" namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(BlendTreeConnection, AnimGraphAllocator, 0) BlendTreeConnection::BlendTreeConnection() : m_animGraph(nullptr) , m_sourceNode(nullptr) , mSourcePort(MCORE_INVALIDINDEX16) , mTargetPort(MCORE_INVALIDINDEX16) { mId = MCore::GetIDGenerator().GenerateID(); #ifdef EMFX_EMSTUDIOBUILD mVisited = false; #endif } BlendTreeConnection::BlendTreeConnection(AnimGraphNode* sourceNode, AZ::u16 sourcePort, AZ::u16 targetPort) : BlendTreeConnection() { if (sourceNode) { m_animGraph = sourceNode->GetAnimGraph(); } mSourcePort = sourcePort; mTargetPort = targetPort; SetSourceNode(sourceNode); } BlendTreeConnection::~BlendTreeConnection() { } void BlendTreeConnection::Reinit() { if (!m_animGraph) { return; } m_sourceNode = m_animGraph->RecursiveFindNodeById(GetSourceNodeId()); AZ_Error("EMotionFX", m_sourceNode, "Could not find node for id %s.", GetSourceNodeId().ToString().c_str()); } bool BlendTreeConnection::InitAfterLoading(AnimGraph* animGraph) { if (!animGraph) { return false; } m_animGraph = animGraph; Reinit(); return true; } void BlendTreeConnection::SetSourceNode(AnimGraphNode* node) { m_sourceNode = node; if (m_sourceNode) { m_sourceNodeId = m_sourceNode->GetId(); } } // check if this connection is valid bool BlendTreeConnection::GetIsValid() const { // make sure the node and input numbers are valid if (!m_sourceNode || mSourcePort == MCORE_INVALIDINDEX16 || mTargetPort == MCORE_INVALIDINDEX16) { return false; } // the connection is valid return true; } void BlendTreeConnection::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (!serializeContext) { return; } serializeContext->Class<BlendTreeConnection>() ->Version(1) ->Field("sourceNodeId", &BlendTreeConnection::m_sourceNodeId) ->Field("sourcePortNr", &BlendTreeConnection::mSourcePort) ->Field("targetPortNr", &BlendTreeConnection::mTargetPort); } } // namespace EMotionFX
26.346774
116
0.642485
Kezryk
0e2c76aecec8ee5d094920e5075b9b368b208575
7,992
cpp
C++
eprp/eprp.cpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
1
2022-03-09T23:29:29.000Z
2022-03-09T23:29:29.000Z
eprp/eprp.cpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
null
null
null
eprp/eprp.cpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
null
null
null
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include <ctype.h> #include <algorithm> #include "eprp.hpp" void Eprp::eat_comments() { while (scan_is_token(Token_id_comment) && !scan_is_end()) scan_next(); } // rule_path = (\. | alnum | / | "asdad.." | \,)+ bool Eprp::rule_path(std::string &path) { assert(!scan_is_end()); if (!(scan_is_token(Token_id_dot) || scan_is_token(Token_id_alnum) || scan_is_token(Token_id_string) || scan_is_token(Token_id_div))) return false; do { absl::StrAppend(&path, scan_text()); ast->add(Eprp_rule_path, scan_token()); bool ok = scan_next(); if (!ok) break; eat_comments(); if (scan_is_next_token(1, Token_id_colon)) break; // stop if file:foo is the next argument list } while (scan_is_token(Token_id_dot) || scan_is_token(Token_id_alnum) || scan_is_token(Token_id_string) || scan_is_token(Token_id_comma) || scan_is_token(Token_id_div)); return true; } // rule_label_path = label path bool Eprp::rule_label_path(const std::string &cmd_line, Eprp_var &next_var) { if (!(scan_is_token(Token_id_alnum) && scan_is_next_token(1, Token_id_colon))) return false; auto label = scan_text(); ast->add(Eprp_rule_label_path, scan_token()); scan_next(); // Skip alnum token scan_next(); // Skip colon token eat_comments(); if (scan_is_end()) { scan_error("the {} field in {} command has no argument", label, cmd_line); return false; } std::string path; ast->down(); bool ok = rule_path(path); ast->up(Eprp_rule_label_path); if (!ok) { if (scan_is_token(Token_id_register)) { scan_error("could not pass a register {} to a method {}", scan_text(), cmd_line); } else { scan_error("field {} with invalid value in {} command", label, cmd_line); } return false; } next_var.add(label, path); return true; } // rule_reg = reg+ bool Eprp::rule_reg(bool first) { if (!scan_is_token(Token_id_register)) return false; std::string var{scan_text()}; ast->add(Eprp_rule_reg, scan_token()); if (first) { // First in line #a |> ... if (variables.find(var) == variables.end()) { scan_error("variable {} is empty", var); return false; } last_cmd_var = variables[var]; } else { variables[var] = last_cmd_var; } scan_next(); eat_comments(); return true; } // rule_cmd_line = alnum (dot alnum)* bool Eprp::rule_cmd_line(std::string &path) { if (scan_is_end()) return false; if (!scan_is_token(Token_id_alnum)) return false; do { absl::StrAppend(&path, scan_text()); // Add the Token_id_alnum ast->add(Eprp_rule_cmd_line, scan_token()); bool ok1 = scan_next(); if (!ok1) break; if (!scan_is_token(Token_id_dot)) break; absl::StrAppend(&path, scan_text()); // Add the Token_id_dot ast->add(Eprp_rule_cmd_line, scan_token()); bool ok2 = scan_next(); if (!ok2) break; } while (scan_is_token(Token_id_alnum)); eat_comments(); return true; } // rule_cmd_full =rule_cmd_line rule_label_path* bool Eprp::rule_cmd_full() { std::string cmd_line; Eprp_var next_var; ast->down(); bool cmd_found = rule_cmd_line(cmd_line); ast->up(Eprp_rule_cmd_full); if (!cmd_found) return false; bool path_found; do { ast->down(); path_found = rule_label_path(cmd_line, next_var); ast->up(Eprp_rule_cmd_full); } while (path_found); ast->down(); run_cmd(cmd_line, next_var); ast->up(Eprp_rule_cmd_full); return true; } // rule_pipe = |> rule_cmd_or_reg bool Eprp::rule_pipe() { if (scan_is_end()) return false; if (!scan_is_token(Token_id_pipe)) return false; scan_next(); eat_comments(); ast->down(); bool try_either = rule_cmd_or_reg(false); ast->up(Eprp_rule_pipe); if (!try_either) { scan_error("after a pipe there should be a register or a command"); return false; } return true; } // rule_cmd_or_reg = rule_reg | rule_cmd_full bool Eprp::rule_cmd_or_reg(bool first) { ast->down(); bool try_reg_rule = rule_reg(first); ast->up(Eprp_rule_cmd_or_reg); if (try_reg_rule) return true; ast->down(); bool cmd_found = rule_cmd_full(); ast->up(Eprp_rule_cmd_or_reg); return cmd_found; } // rule_top = rule_cmd_or_reg(first) rule_pipe* bool Eprp::rule_top() { ast->down(); bool try_either = rule_cmd_or_reg(true); ast->up(Eprp_rule_top); if (!try_either) { scan_error("statements start with a register or a command"); return false; } // tree.add_lazy_child(1); bool try_pipe = rule_pipe(); if (!try_pipe) { if (scan_is_token(Token_id_or)) { scan_error("eprp pipe is |> not |"); return false; } else if (scan_is_end()) { return true; } else { scan_error("invalid command"); return false; } } // tree.add_lazy_child(1); while (rule_pipe()) { // tree.add_lazy_child(1); ; } return true; } // top = parse_top+ void Eprp::elaborate() { ast = std::make_unique<Ast_parser>(get_memblock(), Eprp_rule); ast->down(); while (!scan_is_end()) { eat_comments(); if (scan_is_end()) return; bool cmd = rule_top(); if (!cmd) return; } ast->up(Eprp_rule); //process_ast(); ast = nullptr; last_cmd_var.clear(); }; void Eprp::process_ast_handler(const mmap_lib::Tree_index &self, const Ast_parser_node &node) { auto txt = scan_text(node.token_entry); fmt::print("level:{} pos:{} te:{} rid:{} txt:{}\n", self.level, self.pos, node.token_entry, node.rule_id, txt); if (node.rule_id == Eprp_rule_cmd_or_reg) { std::string children_txt; // HERE: Children should iterate FAST, over all the children recursively // HERE: Move this iterate over children as a handle_command for (const auto &ti : ast->children(self)) { auto txt2 = scan_text(ast->get_data(ti).token_entry); if (ast->get_data(ti).rule_id == Eprp_rule_label_path) absl::StrAppend(&children_txt, " ", txt2, ":"); else absl::StrAppend(&children_txt, txt2); } fmt::print(" children: {}\n", children_txt); } } void Eprp::process_ast() { for(const auto &ti:ast->depth_preorder(ast->get_root())) { fmt::print("ti.level:{} ti.pos:{}\n", ti.level, ti.pos); } ast->each_bottom_up_fast(std::bind(&Eprp::process_ast_handler, this, std::placeholders::_1, std::placeholders::_2)); } void Eprp::run_cmd(const std::string &cmd, Eprp_var &var) { const auto &it = methods.find(cmd); if (it == methods.end()) { parser_error("method {} not registered", cmd); return; } const auto &m = it->second; last_cmd_var.add(var); std::string err_msg; bool err = m.check_labels(last_cmd_var, err_msg); if (err) { parser_error(err_msg); return; } #if 0 for(const auto &v:var.dict) { if (!m.has_label(v.first)) { parser_warn("method {} does not have passed label {}", cmd, v.first); } } #endif for (const auto &label : m.labels) { if (!label.second.default_value.empty() && !last_cmd_var.has_label(label.first)) last_cmd_var.add(label.first, label.second.default_value); } m.method(last_cmd_var); } const std::string &Eprp::get_command_help(const std::string &cmd) const { const auto &it = methods.find(cmd); if (it == methods.end()) { static const std::string empty = ""; return empty; } return it->second.help; } void Eprp::get_commands(std::function<void(const std::string &, const std::string &)> fn) const { for (const auto &v : methods) { fn(v.first, v.second.help); } } void Eprp::get_labels(const std::string & cmd, std::function<void(const std::string &, const std::string &, bool required)> fn) const { const auto &it = methods.find(cmd); if (it == methods.end()) return; for (const auto &v : it->second.labels) { fn(v.first, v.second.help, v.second.required); } } Eprp::Eprp() {}
24.145015
118
0.646021
milad621
0e2ef69313c2609d4b2d4d9e3e853a5dc38131e8
449
cpp
C++
void_data.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
void_data.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
void_data.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int a[6] = {[4] = 29, [2] = 15}; struct node { int data; node *next; node(int d) : data(d), next(NULL) {} }; int add_node(void *data) { node *n = (node *)data; cout << n->data << endl; return 0; } int main(int argc, char const *argv[]) { node *n1 = new node(1000); add_node((void *)n1); for (int i = 0; i < 6; ++i) { cout << a[i] << " "; } cout << endl; return 0; }
11.512821
38
0.514477
shirishbahirat
0e317907bb73e475fe9114aaa47362016e00f1af
6,413
cpp
C++
SuperMarioBros3/IntroScene.cpp
ThienUIT/Super-Mario-Bros-3
dc14eaa6a20b17a9ec13908e7e42947662c26005
[ "MIT" ]
3
2021-07-26T04:03:47.000Z
2021-08-31T15:17:29.000Z
SuperMarioBros3/IntroScene.cpp
ThienUIT/Super-Mario-Bros-3
dc14eaa6a20b17a9ec13908e7e42947662c26005
[ "MIT" ]
null
null
null
SuperMarioBros3/IntroScene.cpp
ThienUIT/Super-Mario-Bros-3
dc14eaa6a20b17a9ec13908e7e42947662c26005
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include "IntroScene.h" #include "Textures.h" #include "Utils.h" #include "Brick.h" #include "IntroGround.h" #include "Leaf.h" #include "MushRoom.h" #include "Goomba.h" #include "Koopas.h" using namespace std; CIntroScene::CIntroScene(int id, LPCWSTR filePath) : CScene(id, filePath) { key_handler = new IntroSceneKeyHandler(this); BackGround = nullptr; Three = nullptr; Arrow = nullptr; //StartScrolling(); } void CIntroScene::_ParseSection_TEXTURES(string line) { vector<string> tokens = split(line); if (tokens.size() < 5) return; // skip invalid lines int texID = atoi(tokens[0].c_str()); wstring path = ToWSTR(tokens[1]); int R = atoi(tokens[2].c_str()); int G = atoi(tokens[3].c_str()); int B = atoi(tokens[4].c_str()); CTextures::GetInstance()->Add(texID, path.c_str(), D3DCOLOR_XRGB(R, G, B)); } void CIntroScene::_ParseSection_SPRITES(string line) { vector<string> tokens = split(line); if (tokens.size() < 6) return; // skip invalid lines int ID = atoi(tokens[0].c_str()); int l = atoi(tokens[1].c_str()); int t = atoi(tokens[2].c_str()); int r = atoi(tokens[3].c_str()); int b = atoi(tokens[4].c_str()); int texID = atoi(tokens[5].c_str()); LPDIRECT3DTEXTURE9 tex = CTextures::GetInstance()->Get(texID); if (tex == NULL) { DebugOut(L"[ERROR] Texture ID %d not found!\n", texID); return; } CSprites::GetInstance()->Add(ID, l, t, r, b, tex); } void CIntroScene::_ParseSection_ANIMATIONS(string line) { vector<string> tokens = split(line); if (tokens.size() < 3) return; // skip invalid lines - an animation must at least has 1 frame and 1 frame time //DebugOut(L"--> %s\n",ToWSTR(line).c_str()); LPANIMATION ani = new CAnimation(); int ani_id = atoi(tokens[0].c_str()); for (unsigned int i = 1; i < tokens.size(); i += 2) // why i+=2 ? sprite_id | frame_time { int sprite_id = atoi(tokens[i].c_str()); int frame_time = atoi(tokens[i + 1].c_str()); ani->Add(sprite_id, frame_time); } CAnimations::GetInstance()->Add(ani_id, ani); if (ani_id == 800) Three = ani; } void CIntroScene::_ParseSection_ANIMATION_SETS(string line) { vector<string> tokens = split(line); if (tokens.size() < 2) return; // skip invalid lines - an animation set must at least id and one animation id //DebugOut(L"--> %s\n", ToWSTR(line).c_str()); int ani_set_id = atoi(tokens[0].c_str()); LPANIMATION_SET s; if (CAnimationSets::GetInstance()->animation_sets[ani_set_id] != NULL) s = CAnimationSets::GetInstance()->animation_sets[ani_set_id]; else s = new CAnimationSet(); CAnimations* animations = CAnimations::GetInstance(); for (unsigned int i = 1; i < tokens.size(); i++) { int ani_id = atoi(tokens[i].c_str()); LPANIMATION ani = animations->Get(ani_id); s->push_back(ani); } CAnimationSets::GetInstance()->Add(ani_set_id, s); if (ani_set_id == ANISET_BACKGROUND_ID) BackGround = s; if (ani_set_id == ANISET_ARROW_ID) Arrow = s; } void CIntroScene::_ParseSection_OBJECTS(string line) { vector<string> tokens = split(line); if (tokens.size() < 3) return; // skip invalid lines - an object set must have at least id, x, y int tag = 0, option_tag_1 = 0, option_tag_2 = 0; int object_type = atoi(tokens[0].c_str()); float x = (float)atof(tokens[1].c_str()); float y = (float)atof(tokens[2].c_str()); int ani_set_id = atoi(tokens[3].c_str()); if (tokens.size() >= 5) tag = (int)atof(tokens[4].c_str()); if (tokens.size() >= 6) option_tag_1 = (int)atof(tokens[5].c_str()); if (tokens.size() >= 7) option_tag_2 = (int)atof(tokens[6].c_str()); CAnimationSets* animation_sets = CAnimationSets::GetInstance(); CGameObject* obj = NULL; switch (object_type) { case OBJECT_TYPE_GROUND: obj = new CIntroGround(); break; default: DebugOut(L"[ERR] Invalid object type: %d\n", object_type); return; } obj->SetPosition(x, y); LPANIMATION_SET ani_set = animation_sets->Get(ani_set_id); obj->SetAnimationSet(ani_set); objects.push_back(obj); } void CIntroScene::Update(DWORD dt) { if (switchTimer.ElapsedTime() >= SWITCH_TIME && switchTimer.IsStarted()) { CGame::GetInstance()->SwitchScene(WORLD_SCENE_ID); } } void CIntroScene::Load() { DebugOut(L"[INFO] Start loading scene resources from : %s \n", sceneFilePath); ifstream f; f.open(sceneFilePath); // current resource section flag int section = SCENE_SECTION_UNKNOWN; DebugOut(L"%d", section); char str[MAX_SCENE_LINE]; while (f.getline(str, MAX_SCENE_LINE)) { string line(str); if (line[0] == '#') continue; // skip comment lines if (line == "[TEXTURES]") { section = SCENE_SECTION_TEXTURES; continue; } if (line == "[SPRITES]") { section = SCENE_SECTION_SPRITES; continue; } if (line == "[ANIMATIONS]") { section = SCENE_SECTION_ANIMATIONS; continue; } if (line == "[ANIMATION_SETS]") { section = SCENE_SECTION_ANIMATION_SETS; continue; } if (line == "[OBJECTS]") { section = SCENE_SECTION_OBJECTS; continue; } if (line[0] == '[' || line == "") { section = SCENE_SECTION_UNKNOWN; continue; } // // data section // switch (section) { case SCENE_SECTION_TEXTURES: _ParseSection_TEXTURES(line); break; case SCENE_SECTION_SPRITES: _ParseSection_SPRITES(line); break; case SCENE_SECTION_ANIMATIONS: _ParseSection_ANIMATIONS(line); break; case SCENE_SECTION_ANIMATION_SETS: _ParseSection_ANIMATION_SETS(line); break; case SCENE_SECTION_OBJECTS: _ParseSection_OBJECTS(line); break; } } f.close(); CTextures::GetInstance()->Add(ID_TEX_BBOX, L"Resources\\Textures\\bbox.png", D3DCOLOR_XRGB(255, 255, 255)); DebugOut(L"[INFO] Done loading scene resources %s\n", sceneFilePath); } void CIntroScene::Render() { BackGround->at(3)->Render(0, 0); Three->Render(THREE_X, THREE_Y); for (size_t i = 0; i < objects.size(); i++) objects[i]->Render(); if (switchTimer.IsStarted()) Arrow->at(0)->Render(ARROW_X, ARROW_Y); else Arrow->at(1)->Render(ARROW_X, ARROW_Y); } void CIntroScene::Unload() { for (size_t i = 2; i < objects.size(); i++) delete objects[i]; objects.clear(); BackGround = NULL; Arrow = NULL; Three = NULL; switchTimer.Reset(); DebugOut(L"Unload Intro Scene\n"); } void IntroSceneKeyHandler::OnKeyDown(int KeyCode) { CIntroScene* intro = ((CIntroScene*)CGame::GetInstance()->GetCurrentScene()); switch (KeyCode) { case DIK_RETURN: intro->switchTimer.Start(); DebugOut(L"Enter"); break; default: break; } }
27.059072
111
0.684703
ThienUIT
0e3243e42b424f841913651fb56b4e6d859e1e8c
10,153
cpp
C++
test/variant_add.t.cpp
sheehamj13/task
67ed9cadfcbccf1f1071fc1b04cde61a2aba2f69
[ "MIT" ]
null
null
null
test/variant_add.t.cpp
sheehamj13/task
67ed9cadfcbccf1f1071fc1b04cde61a2aba2f69
[ "MIT" ]
null
null
null
test/variant_add.t.cpp
sheehamj13/task
67ed9cadfcbccf1f1071fc1b04cde61a2aba2f69
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2013 - 2015, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <test.h> #include <Variant.h> #include <Context.h> Context context; #define EPSILON 0.001 //////////////////////////////////////////////////////////////////////////////// int main (int, char**) { UnitTest t (80); Variant v0 (true); Variant v1 (42); Variant v2 (3.14); Variant v3 ("foo"); Variant v4 (1234567890, Variant::type_date); Variant v5 (1200, Variant::type_duration); // boolean + boolean -> ERROR try {Variant v00 = v0 + v0; t.fail ("true + true --> error");} catch (...) {t.pass ("true + true --> error");} // boolean + integer -> integer Variant v01 = v0 + v1; t.is (v01.type (), Variant::type_integer, "true + 42 --> integer"); t.is (v01.get_integer (), 43, "true + 42 --> 43"); // boolean + real -> real Variant v02 = v0 + v2; t.is (v02.type (), Variant::type_real, "true + 3.14 --> real"); t.is (v02.get_real (), 4.14, EPSILON, "true + 3.14 --> 4.14"); // boolean + string -> string Variant v03 = v0 + v3; t.is (v03.type (), Variant::type_string, "true + foo --> string"); t.is (v03.get_string (), "truefoo", "true + foo --> truefoo"); // boolean + date -> date Variant v04 = v0 + v4; t.is (v04.type (), Variant::type_date, "true + 1234567890 --> date"); t.is (v04.get_date (), "1234567891", "true + 1234567890 --> 1234567891"); // boolean + duration -> duration Variant v05 = v0 + v5; t.is (v05.type (), Variant::type_duration, "true + 1200 --> duration"); t.is (v05.get_duration (), "1201", "true + 1200 --> 1201"); // integer + boolean -> integer Variant v10 = v1 + v0; t.is (v10.type (), Variant::type_integer, "42 + true --> integer"); t.is (v10.get_integer (), 43, "42 + true --> 43"); // integer + integer -> integer Variant v11 = v1 + v1; t.is (v11.type (), Variant::type_integer, "42 + 42 --> integer"); t.is (v11.get_integer (), 84, "42 + 42 --> 84"); // integer + real -> real Variant v12 = v1 + v2; t.is (v12.type (), Variant::type_real, "42 + 3.14 --> real"); t.is (v12.get_real (), 45.14, EPSILON, "42 + 3.14 --> 45.14"); // integer + string -> string Variant v13 = v1 + v3; t.is (v13.type (), Variant::type_string, "42 + foo --> string"); t.is (v13.get_string (), "42foo", "42 + foo --> 42foo"); // integer + date -> date Variant v14 = v1 + v4; t.is (v14.type (), Variant::type_date, "42 + 1234567890 --> date"); t.is (v14.get_date (), 1234567932, "42 + 1234567890 --> 1234567932"); // integer + duration -> duration Variant v15 = v1 + v5; t.is (v15.type (), Variant::type_duration, "42 + 1200 --> duration"); t.is (v15.get_duration (), 1242, "42 + 1200 --> 1242"); // real + boolean -> real Variant v20 = v2 + v0; t.is (v20.type (), Variant::type_real, "3.14 + true --> real"); t.is (v20.get_real (), 4.14, EPSILON, "3.14 + true --> 4.14"); // real + integer -> real Variant v21 = v2 + v1; t.is (v21.type (), Variant::type_real, "3.14 + 42 --> real"); t.is (v21.get_real (), 45.14, EPSILON, "3.14 + 42 --> 45.14"); // real + real -> real Variant v22 = v2 + v2; t.is (v22.type (), Variant::type_real, "3.14 + 3.14 --> real"); t.is (v22.get_real (), 6.28, EPSILON, "3.14 + 3.14 --> 6.28"); // real + string -> string Variant v23 = v2 + v3; t.is (v23.type (), Variant::type_string, "3.14 + foo --> string"); t.is (v23.get_string (), "3.14foo", "3.14 + foo --> 3.14foo"); // real + date -> date Variant v24 = v2 + v4; t.is (v24.type (), Variant::type_date, "3.14 + 1234567890 --> date"); t.is (v24.get_date (), 1234567893, "3.14 + 1234567890 --> 1234567893"); // real + duration -> duration Variant v25 = v2 + v5; t.is (v25.type (), Variant::type_duration, "3.14 + 1200 --> duration"); t.is (v25.get_duration (), 1203, "3.14 + 1200 --> 1203"); // string + boolean -> string Variant v30 = v3 + v0; t.is (v30.type (), Variant::type_string, "foo + true --> string"); t.is (v30.get_string (), "footrue", "foo + true --> footrue"); // string + integer -> string Variant v31 = v3 + v1; t.is (v31.type (), Variant::type_string, "foo + 42 --> string"); t.is (v31.get_string (), "foo42", "foo + 42 --> foo42"); // string + real -> string Variant v32 = v3 + v2; t.is (v32.type (), Variant::type_string, "foo + 3.14 --> string"); t.is (v32.get_string (), "foo3.14", "foo + 3.14 --> foo3.14"); // string + string -> string Variant v33 = v3 + v3; t.is (v33.type (), Variant::type_string, "foo + foo --> string"); t.is (v33.get_string (), "foofoo", "foo + foo --> foofoo"); // string + date -> string Variant v34 = v3 + v4; t.is (v34.type (), Variant::type_string, "foo + 1234567890 --> string"); std::string s = v34.get_string (); t.is ((int)s[7], (int)'-', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[10], (int)'-', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[13], (int)'T', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[16], (int)':', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[19], (int)':', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s.length (), 22, "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); // string + duration -> string Variant v35 = v3 + v5; t.is (v35.type (), Variant::type_string, "foo + 1200 --> string"); t.is (v35.get_string (), "fooPT20M", "foo + 1200 --> fooPT20M"); // date + boolean -> date Variant v40 = v4 + v0; t.is (v40.type (), Variant::type_date, "1234567890 + true --> date"); t.is (v40.get_date (), 1234567891, "1234567890 + true --> 1234567891"); // date + integer -> date Variant v41 = v4 + v1; t.is (v41.type (), Variant::type_date, "1234567890 + 42 --> date"); t.is (v41.get_date (), 1234567932, "1234567890 + 42 --> 1234567932"); // date + real -> date Variant v42 = v4 + v2; t.is (v42.type (), Variant::type_date, "1234567890 + 3.14 --> date"); t.is (v42.get_date (), 1234567893, "1234567890 + 3.14 --> 1234567893"); // date + string -> string Variant v43 = v4 + v3; t.is (v43.type (), Variant::type_string, "1234567890 + foo --> string"); s = v43.get_string (); t.is ((int)s[4], (int)'-', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[7], (int)'-', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[10], (int)'T', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[13], (int)':', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[16], (int)':', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s.length (), 22, "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); // date + date -> ERROR try {Variant v44 = v4 + v4; t.fail ("1234567890 + 1234567890 --> error");} catch (...) {t.pass ("1234567890 + 1234567890 --> error");} // date + duration -> date Variant v45 = v4 + v5; t.is (v45.type (), Variant::type_date, "1234567890 + 1200 --> date"); t.is (v45.get_date (), 1234569090, "1234567890 + 1200 --> 1234569090"); // duration + boolean -> duration Variant v50 = v5 + v0; t.is (v50.type (), Variant::type_duration, "1200 + true --> duration"); t.is (v50.get_duration (), 1201, "1200 + true --> 1201"); // duration + integer -> duration Variant v51 = v5 + v1; t.is (v51.type (), Variant::type_duration, "1200 + 42 --> duration"); t.is (v51.get_duration (), 1242, "1200 + 42 --> 1242"); // duration + real -> duration Variant v52 = v5 + v2; t.is (v52.type (), Variant::type_duration, "1200 + 3.14 --> duration"); t.is (v52.get_duration (), 1203, "1200 + 3.14 --> 1203"); // duration + string -> string Variant v53 = v5 + v3; t.is (v53.type (), Variant::type_string, "1200 + foo --> string"); t.is (v53.get_string (), "PT20Mfoo", "1200 + foo --> PT20Mfoo"); // duration + date -> date Variant v54 = v5 + v4; t.is (v54.type (), Variant::type_date, "1200 + 1234567890 --> date"); t.is (v54.get_date (), 1234569090, "1200 + 1234567890 --> 1234569090"); // duration + duration -> duration Variant v55 = v5 + v5; t.is (v55.type (), Variant::type_duration, "1200 + 1200 --> duration"); t.is (v55.get_duration (), 2400, "1200 + 1200 --> 2400"); return 0; } ////////////////////////////////////////////////////////////////////////////////
41.781893
92
0.547424
sheehamj13
0e33ea5cfe8ffe7b19dfe9e067fc572c542facfe
9,190
cpp
C++
Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp
qmuntal/lib3mf
ad82d2f17bd37b942635c9cc7a33e4ea060b7adf
[ "BSD-2-Clause" ]
1
2021-11-26T13:23:39.000Z
2021-11-26T13:23:39.000Z
Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp
qmuntal/lib3mf
ad82d2f17bd37b942635c9cc7a33e4ea060b7adf
[ "BSD-2-Clause" ]
null
null
null
Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp
qmuntal/lib3mf
ad82d2f17bd37b942635c9cc7a33e4ea060b7adf
[ "BSD-2-Clause" ]
null
null
null
/*++ Copyright (C) 2018 3MF Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. Abstract: NMR_ModelWriter_3MF_Native.cpp implements the platform independent 3MF Model Writer Class. This model writer exports the in memory represenation into a 3MF file, using LibZ and a native XML writer implementation. --*/ #include "Model/Writer/NMR_ModelWriter_3MF_Native.h" #include "Model/Classes/NMR_ModelConstants.h" #include "Model/Classes/NMR_ModelAttachment.h" #include "Model/Classes/NMR_ModelTextureAttachment.h" #include "Model/Classes/NMR_ModelSliceResource.h" #include "Common/Platform/NMR_ImportStream.h" #include "Common/NMR_Exception.h" #include "Common/Platform/NMR_XmlWriter.h" #include "Common/Platform/NMR_XmlWriter_Native.h" #include "Common/Platform/NMR_ImportStream_Unique_Memory.h" #include "Common/Platform/NMR_ExportStream_Memory.h" #include "Common/NMR_StringUtils.h" #include "Common/3MF_ProgressMonitor.h" #include <functional> #include <sstream> namespace NMR { CModelWriter_3MF_Native::CModelWriter_3MF_Native(_In_ PModel pModel) : CModelWriter_3MF(pModel) { m_nRelationIDCounter = 0; m_pModel = nullptr; } // These are OPC dependent functions void CModelWriter_3MF_Native::createPackage(_In_ CModel * pModel) { __NMRASSERT(pModel != nullptr); m_pModel = pModel; m_nRelationIDCounter = 0; } void CModelWriter_3MF_Native::releasePackage() { m_pModel = nullptr; } void CModelWriter_3MF_Native::writePackageToStream(_In_ PExportStream pStream) { if (pStream.get() == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); if (m_pModel == nullptr) throw CNMRException(NMR_ERROR_NOMODELTOWRITE); // Write Model Stream POpcPackageWriter pPackageWriter = std::make_shared<COpcPackageWriter>(pStream); POpcPackagePart pModelPart = pPackageWriter->addPart(PACKAGE_3D_MODEL_URI); PXmlWriter_Native pXMLWriter = std::make_shared<CXmlWriter_Native>(pModelPart->getExportStream()); if (!m_pProgressMonitor->Progress(0.01, ProgressIdentifier::PROGRESS_WRITEROOTMODEL)) throw CNMRException(NMR_USERABORTED); writeModelStream(pXMLWriter.get(), m_pModel); // add Root relationships pPackageWriter->addRootRelationship(generateRelationShipID(), PACKAGE_START_PART_RELATIONSHIP_TYPE, pModelPart.get()); PModelAttachment pPackageThumbnail = m_pModel->getPackageThumbnail(); if (pPackageThumbnail.get() != nullptr) { // create Package Thumbnail Part POpcPackagePart pThumbnailPart = pPackageWriter->addPart(pPackageThumbnail->getPathURI()); PExportStream pExportStream = pThumbnailPart->getExportStream(); // Copy data PImportStream pPackageThumbnailStream = pPackageThumbnail->getStream(); pPackageThumbnailStream->seekPosition(0, true); pExportStream->copyFrom(pPackageThumbnailStream.get(), pPackageThumbnailStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE); // add root relationship pPackageWriter->addRootRelationship(generateRelationShipID(), pPackageThumbnail->getRelationShipType(), pThumbnailPart.get()); } if (!m_pProgressMonitor->Progress(0.5, ProgressIdentifier::PROGRESS_WRITENONROOTMODELS)) throw CNMRException(NMR_USERABORTED); // add slicestacks that reference other files m_pProgressMonitor->PushLevel(0.5, 0.85); addSlicerefAttachments(m_pModel); m_pProgressMonitor->PopLevel(); // add Attachments if (!m_pProgressMonitor->Progress(0.85, ProgressIdentifier::PROGRESS_WRITEATTACHMENTS)) throw CNMRException(NMR_USERABORTED); m_pProgressMonitor->PushLevel(0.85, 0.99); addAttachments(m_pModel, pPackageWriter, pModelPart); m_pProgressMonitor->PopLevel(); if (!m_pProgressMonitor->Progress(0.99, ProgressIdentifier::PROGRESS_WRITECONTENTTYPES)) throw CNMRException(NMR_USERABORTED); // add Content Types pPackageWriter->addContentType(PACKAGE_3D_RELS_EXTENSION, PACKAGE_3D_RELS_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_MODEL_EXTENSION, PACKAGE_3D_MODEL_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_TEXTURE_EXTENSION, PACKAGE_TEXTURE_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_PNG_EXTENSION, PACKAGE_PNG_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_JPEG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_JPG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE); std::map<std::string, std::string> CustomContentTypes = m_pModel->getCustomContentTypes(); std::map<std::string, std::string>::iterator iContentTypeIterator; for (iContentTypeIterator = CustomContentTypes.begin(); iContentTypeIterator != CustomContentTypes.end(); iContentTypeIterator++) { if (!m_pModel->contentTypeIsDefault(iContentTypeIterator->first)) { pPackageWriter->addContentType(iContentTypeIterator->first, iContentTypeIterator->second); } } } std::string CModelWriter_3MF_Native::generateRelationShipID() { // Create Unique ID String std::stringstream sStream; sStream << "rel" << m_nRelationIDCounter; m_nRelationIDCounter++; return sStream.str(); } void CModelWriter_3MF_Native::addSlicerefAttachments(_In_ CModel *pModel) { __NMRASSERT(pModel != nullptr); nfUint32 nCount = pModel->getSliceStackCount(); if (nCount > 0) { nfUint32 nIndex; for (nIndex = 0; nIndex < nCount; nIndex++) { if (!m_pProgressMonitor->Progress(double(nIndex) / nCount, ProgressIdentifier::PROGRESS_WRITENONROOTMODELS)) throw CNMRException(NMR_USERABORTED); CModelSliceStackResource* pSliceStackResource = dynamic_cast<CModelSliceStackResource*>(pModel->getSliceStackResource(nIndex).get()); CSliceStack* pSliceStack = pSliceStackResource->getSliceStack().get(); if (pSliceStack->usesSliceRef()) { PExportStreamMemory p = std::make_shared<CExportStreamMemory>(); PXmlWriter_Native pXMLWriter = std::make_shared<CXmlWriter_Native>(p); writeSlicestackStream(pXMLWriter.get(), pModel, pSliceStackResource); PImportStream pStream = std::make_shared<CImportStream_Unique_Memory>(p->getData(), p->getDataSize()); // check, whether that's already in here PModelAttachment pSliceRefAttachment = m_pModel->findModelAttachment(pSliceStackResource->sliceRefPath()); if (pSliceRefAttachment.get() != nullptr) { if (pSliceRefAttachment->getRelationShipType() != PACKAGE_START_PART_RELATIONSHIP_TYPE) throw CNMRException(NMR_ERROR_DUPLICATEATTACHMENTPATH); pSliceRefAttachment->setStream(pStream); } else m_pModel->addAttachment(pSliceStackResource->sliceRefPath(), PACKAGE_START_PART_RELATIONSHIP_TYPE, pStream); } } } } void CModelWriter_3MF_Native::addAttachments(_In_ CModel * pModel, _In_ POpcPackageWriter pPackageWriter, _In_ POpcPackagePart pModelPart) { __NMRASSERT(pModel != nullptr); __NMRASSERT(pModelPart.get() != nullptr); __NMRASSERT(pPackageWriter.get() != nullptr); nfUint32 nCount = pModel->getAttachmentCount(); nfUint32 nIndex; if (nCount > 0) { for (nIndex = 0; nIndex < nCount; nIndex++) { if (!m_pProgressMonitor->Progress(double(nIndex) / nCount, ProgressIdentifier::PROGRESS_WRITEATTACHMENTS)) throw CNMRException(NMR_USERABORTED); PModelAttachment pAttachment = pModel->getModelAttachment(nIndex); PImportStream pStream = pAttachment->getStream(); std::string sPath = fnIncludeLeadingPathDelimiter(pAttachment->getPathURI()); std::string sRelationShipType = pAttachment->getRelationShipType(); if (pStream.get() == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); // create Texture Part POpcPackagePart pAttachmentPart = pPackageWriter->addPart(sPath); PExportStream pExportStream = pAttachmentPart->getExportStream(); // Copy data pStream->seekPosition(0, true); pExportStream->copyFrom(pStream.get(), pStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE); // add relationships pModelPart->addRelationship(generateRelationShipID(), sRelationShipType.c_str(), pAttachmentPart->getURI()); } } } }
40.844444
139
0.783134
qmuntal
0e389f04c7c038d92b3fa332cfb5950e71b90f27
321
cpp
C++
src/actions/action.cpp
Spark-NF/organizer
d8bcd459f8bebcb76d07ce3a125246944d1a1824
[ "Apache-2.0" ]
3
2020-12-17T19:35:27.000Z
2021-09-29T09:34:51.000Z
src/actions/action.cpp
Spark-NF/organizer
d8bcd459f8bebcb76d07ce3a125246944d1a1824
[ "Apache-2.0" ]
null
null
null
src/actions/action.cpp
Spark-NF/organizer
d8bcd459f8bebcb76d07ce3a125246944d1a1824
[ "Apache-2.0" ]
1
2019-06-18T17:34:16.000Z
2019-06-18T17:34:16.000Z
#include "action.h" Action::Action(QString name, QKeySequence shortcut, bool terminal) : m_name(name), m_shortcut(shortcut), m_terminal(terminal) {} QString Action::name() const { return m_name; } QKeySequence Action::shortcut() const { return m_shortcut; } bool Action::terminal() const { return m_terminal; }
13.956522
66
0.732087
Spark-NF
0e38c4cf3522bcb698c563a2e88b2038b36fcdd3
23,864
cpp
C++
SOUI/src/control/SListCtrl.cpp
fengjixuchui/soui
360d9b63cab96e7c01d600ff772578c2fdc9af24
[ "MIT" ]
1
2021-11-12T01:53:04.000Z
2021-11-12T01:53:04.000Z
SOUI/src/control/SListCtrl.cpp
fengjixuchui/soui
360d9b63cab96e7c01d600ff772578c2fdc9af24
[ "MIT" ]
null
null
null
SOUI/src/control/SListCtrl.cpp
fengjixuchui/soui
360d9b63cab96e7c01d600ff772578c2fdc9af24
[ "MIT" ]
null
null
null
#include "souistd.h" #include "control/SListCtrl.h" #include <algorithm> #pragma warning(disable : 4267 4018) #define ITEM_MARGIN 4 namespace SOUI { ////////////////////////////////////////////////////////////////////////// // SListCtrl SListCtrl::SListCtrl() : m_nHeaderHeight(20) , m_nItemHeight(20) , m_pHeader(NULL) , m_nSelectItem(-1) , m_crItemBg(RGBA(255,255,255,255)) , m_crItemBg2(RGBA(226,226,226,255)) , m_crItemSelBg(RGBA(57,145,209,255)) , m_crItemHotBg(RGBA(57,145,209,128)) , m_crText(RGBA(0,0,0,255)) , m_crSelText(RGBA(255,255,0,255)) , m_pItemSkin(NULL) , m_pIconSkin(NULL) , m_pCheckSkin(GETBUILTINSKIN(SKIN_SYS_CHECKBOX)) , m_ptIcon(-1,-1) , m_ptText(-1,-1) , m_bHotTrack(FALSE) , m_bCheckBox(FALSE) , m_bMultiSelection(FALSE) { m_bClipClient = TRUE; m_bFocusable = TRUE; m_evtSet.addEvent(EVENTID(EventLCSelChanging)); m_evtSet.addEvent(EVENTID(EventLCSelChanged)); m_evtSet.addEvent(EVENTID(EventLCDbClick)); m_evtSet.addEvent(EVENTID(EventLCItemDeleted)); } SListCtrl::~SListCtrl() { } int SListCtrl::InsertColumn(int nIndex, LPCTSTR pszText, int nWidth, LPARAM lParam) { SASSERT(m_pHeader); int nRet = m_pHeader->InsertItem(nIndex, pszText, nWidth, ST_NULL, lParam); for(int i=0;i<GetItemCount();i++) { m_arrItems[i].arSubItems->SetCount(GetColumnCount()); } UpdateScrollBar(); return nRet; } BOOL SListCtrl::CreateChildren(pugi::xml_node xmlNode) { // listctrl的子控件只能是一个header控件 if (!__super::CreateChildren(xmlNode)) return FALSE; m_pHeader=NULL; SWindow *pChild=GetWindow(GSW_FIRSTCHILD); while(pChild) { if(pChild->IsClass(SHeaderCtrl::GetClassName())) { m_pHeader=(SHeaderCtrl*)pChild; break; } pChild=pChild->GetWindow(GSW_NEXTSIBLING); } if(!m_pHeader) return FALSE; SStringW strPos; strPos.Format(L"0,0,-0,%d",m_nHeaderHeight); m_pHeader->SetAttribute(L"pos",strPos,TRUE); m_pHeader->GetEventSet()->subscribeEvent(EventHeaderItemChanging::EventID, Subscriber(&SListCtrl::OnHeaderSizeChanging,this)); m_pHeader->GetEventSet()->subscribeEvent(EventHeaderItemSwap::EventID, Subscriber(&SListCtrl::OnHeaderSwap,this)); return TRUE; } int SListCtrl::InsertItem(int nItem, LPCTSTR pszText, int nImage) { if(GetColumnCount()==0) return -1; if (nItem<0 || nItem>GetItemCount()) nItem = GetItemCount(); DXLVITEM lvi; lvi.dwData = 0; lvi.arSubItems=new ArrSubItem(); lvi.arSubItems->SetCount(GetColumnCount()); DXLVSUBITEM &subItem=lvi.arSubItems->GetAt(0); subItem.strText = _tcsdup(pszText); subItem.cchTextMax = _tcslen(pszText); subItem.nImage = nImage; m_arrItems.InsertAt(nItem, lvi); UpdateScrollBar(); return nItem; } BOOL SListCtrl::SetItemData(int nItem, LPARAM dwData) { if (nItem >= GetItemCount() || nItem<0) return FALSE; m_arrItems[nItem].dwData = dwData; return TRUE; } LPARAM SListCtrl::GetItemData(int nItem) { if (nItem >= GetItemCount() || nItem<0) return 0; DXLVITEM& lvi = m_arrItems[nItem]; return lvi.dwData; } BOOL SListCtrl::SetSubItem(int nItem, int nSubItem, const DXLVSUBITEM* plv) { if (nItem>=GetItemCount() || nSubItem>=GetColumnCount() || nItem<0) return FALSE; DXLVSUBITEM & lvsi_dst=m_arrItems[nItem].arSubItems->GetAt(nSubItem); if(plv->mask & S_LVIF_TEXT) { if(lvsi_dst.strText) free(lvsi_dst.strText); lvsi_dst.strText=_tcsdup(plv->strText); lvsi_dst.cchTextMax=_tcslen(plv->strText); } if(plv->mask&S_LVIF_IMAGE) lvsi_dst.nImage=plv->nImage; if(plv->mask&S_LVIF_INDENT) lvsi_dst.nIndent=plv->nIndent; RedrawItem(nItem); return TRUE; } BOOL SListCtrl::GetSubItem(int nItem, int nSubItem, DXLVSUBITEM* plv) const { if (nItem>=GetItemCount() || nSubItem>=GetColumnCount() || nItem<0) return FALSE; const DXLVSUBITEM & lvsi_src=m_arrItems[nItem].arSubItems->GetAt(nSubItem); if(plv->mask & S_LVIF_TEXT) { _tcscpy_s(plv->strText,plv->cchTextMax,lvsi_src.strText); } if(plv->mask&S_LVIF_IMAGE) plv->nImage=lvsi_src.nImage; if(plv->mask&S_LVIF_INDENT) plv->nIndent=lvsi_src.nIndent; return TRUE; } BOOL SListCtrl::SetSubItemText(int nItem, int nSubItem, LPCTSTR pszText) { if (nItem < 0 || nItem >= GetItemCount()) return FALSE; if (nSubItem < 0 || nSubItem >= GetColumnCount()) return FALSE; DXLVSUBITEM &lvi=m_arrItems[nItem].arSubItems->GetAt(nSubItem); if(lvi.strText) { free(lvi.strText); } lvi.strText = _tcsdup(pszText); lvi.cchTextMax= _tcslen(pszText); CRect rcItem=GetItemRect(nItem,nSubItem); InvalidateRect(rcItem); return TRUE; } SStringT SListCtrl::GetSubItemText( int nItem, int nSubItem ) const { if (nItem>=GetItemCount() || nSubItem>=GetColumnCount() || nItem<0) return _T(""); const DXLVSUBITEM & lvsi_src=m_arrItems[nItem].arSubItems->GetAt(nSubItem); return lvsi_src.strText; } int SListCtrl::GetSelectedItem() { return m_nSelectItem; } void SListCtrl::SetSelectedItem(int nItem) { if (nItem != m_nSelectItem) { NotifySelChange(m_nSelectItem, nItem); } } int SListCtrl::GetItemCount() const { if (GetColumnCount() <= 0) return 0; return m_arrItems.GetCount(); } BOOL SListCtrl::SetItemCount( int nItems ,int nGrowBy) { int nOldCount=GetItemCount(); if(nItems<nOldCount) return FALSE; BOOL bRet=m_arrItems.SetCount(nItems,nGrowBy); if(bRet) { for(int i=nOldCount;i<nItems;i++) { DXLVITEM & lvi=m_arrItems[i]; lvi.arSubItems=new ArrSubItem; lvi.arSubItems->SetCount(GetColumnCount()); } } UpdateScrollBar(); return bRet; } CRect SListCtrl::GetListRect() { CRect rcList; GetClientRect(&rcList); rcList.top += m_nHeaderHeight; return rcList; } ////////////////////////////////////////////////////////////////////////// // 更新滚动条 void SListCtrl::UpdateScrollBar() { CSize szView; szView.cx = m_pHeader->GetTotalWidth(); szView.cy = GetItemCount()*m_nItemHeight; CRect rcClient; SWindow::GetClientRect(&rcClient);//不计算滚动条大小 rcClient.top+=m_nHeaderHeight; CSize size = rcClient.Size(); // 关闭滚动条 m_wBarVisible = SSB_NULL; if (size.cy<szView.cy || (size.cy<szView.cy+GetSbWidth() && size.cx<szView.cx)) { // 需要纵向滚动条 m_wBarVisible |= SSB_VERT; m_siVer.nMin = 0; m_siVer.nMax = szView.cy-1; m_siVer.nPage = GetCountPerPage(FALSE)*m_nItemHeight; if (size.cx-GetSbWidth() < szView.cx) { // 需要横向滚动条 m_wBarVisible |= SSB_HORZ; m_siVer.nPage=size.cy-GetSbWidth() > 0 ? size.cy-GetSbWidth() : 0;//注意同时调整纵向滚动条page信息 m_siHoz.nMin = 0; m_siHoz.nMax = szView.cx-1; m_siHoz.nPage = size.cx-GetSbWidth() > 0 ? size.cx-GetSbWidth() : 0; } else { // 不需要横向滚动条 m_siHoz.nPage = size.cx; m_siHoz.nMin = 0; m_siHoz.nMax = m_siHoz.nPage-1; m_siHoz.nPos = 0; m_ptOrigin.x = 0; } } else { // 不需要纵向滚动条 m_siVer.nPage = size.cy; m_siVer.nMin = 0; m_siVer.nMax = size.cy-1; m_siVer.nPos = 0; m_ptOrigin.y = 0; if (size.cx < szView.cx) { // 需要横向滚动条 m_wBarVisible |= SSB_HORZ; m_siHoz.nMin = 0; m_siHoz.nMax = szView.cx-1; m_siHoz.nPage = size.cx; } else { // 不需要横向滚动条 m_siHoz.nPage = size.cx; m_siHoz.nMin = 0; m_siHoz.nMax = m_siHoz.nPage-1; m_siHoz.nPos = 0; m_ptOrigin.x = 0; } } SetScrollPos(TRUE, m_siVer.nPos, TRUE); SetScrollPos(FALSE, m_siHoz.nPos, TRUE); // 重新计算客户区及非客户区 SSendMessage(WM_NCCALCSIZE); // 根据需要调整原点位置 if (HasScrollBar(FALSE) && m_ptOrigin.x+m_siHoz.nPage>szView.cx) { m_ptOrigin.x = szView.cx-m_siHoz.nPage; } if (HasScrollBar(TRUE) && m_ptOrigin.y+m_siVer.nPage>szView.cy) { m_ptOrigin.y = szView.cy-m_siVer.nPage; } Invalidate(); } //更新表头位置 void SListCtrl::UpdateHeaderCtrl() { CRect rcClient; GetClientRect(&rcClient); CRect rcHeader(rcClient); rcHeader.bottom=rcHeader.top+m_nHeaderHeight; rcHeader.left-=m_ptOrigin.x; if(m_pHeader) m_pHeader->Move(rcHeader); } void SListCtrl::DeleteItem(int nItem) { if (nItem>=0 && nItem < GetItemCount()) { DXLVITEM &lvi=m_arrItems[nItem]; EventLCItemDeleted evt2(this); evt2.nItem = nItem; evt2.dwData = lvi.dwData; FireEvent(evt2); for(int i=0;i<GetColumnCount();i++) { DXLVSUBITEM &lvsi =lvi.arSubItems->GetAt(i); if(lvsi.strText) free(lvsi.strText); } delete lvi.arSubItems; m_arrItems.RemoveAt(nItem); UpdateScrollBar(); } } void SListCtrl::DeleteColumn( int iCol ) { if(m_pHeader->DeleteItem(iCol)) { int nColumnCount = m_pHeader->GetItemCount(); for(int i=0;i<GetItemCount();i++) { DXLVITEM &lvi = m_arrItems[i]; if (0 == nColumnCount) { EventLCItemDeleted evt2(this); evt2.nItem = i; evt2.dwData = lvi.dwData; FireEvent(evt2); } DXLVSUBITEM &lvsi=lvi.arSubItems->GetAt(iCol); if(lvsi.strText) free(lvsi.strText); m_arrItems[i].arSubItems->RemoveAt(iCol); } UpdateScrollBar(); } } void SListCtrl::DeleteAllItems() { m_nSelectItem = -1; for(int i=0;i<GetItemCount();i++) { DXLVITEM &lvi = m_arrItems[i]; EventLCItemDeleted evt2(this); evt2.nItem = i; evt2.dwData = lvi.dwData; FireEvent(evt2); for(int j=0;j<GetColumnCount();j++) { DXLVSUBITEM &lvsi =lvi.arSubItems->GetAt(j); if(lvsi.strText) free(lvsi.strText); } delete lvi.arSubItems; } m_arrItems.RemoveAll(); UpdateScrollBar(); } CRect SListCtrl::GetItemRect(int nItem, int nSubItem) { if (!(nItem>=0 && nItem<GetItemCount() && nSubItem>=0 && nSubItem<GetColumnCount())) return CRect(); CRect rcItem; rcItem.top = m_nItemHeight*nItem; rcItem.bottom = rcItem.top+m_nItemHeight; rcItem.left = 0; rcItem.right = 0; for (int nCol = 0; nCol < GetColumnCount(); nCol++) { SHDITEM hdi; hdi.mask = SHDI_WIDTH|SHDI_ORDER; m_pHeader->GetItem(nCol, &hdi); rcItem.left = rcItem.right; rcItem.right = rcItem.left+hdi.cx.toPixelSize(GetScale()); if (hdi.iOrder == nSubItem) break; } CRect rcList = GetListRect(); // 变换到窗口坐标 rcItem.OffsetRect(rcList.TopLeft()); // 根据原点坐标修正 rcItem.OffsetRect(-m_ptOrigin); return rcItem; } ////////////////////////////////////////////////////////////////////////// // 自动修改pt的位置为相对当前项的偏移量 int SListCtrl::HitTest(const CPoint& pt) { CRect rcList = GetListRect(); CPoint pt2 = pt; pt2.y -= rcList.top - m_ptOrigin.y; int nRet = pt2.y / m_nItemHeight; if (nRet >= GetItemCount()) { nRet = -1; } return nRet; } void SListCtrl::RedrawItem(int nItem) { if (!IsVisible(TRUE)) return; CRect rcList = GetListRect(); int nTopItem = GetTopIndex(); int nPageItems = (rcList.Height()+m_nItemHeight-1)/m_nItemHeight; if (nItem>=nTopItem && nItem<GetItemCount() && nItem<=nTopItem+nPageItems) { CRect rcItem(0,0,rcList.Width(),m_nItemHeight); rcItem.OffsetRect(0, m_nItemHeight*nItem-m_ptOrigin.y); rcItem.OffsetRect(rcList.TopLeft()); CRect rcDC; rcDC.IntersectRect(rcItem,rcList); IRenderTarget *pRT = GetRenderTarget(&rcDC, OLEDC_PAINTBKGND); SSendMessage(WM_ERASEBKGND, (WPARAM)pRT); DrawItem(pRT, rcItem, nItem); ReleaseRenderTarget(pRT); } } int SListCtrl::GetCountPerPage(BOOL bPartial) { CRect rcClient = GetListRect(); // calculate number of items per control height (include partial item) div_t divHeight = div(rcClient.Height(), m_nItemHeight); // round up to nearest item count return (std::max)((int)(bPartial && divHeight.rem > 0 ? divHeight.quot + 1 : divHeight.quot), 1); } BOOL SListCtrl::SortItems( PFNLVCOMPAREEX pfnCompare, void * pContext ) { qsort_s(m_arrItems.GetData(),m_arrItems.GetCount(),sizeof(DXLVITEM),pfnCompare,pContext); m_nSelectItem=-1; m_nHoverItem=-1; InvalidateRect(GetListRect()); return TRUE; } void SListCtrl::OnPaint(IRenderTarget * pRT) { SPainter painter; BeforePaint(pRT, painter); CRect rcList = GetListRect(); int nTopItem = GetTopIndex(); pRT->PushClipRect(&rcList); CRect rcItem(rcList); rcItem.bottom = rcItem.top; rcItem.OffsetRect(0,-(m_ptOrigin.y%m_nItemHeight)); for (int nItem = nTopItem; nItem <= (nTopItem+GetCountPerPage(TRUE)) && nItem<GetItemCount(); rcItem.top = rcItem.bottom, nItem++) { rcItem.bottom = rcItem.top + m_nItemHeight; DrawItem(pRT, rcItem, nItem); } pRT->PopClip(); AfterPaint(pRT, painter); } BOOL SListCtrl::HitCheckBox(const CPoint& pt) { if (!m_bCheckBox) return FALSE; CRect rect = GetListRect(); rect.left += ITEM_MARGIN; rect.OffsetRect(-m_ptOrigin.x,0); CSize sizeSkin = m_pCheckSkin->GetSkinSize(); int nOffsetX = 3; CRect rcCheck; rcCheck.SetRect(0, 0, sizeSkin.cx, sizeSkin.cy); rcCheck.OffsetRect(rect.left + nOffsetX, 0); if (pt.x >= rcCheck.left && pt.x <= rcCheck.right) return TRUE; return FALSE; } void SListCtrl::DrawItem(IRenderTarget * pRT, CRect rcItem, int nItem) { BOOL bTextColorChanged = FALSE; int nBgImg = 0; COLORREF crOldText=RGBA(0xFF,0xFF,0xFF,0xFF); COLORREF crItemBg = m_crItemBg; COLORREF crText = m_crText; DXLVITEM lvItem = m_arrItems[nItem]; CRect rcIcon, rcText; if (nItem % 2) { // if (m_pItemSkin != NULL) // nBgImg = 1; // else if (CR_INVALID != m_crItemBg2) // crItemBg = m_crItemBg2; //上面的代码不要了,因为skin间隔效果没必要,只留下颜色间隔就好了 if (CR_INVALID != m_crItemBg2) crItemBg = m_crItemBg2; } if ( lvItem.checked) {//和下面那个if的条件分开,才会有sel和hot的区别 if (m_pItemSkin != NULL) nBgImg = 2; else if (CR_INVALID != m_crItemSelBg) crItemBg = m_crItemSelBg; if (CR_INVALID != m_crSelText) crText = m_crSelText; } else if (m_bHotTrack && nItem == m_nHoverItem) { if (m_pItemSkin != NULL) nBgImg = 1; else if (CR_INVALID != m_crItemHotBg) crItemBg = m_crItemHotBg; if (CR_INVALID != m_crSelText) crText = m_crSelText; } //绘制背景 // if (m_pItemSkin != NULL) // m_pItemSkin->Draw(pRT, rc, nBgImg); // else if (CR_INVALID != crItemBg) // pRT->FillSolidRect( rc, crItemBg); //上面的代码在某些时候,【指定skin的时候,会导致背景异常】,所以颠倒一下顺序 if (CR_INVALID != crItemBg)//先画背景 pRT->FillSolidRect( rcItem, crItemBg); if (m_pItemSkin != NULL)//有skin,则覆盖背景 m_pItemSkin->Draw(pRT, rcItem, nBgImg); // 左边加上空白 rcItem.left += ITEM_MARGIN; if (CR_INVALID != crText) { bTextColorChanged = TRUE; crOldText = pRT->SetTextColor(crText); } CRect rcCol(rcItem); rcCol.right = rcCol.left; rcCol.OffsetRect(-m_ptOrigin.x,0); for (int nCol = 0; nCol < GetColumnCount(); nCol++) { CRect rcVisiblePart; SHDITEM hdi; hdi.mask=SHDI_WIDTH|SHDI_ORDER; m_pHeader->GetItem(nCol,&hdi); rcCol.left=rcCol.right; rcCol.right = rcCol.left + hdi.cx.toPixelSize(GetScale()); rcVisiblePart.IntersectRect(rcItem, rcCol); if (rcVisiblePart.IsRectEmpty()) continue; // 绘制 checkbox if (nCol == 0 && m_bCheckBox && m_pCheckSkin) { CSize sizeSkin = m_pCheckSkin->GetSkinSize(); int nOffsetX = 3; int nOffsetY = (m_nItemHeight - sizeSkin.cy) / 2; CRect rcCheck; rcCheck.SetRect(0, 0, sizeSkin.cx, sizeSkin.cy); rcCheck.OffsetRect(rcCol.left + nOffsetX, rcCol.top + nOffsetY); m_pCheckSkin->Draw(pRT, rcCheck, lvItem.checked ? 4 : 0); rcCol.left = sizeSkin.cx + 6 + rcCol.left; } DXLVSUBITEM& subItem = lvItem.arSubItems->GetAt(hdi.iOrder); if (subItem.nImage != -1 && m_pIconSkin) { int nOffsetX = m_ptIcon.x; int nOffsetY = m_ptIcon.y; CSize sizeSkin = m_pIconSkin->GetSkinSize(); rcIcon.SetRect(0, 0, sizeSkin.cx, sizeSkin.cy); if (m_ptIcon.x == -1) nOffsetX = m_nItemHeight / 6; if (m_ptIcon.y == -1) nOffsetY = (m_nItemHeight - sizeSkin.cy) / 2; rcIcon.OffsetRect(rcCol.left + nOffsetX, rcCol.top + nOffsetY); m_pIconSkin->Draw(pRT, rcIcon, subItem.nImage); } UINT align = DT_SINGLELINE; rcText = rcCol; if (m_ptText.x == -1) rcText.left = rcIcon.Width() > 0 ? rcIcon.right + m_nItemHeight / 6 : rcCol.left; else rcText.left = rcCol.left + m_ptText.x; if (m_ptText.y == -1) align |= DT_VCENTER; else rcText.top = rcCol.top + m_ptText.y; pRT->DrawText(subItem.strText, subItem.cchTextMax, rcText, align); } if (bTextColorChanged) pRT->SetTextColor(crOldText); } void SListCtrl::OnDestroy() { DeleteAllItems(); __super::OnDestroy(); } int SListCtrl::GetColumnCount() const { if (!m_pHeader) return 0; return m_pHeader->GetItemCount(); } int SListCtrl::GetTopIndex() const { return m_ptOrigin.y / m_nItemHeight; } void SListCtrl::NotifySelChange(int nOldSel, int nNewSel, BOOL checkBox) { EventLCSelChanging evt1(this); evt1.bCancel = FALSE; evt1.nOldSel=nOldSel; evt1.nNewSel=nNewSel; FireEvent(evt1); if(evt1.bCancel) return; if (checkBox) { if (nNewSel != -1) { DXLVITEM &newItem = m_arrItems[nNewSel]; newItem.checked = newItem.checked? FALSE:TRUE; m_nSelectItem = nNewSel; RedrawItem(nNewSel); } } else { if ((m_bMultiSelection || m_bCheckBox) && GetKeyState(VK_CONTROL) < 0) { if (nNewSel != -1) { DXLVITEM &newItem = m_arrItems[nNewSel]; newItem.checked = newItem.checked? FALSE:TRUE; m_nSelectItem = nNewSel; RedrawItem(nNewSel); } } else if ((m_bMultiSelection || m_bCheckBox) && GetKeyState(VK_SHIFT) < 0) { if (nNewSel != -1) { if (nOldSel == -1) nOldSel = 0; int imax = (nOldSel > nNewSel) ? nOldSel : nNewSel; int imin = (imax == nOldSel) ? nNewSel : nOldSel; for (int i = 0; i < GetItemCount(); i++) { DXLVITEM &lvItem = m_arrItems[i]; BOOL last = lvItem.checked; if (i >= imin && i<= imax) { lvItem.checked = TRUE; } else { lvItem.checked = FALSE; } if (last != lvItem.checked) RedrawItem(i); } } } else { m_nSelectItem = -1; for (int i = 0; i < GetItemCount(); i++) { DXLVITEM &lvItem = m_arrItems[i]; if (i != nNewSel && lvItem.checked) { BOOL last = lvItem.checked; lvItem.checked = FALSE; if (last != lvItem.checked) RedrawItem(i); } } if (nNewSel != -1) { DXLVITEM &newItem = m_arrItems[nNewSel]; newItem.checked = TRUE; m_nSelectItem = nNewSel; RedrawItem(nNewSel); } } } EventLCSelChanged evt2(this); evt2.nOldSel=nOldSel; evt2.nNewSel=nNewSel; FireEvent(evt2); } BOOL SListCtrl::OnScroll(BOOL bVertical, UINT uCode, int nPos) { BOOL bRet = __super::OnScroll(bVertical, uCode, nPos); if (bVertical) { m_ptOrigin.y = m_siVer.nPos; } else { m_ptOrigin.x = m_siHoz.nPos; // 处理列头滚动 UpdateHeaderCtrl(); } Invalidate(); if (uCode==SB_THUMBTRACK) ScrollUpdate(); return bRet; } void SListCtrl::OnLButtonDown(UINT nFlags, CPoint pt) { __super::OnLButtonDown(nFlags,pt); m_nHoverItem = HitTest(pt); BOOL hitCheckBox = HitCheckBox(pt); if (hitCheckBox) NotifySelChange(m_nSelectItem, m_nHoverItem, TRUE); else if (m_nHoverItem!=m_nSelectItem && !m_bHotTrack) NotifySelChange(m_nSelectItem, m_nHoverItem); else if (m_nHoverItem != -1 || m_nSelectItem != -1) NotifySelChange(m_nSelectItem, m_nHoverItem); } void SListCtrl::OnLButtonDbClick(UINT nFlags, CPoint pt) { m_nHoverItem = HitTest(pt); if (m_nHoverItem != m_nSelectItem) NotifySelChange(m_nSelectItem, m_nHoverItem); EventLCDbClick evt2(this); evt2.nCurSel = m_nHoverItem; FireEvent(evt2); } void SListCtrl::OnLButtonUp(UINT nFlags, CPoint pt) { __super::OnLButtonUp(nFlags,pt); } void SListCtrl::UpdateChildrenPosition() { __super::UpdateChildrenPosition(); UpdateHeaderCtrl(); } void SListCtrl::OnSize(UINT nType, CSize size) { __super::OnSize(nType,size); UpdateScrollBar(); UpdateHeaderCtrl(); } bool SListCtrl::OnHeaderClick(EventArgs *pEvt) { return true; } bool SListCtrl::OnHeaderSizeChanging(EventArgs *pEvt) { UpdateScrollBar(); InvalidateRect(GetListRect()); return true; } bool SListCtrl::OnHeaderSwap(EventArgs *pEvt) { InvalidateRect(GetListRect()); return true; } void SListCtrl::OnMouseMove( UINT nFlags, CPoint pt ) { int nHoverItem = HitTest(pt); if(m_bHotTrack && nHoverItem != m_nHoverItem) { m_nHoverItem= nHoverItem; Invalidate(); } } void SListCtrl::OnMouseLeave() { if(m_bHotTrack) { m_nHoverItem=-1; Invalidate(); } __super::OnMouseLeave(); } BOOL SListCtrl::GetCheckState(int nItem) { if (nItem >= GetItemCount()) return FALSE; const DXLVITEM lvItem = m_arrItems[nItem]; return lvItem.checked; } BOOL SListCtrl::SetCheckState(int nItem, BOOL bCheck) { if (!m_bCheckBox) return FALSE; if (nItem >= GetItemCount()) return FALSE; DXLVITEM &lvItem = m_arrItems[nItem]; lvItem.checked = bCheck; return TRUE; } int SListCtrl::GetCheckedItemCount() { int ret = 0; for (int i = 0; i < GetItemCount(); i++) { const DXLVITEM lvItem = m_arrItems[i]; if (lvItem.checked) ret++; } return ret; } int SListCtrl::GetFirstCheckedItem() { int ret = -1; for (int i = 0; i < GetItemCount(); i++) { const DXLVITEM lvItem = m_arrItems[i]; if (lvItem.checked) { ret = i; break; } } return ret; } int SListCtrl::GetLastCheckedItem() { int ret = -1; for (int i = GetItemCount() - 1; i >= 0; i--) { const DXLVITEM lvItem = m_arrItems[i]; if (lvItem.checked) { ret = i; break; } } return ret; } }//end of namespace
24.652893
134
0.595206
fengjixuchui
0e3ac1f2b7da5a645ffa48ed25eb3dc94b4788ec
1,325
cpp
C++
Source/controls/menu_controls.cpp
julealgon/devilutionX
0c8e4edba1521a78d993a7eceba8bc1df7e28fd5
[ "Unlicense" ]
null
null
null
Source/controls/menu_controls.cpp
julealgon/devilutionX
0c8e4edba1521a78d993a7eceba8bc1df7e28fd5
[ "Unlicense" ]
null
null
null
Source/controls/menu_controls.cpp
julealgon/devilutionX
0c8e4edba1521a78d993a7eceba8bc1df7e28fd5
[ "Unlicense" ]
null
null
null
#include "controls/menu_controls.h" #include "DiabloUI/diabloui.h" #include "controls/remap_keyboard.h" #include "utils/sdl_compat.h" namespace devilution { MenuAction GetMenuAction(const SDL_Event &event) { if (event.type == SDL_KEYDOWN) { auto sym = event.key.keysym.sym; remap_keyboard_key(&sym); switch (sym) { case SDLK_UP: return MenuAction_UP; case SDLK_DOWN: return MenuAction_DOWN; case SDLK_TAB: if ((SDL_GetModState() & KMOD_SHIFT) != 0) return MenuAction_UP; else return MenuAction_DOWN; case SDLK_PAGEUP: return MenuAction_PAGE_UP; case SDLK_PAGEDOWN: return MenuAction_PAGE_DOWN; case SDLK_RETURN: { const Uint8 *state = SDLC_GetKeyState(); if (state[SDLC_KEYSTATE_LALT] == 0 && state[SDLC_KEYSTATE_RALT] == 0) { return MenuAction_SELECT; } break; } case SDLK_KP_ENTER: return MenuAction_SELECT; case SDLK_SPACE: if (!textInputActive) { return MenuAction_SELECT; } break; case SDLK_DELETE: return MenuAction_DELETE; case SDLK_LEFT: return MenuAction_LEFT; case SDLK_RIGHT: return MenuAction_RIGHT; case SDLK_ESCAPE: return MenuAction_BACK; default: break; } } return MenuAction_NONE; } // namespace devilution } // namespace devilution
22.457627
75
0.687547
julealgon
0e3b1e66e59f8992acebe489f611820cd668b980
1,075
hpp
C++
include/Nazara/Core/ConfigCheck.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Core/ConfigCheck.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Core/ConfigCheck.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_CONFIG_CHECK_CORE_HPP #define NAZARA_CONFIG_CHECK_CORE_HPP /// This file is used to check the constant values defined in Config.hpp #include <type_traits> #define NazaraCheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type <decltype(name)>::value && name op val, #type err) // We force the value of MANAGE_MEMORY in debug #if defined(NAZARA_DEBUG) && !NAZARA_CORE_MANAGE_MEMORY #undef NAZARA_CORE_MANAGE_MEMORY #define NAZARA_CORE_MANAGE_MEMORY 0 #endif NazaraCheckTypeAndVal(NAZARA_CORE_DECIMAL_DIGITS, integral, >, 0, " shall be a strictly positive integer"); NazaraCheckTypeAndVal(NAZARA_CORE_FILE_BUFFERSIZE, integral, >, 0, " shall be a strictly positive integer"); NazaraCheckTypeAndVal(NAZARA_CORE_WINDOWS_CS_SPINLOCKS, integral, >=, 0, " shall be a positive integer"); #undef NazaraCheckTypeAndVal #endif // NAZARA_CONFIG_CHECK_CORE_HPP
38.392857
136
0.791628
AntoineJT
0e3e0ea60c16aa6aa2ce5a7a33fdc3f93013a929
956
cpp
C++
examples/undocumented/libshogun/library_hash.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2019-10-02T11:10:08.000Z
2019-10-02T11:10:08.000Z
examples/undocumented/libshogun/library_hash.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
null
null
null
examples/undocumented/libshogun/library_hash.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2020-06-02T09:15:40.000Z
2020-06-02T09:15:40.000Z
#include <shogun/lib/Hash.h> #include <stdio.h> using namespace shogun; int main(int argc, char** argv) { uint8_t array[4]={0,1,2,3}; printf("hash(0)=%0x\n", CHash::MurmurHash3(&array[0], 1, 0xDEADBEAF)); printf("hash(1)=%0x\n", CHash::MurmurHash3(&array[1], 1, 0xDEADBEAF)); printf("hash(2)=%0x\n", CHash::MurmurHash3(&array[0], 2, 0xDEADBEAF)); printf("hash(3)=%0x\n", CHash::MurmurHash3(&array[0], 4, 0xDEADBEAF)); uint32_t h = 0xDEADBEAF; uint32_t carry = 0; CHash::IncrementalMurmurHash3(&h, &carry, &array[0], 1); printf("inc_hash(0)=%0x\n", h); CHash::IncrementalMurmurHash3(&h, &carry, &array[1], 1); printf("inc_hash(1)=%0x\n", h); CHash::IncrementalMurmurHash3(&h, &carry, &array[2], 1); printf("inc_hash(2)=%0x\n", h); CHash::IncrementalMurmurHash3(&h, &carry, &array[3], 1); printf("inc_hash(3)=%0x\n", h); h = CHash::FinalizeIncrementalMurmurHash3(h, carry, 4); printf("Final inc_hash(3)=%0x\n", h); return 0; }
30.83871
71
0.65272
Arpit2601
0e3fe2ad88d6866a4396df74bbfbf4539acaabc3
4,279
cpp
C++
src/widgets/settingspages/IgnoresPage.cpp
NilsIrl/chatterino2
b7e86a8de66e53876d7a71376c43529597ee6c12
[ "MIT" ]
1
2021-08-16T15:39:56.000Z
2021-08-16T15:39:56.000Z
src/widgets/settingspages/IgnoresPage.cpp
NilsIrl/chatterino2
b7e86a8de66e53876d7a71376c43529597ee6c12
[ "MIT" ]
28
2020-10-26T07:29:15.000Z
2022-03-31T01:06:49.000Z
src/widgets/settingspages/IgnoresPage.cpp
NilsIrl/chatterino2
b7e86a8de66e53876d7a71376c43529597ee6c12
[ "MIT" ]
null
null
null
#include "IgnoresPage.hpp" #include "Application.hpp" #include "controllers/accounts/AccountController.hpp" #include "controllers/ignores/IgnoreController.hpp" #include "controllers/ignores/IgnoreModel.hpp" #include "providers/twitch/TwitchAccount.hpp" #include "singletons/Settings.hpp" #include "util/LayoutCreator.hpp" #include "widgets/helper/EditableModelView.hpp" #include <QCheckBox> #include <QGroupBox> #include <QHeaderView> #include <QLabel> #include <QListView> #include <QPushButton> #include <QTableView> #include <QVBoxLayout> // clang-format off #define INFO "/ignore <user> in chat ignores a user.\n/unignore <user> in chat unignores a user.\nYou can also click on a user to open the usercard." // clang-format on namespace chatterino { static void addPhrasesTab(LayoutCreator<QVBoxLayout> box); static void addUsersTab(IgnoresPage &page, LayoutCreator<QVBoxLayout> box, QStringListModel &model); IgnoresPage::IgnoresPage() { LayoutCreator<IgnoresPage> layoutCreator(this); auto layout = layoutCreator.setLayoutType<QVBoxLayout>(); auto tabs = layout.emplace<QTabWidget>(); addPhrasesTab(tabs.appendTab(new QVBoxLayout, "Messages")); addUsersTab(*this, tabs.appendTab(new QVBoxLayout, "Users"), this->userListModel_); } void addPhrasesTab(LayoutCreator<QVBoxLayout> layout) { layout.emplace<QLabel>("Ignore messages based certain patterns."); EditableModelView *view = layout .emplace<EditableModelView>( (new IgnoreModel(nullptr)) ->initialized(&getSettings()->ignoredMessages)) .getElement(); view->setTitles( {"Pattern", "Regex", "Case Sensitive", "Block", "Replacement"}); view->getTableView()->horizontalHeader()->setSectionResizeMode( QHeaderView::Fixed); view->getTableView()->horizontalHeader()->setSectionResizeMode( 0, QHeaderView::Stretch); view->addRegexHelpLink(); QTimer::singleShot(1, [view] { view->getTableView()->resizeColumnsToContents(); view->getTableView()->setColumnWidth(0, 200); }); view->addButtonPressed.connect([] { getSettings()->ignoredMessages.append( IgnorePhrase{"my pattern", false, false, getSettings()->ignoredPhraseReplace.getValue(), true}); }); } void addUsersTab(IgnoresPage &page, LayoutCreator<QVBoxLayout> users, QStringListModel &userModel) { auto label = users.emplace<QLabel>(INFO); label->setWordWrap(true); users.append(page.createCheckBox("Enable twitch ignored users", getSettings()->enableTwitchIgnoredUsers)); auto anyways = users.emplace<QHBoxLayout>().withoutMargin(); { anyways.emplace<QLabel>("Show messages from ignored users anyways:"); auto combo = anyways.emplace<QComboBox>().getElement(); combo->addItems( {"Never", "If you are Moderator", "If you are Broadcaster"}); auto &setting = getSettings()->showIgnoredUsersMessages; setting.connect( [combo](const int value) { combo->setCurrentIndex(value); }); QObject::connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), [&setting](int index) { if (index != -1) setting = index; }); anyways->addStretch(1); } /*auto addremove = users.emplace<QHBoxLayout>().withoutMargin(); { auto add = addremove.emplace<QPushButton>("Ignore user"); auto remove = addremove.emplace<QPushButton>("Unignore User"); addremove->addStretch(1); }*/ users.emplace<QLabel>("List of ignored users:"); users.emplace<QListView>()->setModel(&userModel); } void IgnoresPage::onShow() { auto app = getApp(); auto user = app->accounts->twitch.getCurrent(); if (user->isAnon()) { return; } QStringList users; for (const auto &ignoredUser : user->getIgnores()) { users << ignoredUser.name; } users.sort(Qt::CaseInsensitive); this->userListModel_.setStringList(users); } } // namespace chatterino
31.932836
149
0.643842
NilsIrl
0e4124b1bc075ab6fb060d145653ac4bbaa95360
2,218
cc
C++
src/core/film.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/film.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/film.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 Zhehang Ding 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 "core/film.h" #include <math.h> #include <fstream> #include <sstream> namespace qjulia { CPU_AND_CUDA Point2f GenerateCameraCoords(Point2f src, Size size) { Float c = src[1]; Float r= src[0]; Float ss = (Float)(size.width < size.height ? size.width : size.height - 1); Float x = (c - (size.width - 1) * 0.5f) / ss; Float y = ((size.height - 1) * 0.5f - r) / ss; return {x, y}; } /* void SaveToPPM(const std::string &filename, const Film &film, Float scale) { int w = film.Width(); int h = film.Height(); std::vector<unsigned char> buf(w * h * 3); auto *p = buf.data(); for (int i = 0; i < (w * h); ++i) { const auto &sp = film.At(i); for (int ch = 0; ch < 3; ++ch) { *(p++) = std::min(255, std::max(0, (int)std::round(sp[ch] * scale))); } } std::ostringstream header_stream; header_stream << "P6 " << w << ' ' << h << ' ' << 255 << '\n'; std::string header = header_stream.str(); std::ofstream file_stream(filename, std::ofstream::binary); file_stream.write(header.c_str(), header.size()); file_stream.write(reinterpret_cast<const char*>(buf.data()), buf.size()); }*/ }
33.606061
78
0.693417
zhehangd
0e41a058de70310d29a28a408d1cb8afa336e1aa
336
cpp
C++
practical 7/task5.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
1
2021-09-23T16:06:39.000Z
2021-09-23T16:06:39.000Z
practical 7/task5.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
null
null
null
practical 7/task5.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
1
2021-09-24T15:10:07.000Z
2021-09-24T15:10:07.000Z
#include<iostream> using namespace std; int main() { int b[3][3]; int a [3] [3]={1,2,3,4,5,6,7,8,9}; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { b[i][j]=a[2-i] [2-j]; } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cout<<b[i][j]<<" "; } cout<<endl; } return 0; }
14.608696
36
0.39881
sahilnegi30
0e424e511af987030f273557f62e14989f01ba2a
851
cpp
C++
src/keyboard.cpp
astrellon/simple-snake
3dbe1f2af1afe31d3cef8bcc995d9150beafa1b2
[ "MIT" ]
1
2020-06-26T07:51:45.000Z
2020-06-26T07:51:45.000Z
src/keyboard.cpp
astrellon/starter-sfml
3679e76c01275d07fa9af5ead92a5d41c6fccfea
[ "MIT" ]
null
null
null
src/keyboard.cpp
astrellon/starter-sfml
3679e76c01275d07fa9af5ead92a5d41c6fccfea
[ "MIT" ]
null
null
null
#include "keyboard.hpp" #include <algorithm> namespace town { Keyboard::KeyList Keyboard::_KeysUp; Keyboard::KeyList Keyboard::_KeysDown; bool Keyboard::isKeyPressed(sf::Keyboard::Key key) { return sf::Keyboard::isKeyPressed(key); } bool Keyboard::isKeyUp(sf::Keyboard::Key key) { return std::find(_KeysUp.begin(), _KeysUp.end(), key) != _KeysUp.end(); } bool Keyboard::isKeyDown(sf::Keyboard::Key key) { return std::find(_KeysDown.begin(), _KeysDown.end(), key) != _KeysDown.end(); } void Keyboard::resetKeys() { _KeysUp.clear(); _KeysDown.clear(); } void Keyboard::setKeyUp(sf::Keyboard::Key key) { _KeysUp.push_back(key); } void Keyboard::setKeyDown(sf::Keyboard::Key key) { _KeysDown.push_back(key); } }
21.275
85
0.60517
astrellon
0e46716c715ab49ca4c735de2458309957798b73
270
hpp
C++
include/UTemplate/StdName/Name_list.hpp
Ubpa/Template
9d501bbf9d306d7c7dc2c8ac86247ba346dc4710
[ "MIT" ]
16
2020-02-15T06:16:22.000Z
2021-10-31T13:49:05.000Z
include/UTemplate/StdName/Name_list.hpp
Ubpa/Template
9d501bbf9d306d7c7dc2c8ac86247ba346dc4710
[ "MIT" ]
null
null
null
include/UTemplate/StdName/Name_list.hpp
Ubpa/Template
9d501bbf9d306d7c7dc2c8ac86247ba346dc4710
[ "MIT" ]
4
2020-08-06T04:46:14.000Z
2022-03-07T07:31:04.000Z
#pragma once #include "../Name.hpp" #include <list> template<typename T> struct Ubpa::details::custom_type_name<std::list<T>> { static constexpr auto get() noexcept { return concat_seq( TSTR("std::list<{"), type_name<T>(), TStrC_of<'}', '>'>{} ); } };
15.882353
54
0.622222
Ubpa
0e46f42529f2eed7cb5196249fed406637d1f5d6
5,032
hpp
C++
src/controls/TreeViewModelAdaptor.hpp
oclero/luna
00bd5736e7bab57daa5d622bcd5379992ca6505c
[ "MIT" ]
5
2021-07-19T19:57:41.000Z
2021-09-25T01:41:13.000Z
src/controls/TreeViewModelAdaptor.hpp
chiefstone/luna
00bd5736e7bab57daa5d622bcd5379992ca6505c
[ "MIT" ]
2
2021-09-25T08:35:49.000Z
2021-09-25T11:14:49.000Z
src/controls/TreeViewModelAdaptor.hpp
chiefstone/luna
00bd5736e7bab57daa5d622bcd5379992ca6505c
[ "MIT" ]
3
2021-08-20T10:19:12.000Z
2021-09-25T10:46:40.000Z
#pragma once #include <QSet> #include <QPointer> #include <QAbstractItemModel> #include <QItemSelectionModel> #include <QPersistentModelIndex> class TreeViewModelAdaptor : public QAbstractItemModel { Q_OBJECT Q_PROPERTY(QAbstractItemModel* model READ model WRITE setModel NOTIFY modelChanged) Q_PROPERTY(QModelIndex rootIndex READ rootIndex WRITE setRootIndex RESET resetRootIndex NOTIFY rootIndexChanged) struct TreeItem; public: explicit TreeViewModelAdaptor(QObject* parent = nullptr); QAbstractItemModel* model() const; const QModelIndex& rootIndex() const; void setRootIndex(const QModelIndex& idx); void resetRootIndex(); QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; QModelIndex parent(const QModelIndex& child) const; int rowCount(const QModelIndex& parent = QModelIndex()) const; int columnCount(const QModelIndex& parent = QModelIndex()) const; enum { DepthRole = Qt::UserRole - 5, ExpandedRole, HasChildrenRole, HasSiblingRole, ModelIndexRole, }; QHash<int, QByteArray> roleNames() const; QVariant data(const QModelIndex&, int role) const; bool setData(const QModelIndex& index, const QVariant& value, int role); QVariant headerData(int section, Qt::Orientation orientation, int role) const; void clearModelData(); bool isVisible(const QModelIndex& index); bool childrenVisible(const QModelIndex& index); QModelIndex mapToModel(const QModelIndex& index) const; QModelIndex mapFromModel(const QModelIndex& index) const; QModelIndex mapToModel(int row) const; Q_INVOKABLE QItemSelection selectionForRowRange(const QModelIndex& fromIndex, const QModelIndex& toIndex) const; void showModelTopLevelItems(bool doInsertRows = true); void showModelChildItems( const TreeItem& parent, int start, int end, bool doInsertRows = true, bool doExpandPendingRows = true); int itemIndex(const QModelIndex& index) const; void expandPendingRows(bool doInsertRows = true); int lastChildIndex(const QModelIndex& index); void removeVisibleRows(int startIndex, int endIndex, bool doRemoveRows = true); void dump() const; bool testConsistency(bool dumpOnFail = false) const; using QAbstractItemModel::hasChildren; signals: void modelChanged(QAbstractItemModel* model); void rootIndexChanged(); void expanded(const QModelIndex& index); void collapsed(const QModelIndex& index); public slots: void expand(const QModelIndex&); void collapse(const QModelIndex&); void setModel(QAbstractItemModel* model); bool isExpanded(const QModelIndex&) const; bool isExpanded(int row) const; bool hasChildren(int row) const; bool hasSiblings(int row) const; int depthAtRow(int row) const; void expandRow(int n); void collapseRow(int n); private slots: void modelHasBeenDestroyed(); void modelHasBeenReset(); void modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRigth, const QVector<int>& roles); void modelLayoutAboutToBeChanged( const QList<QPersistentModelIndex>& parents, QAbstractItemModel::LayoutChangeHint hint); void modelLayoutChanged(const QList<QPersistentModelIndex>& parents, QAbstractItemModel::LayoutChangeHint hint); void modelRowsAboutToBeInserted(const QModelIndex& parent, int start, int end); void modelRowsAboutToBeMoved(const QModelIndex& sourceParent, int sourceStart, int sourceEnd, const QModelIndex& destinationParent, int destinationRow); void modelRowsAboutToBeRemoved(const QModelIndex& parent, int start, int end); void modelRowsInserted(const QModelIndex& parent, int start, int end); void modelRowsMoved(const QModelIndex& sourceParent, int sourceStart, int sourceEnd, const QModelIndex& destinationParent, int destinationRow); void modelRowsRemoved(const QModelIndex& parent, int start, int end); private: struct TreeItem { QPersistentModelIndex index; int depth; bool expanded; explicit TreeItem(const QModelIndex& idx = {}, int d = 0, int e = false) : index(idx) , depth(d) , expanded(e) {} inline bool operator==(const TreeItem& other) const { return this->index == other.index; } }; struct DataChangedParams { QModelIndex topLeft; QModelIndex bottomRight; QVector<int> roles; }; struct SignalFreezer { SignalFreezer(TreeViewModelAdaptor* parent) : parent(parent) { parent->enableSignalAggregation(); } ~SignalFreezer() { parent->disableSignalAggregation(); } private: TreeViewModelAdaptor* parent; }; void enableSignalAggregation(); void disableSignalAggregation(); bool isAggregatingSignals() const; void queueDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles); void emitQueuedSignals(); QPointer<QAbstractItemModel> _model = nullptr; QPersistentModelIndex _rootIndex; QList<TreeItem> _items; QSet<QPersistentModelIndex> _expandedItems; QList<TreeItem*> _itemsToExpand; mutable int _lastItemIndex = 0; bool _visibleRowsMoved = false; int _signalAggregatorStack = 0; QVector<DataChangedParams> _queuedDataChanged; int _column = 0; };
32.464516
113
0.783386
oclero
0e4a59069b9151279c3ec782557d638585c2baa2
381
hpp
C++
EyeOfSauronDHTMonitor/tests/test_esdhttp.hpp
zhaishuai/EyeOfSauronDHTMonitor
5f4fdb6056f54c13b7f47821bb714c1a041f5f16
[ "MIT" ]
1
2017-10-06T02:01:59.000Z
2017-10-06T02:01:59.000Z
EyeOfSauronDHTMonitor/tests/test_esdhttp.hpp
zhaishuai/EyeOfSauronDHTMonitor
5f4fdb6056f54c13b7f47821bb714c1a041f5f16
[ "MIT" ]
1
2016-01-24T04:05:04.000Z
2016-01-25T14:43:35.000Z
EyeOfSauronDHTMonitor/tests/test_esdhttp.hpp
zhaishuai/EyeOfSauronDHTMonitor
5f4fdb6056f54c13b7f47821bb714c1a041f5f16
[ "MIT" ]
null
null
null
// // test_esdhttp.hpp // EyeOfSauronDHTMonitor // // Created by shuaizhai on 4/25/16. // Copyright © 2016 com.dhtMonitor.www. All rights reserved. // #ifndef test_esdhttp_hpp #define test_esdhttp_hpp #include <stdio.h> #include "ESDHttpUtility.hpp" #include "ESDHttpProtocol.hpp" namespace test_esdhttp { void test_esdhttp(); } #endif /* test_esdhttp_hpp */
16.565217
61
0.711286
zhaishuai
0e4ae30186abac669f5fbad7565a7cf6949110b3
43,845
cpp
C++
vendor/Arduino/libraries/RF24Network/RF24Network.cpp
hvos234/raspberrypi.home.website
72376beb55167da4b5fadda51992724451166129
[ "BSD-3-Clause" ]
null
null
null
vendor/Arduino/libraries/RF24Network/RF24Network.cpp
hvos234/raspberrypi.home.website
72376beb55167da4b5fadda51992724451166129
[ "BSD-3-Clause" ]
null
null
null
vendor/Arduino/libraries/RF24Network/RF24Network.cpp
hvos234/raspberrypi.home.website
72376beb55167da4b5fadda51992724451166129
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2011 James Coliz, Jr. <maniacbug@ymail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. */ #include "RF24Network_config.h" #if defined (RF24_LINUX) #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include <iostream> #include <algorithm> #include <RF24/RF24.h> #include "RF24Network.h" #else #include "RF24.h" #include "RF24Network.h" #endif #if defined (ENABLE_SLEEP_MODE) && !defined (RF24_LINUX) && !defined (__ARDUINO_X86__) #include <avr/sleep.h> #include <avr/power.h> volatile byte sleep_cycles_remaining; volatile bool wasInterrupted; #endif uint16_t RF24NetworkHeader::next_id = 1; #if defined ENABLE_NETWORK_STATS uint32_t RF24Network::nFails = 0; uint32_t RF24Network::nOK = 0; #endif uint64_t pipe_address( uint16_t node, uint8_t pipe ); #if defined (RF24NetworkMulticast) uint16_t levelToAddress( uint8_t level ); #endif bool is_valid_address( uint16_t node ); /******************************************************************/ #if defined (RF24_LINUX) #if !defined (DUAL_HEAD_RADIO) RF24Network::RF24Network( RF24& _radio ): radio(_radio), frame_size(MAX_FRAME_SIZE) #else RF24Network::RF24Network( RF24& _radio, RF24& _radio1 ): radio(_radio), radio1(_radio1),frame_size(MAX_FRAME_SIZE) #endif { } #elif !defined (DUAL_HEAD_RADIO) RF24Network::RF24Network( RF24& _radio ): radio(_radio), next_frame(frame_queue) { #if !defined ( DISABLE_FRAGMENTATION ) frag_queue.message_buffer=&frag_queue_message_buffer[0]; frag_ptr = &frag_queue; #endif } #else RF24Network::RF24Network( RF24& _radio, RF24& _radio1 ): radio(_radio), radio1(_radio1), next_frame(frame_queue) { #if !defined ( DISABLE_FRAGMENTATION ) frag_queue.message_buffer=&frag_queue_message_buffer[0]; frag_ptr = &frag_queue; #endif } #endif /******************************************************************/ void RF24Network::begin(uint8_t _channel, uint16_t _node_address ) { if (! is_valid_address(_node_address) ) return; node_address = _node_address; if ( ! radio.isValid() ){ return; } // Set up the radio the way we want it to look if(_channel != USE_CURRENT_CHANNEL){ radio.setChannel(_channel); } //radio.enableDynamicAck(); radio.setAutoAck(0,0); #if defined (ENABLE_DYNAMIC_PAYLOADS) radio.enableDynamicPayloads(); #endif // Use different retry periods to reduce data collisions uint8_t retryVar = (((node_address % 6)+1) *2) + 3; radio.setRetries(retryVar, 5); // max about 85ms per attempt txTimeout = 25; routeTimeout = txTimeout*3; // Adjust for max delay per node within a single chain #if defined (DUAL_HEAD_RADIO) radio1.setChannel(_channel); radio1.enableDynamicAck(); radio1.enableDynamicPayloads(); #endif // Setup our address helper cache setup_address(); // Open up all listening pipes uint8_t i = 6; while (i--){ radio.openReadingPipe(i,pipe_address(_node_address,i)); } radio.startListening(); } /******************************************************************/ #if defined ENABLE_NETWORK_STATS void RF24Network::failures(uint32_t *_fails, uint32_t *_ok){ *_fails = nFails; *_ok = nOK; } #endif /******************************************************************/ uint8_t RF24Network::update(void) { // if there is data ready uint8_t pipe_num; uint8_t returnVal = 0; // If bypass is enabled, continue although incoming user data may be dropped // Allows system payloads to be read while user cache is full // Incoming Hold prevents data from being read from the radio, preventing incoming payloads from being acked #if !defined (RF24_LINUX) if(!(networkFlags & FLAG_BYPASS_HOLDS)){ if( (networkFlags & FLAG_HOLD_INCOMING) || (next_frame-frame_queue) + 34 > MAIN_BUFFER_SIZE ){ if(!available()){ networkFlags &= ~FLAG_HOLD_INCOMING; }else{ return 0; } } } #endif while ( radio.isValid() && radio.available(&pipe_num) ){ #if defined (ENABLE_DYNAMIC_PAYLOADS) if( (frame_size = radio.getDynamicPayloadSize() ) < sizeof(RF24NetworkHeader)){ delay(10); continue; } #else frame_size=32; #endif // Dump the payloads until we've gotten everything // Fetch the payload, and see if this was the last one. radio.read( frame_buffer, frame_size ); // Read the beginning of the frame as the header RF24NetworkHeader *header = (RF24NetworkHeader*)(&frame_buffer); #if defined (RF24_LINUX) IF_SERIAL_DEBUG(printf_P("%u: MAC Received on %u %s\n\r",millis(),pipe_num,header->toString())); if (frame_size) { IF_SERIAL_DEBUG_FRAGMENTATION_L2(printf("%u: FRG Rcv frame size %i\n",millis(),frame_size);); IF_SERIAL_DEBUG_FRAGMENTATION_L2(printf("%u: FRG Rcv frame ",millis()); const char* charPtr = reinterpret_cast<const char*>(frame_buffer); for (uint16_t i = 0; i < frame_size; i++) { printf("%02X ", charPtr[i]); }; printf("\n\r")); } #else IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Received on %u %s\n\r"),millis(),pipe_num,header->toString())); IF_SERIAL_DEBUG(const uint16_t* i = reinterpret_cast<const uint16_t*>(frame_buffer + sizeof(RF24NetworkHeader));printf_P(PSTR("%lu: NET message %04x\n\r"),millis(),*i)); #endif // Throw it away if it's not a valid address if ( !is_valid_address(header->to_node) ){ continue; } uint8_t returnVal = header->type; // Is this for us? if ( header->to_node == node_address ){ if(header->type == NETWORK_PING){ continue; } if(header->type == NETWORK_ADDR_RESPONSE ){ uint16_t requester = 04444; if(requester != node_address){ header->to_node = requester; write(header->to_node,USER_TX_TO_PHYSICAL_ADDRESS); delay(10); write(header->to_node,USER_TX_TO_PHYSICAL_ADDRESS); //printf("Fwd add response to 0%o\n",requester); continue; } } if(header->type == NETWORK_REQ_ADDRESS && node_address){ //printf("Fwd add req to 0\n"); header->from_node = node_address; header->to_node = 0; write(header->to_node,TX_NORMAL); continue; } if( (returnSysMsgs && header->type > 127) || header->type == NETWORK_ACK ){ IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu MAC: System payload rcvd %d\n"),millis(),returnVal); ); //if( (header->type < 148 || header->type > 150) && header->type != NETWORK_MORE_FRAGMENTS_NACK && header->type != EXTERNAL_DATA_TYPE && header->type!= NETWORK_LAST_FRAGMENT){ if( header->type != NETWORK_FIRST_FRAGMENT && header->type != NETWORK_MORE_FRAGMENTS && header->type != NETWORK_MORE_FRAGMENTS_NACK && header->type != EXTERNAL_DATA_TYPE && header->type!= NETWORK_LAST_FRAGMENT){ return returnVal; } } if( enqueue(header) == 2 ){ //External data received #if defined (SERIAL_DEBUG_MINIMAL) printf("ret ext\n"); #endif return EXTERNAL_DATA_TYPE; } }else{ #if defined (RF24NetworkMulticast) if( header->to_node == 0100){ if(header->type == NETWORK_POLL && node_address != 04444 ){ if( !(networkFlags & FLAG_NO_POLL) ){ header->to_node = header->from_node; header->from_node = node_address; delay(parent_pipe); write(header->to_node,USER_TX_TO_PHYSICAL_ADDRESS); } continue; } uint8_t val = enqueue(header); if(multicastRelay){ IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u MAC: FWD multicast frame from 0%o to level %u\n"),millis(),header->from_node,multicast_level+1); ); write(levelToAddress(multicast_level)<<3,4); } if( val == 2 ){ //External data received //Serial.println("ret ext multicast"); return EXTERNAL_DATA_TYPE; } }else{ write(header->to_node,1); //Send it on, indicate it is a routed payload } #else write(header->to_node,1); //Send it on, indicate it is a routed payload #endif } } return returnVal; } #if defined (RF24_LINUX) /******************************************************************/ uint8_t RF24Network::enqueue(RF24NetworkHeader* header) { uint8_t result = false; RF24NetworkFrame frame = RF24NetworkFrame(*header,frame_buffer+sizeof(RF24NetworkHeader),frame_size-sizeof(RF24NetworkHeader)); bool isFragment = ( frame.header.type == NETWORK_FIRST_FRAGMENT || frame.header.type == NETWORK_MORE_FRAGMENTS || frame.header.type == NETWORK_LAST_FRAGMENT || frame.header.type == NETWORK_MORE_FRAGMENTS_NACK); // This is sent to itself if (frame.header.from_node == node_address) { if (isFragment) { printf("Cannot enqueue multi-payload frames to self\n"); result = false; }else{ frame_queue.push(frame); result = true; } }else if (isFragment) { //The received frame contains the a fragmented payload //Set the more fragments flag to indicate a fragmented frame IF_SERIAL_DEBUG_FRAGMENTATION_L2(printf("%u: FRG Payload type %d of size %i Bytes with fragmentID '%i' received.\n\r",millis(),frame.header.type,frame.message_size,frame.header.reserved);); //Append payload result = appendFragmentToFrame(frame); //The header.reserved contains the actual header.type on the last fragment if ( result && frame.header.type == NETWORK_LAST_FRAGMENT) { IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG Last fragment received. \n",millis() );); IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET Enqueue assembled frame @%x "),millis(),frame_queue.size())); RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ] ); result=f->header.type == EXTERNAL_DATA_TYPE ? 2 : 1; //Load external payloads into a separate queue on linux if(result == 2){ external_queue.push( frameFragmentsCache[ frame.header.from_node ] ); }else{ frame_queue.push( frameFragmentsCache[ frame.header.from_node ] ); } frameFragmentsCache.erase( frame.header.from_node ); } }else{// if (frame.header.type <= MAX_USER_DEFINED_HEADER_TYPE) { //This is not a fragmented payload but a whole frame. IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET Enqueue @%x "),millis(),frame_queue.size())); // Copy the current frame into the frame queue result=frame.header.type == EXTERNAL_DATA_TYPE ? 2 : 1; //Load external payloads into a separate queue on linux if(result == 2){ external_queue.push( frame ); }else{ frame_queue.push( frame ); } }/* else { //Undefined/Unknown header.type received. Drop frame! IF_SERIAL_DEBUG_MINIMAL( printf("%u: FRG Received unknown or system header type %d with fragment id %d\n",millis(),frame.header.type, frame.header.reserved); ); //The frame is not explicitly dropped, but the given object is ignored. //FIXME: does this causes problems with memory management? }*/ if (result) { //IF_SERIAL_DEBUG(printf("ok\n\r")); } else { IF_SERIAL_DEBUG(printf("failed\n\r")); } return result; } /******************************************************************/ bool RF24Network::appendFragmentToFrame(RF24NetworkFrame frame) { // This is the first of 2 or more fragments. if (frame.header.type == NETWORK_FIRST_FRAGMENT){ if( frameFragmentsCache.count(frame.header.from_node) != 0 ){ RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ]); //Already rcvd first frag if (f->header.id == frame.header.id){ return false; } } if(frame.header.reserved > (MAX_PAYLOAD_SIZE /24) + 1 ){ IF_SERIAL_DEBUG_FRAGMENTATION( printf("%u FRG Too many fragments in payload %u, dropping...",millis(),frame.header.reserved); ); // If there are more fragments than we can possibly handle, return return false; } frameFragmentsCache[ frame.header.from_node ] = frame; return true; }else if ( frame.header.type == NETWORK_MORE_FRAGMENTS || frame.header.type == NETWORK_MORE_FRAGMENTS_NACK ){ if( frameFragmentsCache.count(frame.header.from_node) < 1 ){ return false; } RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ]); if( f->header.reserved - 1 == frame.header.reserved && f->header.id == frame.header.id){ // Cache the fragment memcpy(f->message_buffer+f->message_size, frame.message_buffer, frame.message_size); f->message_size += frame.message_size; //Increment message size f->header = frame.header; //Update header return true; } else { IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG Dropping fragment for frame with header id:%d, out of order fragment(s).\n",millis(),frame.header.id);); return false; } }else if ( frame.header.type == NETWORK_LAST_FRAGMENT ){ //We have received the last fragment if(frameFragmentsCache.count(frame.header.from_node) < 1){ return false; } //Create pointer to the cached frame RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ]); if( f->message_size + frame.message_size > MAX_PAYLOAD_SIZE){ IF_SERIAL_DEBUG_FRAGMENTATION( printf("%u FRG Frame of size %u plus enqueued frame of size %u exceeds max payload size \n",millis(),frame.message_size,f->message_size); ); return false; } //Error checking for missed fragments and payload size if ( f->header.reserved-1 != 1 || f->header.id != frame.header.id) { IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG Duplicate or out of sequence frame %d, expected %d. Cleared.\n",millis(),frame.header.reserved,f->header.reserved);); //frameFragmentsCache.erase( std::make_pair(frame.header.id,frame.header.from_node) ); return false; } //The user specified header.type is sent with the last fragment in the reserved field frame.header.type = frame.header.reserved; frame.header.reserved = 1; //Append the received fragment to the cached frame memcpy(f->message_buffer+f->message_size, frame.message_buffer, frame.message_size); f->message_size += frame.message_size; //Increment message size f->header = frame.header; //Update header return true; } return false; } /******************************************************************/ /******************************************************************/ #else // Not defined RF24_Linux: /******************************************************************/ /******************************************************************/ uint8_t RF24Network::enqueue(RF24NetworkHeader* header) { bool result = false; uint8_t message_size = frame_size - sizeof(RF24NetworkHeader); IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Enqueue @%x "),millis(),next_frame-frame_queue)); #if !defined ( DISABLE_FRAGMENTATION ) bool isFragment = header->type == NETWORK_FIRST_FRAGMENT || header->type == NETWORK_MORE_FRAGMENTS || header->type == NETWORK_LAST_FRAGMENT || header->type == NETWORK_MORE_FRAGMENTS_NACK ; if(isFragment){ if(header->type == NETWORK_FIRST_FRAGMENT){ // Drop frames exceeding max size and duplicates (MAX_PAYLOAD_SIZE needs to be divisible by 24) if(header->reserved > (MAX_PAYLOAD_SIZE / max_frame_payload_size) ){ #if defined (SERIAL_DEBUG_FRAGMENTATION) || defined (SERIAL_DEBUG_MINIMAL) printf_P(PSTR("Frag frame with %d frags exceeds MAX_PAYLOAD_SIZE or out of sequence\n"),header->reserved); #endif frag_queue.header.reserved = 0; return false; }else if(frag_queue.header.id == header->id && frag_queue.header.from_node == header->from_node){ return true; } if( (header->reserved * 24) > (MAX_PAYLOAD_SIZE - (next_frame-frame_queue)) ){ networkFlags |= FLAG_HOLD_INCOMING; radio.stopListening(); } memcpy(&frag_queue,&frame_buffer,8); memcpy(frag_queue.message_buffer,frame_buffer+sizeof(RF24NetworkHeader),message_size); //IF_SERIAL_DEBUG_FRAGMENTATION( Serial.print(F("queue first, total frags ")); Serial.println(header->reserved); ); //Store the total size of the stored frame in message_size frag_queue.message_size = message_size; --frag_queue.header.reserved; IF_SERIAL_DEBUG_FRAGMENTATION_L2( for(int i=0; i<frag_queue.message_size;i++){ Serial.println(frag_queue.message_buffer[i],HEX); } ); return true; }else // NETWORK_MORE_FRAGMENTS if(header->type == NETWORK_LAST_FRAGMENT || header->type == NETWORK_MORE_FRAGMENTS || header->type == NETWORK_MORE_FRAGMENTS_NACK){ if(frag_queue.message_size + message_size > MAX_PAYLOAD_SIZE){ #if defined (SERIAL_DEBUG_FRAGMENTATION) || defined (SERIAL_DEBUG_MINIMAL) Serial.print(F("Drop frag ")); Serial.print(header->reserved); Serial.println(F(" Size exceeds max")); #endif frag_queue.header.reserved=0; return false; } if( frag_queue.header.reserved == 0 || (header->type != NETWORK_LAST_FRAGMENT && header->reserved != frag_queue.header.reserved ) || frag_queue.header.id != header->id ){ #if defined (SERIAL_DEBUG_FRAGMENTATION) || defined (SERIAL_DEBUG_MINIMAL) Serial.print(F("Drop frag ")); Serial.print(header->reserved); //Serial.print(F(" header id ")); Serial.print(header->id); Serial.println(F(" Out of order ")); #endif return false; } memcpy(frag_queue.message_buffer+frag_queue.message_size,frame_buffer+sizeof(RF24NetworkHeader),message_size); frag_queue.message_size += message_size; if(header->type != NETWORK_LAST_FRAGMENT){ --frag_queue.header.reserved; return true; } frag_queue.header.reserved = 0; frag_queue.header.type = header->reserved; IF_SERIAL_DEBUG_FRAGMENTATION( printf_P(PSTR("fq 3: %d\n"),frag_queue.message_size); ); IF_SERIAL_DEBUG_FRAGMENTATION_L2(for(int i=0; i< frag_queue.message_size;i++){ Serial.println(frag_queue.message_buffer[i],HEX); } ); //Frame assembly complete, copy to main buffer if OK if(frag_queue.header.type == EXTERNAL_DATA_TYPE){ return 2; } #if defined (DISABLE_USER_PAYLOADS) return 0; #endif if(MAX_PAYLOAD_SIZE - (next_frame-frame_queue) >= frag_queue.message_size){ memcpy(next_frame,&frag_queue,10); memcpy(next_frame+10,frag_queue.message_buffer,frag_queue.message_size); next_frame += (10+frag_queue.message_size); IF_SERIAL_DEBUG_FRAGMENTATION( printf_P(PSTR("enq size %d\n"),frag_queue.message_size); ); return true; }else{ radio.stopListening(); networkFlags |= FLAG_HOLD_INCOMING; } IF_SERIAL_DEBUG_FRAGMENTATION( printf_P(PSTR("Drop frag payload, queue full\n")); ); return false; }//If more or last fragments }else //else is not a fragment #endif // End fragmentation enabled // Copy the current frame into the frame queue #if !defined( DISABLE_FRAGMENTATION ) if(header->type == EXTERNAL_DATA_TYPE){ memcpy(&frag_queue,&frame_buffer,8); frag_queue.message_buffer = frame_buffer+sizeof(RF24NetworkHeader); frag_queue.message_size = message_size; return 2; } #endif #if defined (DISABLE_USER_PAYLOADS) return 0; } #else if(message_size + (next_frame-frame_queue) <= MAIN_BUFFER_SIZE){ memcpy(next_frame,&frame_buffer,8); RF24NetworkFrame *f = (RF24NetworkFrame*)next_frame; f->message_size = message_size; memcpy(next_frame+10,frame_buffer+sizeof(RF24NetworkHeader),message_size); //IF_SERIAL_DEBUG_FRAGMENTATION( for(int i=0; i<message_size;i++){ Serial.print(next_frame[i],HEX); Serial.print(" : "); } Serial.println(""); ); next_frame += (message_size + 10); //IF_SERIAL_DEBUG_FRAGMENTATION( Serial.print("Enq "); Serial.println(next_frame-frame_queue); );//printf_P(PSTR("enq %d\n"),next_frame-frame_queue); ); result = true; }else{ result = false; IF_SERIAL_DEBUG(printf_P(PSTR("NET **Drop Payload** Buffer Full"))); } return result; } #endif //USER_PAYLOADS_ENABLED #endif //End not defined RF24_Linux /******************************************************************/ bool RF24Network::available(void) { #if defined (RF24_LINUX) return (!frame_queue.empty()); #else // Are there frames on the queue for us? return (next_frame > frame_queue); #endif } /******************************************************************/ uint16_t RF24Network::parent() const { if ( node_address == 0 ) return -1; else return parent_node; } /******************************************************************/ /*uint8_t RF24Network::peekData(){ return frame_queue[0]; }*/ uint16_t RF24Network::peek(RF24NetworkHeader& header) { if ( available() ) { #if defined (RF24_LINUX) RF24NetworkFrame frame = frame_queue.front(); memcpy(&header,&frame.header,sizeof(RF24NetworkHeader)); return frame.message_size; #else RF24NetworkFrame *frame = (RF24NetworkFrame*)(frame_queue); memcpy(&header,&frame->header,sizeof(RF24NetworkHeader)); return frame->message_size; #endif } return 0; } /******************************************************************/ uint16_t RF24Network::read(RF24NetworkHeader& header,void* message, uint16_t maxlen) { uint16_t bufsize = 0; #if defined (RF24_LINUX) if ( available() ) { RF24NetworkFrame frame = frame_queue.front(); // How much buffer size should we actually copy? bufsize = rf24_min(frame.message_size,maxlen); memcpy(&header,&(frame.header),sizeof(RF24NetworkHeader)); memcpy(message,frame.message_buffer,bufsize); IF_SERIAL_DEBUG(printf("%u: FRG message size %i\n",millis(),frame.message_size);); IF_SERIAL_DEBUG(printf("%u: FRG message ",millis()); const char* charPtr = reinterpret_cast<const char*>(message); for (uint16_t i = 0; i < bufsize; i++) { printf("%02X ", charPtr[i]); }; printf("\n\r")); IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET read %s\n\r"),millis(),header.toString())); frame_queue.pop(); } #else if ( available() ) { memcpy(&header,frame_queue,8); RF24NetworkFrame *f = (RF24NetworkFrame*)frame_queue; bufsize = f->message_size; if (maxlen > 0) { maxlen = rf24_min(maxlen,bufsize); memcpy(message,frame_queue+10,maxlen); IF_SERIAL_DEBUG(printf("%lu: NET message size %d\n",millis(),bufsize);); IF_SERIAL_DEBUG( uint16_t len = maxlen; printf_P(PSTR("%lu: NET r message "),millis());const uint8_t* charPtr = reinterpret_cast<const uint8_t*>(message);while(len--){ printf("%02x ",charPtr[len]);} printf_P(PSTR("\n\r") ) ); } memmove(frame_queue,frame_queue+bufsize+10,sizeof(frame_queue)- bufsize); next_frame-=bufsize+10; //IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Received %s\n\r"),millis(),header.toString())); } #endif return bufsize; } #if defined RF24NetworkMulticast /******************************************************************/ bool RF24Network::multicast(RF24NetworkHeader& header,const void* message, uint16_t len, uint8_t level){ // Fill out the header header.to_node = 0100; header.from_node = node_address; return write(header, message, len, levelToAddress(level)); } #endif /******************************************************************/ bool RF24Network::write(RF24NetworkHeader& header,const void* message, uint16_t len){ return write(header,message,len,070); } /******************************************************************/ bool RF24Network::write(RF24NetworkHeader& header,const void* message, uint16_t len, uint16_t writeDirect){ //Allows time for requests (RF24Mesh) to get through between failed writes on busy nodes while(millis()-txTime < 25){ if(update() > 127){break;} } delayMicroseconds(200); #if defined (DISABLE_FRAGMENTATION) frame_size = rf24_min(len+sizeof(RF24NetworkHeader),MAX_FRAME_SIZE); return _write(header,message,rf24_min(len,max_frame_payload_size),writeDirect); #else if(len <= max_frame_payload_size){ //Normal Write (Un-Fragmented) frame_size = len + sizeof(RF24NetworkHeader); if(_write(header,message,len,writeDirect)){ return 1; } txTime = millis(); return 0; } //Check payload size if (len > MAX_PAYLOAD_SIZE) { IF_SERIAL_DEBUG(printf("%u: NET write message failed. Given 'len' %d is bigger than the MAX Payload size %i\n\r",millis(),len,MAX_PAYLOAD_SIZE);); return false; } //Divide the message payload into chunks of max_frame_payload_size uint8_t fragment_id = (len % max_frame_payload_size != 0) + ((len ) / max_frame_payload_size); //the number of fragments to send = ceil(len/max_frame_payload_size) uint8_t msgCount = 0; IF_SERIAL_DEBUG_FRAGMENTATION(printf("%lu: FRG Total message fragments %d\n\r",millis(),fragment_id);); if(header.to_node != 0100){ networkFlags |= FLAG_FAST_FRAG; #if !defined (DUAL_HEAD_RADIO) radio.stopListening(); #endif } uint8_t retriesPerFrag = 0; uint8_t type = header.type; bool ok = 0; while (fragment_id > 0) { //Copy and fill out the header //RF24NetworkHeader fragmentHeader = header; header.reserved = fragment_id; if (fragment_id == 1) { header.type = NETWORK_LAST_FRAGMENT; //Set the last fragment flag to indicate the last fragment header.reserved = type; //The reserved field is used to transmit the header type } else { if (msgCount == 0) { header.type = NETWORK_FIRST_FRAGMENT; }else{ header.type = NETWORK_MORE_FRAGMENTS; //Set the more fragments flag to indicate a fragmented frame } } uint16_t offset = msgCount*max_frame_payload_size; uint16_t fragmentLen = rf24_min((uint16_t)(len-offset),max_frame_payload_size); //Try to send the payload chunk with the copied header frame_size = sizeof(RF24NetworkHeader)+fragmentLen; ok = _write(header,((char *)message)+offset,fragmentLen,writeDirect); if (!ok) { delay(2); ++retriesPerFrag; }else{ retriesPerFrag = 0; fragment_id--; msgCount++; } //if(writeDirect != 070){ delay(2); } //Delay 2ms between sending multicast payloads if (!ok && retriesPerFrag >= 3) { IF_SERIAL_DEBUG_FRAGMENTATION(printf("%lu: FRG TX with fragmentID '%d' failed after %d fragments. Abort.\n\r",millis(),fragment_id,msgCount);); break; } //Message was successful sent #if defined SERIAL_DEBUG_FRAGMENTATION_L2 printf("%lu: FRG message transmission with fragmentID '%d' sucessfull.\n\r",millis(),fragment_id); #endif } header.type = type; #if !defined (DUAL_HEAD_RADIO) if(networkFlags & FLAG_FAST_FRAG){ ok = radio.txStandBy(txTimeout); radio.startListening(); radio.setAutoAck(0,0); } networkFlags &= ~FLAG_FAST_FRAG; if(!ok){ return false; } #endif //int frag_delay = uint8_t(len/48); //delay( rf24_min(len/48,20)); //Return true if all the chunks where sent successfully IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG total message fragments sent %i. \n",millis(),msgCount); ); if(fragment_id > 0){ txTime = millis(); return false; } return true; #endif //Fragmentation enabled } /******************************************************************/ bool RF24Network::_write(RF24NetworkHeader& header,const void* message, uint16_t len, uint16_t writeDirect) { // Fill out the header header.from_node = node_address; // Build the full frame to send memcpy(frame_buffer,&header,sizeof(RF24NetworkHeader)); #if defined (RF24_LINUX) IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET Sending %s\n\r"),millis(),header.toString())); #else IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Sending %s\n\r"),millis(),header.toString())); #endif if (len){ #if defined (RF24_LINUX) memcpy(frame_buffer + sizeof(RF24NetworkHeader),message,rf24_min(frame_size-sizeof(RF24NetworkHeader),len)); IF_SERIAL_DEBUG(printf("%u: FRG frame size %i\n",millis(),frame_size);); IF_SERIAL_DEBUG(printf("%u: FRG frame ",millis()); const char* charPtr = reinterpret_cast<const char*>(frame_buffer); for (uint16_t i = 0; i < frame_size; i++) { printf("%02X ", charPtr[i]); }; printf("\n\r")); #else memcpy(frame_buffer + sizeof(RF24NetworkHeader),message,len); IF_SERIAL_DEBUG(uint16_t tmpLen = len;printf_P(PSTR("%lu: NET message "),millis());const uint8_t* charPtr = reinterpret_cast<const uint8_t*>(message);while(tmpLen--){ printf("%02x ",charPtr[tmpLen]);} printf_P(PSTR("\n\r") ) ); #endif } // If the user is trying to send it to himself /*if ( header.to_node == node_address ){ #if defined (RF24_LINUX) RF24NetworkFrame frame = RF24NetworkFrame(header,message,rf24_min(MAX_FRAME_SIZE-sizeof(RF24NetworkHeader),len)); #else RF24NetworkFrame frame(header,len); #endif // Just queue it in the received queue return enqueue(frame); }*/ // Otherwise send it out over the air if(writeDirect != 070){ uint8_t sendType = USER_TX_TO_LOGICAL_ADDRESS; // Payload is multicast to the first node, and routed normally to the next if(header.to_node == 0100){ sendType = USER_TX_MULTICAST; } if(header.to_node == writeDirect){ sendType = USER_TX_TO_PHYSICAL_ADDRESS; // Payload is multicast to the first node, which is the recipient } return write(writeDirect,sendType); } return write(header.to_node,TX_NORMAL); } /******************************************************************/ bool RF24Network::write(uint16_t to_node, uint8_t directTo) // Direct To: 0 = First Payload, standard routing, 1=routed payload, 2=directRoute to host, 3=directRoute to Route { bool ok = false; bool isAckType = false; if(frame_buffer[6] > 64 && frame_buffer[6] < 192 ){ isAckType=true; } /*if( ( (frame_buffer[7] % 2) && frame_buffer[6] == NETWORK_MORE_FRAGMENTS) ){ isAckType = 0; }*/ // Throw it away if it's not a valid address if ( !is_valid_address(to_node) ) return false; //Load info into our conversion structure, and get the converted address info logicalToPhysicalStruct conversion = { to_node,directTo,0}; logicalToPhysicalAddress(&conversion); #if defined (RF24_LINUX) IF_SERIAL_DEBUG(printf_P(PSTR("%u: MAC Sending to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe)); #else IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sending to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe)); #endif /**Write it*/ ok=write_to_pipe(conversion.send_node, conversion.send_pipe, conversion.multicast); if(!ok){ #if defined (RF24_LINUX) IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u: MAC Send fail to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe);); } #else IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu: MAC Send fail to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe);); } #endif if( directTo == TX_ROUTED && ok && conversion.send_node == to_node && isAckType){ RF24NetworkHeader* header = (RF24NetworkHeader*)&frame_buffer; header->type = NETWORK_ACK; // Set the payload type to NETWORK_ACK header->to_node = header->from_node; // Change the 'to' address to the 'from' address conversion.send_node = header->from_node; conversion.send_pipe = TX_ROUTED; conversion.multicast = 0; logicalToPhysicalAddress(&conversion); //Write the data using the resulting physical address frame_size = sizeof(RF24NetworkHeader); write_to_pipe(conversion.send_node, conversion.send_pipe, conversion.multicast); //dynLen=0; #if defined (RF24_LINUX) IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u MAC: Route OK to 0%o ACK sent to 0%o\n"),millis(),to_node,header->from_node); ); #else IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu MAC: Route OK to 0%o ACK sent to 0%o\n"),millis(),to_node,header->from_node); ); #endif } if( ok && conversion.send_node != to_node && (directTo==0 || directTo==3) && isAckType){ #if !defined (DUAL_HEAD_RADIO) // Now, continue listening if(networkFlags & FLAG_FAST_FRAG){ radio.txStandBy(txTimeout); networkFlags &= ~FLAG_FAST_FRAG; radio.setAutoAck(0,0); } radio.startListening(); #endif uint32_t reply_time = millis(); while( update() != NETWORK_ACK){ #if defined (RF24_LINUX) delayMicroseconds(900); #endif if(millis() - reply_time > routeTimeout){ #if defined (RF24_LINUX) IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u: MAC Network ACK fail from 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe); ); #else IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu: MAC Network ACK fail from 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe); ); #endif ok=false; break; } } } if( !(networkFlags & FLAG_FAST_FRAG) ){ #if !defined (DUAL_HEAD_RADIO) // Now, continue listening radio.startListening(); #endif } #if defined ENABLE_NETWORK_STATS if(ok == true){ ++nOK; }else{ ++nFails; } #endif return ok; } /******************************************************************/ // Provided the to_node and directTo option, it will return the resulting node and pipe bool RF24Network::logicalToPhysicalAddress(logicalToPhysicalStruct *conversionInfo){ //Create pointers so this makes sense.. kind of //We take in the to_node(logical) now, at the end of the function, output the send_node(physical) address, etc. //back to the original memory address that held the logical information. uint16_t *to_node = &conversionInfo->send_node; uint8_t *directTo = &conversionInfo->send_pipe; bool *multicast = &conversionInfo->multicast; // Where do we send this? By default, to our parent uint16_t pre_conversion_send_node = parent_node; // On which pipe uint8_t pre_conversion_send_pipe = parent_pipe %5; if(*directTo > TX_ROUTED ){ pre_conversion_send_node = *to_node; *multicast = 1; //if(*directTo == USER_TX_MULTICAST || *directTo == USER_TX_TO_PHYSICAL_ADDRESS){ pre_conversion_send_pipe=0; //} } // If the node is a direct child, else if ( is_direct_child(*to_node) ) { // Send directly pre_conversion_send_node = *to_node; // To its listening pipe pre_conversion_send_pipe = 5; } // If the node is a child of a child // talk on our child's listening pipe, // and let the direct child relay it. else if ( is_descendant(*to_node) ) { pre_conversion_send_node = direct_child_route_to(*to_node); pre_conversion_send_pipe = 5; } *to_node = pre_conversion_send_node; *directTo = pre_conversion_send_pipe; return 1; } /********************************************************/ bool RF24Network::write_to_pipe( uint16_t node, uint8_t pipe, bool multicast ) { bool ok = false; uint64_t out_pipe = pipe_address( node, pipe ); #if !defined (DUAL_HEAD_RADIO) // Open the correct pipe for writing. // First, stop listening so we can talk if(!(networkFlags & FLAG_FAST_FRAG)){ radio.stopListening(); } if(multicast){ radio.setAutoAck(0,0);}else{radio.setAutoAck(0,1);} radio.openWritingPipe(out_pipe); ok = radio.writeFast(frame_buffer, frame_size,multicast); if(!(networkFlags & FLAG_FAST_FRAG)){ ok = radio.txStandBy(txTimeout); radio.setAutoAck(0,0); } #else radio1.openWritingPipe(out_pipe); radio1.writeFast(frame_buffer, frame_size); ok = radio1.txStandBy(txTimeout,multicast); #endif #if defined (__arm__) || defined (RF24_LINUX) IF_SERIAL_DEBUG(printf_P(PSTR("%u: MAC Sent on %x %s\n\r"),millis(),(uint32_t)out_pipe,ok?PSTR("ok"):PSTR("failed"))); #else IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sent on %lx %S\n\r"),millis(),(uint32_t)out_pipe,ok?PSTR("ok"):PSTR("failed"))); #endif return ok; } /******************************************************************/ const char* RF24NetworkHeader::toString(void) const { static char buffer[45]; //snprintf_P(buffer,sizeof(buffer),PSTR("id %04x from 0%o to 0%o type %c"),id,from_node,to_node,type); sprintf_P(buffer,PSTR("id %u from 0%o to 0%o type %d"),id,from_node,to_node,type); return buffer; } /******************************************************************/ bool RF24Network::is_direct_child( uint16_t node ) { bool result = false; // A direct child of ours has the same low numbers as us, and only // one higher number. // // e.g. node 0234 is a direct child of 034, and node 01234 is a // descendant but not a direct child // First, is it even a descendant? if ( is_descendant(node) ) { // Does it only have ONE more level than us? uint16_t child_node_mask = ( ~ node_mask ) << 3; result = ( node & child_node_mask ) == 0 ; } return result; } /******************************************************************/ bool RF24Network::is_descendant( uint16_t node ) { return ( node & node_mask ) == node_address; } /******************************************************************/ void RF24Network::setup_address(void) { // First, establish the node_mask uint16_t node_mask_check = 0xFFFF; #if defined (RF24NetworkMulticast) uint8_t count = 0; #endif while ( node_address & node_mask_check ){ node_mask_check <<= 3; #if defined (RF24NetworkMulticast) count++; } multicast_level = count; #else } #endif node_mask = ~ node_mask_check; // parent mask is the next level down uint16_t parent_mask = node_mask >> 3; // parent node is the part IN the mask parent_node = node_address & parent_mask; // parent pipe is the part OUT of the mask uint16_t i = node_address; uint16_t m = parent_mask; while (m) { i >>= 3; m >>= 3; } parent_pipe = i; IF_SERIAL_DEBUG( printf_P(PSTR("setup_address node=0%o mask=0%o parent=0%o pipe=0%o\n\r"),node_address,node_mask,parent_node,parent_pipe);); } /******************************************************************/ uint16_t RF24Network::addressOfPipe( uint16_t node, uint8_t pipeNo ) { //Say this node is 013 (1011), mask is 077 or (00111111) //Say we want to use pipe 3 (11) //6 bits in node mask, so shift pipeNo 6 times left and | into address uint16_t m = node_mask >> 3; uint8_t i=0; while (m){ //While there are bits left in the node mask m>>=1; //Shift to the right i++; //Count the # of increments } return node | (pipeNo << i); } /******************************************************************/ uint16_t RF24Network::direct_child_route_to( uint16_t node ) { // Presumes that this is in fact a child!! uint16_t child_mask = ( node_mask << 3 ) | 0B111; return node & child_mask; } /******************************************************************/ /* uint8_t RF24Network::pipe_to_descendant( uint16_t node ) { uint16_t i = node; uint16_t m = node_mask; while (m) { i >>= 3; m >>= 3; } return i & 0B111; }*/ /******************************************************************/ bool RF24Network::is_valid_address( uint16_t node ) { bool result = true; while(node) { uint8_t digit = node & 0B111; #if !defined (RF24NetworkMulticast) if (digit < 1 || digit > 5) #else if (digit < 0 || digit > 5) //Allow our out of range multicast address #endif { result = false; IF_SERIAL_DEBUG_MINIMAL(printf_P(PSTR("*** WARNING *** Invalid address 0%o\n\r"),node);); break; } node >>= 3; } return result; } /******************************************************************/ #if defined (RF24NetworkMulticast) void RF24Network::multicastLevel(uint8_t level){ multicast_level = level; //radio.stopListening(); radio.openReadingPipe(0,pipe_address(levelToAddress(level),0)); //radio.startListening(); } uint16_t levelToAddress(uint8_t level){ uint16_t levelAddr = 1; if(level){ levelAddr = levelAddr << ((level-1) * 3); }else{ return 0; } return levelAddr; } #endif /******************************************************************/ uint64_t pipe_address( uint16_t node, uint8_t pipe ) { static uint8_t address_translation[] = { 0xc3,0x3c,0x33,0xce,0x3e,0xe3,0xec }; uint64_t result = 0xCCCCCCCCCCLL; uint8_t* out = reinterpret_cast<uint8_t*>(&result); // Translate the address to use our optimally chosen radio address bytes uint8_t count = 1; uint16_t dec = node; while(dec){ #if defined (RF24NetworkMulticast) if(pipe != 0 || !node) #endif out[count]=address_translation[(dec % 8)]; // Convert our decimal values to octal, translate them to address bytes, and set our address dec /= 8; count++; } #if defined (RF24NetworkMulticast) if(pipe != 0 || !node) #endif out[0] = address_translation[pipe]; #if defined (RF24NetworkMulticast) else out[1] = address_translation[count-1]; #endif #if defined (RF24_LINUX) IF_SERIAL_DEBUG(uint32_t* top = reinterpret_cast<uint32_t*>(out+1);printf_P(PSTR("%u: NET Pipe %i on node 0%o has address %x%x\n\r"),millis(),pipe,node,*top,*out)); #else IF_SERIAL_DEBUG(uint32_t* top = reinterpret_cast<uint32_t*>(out+1);printf_P(PSTR("%lu: NET Pipe %i on node 0%o has address %lx%x\n\r"),millis(),pipe,node,*top,*out)); #endif return result; } /************************ Sleep Mode ******************************************/ #if defined ENABLE_SLEEP_MODE #if !defined(__arm__) && !defined(__ARDUINO_X86__) void wakeUp(){ wasInterrupted=true; sleep_cycles_remaining = 0; } ISR(WDT_vect){ --sleep_cycles_remaining; } bool RF24Network::sleepNode( unsigned int cycles, int interruptPin ){ sleep_cycles_remaining = cycles; set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here sleep_enable(); if(interruptPin != 255){ wasInterrupted = false; //Reset Flag attachInterrupt(interruptPin,wakeUp, LOW); } #if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) WDTCR |= _BV(WDIE); #else WDTCSR |= _BV(WDIE); #endif while(sleep_cycles_remaining){ sleep_mode(); // System sleeps here } // The WDT_vect interrupt wakes the MCU from here sleep_disable(); // System continues execution here when watchdog timed out detachInterrupt(interruptPin); #if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) WDTCR &= ~_BV(WDIE); #else WDTCSR &= ~_BV(WDIE); #endif return !wasInterrupted; } void RF24Network::setup_watchdog(uint8_t prescalar){ uint8_t wdtcsr = prescalar & 7; if ( prescalar & 8 ) wdtcsr |= _BV(WDP3); MCUSR &= ~_BV(WDRF); // Clear the WD System Reset Flag #if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) WDTCR = _BV(WDCE) | _BV(WDE); // Write the WD Change enable bit to enable changing the prescaler and enable system reset WDTCR = _BV(WDCE) | wdtcsr | _BV(WDIE); // Write the prescalar bits (how long to sleep, enable the interrupt to wake the MCU #else WDTCSR = _BV(WDCE) | _BV(WDE); // Write the WD Change enable bit to enable changing the prescaler and enable system reset WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE); // Write the prescalar bits (how long to sleep, enable the interrupt to wake the MCU #endif } #endif // not ATTiny #endif // Enable sleep mode
32.990971
241
0.651887
hvos234
0e4c8eb8d1f3f06e805a435f4d9027e443b1ca1d
31,177
cpp
C++
exportGOAT/release/windows/obj/src/polymod/backends/PolymodAssetLibrary.cpp
SamuraiOfSecrets/Goatmeal-Time-v0.2
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
[ "Apache-2.0" ]
null
null
null
exportGOAT/release/windows/obj/src/polymod/backends/PolymodAssetLibrary.cpp
SamuraiOfSecrets/Goatmeal-Time-v0.2
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
[ "Apache-2.0" ]
null
null
null
exportGOAT/release/windows/obj/src/polymod/backends/PolymodAssetLibrary.cpp
SamuraiOfSecrets/Goatmeal-Time-v0.2
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_haxe_io_Encoding #include <haxe/io/Encoding.h> #endif #ifndef INCLUDED_polymod_backends_IBackend #include <polymod/backends/IBackend.h> #endif #ifndef INCLUDED_polymod_backends_PolymodAssetLibrary #include <polymod/backends/PolymodAssetLibrary.h> #endif #ifndef INCLUDED_polymod_format_ParseRules #include <polymod/format/ParseRules.h> #endif #ifndef INCLUDED_polymod_fs_SysFileSystem #include <polymod/fs/SysFileSystem.h> #endif #ifndef INCLUDED_polymod_util_Util #include <polymod/util/Util.h> #endif #ifndef INCLUDED_sys_FileSystem #include <sys/FileSystem.h> #endif #ifndef INCLUDED_sys_io_File #include <sys/io/File.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_41154335dca776f0_63_new,"polymod.backends.PolymodAssetLibrary","new",0xd3ebdd3c,"polymod.backends.PolymodAssetLibrary.new","polymod/backends/PolymodAssetLibrary.hx",63,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_88_destroy,"polymod.backends.PolymodAssetLibrary","destroy",0x1f3bd7d6,"polymod.backends.PolymodAssetLibrary.destroy","polymod/backends/PolymodAssetLibrary.hx",88,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_95_mergeAndAppendText,"polymod.backends.PolymodAssetLibrary","mergeAndAppendText",0xf742862a,"polymod.backends.PolymodAssetLibrary.mergeAndAppendText","polymod/backends/PolymodAssetLibrary.hx",95,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_101_getExtensionType,"polymod.backends.PolymodAssetLibrary","getExtensionType",0x9080a107,"polymod.backends.PolymodAssetLibrary.getExtensionType","polymod/backends/PolymodAssetLibrary.hx",101,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_114_getTextDirectly,"polymod.backends.PolymodAssetLibrary","getTextDirectly",0x8a3e4055,"polymod.backends.PolymodAssetLibrary.getTextDirectly","polymod/backends/PolymodAssetLibrary.hx",114,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_136_exists,"polymod.backends.PolymodAssetLibrary","exists",0xbb428280,"polymod.backends.PolymodAssetLibrary.exists","polymod/backends/PolymodAssetLibrary.hx",136,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_137_getText,"polymod.backends.PolymodAssetLibrary","getText",0x1a32273f,"polymod.backends.PolymodAssetLibrary.getText","polymod/backends/PolymodAssetLibrary.hx",137,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_138_getBytes,"polymod.backends.PolymodAssetLibrary","getBytes",0x81aeed99,"polymod.backends.PolymodAssetLibrary.getBytes","polymod/backends/PolymodAssetLibrary.hx",138,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_139_getPath,"polymod.backends.PolymodAssetLibrary","getPath",0x178a4037,"polymod.backends.PolymodAssetLibrary.getPath","polymod/backends/PolymodAssetLibrary.hx",139,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_141_list,"polymod.backends.PolymodAssetLibrary","list",0x99265002,"polymod.backends.PolymodAssetLibrary.list","polymod/backends/PolymodAssetLibrary.hx",141,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_144_listModFiles,"polymod.backends.PolymodAssetLibrary","listModFiles",0x114a5677,"polymod.backends.PolymodAssetLibrary.listModFiles","polymod/backends/PolymodAssetLibrary.hx",144,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_166_check,"polymod.backends.PolymodAssetLibrary","check",0x391094a4,"polymod.backends.PolymodAssetLibrary.check","polymod/backends/PolymodAssetLibrary.hx",166,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_177_getType,"polymod.backends.PolymodAssetLibrary","getType",0x1a414d4c,"polymod.backends.PolymodAssetLibrary.getType","polymod/backends/PolymodAssetLibrary.hx",177,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_187_checkDirectly,"polymod.backends.PolymodAssetLibrary","checkDirectly",0xba101aba,"polymod.backends.PolymodAssetLibrary.checkDirectly","polymod/backends/PolymodAssetLibrary.hx",187,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_211_file,"polymod.backends.PolymodAssetLibrary","file",0x952f0220,"polymod.backends.PolymodAssetLibrary.file","polymod/backends/PolymodAssetLibrary.hx",211,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_231__checkExists,"polymod.backends.PolymodAssetLibrary","_checkExists",0xbf011669,"polymod.backends.PolymodAssetLibrary._checkExists","polymod/backends/PolymodAssetLibrary.hx",231,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_246_init,"polymod.backends.PolymodAssetLibrary","init",0x972e6eb4,"polymod.backends.PolymodAssetLibrary.init","polymod/backends/PolymodAssetLibrary.hx",246,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_260_initExtensions,"polymod.backends.PolymodAssetLibrary","initExtensions",0x4b48d7e8,"polymod.backends.PolymodAssetLibrary.initExtensions","polymod/backends/PolymodAssetLibrary.hx",260,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_287__extensionSet,"polymod.backends.PolymodAssetLibrary","_extensionSet",0x73b0841e,"polymod.backends.PolymodAssetLibrary._extensionSet","polymod/backends/PolymodAssetLibrary.hx",287,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_294_initMod,"polymod.backends.PolymodAssetLibrary","initMod",0xc63f886e,"polymod.backends.PolymodAssetLibrary.initMod","polymod/backends/PolymodAssetLibrary.hx",294,0xd1edfd94) namespace polymod{ namespace backends{ void PolymodAssetLibrary_obj::__construct( ::Dynamic params){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_63_new) HXLINE( 71) this->parseRules = null(); HXLINE( 70) this->ignoredFiles = null(); HXLINE( 69) this->dirs = null(); HXLINE( 76) this->backend = ::Dynamic(params->__Field(HX_("backend",14,bc,87,fb),::hx::paccDynamic)); HXLINE( 77) this->backend->__SetField(HX_("polymodLibrary",a5,49,05,cb),::hx::ObjectPtr<OBJ_>(this),::hx::paccDynamic); HXLINE( 78) this->dirs = ( (::Array< ::String >)(params->__Field(HX_("dirs",86,66,69,42),::hx::paccDynamic)) ); HXLINE( 79) this->parseRules = ( ( ::polymod::format::ParseRules)(params->__Field(HX_("parseRules",c4,aa,37,1b),::hx::paccDynamic)) ); HXLINE( 80) ::Array< ::String > _hx_tmp; HXDLIN( 80) if (::hx::IsNotNull( params->__Field(HX_("ignoredFiles",05,36,92,57),::hx::paccDynamic) )) { HXLINE( 80) _hx_tmp = ( (::Array< ::String >)(params->__Field(HX_("ignoredFiles",05,36,92,57),::hx::paccDynamic)) )->copy(); } else { HXLINE( 80) _hx_tmp = ::Array_obj< ::String >::__new(0); } HXDLIN( 80) this->ignoredFiles = _hx_tmp; HXLINE( 81) this->extensions = ( ( ::haxe::ds::StringMap)(params->__Field(HX_("extensionMap",5d,28,7a,23),::hx::paccDynamic)) ); HXLINE( 82) ::polymod::backends::IBackend_obj::clearCache(this->backend); HXLINE( 83) this->init(); } Dynamic PolymodAssetLibrary_obj::__CreateEmpty() { return new PolymodAssetLibrary_obj; } void *PolymodAssetLibrary_obj::_hx_vtable = 0; Dynamic PolymodAssetLibrary_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< PolymodAssetLibrary_obj > _hx_result = new PolymodAssetLibrary_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool PolymodAssetLibrary_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6eaea9ac; } void PolymodAssetLibrary_obj::destroy(){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_88_destroy) HXDLIN( 88) if (::hx::IsNotNull( this->backend )) { HXLINE( 90) ::polymod::backends::IBackend_obj::destroy(this->backend); } } HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,destroy,(void)) ::String PolymodAssetLibrary_obj::mergeAndAppendText(::String id,::String modText){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_95_mergeAndAppendText) HXLINE( 96) modText = ::polymod::util::Util_obj::mergeAndAppendText(modText,id,this->dirs,this->getTextDirectly_dyn(),this->parseRules); HXLINE( 97) return modText; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,mergeAndAppendText,return ) ::String PolymodAssetLibrary_obj::getExtensionType(::String ext){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_101_getExtensionType) HXLINE( 102) ext = ext.toLowerCase(); HXLINE( 103) if ((this->extensions->exists(ext) == false)) { HXLINE( 103) return HX_("BYTES",4b,40,86,3b); } HXLINE( 104) return this->extensions->get_string(ext); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getExtensionType,return ) ::String PolymodAssetLibrary_obj::getTextDirectly(::String id,::String __o_directory){ ::String directory = __o_directory; if (::hx::IsNull(__o_directory)) directory = HX_("",00,00,00,00); HX_STACKFRAME(&_hx_pos_41154335dca776f0_114_getTextDirectly) HXLINE( 115) ::haxe::io::Bytes bytes = null(); HXLINE( 116) if (this->checkDirectly(id,directory)) { HXLINE( 118) ::String path = this->file(id,directory); HXDLIN( 118) if (!(::sys::FileSystem_obj::exists(path))) { HXLINE( 118) bytes = null(); } else { HXLINE( 118) bytes = ::sys::io::File_obj::getBytes(path); } } else { HXLINE( 122) bytes = ::polymod::backends::IBackend_obj::getBytes(this->backend,id); } HXLINE( 125) if (::hx::IsNull( bytes )) { HXLINE( 127) return null(); } else { HXLINE( 131) return bytes->getString(0,bytes->length,null()); } HXLINE( 125) return null(); } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,getTextDirectly,return ) bool PolymodAssetLibrary_obj::exists(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_136_exists) HXDLIN( 136) return ::polymod::backends::IBackend_obj::exists(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,exists,return ) ::String PolymodAssetLibrary_obj::getText(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_137_getText) HXDLIN( 137) return ::polymod::backends::IBackend_obj::getText(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getText,return ) ::haxe::io::Bytes PolymodAssetLibrary_obj::getBytes(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_138_getBytes) HXDLIN( 138) return ::polymod::backends::IBackend_obj::getBytes(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getBytes,return ) ::String PolymodAssetLibrary_obj::getPath(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_139_getPath) HXDLIN( 139) return ::polymod::backends::IBackend_obj::getPath(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getPath,return ) ::Array< ::String > PolymodAssetLibrary_obj::list(::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_141_list) HXDLIN( 141) return ::polymod::backends::IBackend_obj::list(this->backend,type); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,list,return ) ::Array< ::String > PolymodAssetLibrary_obj::listModFiles(::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_144_listModFiles) HXLINE( 145) ::Array< ::String > items = ::Array_obj< ::String >::__new(0); HXLINE( 147) { HXLINE( 147) ::Dynamic id = this->type->keys(); HXDLIN( 147) while(( (bool)(id->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){ HXLINE( 147) ::String id1 = ( (::String)(id->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) ); HXLINE( 149) bool _hx_tmp; HXDLIN( 149) if ((id1.indexOf(HX_("_append",79,f3,4a,fe),null()) != 0)) { HXLINE( 149) _hx_tmp = (id1.indexOf(HX_("_merge",f9,e9,ad,01),null()) == 0); } else { HXLINE( 149) _hx_tmp = true; } HXDLIN( 149) if (_hx_tmp) { HXLINE( 149) continue; } HXLINE( 150) bool _hx_tmp1; HXDLIN( 150) bool _hx_tmp2; HXDLIN( 150) if (::hx::IsNotNull( type )) { HXLINE( 150) _hx_tmp2 = (type == HX_("BYTES",4b,40,86,3b)); } else { HXLINE( 150) _hx_tmp2 = true; } HXDLIN( 150) if (!(_hx_tmp2)) { HXLINE( 150) _hx_tmp1 = this->check(id1,type); } else { HXLINE( 150) _hx_tmp1 = true; } HXDLIN( 150) if (_hx_tmp1) { HXLINE( 152) items->push(id1); } } } HXLINE( 156) return items; } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,listModFiles,return ) bool PolymodAssetLibrary_obj::check(::String id,::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_166_check) HXLINE( 167) bool exists = this->_checkExists(id); HXLINE( 168) bool _hx_tmp; HXDLIN( 168) bool _hx_tmp1; HXDLIN( 168) if (exists) { HXLINE( 168) _hx_tmp1 = ::hx::IsNotNull( type ); } else { HXLINE( 168) _hx_tmp1 = false; } HXDLIN( 168) if (_hx_tmp1) { HXLINE( 168) _hx_tmp = (type != HX_("BYTES",4b,40,86,3b)); } else { HXLINE( 168) _hx_tmp = false; } HXDLIN( 168) if (_hx_tmp) { HXLINE( 170) ::String otherType = this->type->get_string(id); HXLINE( 171) bool exists1; HXDLIN( 171) bool exists2; HXDLIN( 171) if ((otherType != type)) { HXLINE( 171) exists2 = (otherType == HX_("BYTES",4b,40,86,3b)); } else { HXLINE( 171) exists2 = true; } HXDLIN( 171) if (!(exists2)) { HXLINE( 171) exists1 = ::hx::IsNull( otherType ); } else { HXLINE( 171) exists1 = true; } HXDLIN( 171) if (!(exists1)) { HXLINE( 171) exists = (otherType == HX_("",00,00,00,00)); } else { HXLINE( 171) exists = true; } } HXLINE( 173) return exists; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,check,return ) ::String PolymodAssetLibrary_obj::getType(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_177_getType) HXLINE( 178) bool exists = this->_checkExists(id); HXLINE( 179) if (exists) { HXLINE( 181) return this->type->get_string(id); } HXLINE( 183) return null(); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getType,return ) bool PolymodAssetLibrary_obj::checkDirectly(::String id,::String dir){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_187_checkDirectly) HXLINE( 188) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id); HXLINE( 189) bool _hx_tmp; HXDLIN( 189) if (::hx::IsNotNull( dir )) { HXLINE( 189) _hx_tmp = (dir == HX_("",00,00,00,00)); } else { HXLINE( 189) _hx_tmp = true; } HXDLIN( 189) if (_hx_tmp) { HXLINE( 191) return ::sys::FileSystem_obj::exists(id); } else { HXLINE( 195) ::String thePath = ::polymod::util::Util_obj::uCombine(::Array_obj< ::String >::__new(3)->init(0,dir)->init(1,::polymod::util::Util_obj::sl())->init(2,id)); HXLINE( 196) if (::sys::FileSystem_obj::exists(thePath)) { HXLINE( 198) return true; } } HXLINE( 201) return false; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,checkDirectly,return ) ::String PolymodAssetLibrary_obj::file(::String id,::String __o_theDir){ ::String theDir = __o_theDir; if (::hx::IsNull(__o_theDir)) theDir = HX_("",00,00,00,00); HX_STACKFRAME(&_hx_pos_41154335dca776f0_211_file) HXLINE( 212) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id); HXLINE( 213) if ((theDir != HX_("",00,00,00,00))) { HXLINE( 215) return ::polymod::util::Util_obj::pathJoin(theDir,id); } HXLINE( 218) ::String theFile = HX_("",00,00,00,00); HXLINE( 219) { HXLINE( 219) int _g = 0; HXDLIN( 219) ::Array< ::String > _g1 = this->dirs; HXDLIN( 219) while((_g < _g1->length)){ HXLINE( 219) ::String d = _g1->__get(_g); HXDLIN( 219) _g = (_g + 1); HXLINE( 221) ::String thePath = ::polymod::util::Util_obj::pathJoin(d,id); HXLINE( 222) if (::sys::FileSystem_obj::exists(thePath)) { HXLINE( 224) theFile = thePath; } } } HXLINE( 227) return theFile; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,file,return ) bool PolymodAssetLibrary_obj::_checkExists(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_231__checkExists) HXLINE( 232) bool _hx_tmp; HXDLIN( 232) if ((this->ignoredFiles->length > 0)) { HXLINE( 232) _hx_tmp = (this->ignoredFiles->indexOf(id,null()) != -1); } else { HXLINE( 232) _hx_tmp = false; } HXDLIN( 232) if (_hx_tmp) { HXLINE( 232) return false; } HXLINE( 233) bool exists = false; HXLINE( 234) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id); HXLINE( 235) { HXLINE( 235) int _g = 0; HXDLIN( 235) ::Array< ::String > _g1 = this->dirs; HXDLIN( 235) while((_g < _g1->length)){ HXLINE( 235) ::String d = _g1->__get(_g); HXDLIN( 235) _g = (_g + 1); HXLINE( 237) if (::sys::FileSystem_obj::exists(::polymod::util::Util_obj::pathJoin(d,id))) { HXLINE( 239) exists = true; } } } HXLINE( 242) return exists; } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,_checkExists,return ) void PolymodAssetLibrary_obj::init(){ HX_GC_STACKFRAME(&_hx_pos_41154335dca776f0_246_init) HXLINE( 247) this->type = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 248) this->initExtensions(); HXLINE( 249) if (::hx::IsNull( this->parseRules )) { HXLINE( 249) this->parseRules = ::polymod::format::ParseRules_obj::getDefault(); } HXLINE( 250) if (::hx::IsNotNull( this->dirs )) { HXLINE( 252) int _g = 0; HXDLIN( 252) ::Array< ::String > _g1 = this->dirs; HXDLIN( 252) while((_g < _g1->length)){ HXLINE( 252) ::String d = _g1->__get(_g); HXDLIN( 252) _g = (_g + 1); HXLINE( 254) this->initMod(d); } } } HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,init,(void)) void PolymodAssetLibrary_obj::initExtensions(){ HX_GC_STACKFRAME(&_hx_pos_41154335dca776f0_260_initExtensions) HXLINE( 261) this->extensions = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 262) this->_extensionSet(HX_("mp3",70,17,53,00),HX_("AUDIO_GENERIC",2e,f6,26,23)); HXLINE( 263) this->_extensionSet(HX_("ogg",4f,94,54,00),HX_("AUDIO_GENERIC",2e,f6,26,23)); HXLINE( 264) this->_extensionSet(HX_("wav",2c,a1,5a,00),HX_("AUDIO_GENERIC",2e,f6,26,23)); HXLINE( 265) this->_extensionSet(HX_("jpg",e1,d0,50,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 266) this->_extensionSet(HX_("png",a9,5c,55,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 267) this->_extensionSet(HX_("gif",04,84,4e,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 268) this->_extensionSet(HX_("tga",8e,5f,58,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 269) this->_extensionSet(HX_("bmp",45,bc,4a,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 270) this->_extensionSet(HX_("tif",51,61,58,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 271) this->_extensionSet(HX_("tiff",f5,c5,fc,4c),HX_("IMAGE",3b,57,57,3b)); HXLINE( 272) this->_extensionSet(HX_("txt",70,6e,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 273) this->_extensionSet(HX_("xml",d7,6d,5b,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 274) this->_extensionSet(HX_("json",28,42,68,46),HX_("TEXT",ad,94,ba,37)); HXLINE( 275) this->_extensionSet(HX_("csv",c6,83,4b,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 276) this->_extensionSet(HX_("tsv",17,6a,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 277) this->_extensionSet(HX_("mpf",a3,17,53,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 278) this->_extensionSet(HX_("tsx",19,6a,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 279) this->_extensionSet(HX_("tmx",df,64,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 280) this->_extensionSet(HX_("vdf",78,e1,59,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 281) this->_extensionSet(HX_("ttf",e6,6a,58,00),HX_("FONT",cf,25,81,2e)); HXLINE( 282) this->_extensionSet(HX_("otf",a1,9f,54,00),HX_("FONT",cf,25,81,2e)); } HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,initExtensions,(void)) void PolymodAssetLibrary_obj::_extensionSet(::String str,::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_287__extensionSet) HXDLIN( 287) if ((this->extensions->exists(str) == false)) { HXLINE( 289) this->extensions->set(str,type); } } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,_extensionSet,(void)) void PolymodAssetLibrary_obj::initMod(::String d){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_294_initMod) HXLINE( 295) if (::hx::IsNull( d )) { HXLINE( 295) return; } HXLINE( 297) ::Array< ::String > all = null(); HXLINE( 299) bool _hx_tmp; HXDLIN( 299) if ((d != HX_("",00,00,00,00))) { HXLINE( 299) _hx_tmp = ::hx::IsNull( d ); } else { HXLINE( 299) _hx_tmp = true; } HXDLIN( 299) if (_hx_tmp) { HXLINE( 301) all = ::Array_obj< ::String >::__new(0); } HXLINE( 304) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 306) if (::sys::FileSystem_obj::exists(d)) { HXLINE( 308) all = ::polymod::fs::SysFileSystem_obj::readDirectoryRecursive(d); } else { HXLINE( 312) all = ::Array_obj< ::String >::__new(0); } } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic msg = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 317) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown((((HX_("ModAssetLibrary._initMod(",b4,86,f3,80) + d) + HX_(") failed : ",72,52,be,0b)) + ::Std_obj::string(msg)))); } else { HX_STACK_DO_THROW(_hx_e); } } HXLINE( 319) { HXLINE( 319) int _g = 0; HXDLIN( 319) while((_g < all->length)){ HXLINE( 319) ::String f = all->__get(_g); HXDLIN( 319) _g = (_g + 1); HXLINE( 321) int doti = ::polymod::util::Util_obj::uLastIndexOf(f,HX_(".",2e,00,00,00),null()); HXLINE( 322) ::String ext; HXDLIN( 322) if ((doti != -1)) { HXLINE( 322) ext = f.substring((doti + 1),null()); } else { HXLINE( 322) ext = HX_("",00,00,00,00); } HXLINE( 323) ext = ext.toLowerCase(); HXLINE( 324) ::String assetType = this->getExtensionType(ext); HXLINE( 325) this->type->set(f,assetType); } } } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,initMod,(void)) ::hx::ObjectPtr< PolymodAssetLibrary_obj > PolymodAssetLibrary_obj::__new( ::Dynamic params) { ::hx::ObjectPtr< PolymodAssetLibrary_obj > __this = new PolymodAssetLibrary_obj(); __this->__construct(params); return __this; } ::hx::ObjectPtr< PolymodAssetLibrary_obj > PolymodAssetLibrary_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic params) { PolymodAssetLibrary_obj *__this = (PolymodAssetLibrary_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(PolymodAssetLibrary_obj), true, "polymod.backends.PolymodAssetLibrary")); *(void **)__this = PolymodAssetLibrary_obj::_hx_vtable; __this->__construct(params); return __this; } PolymodAssetLibrary_obj::PolymodAssetLibrary_obj() { } void PolymodAssetLibrary_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(PolymodAssetLibrary); HX_MARK_MEMBER_NAME(backend,"backend"); HX_MARK_MEMBER_NAME(type,"type"); HX_MARK_MEMBER_NAME(dirs,"dirs"); HX_MARK_MEMBER_NAME(ignoredFiles,"ignoredFiles"); HX_MARK_MEMBER_NAME(parseRules,"parseRules"); HX_MARK_MEMBER_NAME(extensions,"extensions"); HX_MARK_END_CLASS(); } void PolymodAssetLibrary_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(backend,"backend"); HX_VISIT_MEMBER_NAME(type,"type"); HX_VISIT_MEMBER_NAME(dirs,"dirs"); HX_VISIT_MEMBER_NAME(ignoredFiles,"ignoredFiles"); HX_VISIT_MEMBER_NAME(parseRules,"parseRules"); HX_VISIT_MEMBER_NAME(extensions,"extensions"); } ::hx::Val PolymodAssetLibrary_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"type") ) { return ::hx::Val( type ); } if (HX_FIELD_EQ(inName,"dirs") ) { return ::hx::Val( dirs ); } if (HX_FIELD_EQ(inName,"list") ) { return ::hx::Val( list_dyn() ); } if (HX_FIELD_EQ(inName,"file") ) { return ::hx::Val( file_dyn() ); } if (HX_FIELD_EQ(inName,"init") ) { return ::hx::Val( init_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"check") ) { return ::hx::Val( check_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"exists") ) { return ::hx::Val( exists_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"backend") ) { return ::hx::Val( backend ); } if (HX_FIELD_EQ(inName,"destroy") ) { return ::hx::Val( destroy_dyn() ); } if (HX_FIELD_EQ(inName,"getText") ) { return ::hx::Val( getText_dyn() ); } if (HX_FIELD_EQ(inName,"getPath") ) { return ::hx::Val( getPath_dyn() ); } if (HX_FIELD_EQ(inName,"getType") ) { return ::hx::Val( getType_dyn() ); } if (HX_FIELD_EQ(inName,"initMod") ) { return ::hx::Val( initMod_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"getBytes") ) { return ::hx::Val( getBytes_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"parseRules") ) { return ::hx::Val( parseRules ); } if (HX_FIELD_EQ(inName,"extensions") ) { return ::hx::Val( extensions ); } break; case 12: if (HX_FIELD_EQ(inName,"ignoredFiles") ) { return ::hx::Val( ignoredFiles ); } if (HX_FIELD_EQ(inName,"listModFiles") ) { return ::hx::Val( listModFiles_dyn() ); } if (HX_FIELD_EQ(inName,"_checkExists") ) { return ::hx::Val( _checkExists_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"checkDirectly") ) { return ::hx::Val( checkDirectly_dyn() ); } if (HX_FIELD_EQ(inName,"_extensionSet") ) { return ::hx::Val( _extensionSet_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"initExtensions") ) { return ::hx::Val( initExtensions_dyn() ); } break; case 15: if (HX_FIELD_EQ(inName,"getTextDirectly") ) { return ::hx::Val( getTextDirectly_dyn() ); } break; case 16: if (HX_FIELD_EQ(inName,"getExtensionType") ) { return ::hx::Val( getExtensionType_dyn() ); } break; case 18: if (HX_FIELD_EQ(inName,"mergeAndAppendText") ) { return ::hx::Val( mergeAndAppendText_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val PolymodAssetLibrary_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } if (HX_FIELD_EQ(inName,"dirs") ) { dirs=inValue.Cast< ::Array< ::String > >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"backend") ) { backend=inValue.Cast< ::Dynamic >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"parseRules") ) { parseRules=inValue.Cast< ::polymod::format::ParseRules >(); return inValue; } if (HX_FIELD_EQ(inName,"extensions") ) { extensions=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"ignoredFiles") ) { ignoredFiles=inValue.Cast< ::Array< ::String > >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void PolymodAssetLibrary_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("backend",14,bc,87,fb)); outFields->push(HX_("type",ba,f2,08,4d)); outFields->push(HX_("dirs",86,66,69,42)); outFields->push(HX_("ignoredFiles",05,36,92,57)); outFields->push(HX_("parseRules",c4,aa,37,1b)); outFields->push(HX_("extensions",14,7c,70,89)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo PolymodAssetLibrary_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(PolymodAssetLibrary_obj,backend),HX_("backend",14,bc,87,fb)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(PolymodAssetLibrary_obj,type),HX_("type",ba,f2,08,4d)}, {::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PolymodAssetLibrary_obj,dirs),HX_("dirs",86,66,69,42)}, {::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PolymodAssetLibrary_obj,ignoredFiles),HX_("ignoredFiles",05,36,92,57)}, {::hx::fsObject /* ::polymod::format::ParseRules */ ,(int)offsetof(PolymodAssetLibrary_obj,parseRules),HX_("parseRules",c4,aa,37,1b)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(PolymodAssetLibrary_obj,extensions),HX_("extensions",14,7c,70,89)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *PolymodAssetLibrary_obj_sStaticStorageInfo = 0; #endif static ::String PolymodAssetLibrary_obj_sMemberFields[] = { HX_("backend",14,bc,87,fb), HX_("type",ba,f2,08,4d), HX_("dirs",86,66,69,42), HX_("ignoredFiles",05,36,92,57), HX_("parseRules",c4,aa,37,1b), HX_("extensions",14,7c,70,89), HX_("destroy",fa,2c,86,24), HX_("mergeAndAppendText",86,bb,89,90), HX_("getExtensionType",63,87,3c,56), HX_("getTextDirectly",79,59,58,bb), HX_("exists",dc,1d,e0,bf), HX_("getText",63,7c,7c,1f), HX_("getBytes",f5,17,6f,1d), HX_("getPath",5b,95,d4,1c), HX_("list",5e,1c,b3,47), HX_("listModFiles",d3,de,44,5a), HX_("check",c8,98,b6,45), HX_("getType",70,a2,8b,1f), HX_("checkDirectly",de,e2,4c,4c), HX_("file",7c,ce,bb,43), HX_("_checkExists",c5,9e,fb,07), HX_("init",10,3b,bb,45), HX_("initExtensions",44,2f,3b,ae), HX_("_extensionSet",42,4c,ed,05), HX_("initMod",92,dd,89,cb), ::String(null()) }; ::hx::Class PolymodAssetLibrary_obj::__mClass; void PolymodAssetLibrary_obj::__register() { PolymodAssetLibrary_obj _hx_dummy; PolymodAssetLibrary_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("polymod.backends.PolymodAssetLibrary",4a,cf,f5,08); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(PolymodAssetLibrary_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< PolymodAssetLibrary_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = PolymodAssetLibrary_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = PolymodAssetLibrary_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace polymod } // end namespace backends
44.411681
253
0.687077
SamuraiOfSecrets
0e4da04dc84d73b9ce4275f2637c9f96f95c4dce
6,521
cpp
C++
tools/llvm37-pdbdump/ClassDefinitionDumper.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
tools/llvm37-pdbdump/ClassDefinitionDumper.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
tools/llvm37-pdbdump/ClassDefinitionDumper.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
//===- ClassDefinitionDumper.cpp --------------------------------*- C++ -*-===// // // The LLVM37 Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ClassDefinitionDumper.h" #include "EnumDumper.h" #include "FunctionDumper.h" #include "LinePrinter.h" #include "llvm37-pdbdump.h" #include "TypedefDumper.h" #include "VariableDumper.h" #include "llvm37/DebugInfo/PDB/IPDBSession.h" #include "llvm37/DebugInfo/PDB/PDBExtras.h" #include "llvm37/DebugInfo/PDB/PDBSymbolData.h" #include "llvm37/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm37/DebugInfo/PDB/PDBSymbolTypeBaseClass.h" #include "llvm37/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm37/DebugInfo/PDB/PDBSymbolTypePointer.h" #include "llvm37/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm37/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm37/DebugInfo/PDB/PDBSymbolTypeVTable.h" #include "llvm37/Support/Format.h" using namespace llvm37; ClassDefinitionDumper::ClassDefinitionDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void ClassDefinitionDumper::start(const PDBSymbolTypeUDT &Class) { std::string Name = Class.getName(); WithColor(Printer, PDB_ColorItem::Keyword).get() << Class.getUdtKind() << " "; WithColor(Printer, PDB_ColorItem::Type).get() << Class.getName(); auto Bases = Class.findAllChildren<PDBSymbolTypeBaseClass>(); if (Bases->getChildCount() > 0) { Printer.Indent(); Printer.NewLine(); Printer << ":"; uint32_t BaseIndex = 0; while (auto Base = Bases->getNext()) { Printer << " "; WithColor(Printer, PDB_ColorItem::Keyword).get() << Base->getAccess(); if (Base->isVirtualBaseClass()) WithColor(Printer, PDB_ColorItem::Keyword).get() << " virtual"; WithColor(Printer, PDB_ColorItem::Type).get() << " " << Base->getName(); if (++BaseIndex < Bases->getChildCount()) { Printer.NewLine(); Printer << ","; } } Printer.Unindent(); } Printer << " {"; auto Children = Class.findAllChildren(); if (Children->getChildCount() == 0) { Printer << "}"; return; } // Try to dump symbols organized by member access level. Public members // first, then protected, then private. This might be slow, so it's worth // reconsidering the value of this if performance of large PDBs is a problem. // NOTE: Access level of nested types is not recorded in the PDB, so we have // a special case for them. SymbolGroupByAccess Groups; Groups.insert(std::make_pair(0, SymbolGroup())); Groups.insert(std::make_pair((int)PDB_MemberAccess::Private, SymbolGroup())); Groups.insert( std::make_pair((int)PDB_MemberAccess::Protected, SymbolGroup())); Groups.insert(std::make_pair((int)PDB_MemberAccess::Public, SymbolGroup())); while (auto Child = Children->getNext()) { PDB_MemberAccess Access = Child->getRawSymbol().getAccess(); if (isa<PDBSymbolTypeBaseClass>(*Child)) continue; auto &AccessGroup = Groups.find((int)Access)->second; if (auto Func = dyn_cast<PDBSymbolFunc>(Child.get())) { if (Func->isCompilerGenerated() && opts::ExcludeCompilerGenerated) continue; if (Func->getLength() == 0 && !Func->isPureVirtual() && !Func->isIntroVirtualFunction()) continue; Child.release(); AccessGroup.Functions.push_back(std::unique_ptr<PDBSymbolFunc>(Func)); } else if (auto Data = dyn_cast<PDBSymbolData>(Child.get())) { Child.release(); AccessGroup.Data.push_back(std::unique_ptr<PDBSymbolData>(Data)); } else { AccessGroup.Unknown.push_back(std::move(Child)); } } int Count = 0; Count += dumpAccessGroup((PDB_MemberAccess)0, Groups[0]); Count += dumpAccessGroup(PDB_MemberAccess::Public, Groups[(int)PDB_MemberAccess::Public]); Count += dumpAccessGroup(PDB_MemberAccess::Protected, Groups[(int)PDB_MemberAccess::Protected]); Count += dumpAccessGroup(PDB_MemberAccess::Private, Groups[(int)PDB_MemberAccess::Private]); if (Count > 0) Printer.NewLine(); Printer << "}"; } int ClassDefinitionDumper::dumpAccessGroup(PDB_MemberAccess Access, const SymbolGroup &Group) { if (Group.Functions.empty() && Group.Data.empty() && Group.Unknown.empty()) return 0; int Count = 0; if (Access == PDB_MemberAccess::Private) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Keyword).get() << "private"; Printer << ":"; } else if (Access == PDB_MemberAccess::Protected) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Keyword).get() << "protected"; Printer << ":"; } else if (Access == PDB_MemberAccess::Public) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Keyword).get() << "public"; Printer << ":"; } Printer.Indent(); for (auto iter = Group.Functions.begin(), end = Group.Functions.end(); iter != end; ++iter) { ++Count; (*iter)->dump(*this); } for (auto iter = Group.Data.begin(), end = Group.Data.end(); iter != end; ++iter) { ++Count; (*iter)->dump(*this); } for (auto iter = Group.Unknown.begin(), end = Group.Unknown.end(); iter != end; ++iter) { ++Count; (*iter)->dump(*this); } Printer.Unindent(); return Count; } void ClassDefinitionDumper::dump(const PDBSymbolTypeBaseClass &Symbol) {} void ClassDefinitionDumper::dump(const PDBSymbolData &Symbol) { VariableDumper Dumper(Printer); Dumper.start(Symbol); } void ClassDefinitionDumper::dump(const PDBSymbolFunc &Symbol) { if (Printer.IsSymbolExcluded(Symbol.getName())) return; Printer.NewLine(); FunctionDumper Dumper(Printer); Dumper.start(Symbol, FunctionDumper::PointerType::None); } void ClassDefinitionDumper::dump(const PDBSymbolTypeVTable &Symbol) {} void ClassDefinitionDumper::dump(const PDBSymbolTypeEnum &Symbol) { if (Printer.IsTypeExcluded(Symbol.getName())) return; Printer.NewLine(); EnumDumper Dumper(Printer); Dumper.start(Symbol); } void ClassDefinitionDumper::dump(const PDBSymbolTypeTypedef &Symbol) { if (Printer.IsTypeExcluded(Symbol.getName())) return; Printer.NewLine(); TypedefDumper Dumper(Printer); Dumper.start(Symbol); } void ClassDefinitionDumper::dump(const PDBSymbolTypeUDT &Symbol) {}
34.141361
80
0.662935
seanbaxter
0e4deb0a3a04d919d8bee3d8939ecd0a3d6b4ba8
20,670
cxx
C++
src/Cxx/Visualization/CreateColorSeriesDemo.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/Visualization/CreateColorSeriesDemo.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/Visualization/CreateColorSeriesDemo.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkActor.h> #include <vtkCellData.h> #include <vtkColorSeries.h> #include <vtkFloatArray.h> #include <vtkLookupTable.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkPlaneSource.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <map> #include <string> #include <vector> namespace { void CreateLookupTableVTKBlue(vtkLookupTable* lut, int tableSize = 0); void CreateLookupTableVTKBrown(vtkLookupTable* lut, int tableSize = 0); void CreateLookupTableVTKRed(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKOrange(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKWhite(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKGrey(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKMagenta(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKCyan(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKYellow(vtkLookupTable* lu, int tableSize = 0); void CreateLookupTableVTKGreen(vtkLookupTable* lu, int tableSize = 0); } // namespace int main(int argc, char* argv[]) { std::string seriesName = "Red"; if (argc > 1) { seriesName = argv[1]; } // Provide some geometry int resolution = 6; vtkNew<vtkPlaneSource> aPlane; aPlane->SetXResolution(resolution); aPlane->SetYResolution(resolution); // Create cell data vtkNew<vtkFloatArray> cellData; for (int i = 0; i < resolution * resolution; i++) { cellData->InsertNextValue(i); } aPlane->Update(); // Force an update so we can set cell data aPlane->GetOutput()->GetCellData()->SetScalars(cellData); vtkNew<vtkNamedColors> colors; vtkNew<vtkLookupTable> lut; if (seriesName == "Blue") { CreateLookupTableVTKBlue(lut, resolution * resolution + 1); } else if (seriesName == "Brown") { CreateLookupTableVTKBrown(lut, resolution * resolution + 1); } else if (seriesName == "Red") { CreateLookupTableVTKRed(lut, resolution * resolution + 1); } else if (seriesName == "Orange") { CreateLookupTableVTKOrange(lut, resolution * resolution + 1); } else if (seriesName == "White") { CreateLookupTableVTKWhite(lut, resolution * resolution + 1); } else if (seriesName == "Grey") { CreateLookupTableVTKGrey(lut, resolution * resolution + 1); } else if (seriesName == "Magenta") { CreateLookupTableVTKMagenta(lut, resolution * resolution + 1); } else if (seriesName == "Cyan") { CreateLookupTableVTKCyan(lut, resolution * resolution + 1); } else if (seriesName == "Yellow") { CreateLookupTableVTKYellow(lut, resolution * resolution + 1); } else if (seriesName == "Green") { CreateLookupTableVTKGreen(lut, resolution * resolution + 1); } else { std::cout << "Bad series name: " << seriesName << std::endl; return EXIT_FAILURE; } // Setup actor and mapper vtkNew<vtkPolyDataMapper> mapper; mapper->SetLookupTable(lut); mapper->SetInputConnection(aPlane->GetOutputPort()); mapper->SetScalarModeToUseCellData(); mapper->SetScalarRange(0, resolution * resolution + 1); vtkNew<vtkActor> actor; actor->SetMapper(mapper); actor->GetProperty()->EdgeVisibilityOn(); // Setup render window, renderer, and interactor vtkNew<vtkRenderer> renderer; vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); renderWindow->SetWindowName("CreateColorSeriesDemo"); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderer->SetBackground(colors->GetColor3d("SlateGray").GetData()); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } namespace { void CreateLookupTableVTKBlue(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKBlueColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("alice_blue")); myColors->AddColor(nc->GetColor3ub("blue")); myColors->AddColor(nc->GetColor3ub("blue_light")); myColors->AddColor(nc->GetColor3ub("blue_medium")); myColors->AddColor(nc->GetColor3ub("cadet")); myColors->AddColor(nc->GetColor3ub("cobalt")); myColors->AddColor(nc->GetColor3ub("cornflower")); myColors->AddColor(nc->GetColor3ub("cerulean")); myColors->AddColor(nc->GetColor3ub("dodger_blue")); myColors->AddColor(nc->GetColor3ub("indigo")); myColors->AddColor(nc->GetColor3ub("manganese_blue")); myColors->AddColor(nc->GetColor3ub("midnight_blue")); myColors->AddColor(nc->GetColor3ub("navy")); myColors->AddColor(nc->GetColor3ub("peacock")); myColors->AddColor(nc->GetColor3ub("powder_blue")); myColors->AddColor(nc->GetColor3ub("royal_blue")); myColors->AddColor(nc->GetColor3ub("slate_blue")); myColors->AddColor(nc->GetColor3ub("slate_blue_dark")); myColors->AddColor(nc->GetColor3ub("slate_blue_light")); myColors->AddColor(nc->GetColor3ub("slate_blue_medium")); myColors->AddColor(nc->GetColor3ub("sky_blue")); myColors->AddColor(nc->GetColor3ub("sky_blue_deep")); myColors->AddColor(nc->GetColor3ub("sky_blue_light")); myColors->AddColor(nc->GetColor3ub("steel_blue")); myColors->AddColor(nc->GetColor3ub("steel_blue_light")); myColors->AddColor(nc->GetColor3ub("turquoise_blue")); myColors->AddColor(nc->GetColor3ub("ultramarine")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKBrown(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKBrownColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("beige")); myColors->AddColor(nc->GetColor3ub("brown")); myColors->AddColor(nc->GetColor3ub("brown_madder")); myColors->AddColor(nc->GetColor3ub("brown_ochre")); myColors->AddColor(nc->GetColor3ub("burlywood")); myColors->AddColor(nc->GetColor3ub("burnt_sienna")); myColors->AddColor(nc->GetColor3ub("burnt_umber")); myColors->AddColor(nc->GetColor3ub("chocolate")); myColors->AddColor(nc->GetColor3ub("deep_ochre")); myColors->AddColor(nc->GetColor3ub("flesh")); myColors->AddColor(nc->GetColor3ub("flesh_ochre")); myColors->AddColor(nc->GetColor3ub("gold_ochre")); myColors->AddColor(nc->GetColor3ub("greenish_umber")); myColors->AddColor(nc->GetColor3ub("khaki")); myColors->AddColor(nc->GetColor3ub("khaki_dark")); myColors->AddColor(nc->GetColor3ub("light_beige")); myColors->AddColor(nc->GetColor3ub("peru")); myColors->AddColor(nc->GetColor3ub("rosy_brown")); myColors->AddColor(nc->GetColor3ub("raw_sienna")); myColors->AddColor(nc->GetColor3ub("raw_umber")); myColors->AddColor(nc->GetColor3ub("sepia")); myColors->AddColor(nc->GetColor3ub("sienna")); myColors->AddColor(nc->GetColor3ub("saddle_brown")); myColors->AddColor(nc->GetColor3ub("sandy_brown")); myColors->AddColor(nc->GetColor3ub("tan")); myColors->AddColor(nc->GetColor3ub("van_dyke_brown")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKRed(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKRedColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("alizarin_crimson")); myColors->AddColor(nc->GetColor3ub("brick")); myColors->AddColor(nc->GetColor3ub("cadmium_red_deep")); myColors->AddColor(nc->GetColor3ub("coral")); myColors->AddColor(nc->GetColor3ub("coral_light")); myColors->AddColor(nc->GetColor3ub("deep_pink")); myColors->AddColor(nc->GetColor3ub("english_red")); myColors->AddColor(nc->GetColor3ub("firebrick")); myColors->AddColor(nc->GetColor3ub("geranium_lake")); myColors->AddColor(nc->GetColor3ub("hot_pink")); myColors->AddColor(nc->GetColor3ub("indian_red")); myColors->AddColor(nc->GetColor3ub("light_salmon")); myColors->AddColor(nc->GetColor3ub("madder_lake_deep")); myColors->AddColor(nc->GetColor3ub("maroon")); myColors->AddColor(nc->GetColor3ub("pink")); myColors->AddColor(nc->GetColor3ub("pink_light")); myColors->AddColor(nc->GetColor3ub("raspberry")); myColors->AddColor(nc->GetColor3ub("red")); myColors->AddColor(nc->GetColor3ub("rose_madder")); myColors->AddColor(nc->GetColor3ub("salmon")); myColors->AddColor(nc->GetColor3ub("tomato")); myColors->AddColor(nc->GetColor3ub("venetian_red")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKGrey(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; vtkNew<vtkNamedColors> nc; myColors->SetColorSchemeByName("VTKGreyColors"); myColors->AddColor(nc->GetColor3ub("cold_grey")); myColors->AddColor(nc->GetColor3ub("dim_grey")); myColors->AddColor(nc->GetColor3ub("grey")); myColors->AddColor(nc->GetColor3ub("light_grey")); myColors->AddColor(nc->GetColor3ub("slate_grey")); myColors->AddColor(nc->GetColor3ub("slate_grey_dark")); myColors->AddColor(nc->GetColor3ub("slate_grey_light")); myColors->AddColor(nc->GetColor3ub("warm_grey")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKWhite(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; vtkNew<vtkNamedColors> nc; myColors->SetColorSchemeByName("VTKWhiteColors"); myColors->AddColor(nc->GetColor3ub("antique_white")); myColors->AddColor(nc->GetColor3ub("azure")); myColors->AddColor(nc->GetColor3ub("bisque")); myColors->AddColor(nc->GetColor3ub("blanched_almond")); myColors->AddColor(nc->GetColor3ub("cornsilk")); myColors->AddColor(nc->GetColor3ub("eggshell")); myColors->AddColor(nc->GetColor3ub("floral_white")); myColors->AddColor(nc->GetColor3ub("gainsboro")); myColors->AddColor(nc->GetColor3ub("ghost_white")); myColors->AddColor(nc->GetColor3ub("honeydew")); myColors->AddColor(nc->GetColor3ub("ivory")); myColors->AddColor(nc->GetColor3ub("lavender")); myColors->AddColor(nc->GetColor3ub("lavender_blush")); myColors->AddColor(nc->GetColor3ub("lemon_chiffon")); myColors->AddColor(nc->GetColor3ub("linen")); myColors->AddColor(nc->GetColor3ub("mint_cream")); myColors->AddColor(nc->GetColor3ub("misty_rose")); myColors->AddColor(nc->GetColor3ub("moccasin")); myColors->AddColor(nc->GetColor3ub("navajo_white")); myColors->AddColor(nc->GetColor3ub("old_lace")); myColors->AddColor(nc->GetColor3ub("papaya_whip")); myColors->AddColor(nc->GetColor3ub("peach_puff")); myColors->AddColor(nc->GetColor3ub("seashell")); myColors->AddColor(nc->GetColor3ub("snow")); myColors->AddColor(nc->GetColor3ub("thistle")); myColors->AddColor(nc->GetColor3ub("titanium_white")); myColors->AddColor(nc->GetColor3ub("wheat")); myColors->AddColor(nc->GetColor3ub("white")); myColors->AddColor(nc->GetColor3ub("white_smoke")); myColors->AddColor(nc->GetColor3ub("zinc_white")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKOrange(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKOrangeColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("cadmium_orange")); myColors->AddColor(nc->GetColor3ub("cadmium_red_light")); myColors->AddColor(nc->GetColor3ub("carrot")); myColors->AddColor(nc->GetColor3ub("dark_orange")); myColors->AddColor(nc->GetColor3ub("mars_orange")); myColors->AddColor(nc->GetColor3ub("mars_yellow")); myColors->AddColor(nc->GetColor3ub("orange")); myColors->AddColor(nc->GetColor3ub("orange_red")); myColors->AddColor(nc->GetColor3ub("yellow_ochre")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKMagenta(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKMagentaColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("blue_violet")); myColors->AddColor(nc->GetColor3ub("cobalt_violet_deep")); myColors->AddColor(nc->GetColor3ub("magenta")); myColors->AddColor(nc->GetColor3ub("orchid")); myColors->AddColor(nc->GetColor3ub("orchid_dark")); myColors->AddColor(nc->GetColor3ub("orchid_medium")); myColors->AddColor(nc->GetColor3ub("permanent_red_violet")); myColors->AddColor(nc->GetColor3ub("plum")); myColors->AddColor(nc->GetColor3ub("purple")); myColors->AddColor(nc->GetColor3ub("purple_medium")); myColors->AddColor(nc->GetColor3ub("ultramarine_violet")); myColors->AddColor(nc->GetColor3ub("violet")); myColors->AddColor(nc->GetColor3ub("violet_dark")); myColors->AddColor(nc->GetColor3ub("violet_red")); myColors->AddColor(nc->GetColor3ub("violet_red_medium")); myColors->AddColor(nc->GetColor3ub("violet_red_pale")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKCyan(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKCyanColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("aquamarine")); myColors->AddColor(nc->GetColor3ub("aquamarine_medium")); myColors->AddColor(nc->GetColor3ub("cyan")); myColors->AddColor(nc->GetColor3ub("cyan_white")); myColors->AddColor(nc->GetColor3ub("turquoise")); myColors->AddColor(nc->GetColor3ub("turquoise_dark")); myColors->AddColor(nc->GetColor3ub("turquoise_medium")); myColors->AddColor(nc->GetColor3ub("turquoise_pale")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKYellow(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKYellowColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("aureoline_yellow")); myColors->AddColor(nc->GetColor3ub("banana")); myColors->AddColor(nc->GetColor3ub("cadmium_lemon")); myColors->AddColor(nc->GetColor3ub("cadmium_yellow")); myColors->AddColor(nc->GetColor3ub("cadmium_yellow_light")); myColors->AddColor(nc->GetColor3ub("gold")); myColors->AddColor(nc->GetColor3ub("goldenrod")); myColors->AddColor(nc->GetColor3ub("goldenrod_dark")); myColors->AddColor(nc->GetColor3ub("goldenrod_light")); myColors->AddColor(nc->GetColor3ub("goldenrod_pale")); myColors->AddColor(nc->GetColor3ub("light_goldenrod")); myColors->AddColor(nc->GetColor3ub("melon")); myColors->AddColor(nc->GetColor3ub("naples_yellow_deep")); myColors->AddColor(nc->GetColor3ub("yellow")); myColors->AddColor(nc->GetColor3ub("yellow_light")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } void CreateLookupTableVTKGreen(vtkLookupTable* lut, int size) { vtkNew<vtkColorSeries> myColors; myColors->SetColorSchemeByName("VTKGreenColors"); vtkNew<vtkNamedColors> nc; myColors->AddColor(nc->GetColor3ub("chartreuse")); myColors->AddColor(nc->GetColor3ub("chrome_oxide_green")); myColors->AddColor(nc->GetColor3ub("cinnabar_green")); myColors->AddColor(nc->GetColor3ub("cobalt_green")); myColors->AddColor(nc->GetColor3ub("emerald_green")); myColors->AddColor(nc->GetColor3ub("forest_green")); myColors->AddColor(nc->GetColor3ub("green")); myColors->AddColor(nc->GetColor3ub("green_dark")); myColors->AddColor(nc->GetColor3ub("green_pale")); myColors->AddColor(nc->GetColor3ub("green_yellow")); myColors->AddColor(nc->GetColor3ub("lawn_green")); myColors->AddColor(nc->GetColor3ub("lime_green")); myColors->AddColor(nc->GetColor3ub("mint")); myColors->AddColor(nc->GetColor3ub("olive")); myColors->AddColor(nc->GetColor3ub("olive_drab")); myColors->AddColor(nc->GetColor3ub("olive_green_dark")); myColors->AddColor(nc->GetColor3ub("permanent_green")); myColors->AddColor(nc->GetColor3ub("sap_green")); myColors->AddColor(nc->GetColor3ub("sea_green")); myColors->AddColor(nc->GetColor3ub("sea_green_dark")); myColors->AddColor(nc->GetColor3ub("sea_green_medium")); myColors->AddColor(nc->GetColor3ub("sea_green_light")); myColors->AddColor(nc->GetColor3ub("spring_green")); myColors->AddColor(nc->GetColor3ub("spring_green_medium")); myColors->AddColor(nc->GetColor3ub("terre_verte")); myColors->AddColor(nc->GetColor3ub("viridian_light")); myColors->AddColor(nc->GetColor3ub("yellow_green")); int numberOfColors = myColors->GetNumberOfColors(); std::cout << "Number of colors: " << numberOfColors << std::endl; lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size); lut->SetTableRange(0, lut->GetNumberOfTableValues()); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { vtkColor3ub color = myColors->GetColorRepeating(i); lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255., color.GetBlue() / 255., 1.); } } } // namespace
39.903475
73
0.715288
ajpmaclean
0e51367d286a3338f585f7234bc5edfcbbd2d1bc
1,868
cc
C++
stapl_release/test/runtime/type_traits/test_lazy_storage.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/runtime/type_traits/test_lazy_storage.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/runtime/type_traits/test_lazy_storage.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #define STAPL_RUNTIME_TEST_MODULE lazy_storage #include "utility.h" #include <stapl/runtime/type_traits/lazy_storage.hpp> template<typename T> union wrapper { stapl::lazy_storage<T> storage; int i; }; struct empty { }; constexpr bool operator==(empty const&, empty const&) noexcept { return true; } BOOST_AUTO_TEST_CASE( test_empty ) { typedef empty value_type; wrapper<value_type> u; u.storage.construct(value_type()); value_type v = u.storage.moveout(); BOOST_CHECK( v==value_type() ); } BOOST_AUTO_TEST_CASE( test_int ) { typedef int value_type; wrapper<value_type> u; u.storage.construct(42); value_type v = u.storage.moveout(); BOOST_CHECK_EQUAL( v, 42 ); } class A { public: static int constructed; int i; public: A(void) : i(42) { ++constructed; } A(A const& other) : i(other.i) { ++constructed; } ~A(void) { --constructed; } }; int A::constructed = 0; constexpr bool operator==(A const & a0, A const& a1) { return (a0.i==a1.i); } BOOST_AUTO_TEST_CASE( test_A ) { typedef A value_type; BOOST_CHECK_EQUAL( A::constructed, 0 ); { const value_type iv; BOOST_CHECK_EQUAL( A::constructed, 1 ); wrapper<value_type> u; BOOST_CHECK_EQUAL( A::constructed, 1 ); u.storage.construct(iv); BOOST_CHECK_EQUAL( A::constructed, 2 ); value_type v = u.storage.moveout(); BOOST_CHECK_EQUAL( A::constructed, 2 ); BOOST_CHECK( v==iv ); } BOOST_CHECK_EQUAL( A::constructed, 0 ); }
18.49505
74
0.682548
parasol-ppl
0e5292bed843dd33e904a5cb5caddc5068c38910
24,442
cpp
C++
src/common/DecFloat.cpp
sas9mba/FB-ISQL-autopadding
033393aa80de4274ed9469767464e9b189b26838
[ "Condor-1.1" ]
null
null
null
src/common/DecFloat.cpp
sas9mba/FB-ISQL-autopadding
033393aa80de4274ed9469767464e9b189b26838
[ "Condor-1.1" ]
null
null
null
src/common/DecFloat.cpp
sas9mba/FB-ISQL-autopadding
033393aa80de4274ed9469767464e9b189b26838
[ "Condor-1.1" ]
null
null
null
/* * PROGRAM: Decimal 64 & 128 type. * MODULE: DecFloat.cpp * DESCRIPTION: Floating point with decimal exponent. * * The contents of this file are subject to the Initial * Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by Alex Peshkov * for the Firebird Open Source RDBMS project. * * Copyright (c) 2016 Alex Peshkov <peshkoff at mail dot ru> * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. * * */ #include "firebird.h" #include "DecFloat.h" #include "StatusArg.h" #include "gen/iberror.h" extern "C" { #include "../../extern/decNumber/decimal128.h" #include "../../extern/decNumber/decimal64.h" #include "../../extern/decNumber/decNumber.h" } #include <stdlib.h> #include <string.h> #include <float.h> using namespace Firebird; namespace { struct Dec2fb { USHORT decError; ISC_STATUS fbError; }; Dec2fb dec2fb[] = { { DEC_IEEE_754_Division_by_zero, isc_decfloat_divide_by_zero }, { DEC_IEEE_754_Inexact, isc_decfloat_inexact_result }, { DEC_IEEE_754_Invalid_operation, isc_decfloat_invalid_operation }, { DEC_IEEE_754_Overflow, isc_decfloat_overflow }, { DEC_IEEE_754_Underflow, isc_decfloat_underflow }, { 0, 0 } }; class DecimalContext : public decContext { public: DecimalContext(const Decimal64*, DecimalStatus ds) : decSt(ds) { init(DEC_INIT_DECIMAL64); } DecimalContext(const Decimal128Base*, DecimalStatus ds) : decSt(ds) { init(DEC_INIT_DECIMAL128); } ~DecimalContext() NOEXCEPT_ARG(false) { // Typically exceptions should better be not thrown from destructors. // But in our case there should never be any exception raised inside // Decimal64/128 functions - C library never throw, i.e. dtor will // be never called due to exception processing. // Therefore checking status in destructor is safe. checkForExceptions(); } void checkForExceptions() { USHORT unmaskedExceptions = decSt.decExtFlag & decContextGetStatus(this); if (!unmaskedExceptions) return; decContextZeroStatus(this); for (Dec2fb* e = dec2fb; e->decError; ++e) { // Arg::Gds(isc_arith_except) as first vector element ? if (e->decError & unmaskedExceptions) Arg::Gds(e->fbError).raise(); } } private: DecimalStatus decSt; void init(int kind) { decContextDefault(this, kind); fb_assert(decSt.roundingMode < USHORT(DEC_ROUND_MAX)); enum rounding rMode = rounding(decSt.roundingMode); decContextSetRounding(this, rMode); traps = 0; // do not raise SIGFPE } }; const CDecimal128 dmax(DBL_MAX, DecimalStatus(0)), dmin(-DBL_MAX, DecimalStatus(0)); const CDecimal128 dzup(DBL_MIN, DecimalStatus(0)), dzlw(-DBL_MIN, DecimalStatus(0)); const CDecimal128 i64max(MAX_SINT64, DecimalStatus(0)), i64min(MIN_SINT64, DecimalStatus(0)); const CDecimal128 c1(1); unsigned digits(const unsigned pMax, unsigned char* const coeff, int& exp) { for (unsigned i = 0; i < pMax; ++i) { if (coeff[i]) { if (i) { memmove(coeff, &coeff[i], pMax - i); memset(&coeff[pMax - i], 0, i); exp -= i; } i = pMax - i; while (!coeff[i - 1]) { fb_assert(i > 0); --i; } return i; } } return 0; } void make(ULONG* key, const unsigned pMax, const int bias, const unsigned decSize, unsigned char* coeff, int sign, int exp) { // normalize coeff & exponent unsigned dig = digits(pMax, coeff, exp); // exponent bias and sign if (!dig) { exp = 0; sign = 0; } else { exp += (bias + 2); if (sign) exp = -exp; } *key++ = exp; // convert to SLONG fb_assert(pMax / 9 < decSize / sizeof(int)); memset(key, 0, decSize); for (unsigned i = 0; i < pMax; ++i) { unsigned c = i / 9; key[c] *= 10; key[c] += (sign ? 9 - coeff[i] : coeff[i]); } } void grab(ULONG* key, const unsigned pMax, const int bias, const unsigned decSize, unsigned char* bcd, int& sign, int& exp) { exp = *key++; sign = 0; // parse exp if (exp < 0) { sign = DECFLOAT_Sign; exp = -exp; } if (exp != 0) exp -= (bias + 2); // convert from SLONG for (int i = pMax; i--;) { int c = i / 9; bcd[i] = key[c] % 10; key[c] /= 10; if (sign) bcd[i] = 9 - bcd[i]; } // normalize for (unsigned i = pMax; i--; ) { if (bcd[i]) { if (i < pMax - 1) { memmove(&bcd[pMax - 1 - i], bcd, i + 1); memset(bcd, 0, pMax - 1 - i); exp += (pMax - 1 - i); } break; } } } } // anonymous namespace namespace Firebird { void Decimal64::setScale(DecimalStatus decSt, int scale) { if (scale) { DecimalContext context(this, decSt); scale += decDoubleGetExponent(&dec); decDoubleSetExponent(&dec, &context, scale); } } #if SIZEOF_LONG < 8 Decimal64 Decimal64::set(int value, DecimalStatus decSt, int scale) { return set(SLONG(value), decSt, scale); } #endif Decimal64 Decimal64::set(SLONG value, DecimalStatus decSt, int scale) { decDoubleFromInt32(&dec, value); setScale(decSt, -scale); return *this; } Decimal64 Decimal64::set(DecimalFixed value, DecimalStatus decSt, int scale) { Decimal128 tmp; tmp.set(value, decSt, scale); *this = tmp.toDecimal64(decSt); return *this; } Decimal64 Decimal64::set(SINT64 value, DecimalStatus decSt, int scale) { { char s[30]; // for sure enough for int64 sprintf(s, "%" SQUADFORMAT, value); DecimalContext context(this, decSt); decDoubleFromString(&dec, s, &context); } setScale(decSt, -scale); return *this; } Decimal64 Decimal64::set(const char* value, DecimalStatus decSt) { DecimalContext context(this, decSt); decDoubleFromString(&dec, value, &context); return *this; } Decimal64 Decimal64::set(double value, DecimalStatus decSt) { char s[50]; sprintf(s, "%.016e", value); DecimalContext context(this, decSt); decDoubleFromString(&dec, s, &context); return *this; } void Decimal64::toString(DecimalStatus decSt, unsigned length, char* to) const { DecimalContext context(this, decSt); if (length) { --length; char s[IDecFloat16::STRING_SIZE]; memset(s, 0, sizeof(s)); decDoubleToString(&dec, s); if (strlen(s) > length) decContextSetStatus(&context, DEC_Invalid_operation); else length = strlen(s); memcpy(to, s, length + 1); } else decContextSetStatus(&context, DEC_Invalid_operation); } void Decimal64::toString(string& to) const { to.grow(IDecFloat16::STRING_SIZE); toString(DecimalStatus(0), to.length(), to.begin()); // provide long enough string, i.e. no traps to.recalculate_length(); } UCHAR* Decimal64::getBytes() { return dec.bytes; } Decimal64 Decimal64::abs() const { Decimal64 rc; decDoubleCopyAbs(&rc.dec, &dec); return rc; } Decimal64 Decimal64::ceil(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_CEILING); return rc; } Decimal64 Decimal64::floor(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_FLOOR); return rc; } int Decimal64::compare(DecimalStatus decSt, Decimal64 tgt) const { DecimalStatus cmpStatus(decSt); cmpStatus.decExtFlag &= ~DEC_IEEE_754_Invalid_operation; DecimalContext context(this, cmpStatus); decDouble r; decDoubleCompare(&r, &dec, &tgt.dec, &context); return decDoubleToInt32(&r, &context, DEC_ROUND_HALF_UP); } bool Decimal64::isInf() const { switch (decDoubleClass(&dec)) { case DEC_CLASS_NEG_INF: case DEC_CLASS_POS_INF: return true; } return false; } bool Decimal64::isNan() const { switch (decDoubleClass(&dec)) { case DEC_CLASS_SNAN: case DEC_CLASS_QNAN: return true; } return false; } int Decimal64::sign() const { if (decDoubleIsZero(&dec)) return 0; if (decDoubleIsSigned(&dec)) return -1; return 1; } #ifdef DEV_BUILD int Decimal64::show() { decDoubleShow(&dec, ""); return 0; } #endif Decimal64 Decimal64::neg() const { Decimal64 rc; decDoubleCopyNegate(&rc.dec, &dec); return rc; } void Decimal64::makeKey(ULONG* key) const { unsigned char coeff[DECDOUBLE_Pmax]; int sign = decDoubleGetCoefficient(&dec, coeff); int exp = decDoubleGetExponent(&dec); make(key, DECDOUBLE_Pmax, DECDOUBLE_Bias, sizeof(dec), coeff, sign, exp); } void Decimal64::grabKey(ULONG* key) { int exp, sign; unsigned char bcd[DECDOUBLE_Pmax]; grab(key, DECDOUBLE_Pmax, DECDOUBLE_Bias, sizeof(dec), bcd, sign, exp); decDoubleFromBCD(&dec, exp, bcd, sign); } Decimal64 Decimal64::quantize(DecimalStatus decSt, Decimal64 op2) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleQuantize(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal64 Decimal64::normalize(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleReduce(&rc.dec, &dec, &context); return rc; } short Decimal64::totalOrder(Decimal64 op2) const { decDouble r; decDoubleCompareTotal(&r, &dec, &op2.dec); fb_assert(!decDoubleIsNaN(&r)); DecimalContext context2(this, 0); return decDoubleToInt32(&r, &context2, DEC_ROUND_HALF_UP); } /* * decCompare() implements SQL function COMPARE_DECFLOAT() which has non-traditional return values. * COMPARE_DECFLOAT (X, Y) * 0 - X == Y * 1 - X < Y * 2 - X > Y * 3 - values unordered */ short Decimal64::decCompare(Decimal64 op2) const { if (decDoubleIsNaN(&dec) || decDoubleIsNaN(&op2.dec)) return 3; switch (totalOrder(op2)) { case -1: return 1; case 0: return 0; case 1: return 2; default: fb_assert(false); } // warning silencer return 3; } Decimal128 Decimal128::set(Decimal64 d64) { decDoubleToWider(&d64.dec, &dec); return *this; } #if SIZEOF_LONG < 8 Decimal128 Decimal128::set(int value, DecimalStatus decSt, int scale) { return set(SLONG(value), decSt, scale); } #endif Decimal128 Decimal128::set(SLONG value, DecimalStatus decSt, int scale) { decQuadFromInt32(&dec, value); setScale(decSt, -scale); return *this; } Decimal128 Decimal128::set(DecimalFixed value, DecimalStatus decSt, int scale) { *this = value; setScale(decSt, -scale); return *this; } Decimal128 Decimal128::set(SINT64 value, DecimalStatus decSt, int scale) { { int high = value >> 32; unsigned low = value & 0xFFFFFFFF; DecimalContext context(this, decSt); decQuad pow2_32; decQuadFromString(&pow2_32, "4294967296", &context); decQuad up, down; decQuadFromInt32(&up, high); decQuadFromUInt32(&down, low); decQuadFMA(&dec, &up, &pow2_32, &down, &context); } setScale(decSt, -scale); return *this; } Decimal128 Decimal128::set(const char* value, DecimalStatus decSt) { DecimalContext context(this, decSt); decQuadFromString(&dec, value, &context); return *this; } Decimal128 Decimal128::set(double value, DecimalStatus decSt) { char s[50]; sprintf(s, "%.016e", value); DecimalContext context(this, decSt); decQuadFromString(&dec, s, &context); return *this; } DecimalFixed DecimalFixed::set(SLONG value) { decQuadFromInt32(&dec, value); return *this; } DecimalFixed DecimalFixed::set(SINT64 value) { int high = value >> 32; unsigned low = value & 0xFFFFFFFF; DecimalContext context(this, DecimalStatus(0)); decQuad pow2_32; decQuadFromString(&pow2_32, "4294967296", &context); decQuad up, down; decQuadFromInt32(&up, high); decQuadFromUInt32(&down, low); decQuadFMA(&dec, &up, &pow2_32, &down, &context); return *this; } DecimalFixed DecimalFixed::set(const char* value, int scale, DecimalStatus decSt) { { // scope for 'context' DecimalContext context(this, decSt); decQuadFromString(&dec, value, &context); } exactInt(decSt, scale); return *this; } DecimalFixed DecimalFixed::set(double value, int scale, DecimalStatus decSt) { char s[50]; sprintf(s, "%18.016e", value); { // scope for 'context' DecimalContext context(this, decSt); decQuadFromString(&dec, s, &context); } exactInt(decSt, scale); return *this; } void DecimalFixed::exactInt(DecimalStatus decSt, int scale) { setScale(decSt, -scale); DecimalContext context(this, decSt); decQuadToIntegralExact(&dec, &dec, &context); decQuadQuantize(&dec, &dec, &c1.dec, &context); } Decimal128 Decimal128::operator=(Decimal64 d64) { decDoubleToWider(&d64.dec, &dec); return *this; } int Decimal128::toInteger(DecimalStatus decSt, int scale) const { Decimal128 tmp(*this); tmp.setScale(decSt, -scale); DecimalContext context(this, decSt); enum rounding rMode = decContextGetRounding(&context); return decQuadToInt32(&tmp.dec, &context, rMode); } int DecimalFixed::toInteger(DecimalStatus decSt) const { DecimalContext context(this, decSt); enum rounding rMode = decContextGetRounding(&context); return decQuadToInt32(&dec, &context, rMode); } void Decimal128::toString(DecimalStatus decSt, unsigned length, char* to) const { DecimalContext context(this, decSt); if (length) { --length; char s[IDecFloat34::STRING_SIZE]; memset(s, 0, sizeof(s)); decQuadToString(&dec, s); if (strlen(s) > length) decContextSetStatus(&context, DEC_Invalid_operation); else length = strlen(s); memcpy(to, s, length + 1); } else decContextSetStatus(&context, DEC_Invalid_operation); } void Decimal128::toString(string& to) const { to.grow(IDecFloat34::STRING_SIZE); toString(DecimalStatus(0), to.length(), to.begin()); // provide long enough string, i.e. no traps to.recalculate_length(); } Decimal128 DecimalFixed::scaled128(DecimalStatus decSt, int scale) const { Decimal128 tmp; tmp.set(*this, decSt, -scale); return tmp; } void DecimalFixed::toString(DecimalStatus decSt, int scale, unsigned length, char* to) const { scaled128(decSt, scale).toString(decSt, length, to); } void DecimalFixed::toString(DecimalStatus decSt, int scale, string& to) const { scaled128(decSt, scale).toString(to); } double Decimal128Base::toDouble(DecimalStatus decSt) const { DecimalContext context(this, decSt); if (compare(decSt, dmin) < 0 || compare(decSt, dmax) > 0) decContextSetStatus(&context, DEC_Overflow); else if ((!decQuadIsZero(&dec)) && compare(decSt, dzlw) > 0 && compare(decSt, dzup) < 0) { decContextSetStatus(&context, DEC_Underflow); return 0.0; } else { char s[IDecFloat34::STRING_SIZE]; decQuadToString(&dec, s); return atof(s); } return 0.0; } SINT64 Decimal128::toInt64(DecimalStatus decSt, int scale) const { static CDecimal128 quant(1); Decimal128 wrk(*this); wrk.setScale(decSt, -scale); wrk = wrk.quantize(decSt, quant); if (wrk.compare(decSt, i64min) < 0 || wrk.compare(decSt, i64max) > 0) { DecimalContext context(this, decSt); decContextSetStatus(&context, DEC_Invalid_operation); return 0; // in case of no trap on invalid operation } unsigned char coeff[DECQUAD_Pmax]; int sign = decQuadGetCoefficient(&wrk.dec, coeff); SINT64 rc = 0; for (int i = 0; i < DECQUAD_Pmax; ++i) { rc *= 10; if (sign) rc -= coeff[i]; else rc += coeff[i]; } return rc; } SINT64 DecimalFixed::toInt64(DecimalStatus decSt) const { if (compare(decSt, i64min) < 0 || compare(decSt, i64max) > 0) { DecimalContext context(this, decSt); decContextSetStatus(&context, DEC_Invalid_operation); return 0; // in case of no trap on invalid operation } unsigned char coeff[DECQUAD_Pmax]; int sign = decQuadGetCoefficient(&dec, coeff); SINT64 rc = 0; for (int i = 0; i < DECQUAD_Pmax; ++i) { rc *= 10; if (sign) rc -= coeff[i]; else rc += coeff[i]; } return rc; } UCHAR* Decimal128Base::getBytes() { return dec.bytes; } Decimal64 Decimal128Base::toDecimal64(DecimalStatus decSt) const { Decimal64 rc; DecimalContext context(this, decSt); decDoubleFromWider(&rc.dec, &dec, &context); return rc; } void Decimal128Base::setScale(DecimalStatus decSt, int scale) { if (scale) { DecimalContext context(this, decSt); scale += decQuadGetExponent(&dec); decQuadSetExponent(&dec, &context, scale); } } int Decimal128Base::compare(DecimalStatus decSt, Decimal128Base tgt) const { DecimalContext context(this, decSt); decQuad r; decQuadCompare(&r, &dec, &tgt.dec, &context); return decQuadToInt32(&r, &context, DEC_ROUND_HALF_UP); } bool Decimal128Base::isInf() const { switch(decQuadClass(&dec)) { case DEC_CLASS_NEG_INF: case DEC_CLASS_POS_INF: return true; } return false; } bool Decimal128Base::isNan() const { switch(decQuadClass(&dec)) { case DEC_CLASS_SNAN: case DEC_CLASS_QNAN: return true; } return false; } int Decimal128Base::sign() const { if (decQuadIsZero(&dec)) return 0; if (decQuadIsSigned(&dec)) return -1; return 1; } Decimal128 Decimal128::ceil(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_CEILING); return rc; } Decimal128 Decimal128::floor(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_FLOOR); return rc; } #ifdef DEV_BUILD int Decimal128Base::show() { decQuadShow(&dec, ""); return 0; } #endif Decimal128 Decimal128::abs() const { Decimal128 rc; decQuadCopyAbs(&rc.dec, &dec); return rc; } Decimal128 Decimal128::neg() const { Decimal128 rc; decQuadCopyNegate(&rc.dec, &dec); return rc; } Decimal128 Decimal128::add(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadAdd(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::sub(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadSubtract(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::mul(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadMultiply(&rc.dec, &dec, &op2.dec, &context); return rc; } DecimalFixed DecimalFixed::abs() const { DecimalFixed rc; decQuadCopyAbs(&rc.dec, &dec); return rc; } DecimalFixed DecimalFixed::neg() const { DecimalFixed rc; decQuadCopyNegate(&rc.dec, &dec); return rc; } DecimalFixed DecimalFixed::add(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadAdd(&rc.dec, &dec, &op2.dec, &context); context.checkForExceptions(); decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context); return rc; } DecimalFixed DecimalFixed::sub(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadSubtract(&rc.dec, &dec, &op2.dec, &context); context.checkForExceptions(); decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context); return rc; } DecimalFixed DecimalFixed::mul(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadMultiply(&rc.dec, &dec, &op2.dec, &context); context.checkForExceptions(); decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context); return rc; } Decimal128 Decimal128::div(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadDivide(&rc.dec, &dec, &op2.dec, &context); return rc; } DecimalFixed DecimalFixed::div(DecimalStatus decSt, DecimalFixed op2, int scale) const { DecimalContext context(this, decSt); DecimalFixed rc; // first divide with full decfloat precision decQuadDivide(&rc.dec, &dec, &op2.dec, &context); // next re-scale & int-ize rc.exactInt(decSt, scale); return rc; } DecimalFixed DecimalFixed::mod(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadRemainder(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::fma(DecimalStatus decSt, Decimal128 op2, Decimal128 op3) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadFMA(&rc.dec, &op2.dec, &op3.dec, &dec, &context); return rc; } Decimal128 Decimal128::sqrt(DecimalStatus decSt) const { decNumber dn; decQuadToNumber(&dec, &dn); DecimalContext context(this, decSt); decNumberSquareRoot(&dn, &dn, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } Decimal128 Decimal128::pow(DecimalStatus decSt, Decimal128 op2) const { decNumber dn, dn2; decQuadToNumber(&dec, &dn); decQuadToNumber(&op2.dec, &dn2); DecimalContext context(this, decSt); decNumberPower(&dn, &dn, &dn2, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } Decimal128 Decimal128::ln(DecimalStatus decSt) const { decNumber dn; decQuadToNumber(&dec, &dn); DecimalContext context(this, decSt); decNumberLn(&dn, &dn, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } Decimal128 Decimal128::log10(DecimalStatus decSt) const { decNumber dn; decQuadToNumber(&dec, &dn); DecimalContext context(this, decSt); decNumberLog10(&dn, &dn, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } void Decimal128Base::makeKey(ULONG* key) const { unsigned char coeff[DECQUAD_Pmax]; int sign = decQuadGetCoefficient(&dec, coeff); int exp = decQuadGetExponent(&dec); make(key, DECQUAD_Pmax, DECQUAD_Bias, sizeof(dec), coeff, sign, exp); } void Decimal128Base::grabKey(ULONG* key) { int exp, sign; unsigned char bcd[DECQUAD_Pmax]; grab(key, DECQUAD_Pmax, DECQUAD_Bias, sizeof(dec), bcd, sign, exp); decQuadFromBCD(&dec, exp, bcd, sign); } ULONG Decimal128Base::getIndexKeyLength() { return 17; } ULONG Decimal128Base::makeIndexKey(vary* buf) { unsigned char coeff[DECQUAD_Pmax + 2]; int sign = decQuadGetCoefficient(&dec, coeff); int exp = decQuadGetExponent(&dec); const int bias = DECQUAD_Bias; const unsigned pMax = DECQUAD_Pmax; // normalize coeff & exponent unsigned dig = digits(pMax, coeff, exp); // exponent bias and sign exp += (bias + 1); if (!dig) exp = 0; if (sign) exp = -exp; exp += 2 * (bias + 1); // make it positive fb_assert(exp >= 0 && exp < 64 * 1024); // encode exp char* k = buf->vary_string; *k++ = exp >> 8; *k++ = exp & 0xff; // invert negative unsigned char* const end = &coeff[dig]; if (sign && dig) { fb_assert(end[-1]); --end[-1]; for (unsigned char* p = coeff; p < end; ++p) *p = 9 - *p; } // Some 0's in the end - caller, do not forget to reserve additional space on stack end[0] = end[1] = 0; // Avoid bad data in k in case when coeff is zero *k = 0; // Shifts for moving 10-bit values to bytes buffer struct ShiftTable { UCHAR rshift, lshift; }; static ShiftTable table[4] = { { 2, 6 }, { 4, 4 }, { 6, 2 }, { 8, 0 } }; // compress coeff - 3 decimal digits (999) per 10 bits (1023) unsigned char* p = coeff; for (ShiftTable* t = table; p < end; p += 3) { USHORT val = p[0] * 100 + p[1] * 10 + p[2]; fb_assert(val < 1000); // 1024, 10 bit *k |= (val >> t->rshift); ++k; *k = (val << t->lshift); if (!t->lshift) { ++k; *k = 0; t = table; } else ++t; } if (*k) ++k; // done buf->vary_length = k - buf->vary_string; return buf->vary_length; } Decimal128 Decimal128::quantize(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadQuantize(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::normalize(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadReduce(&rc.dec, &dec, &context); return rc; } short Decimal128::totalOrder(Decimal128 op2) const { decQuad r; decQuadCompareTotal(&r, &dec, &op2.dec); fb_assert(!decQuadIsNaN(&r)); DecimalContext context2(this, 0); return decQuadToInt32(&r, &context2, DEC_ROUND_HALF_UP); } /* * decCompare() implements SQL function COMPARE_DECFLOAT() which has non-traditional return values. * COMPARE_DECFLOAT (X, Y) * 0 - X == Y * 1 - X < Y * 2 - X > Y * 3 - values unordered */ short Decimal128::decCompare(Decimal128 op2) const { if (decQuadIsNaN(&dec) || decQuadIsNaN(&op2.dec)) return 3; switch (totalOrder(op2)) { case -1: return 1; case 0: return 0; case 1: return 2; default: fb_assert(false); } // warning silencer return 3; } } // namespace Firebird
20.678511
99
0.699247
sas9mba
0e5484a533db09810dc94eebae002aeb085e6af7
2,037
cpp
C++
src/graph_algorithms_tool/shortest_path_graphics_item.cpp
michalmonday/Graph-Algorithms-Teaching-Tool
f7c7efa7a4518805d22c3fd2d2810e4bfb6a5ddf
[ "MIT" ]
null
null
null
src/graph_algorithms_tool/shortest_path_graphics_item.cpp
michalmonday/Graph-Algorithms-Teaching-Tool
f7c7efa7a4518805d22c3fd2d2810e4bfb6a5ddf
[ "MIT" ]
null
null
null
src/graph_algorithms_tool/shortest_path_graphics_item.cpp
michalmonday/Graph-Algorithms-Teaching-Tool
f7c7efa7a4518805d22c3fd2d2810e4bfb6a5ddf
[ "MIT" ]
null
null
null
#include "shortest_path_graphics_item.h" #include "algorithms/controlled_dijkstra_algorithm.h" #include "graph/graph.h" #include "graph/node.h" #include "functions.h" #include "colors.h" #include <QGraphicsScene> static const qreal Y_SPACING = 1.2; // same as vtable_graphics_item.cpp ShortestPathGraphicsItem::ShortestPathGraphicsItem(ControlledDijkstraAlgorithm *algorithm, QGraphicsItem *parent) : MovableGraphicsItem(parent), dijkstra_algorithm(algorithm) { updateEntries(); } void ShortestPathGraphicsItem::updateEntries() { QMap<Node*, int> dist = dijkstra_algorithm->dist(); QMap<Node*, Node*> pred = dijkstra_algorithm->pred(); // delete entry items if they're not there anymore for (Node *n : entries.keys()) { if (!dist.keys().contains(n)) { delete entries[n]; entries.remove(n); } } // SORT nodes (making output neat) QList<Node *> sorted_keys = dist.keys(); std::sort(sorted_keys.begin(), sorted_keys.end(), [](Node *n, Node*n2){ return n->getLabel() < n2->getLabel();}); int y_pos = 0; for (Node *n : sorted_keys) { if (!entries.keys().contains(n)) { entries[n] = new QGraphicsTextItem(this); entries[n]->setPos(0, y_pos); } QString text = QString("V[%1] = (%2, %3)") .arg(colouredHtml(n->getLabel(),n->getColor() == COLOR_NODE_DEFAULT ? Qt::black : n->getColor())) .arg(colouredHtml(QString::number(dist[n]), dist[n] == INT_MAX ? Qt::black : COLOR_DIJKSTRA_OPTIMAL)) .arg(pred[n] ? colouredHtml(pred[n]->getLabel(), pred[n]->getColor()) : "-"); entries[n]->setHtml(text); y_pos += entries[n]->boundingRect().height() * Y_SPACING; } //update(); if (QGraphicsScene *scene = this->scene()) scene->update(); } void ShortestPathGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { MovableGraphicsItem::paint(painter, option, widget); }
33.393443
117
0.63623
michalmonday
0e54e4fbc2b32d5fc58cead03fe19ecf1aef1416
705
cpp
C++
src/cmcandy/C_Language_Answers/_1025.cpp
ch98road/leetcode
a9b4be54a169b30f6711809b892dd1f79f2a17e7
[ "MIT" ]
null
null
null
src/cmcandy/C_Language_Answers/_1025.cpp
ch98road/leetcode
a9b4be54a169b30f6711809b892dd1f79f2a17e7
[ "MIT" ]
null
null
null
src/cmcandy/C_Language_Answers/_1025.cpp
ch98road/leetcode
a9b4be54a169b30f6711809b892dd1f79f2a17e7
[ "MIT" ]
1
2020-11-26T03:01:12.000Z
2020-11-26T03:01:12.000Z
#include <iostream> #include <string> #include <vector> using namespace ::std; class Solution { public: bool divisorGame(int N) { //N=1 必败 //N=2 必胜 //本题有数学证明,但个人想用动归解 //return N%2==0; //dp为1维,找到<i 的false(必输局面即可获胜)若找不到,则必输 //状态转换公式为:i % j == 0 && f[i - j] == false vector<bool> f(N + 1, false); f[1] = false; f[2] = true; for (int i = 3; i <= N; i++) { for (int j = 1; j < i; j++) { if (i % j == 0 && f[i - j] == false) { f[i] = true; break; } } } return f[N]; } };
21.363636
52
0.368794
ch98road
0e5508065b0d797d1fe9131d259423bc02830e86
1,161
cpp
C++
src/sconelib/scone/measures/JointLoadMeasure.cpp
alexxlzhou/scone-core
4a071626e5ee7ba253e72a973d4d214fa6e30cf5
[ "Apache-2.0" ]
5
2021-04-30T14:30:20.000Z
2022-03-27T09:58:24.000Z
src/sconelib/scone/measures/JointLoadMeasure.cpp
alexxlzhou/scone-core
4a071626e5ee7ba253e72a973d4d214fa6e30cf5
[ "Apache-2.0" ]
4
2021-06-15T10:52:10.000Z
2021-12-15T10:25:21.000Z
src/sconelib/scone/measures/JointLoadMeasure.cpp
alexxlzhou/scone-core
4a071626e5ee7ba253e72a973d4d214fa6e30cf5
[ "Apache-2.0" ]
2
2021-05-02T13:38:19.000Z
2021-07-22T19:37:07.000Z
/* ** JointLoadMeasure.cpp ** ** Copyright (C) 2013-2019 Thomas Geijtenbeek and contributors. All rights reserved. ** ** This file is part of SCONE. For more information, see http://scone.software. */ #include "JointLoadMeasure.h" #include "scone/model/Model.h" namespace scone { JointLoadMeasure::JointLoadMeasure( const PropNode& props, Params& par, const Model& model, const Location& loc ) : Measure( props, par, model, loc ), RangePenalty( props ), joint_load(), joint( *FindByName( model.GetJoints(), props.get< String >( "joint" ) ) ) { INIT_PROP( props, method, 1 ); } double JointLoadMeasure::ComputeResult( const Model& model ) { return RangePenalty<Real>::GetResult(); } bool JointLoadMeasure::UpdateMeasure( const Model& model, double timestamp ) { joint_load = joint.GetLoad(); AddSample( timestamp, joint_load ); return false; } scone::String JointLoadMeasure::GetClassSignature() const { return ""; } void JointLoadMeasure::StoreData( Storage< Real >::Frame& frame, const StoreDataFlags& flags ) const { // #todo: store joint load value frame[ joint.GetName() + ".load_penalty" ] = GetLatest(); } }
24.1875
116
0.701981
alexxlzhou
0e5670290456c3434075b3024830adce55ac0697
2,870
cpp
C++
Olympiad Solutions/SPOJ/TWOPATHS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/SPOJ/TWOPATHS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/SPOJ/TWOPATHS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://www.spoj.com/problems/TWOPATHS/ #include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 1e5 + 10; vector<int> grafo[MAXN]; int maior_dist[MAXN][3],maior_diam[MAXN][2]; int temporario_diametro[MAXN],temporario_dist[MAXN],N; ll melhor_produto; void calcula(int v){ temporario_dist[v] = maior_dist[v][0]; temporario_diametro[v] = max(maior_diam[v][0],maior_dist[v][0] + maior_dist[v][1]); } void insert(int v,int u){ int ndist = temporario_dist[u] + 1; if(ndist > maior_dist[v][0]){ maior_dist[v][2] = maior_dist[v][1]; maior_dist[v][1] = maior_dist[v][0]; maior_dist[v][0] = ndist; } else if(ndist > maior_dist[v][1]){ maior_dist[v][2] = maior_dist[v][1]; maior_dist[v][1] = ndist; } else if(ndist > maior_dist[v][2]){ maior_dist[v][2] = ndist; } int ndiam = temporario_diametro[u]; if(ndiam > maior_diam[v][0]){ maior_diam[v][1] = maior_diam[v][0]; maior_diam[v][0] = ndiam; } else if(ndiam > maior_diam[v][1]){ maior_diam[v][1] = ndiam; } calcula(v); } void remove(int v,int u){ int ndist = temporario_dist[u] + 1; int ndiam = temporario_diametro[u]; if(ndist == maior_dist[v][0]){ maior_dist[v][0] = maior_dist[v][1]; maior_dist[v][1] = maior_dist[v][2]; } else if(ndist == maior_dist[v][1]){ maior_dist[v][1] = maior_dist[v][2]; } if(ndiam == maior_diam[v][0]){ maior_diam[v][0] = maior_diam[v][1]; } calcula(v); } void dfs1(int v,int p){ calcula(v); for(int u : grafo[v]){ if(u == p) continue; dfs1(u,v); insert(v,u); } } void dfs2(int v,int p){ calcula(v); for(int u : grafo[v]){ if(u == p) continue; int copiav_dist[3],copiav_diam[2],copiau_dist[3],copiau_diam[2]; copiav_dist[0] = maior_dist[v][0];copiav_dist[1] = maior_dist[v][1];copiav_dist[2] = maior_dist[v][2]; copiau_dist[0] = maior_dist[u][0];copiau_dist[1] = maior_dist[u][1];copiau_dist[2] = maior_dist[u][2]; copiav_diam[0] = maior_diam[v][0];copiav_diam[1] = maior_diam[v][1]; copiau_diam[0] = maior_diam[u][0];copiau_diam[1] = maior_diam[u][1]; remove(v,u); ll candidato = 1LL*temporario_diametro[v]*temporario_diametro[u]; melhor_produto = max(melhor_produto,candidato); insert(u,v); dfs2(u,v); maior_dist[v][0] = copiav_dist[0];maior_dist[v][1] = copiav_dist[1];maior_dist[v][2] = copiav_dist[2]; maior_dist[u][0] = copiau_dist[0];maior_dist[u][1] = copiau_dist[1];maior_dist[u][2] = copiau_dist[2]; maior_diam[v][0] = copiav_diam[0];maior_diam[v][1] = copiav_diam[1]; maior_diam[u][0] = copiau_diam[0];maior_diam[u][1] = copiau_diam[1]; calcula(v); calcula(u); } } int main(){ scanf("%d",&N); for(int i = 1;i<N;i++){ int u,v; scanf("%d %d",&u,&v); grafo[u].push_back(v); grafo[v].push_back(u); } dfs1(1,-1); //printf("MaiorDiam 1 %d\n",temporario_diametro[1]); dfs2(1,-1); printf("%lld\n",melhor_produto); return 0; }
29.587629
104
0.649826
Ashwanigupta9125
0e576d935bdfc6164bafd14477acb0af56ca1832
20,328
hh
C++
dune/xt/la/solver/fasp.hh
dune-community/dune-xt-la
2c3119fcc3798b14aa3c9228aed0e1ae8ee4ebcc
[ "BSD-2-Clause" ]
4
2016-01-26T06:03:13.000Z
2020-02-08T04:09:17.000Z
dune/xt/la/solver/fasp.hh
dune-community/dune-xt-la
2c3119fcc3798b14aa3c9228aed0e1ae8ee4ebcc
[ "BSD-2-Clause" ]
89
2016-01-24T22:09:34.000Z
2020-03-25T08:33:43.000Z
dune/xt/la/solver/fasp.hh
dune-community/dune-xt-la
2c3119fcc3798b14aa3c9228aed0e1ae8ee4ebcc
[ "BSD-2-Clause" ]
2
2018-04-09T11:52:25.000Z
2020-02-08T04:10:27.000Z
// This file is part of the dune-xt-la project: // https://github.com/dune-community/dune-xt-la // Copyright 2009-2018 dune-xt-la developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2013 - 2014, 2016 - 2017) // Rene Milk (2013, 2015 - 2016, 2018) // Tobias Leibner (2017) #ifndef DUNE_XT_LA_SOLVER_FASP_HH #define DUNE_XT_LA_SOLVER_FASP_HH #if HAVE_FASP # if HAVE_EIGEN extern "C" { # include "fasp_functs.h" } # include <dune/xt/la/container/eigen.hh> # include "interface.hh" namespace Dune { namespace XT { namespace LA { template <class ElementImp> class AmgSolver<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>> : public SolverInterface<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>> { public: typedef SolverInterface<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>> BaseType; typedef typename BaseType::MatrixType MatrixType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::ScalarType ScalarType; static Dune::ParameterTree defaultSettings() { Dune::ParameterTree description = BaseType::defaultIterativeSettings(); // these parameters were taken from the init.dat that Ludmil gave me... description["input_param.print_level"] = "3"; description["input_param.output_type"] = "0"; description["input_param.workdir"] = "./"; description["input_param.problem_num"] = "14 "; description["input_param.solver_type"] = "1"; description["input_param.precond_type"] = "2"; description["input_param.stop_type"] = "1"; description["input_param.itsolver_tol"] = "1.000000e-10"; description["input_param.itsolver_maxit"] = "1000"; description["input_param.restart"] = "20"; description["input_param.ILU_type"] = "1"; description["input_param.ILU_lfil"] = "0"; description["input_param.ILU_droptol"] = "1.000000e-01"; description["input_param.ILU_relax"] = "9.000000e-01"; description["input_param.ILU_permtol"] = "1.000000e-03"; description["input_param.Schwarz_mmsize"] = "200"; description["input_param.Schwarz_maxlvl"] = "2"; description["input_param.Schwarz_type"] = "1"; description["input_param.AMG_type"] = "1"; description["input_param.AMG_levels"] = "20"; description["input_param.AMG_cycle_type"] = "1"; description["input_param.AMG_smoother"] = "2"; description["input_param.AMG_relaxation"] = "1.100000e+00"; description["input_param.AMG_polynomial_degree"] = "3"; description["input_param.AMG_presmooth_iter"] = "2"; description["input_param.AMG_postsmooth_iter"] = "2"; description["input_param.AMG_coarse_dof"] = "100"; description["input_param.AMG_tol"] = "1.000000e-08"; description["input_param.AMG_maxit"] = "1"; description["input_param.AMG_ILU_levels"] = "0"; description["input_param.AMG_coarse_scaling"] = "0"; description["input_param.AMG_amli_degree"] = "2"; description["input_param.AMG_nl_amli_krylov_type"] = "6"; description["input_param.AMG_schwarz_levels"] = "0"; description["input_param.AMG_coarsening_type"] = "1"; description["input_param.AMG_interpolation_type"] = "1"; description["input_param.AMG_strong_threshold"] = "3.000000e-01"; description["input_param.AMG_truncation_threshold"] = "4.000000e-01"; description["input_param.AMG_max_row_sum"] = "9.000000e-01"; description["input_param.AMG_strong_coupled"] = "8.000000e-02"; description["input_param.AMG_max_aggregation"] = "20"; description["input_param.AMG_tentative_smooth"] = "6.700000e-01"; description["input_param.AMG_smooth_filter"] = "0"; description["itsolver_param.itsolver_type"] = "1"; description["itsolver_param.precond_type"] = "2"; description["itsolver_param.stop_type"] = "1"; description["itsolver_param.maxit"] = "1000"; description["itsolver_param.tol"] = "1.000000e-10"; description["itsolver_param.restart"] = "20"; description["itsolver_param.print_level"] = "3"; description["AMG_param.AMG_type"] = "1"; description["AMG_param.print_level"] = "3"; description["AMG_param.maxit"] = "1"; description["AMG_param.tol"] = "1.000000e-08"; description["AMG_param.max_levels"] = "20"; description["AMG_param.coarse_dof"] = "100"; description["AMG_param.cycle_type"] = "1"; description["AMG_param.smoother"] = "2"; description["AMG_param.smooth_order"] = "1"; description["AMG_param.presmooth_iter"] = "2"; description["AMG_param.postsmooth_iter"] = "2"; description["AMG_param.relaxation"] = "1.100000e+00"; description["AMG_param.polynomial_degree"] = "3"; description["AMG_param.coarse_scaling"] = "0"; description["AMG_param.amli_degree"] = "2"; description["AMG_param.amli_coef"] = "1.100000e+00"; description["AMG_param.nl_amli_krylov_type"] = "6"; description["AMG_param.coarsening_type"] = "1"; description["AMG_param.interpolation_type"] = "1"; description["AMG_param.strong_threshold"] = "3.000000e-01"; description["AMG_param.max_row_sum"] = "9.000000e-01"; description["AMG_param.truncation_threshold"] = "4.000000e-01"; description["AMG_param.strong_coupled"] = "8.000000e-02"; description["AMG_param.max_aggregation"] = "20"; description["AMG_param.tentative_smooth"] = "6.700000e-01"; description["AMG_param.smooth_filter"] = "0"; description["AMG_param.ILU_levels"] = "0"; description["AMG_param.ILU_type"] = "1"; description["AMG_param.ILU_lfil"] = "0"; description["AMG_param.ILU_droptol"] = "1.000000e-01"; description["AMG_param.ILU_relax"] = "9.000000e-01"; description["AMG_param.ILU_permtol"] = "1.000000e-03"; description["AMG_param.schwarz_levels"] = "0"; description["AMG_param.schwarz_mmsize"] = "200"; description["AMG_param.schwarz_maxlvl"] = "2"; description["AMG_param.schwarz_type"] = "1"; description["ILU_param.print_level"] = "3"; description["ILU_param.ILU_type"] = "1"; description["ILU_param.ILU_lfil"] = "0"; description["ILU_param.ILU_droptol"] = "1.000000e-01"; description["ILU_param.ILU_relax"] = "9.000000e-01"; description["ILU_param.ILU_permtol"] = "1.000000e-03"; description["Schwarz_param.print_level"] = "3"; description["Schwarz_param.schwarz_type"] = "1"; description["Schwarz_param.schwarz_maxlvl"] = "2"; description["Schwarz_param.schwarz_mmsize"] = "200"; return description; } // Dune::ParameterTree defaultSettings() /** * \attention There is a const_cast inside, in order to forward non-const pointers to fasp. I hope they do not * touch the matrix, but who knows... */ virtual size_t apply(const MatrixType& _systemMatrix, const VectorType& _rhsVector, VectorType& solutionVector, const Dune::ParameterTree description = defaultSettings()) const { const size_t maxIter = description.get<size_t>("maxIter"); const ScalarType precision = description.get<ScalarType>("precision"); // init system matrix and right hand side MatrixType& systemMatrix = const_cast<MatrixType&>(_systemMatrix); VectorType& rhsVector = const_cast<VectorType&>(_rhsVector); dCSRmat A; A.row = systemMatrix.rows(); A.col = systemMatrix.cols(); A.nnz = systemMatrix.backend().nonZeros(); A.IA = systemMatrix.backend().outerIndexPtr(); A.JA = systemMatrix.backend().innerIndexPtr(); A.val = systemMatrix.backend().valuePtr(); dvector f, x; f.row = rhsVector.size(); f.val = rhsVector.backend().data(); x.row = rhsVector.backend().rows(); x.val = solutionVector.backend().data(); // init parameters input_param inparam = initInputParams(maxIter, precision, description); itsolver_param itparam = initItsolverParams(maxIter, precision, description); AMG_param amgparam = initAMGParams(1, precision, description); // the 1 is on purpose! ILU_param iluparam = initIluParams(maxIter, precision, description); Schwarz_param swzparam = initSchwarzParams(maxIter, precision, description); // call fasp (this is taken from the fasp example test) int status = -1; // Preconditioned Krylov methods if (inparam.solver_type >= 1 && inparam.solver_type <= 20) { // Using no preconditioner for Krylov iterative methods if (inparam.precond_type == PREC_NULL) { status = fasp_solver_dcsr_krylov(&A, &f, &x, &itparam); } // Using diag(A) as preconditioner for Krylov iterative methods else if (inparam.precond_type == PREC_DIAG) { status = fasp_solver_dcsr_krylov_diag(&A, &f, &x, &itparam); } // Using AMG as preconditioner for Krylov iterative methods else if (inparam.precond_type == PREC_AMG || inparam.precond_type == PREC_FMG) { if (inparam.print_level > PRINT_NONE) fasp_param_amg_print(&amgparam); status = fasp_solver_dcsr_krylov_amg(&A, &f, &x, &itparam, &amgparam); } // Using ILU as preconditioner for Krylov iterative methods Q: Need to change! else if (inparam.precond_type == PREC_ILU) { if (inparam.print_level > PRINT_NONE) fasp_param_ilu_print(&iluparam); status = fasp_solver_dcsr_krylov_ilu(&A, &f, &x, &itparam, &iluparam); } // Using Schwarz as preconditioner for Krylov iterative methods else if (inparam.precond_type == PREC_SCHWARZ) { if (inparam.print_level > PRINT_NONE) fasp_param_schwarz_print(&swzparam); status = fasp_solver_dcsr_krylov_schwarz(&A, &f, &x, &itparam, &swzparam); } else { printf("### ERROR: Wrong preconditioner type %d!!!\n", inparam.precond_type); status = ERROR_SOLVER_PRECTYPE; } } // AMG as the iterative solver else if (inparam.solver_type == SOLVER_AMG) { if (inparam.print_level > PRINT_NONE) fasp_param_amg_print(&amgparam); fasp_solver_amg(&A, &f, &x, &amgparam); } // Full AMG as the iterative solver else if (inparam.solver_type == SOLVER_FMG) { if (inparam.print_level > PRINT_NONE) fasp_param_amg_print(&amgparam); fasp_solver_famg(&A, &f, &x, &amgparam); } else { DUNE_THROW(Dune::RangeError, "### ERROR: Wrong solver type: " << inparam.solver_type << "!"); status = ERROR_SOLVER_TYPE; } if (status > 0) return 0; else return 3; } // ... apply(...) private: input_param initInputParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const { input_param inputParam; inputParam.print_level = description.get<int>("input_param.print_level", 0); inputParam.output_type = description.get<int>("input_param.output_type", 0); // inputParam.workdir = description.get< char >("input_param.workdir", '.'); inputParam.problem_num = 14; inputParam.solver_type = description.get<int>("input_param.solver_type", 1); inputParam.precond_type = description.get<int>("input_param.precond_type", 2); inputParam.stop_type = description.get<int>("input_param.stop_type", 1); inputParam.itsolver_tol = precision; inputParam.itsolver_maxit = maxIter; inputParam.restart = description.get<int>("input_param.restart", 20); inputParam.ILU_type = description.get<int>("input_param.ILU_type", 1); inputParam.ILU_lfil = description.get<int>("input_param.ILU_lfil", 0); inputParam.ILU_droptol = description.get<double>("input_param.ILU_droptol", 1.000000e-01); inputParam.ILU_relax = description.get<double>("input_param.ILU_relax", 9.000000e-01); inputParam.ILU_permtol = description.get<double>("input_param.ILU_permtol", 1.000000e-03); inputParam.Schwarz_mmsize = description.get<int>("input_param.Schwarz_mmsize", 200); inputParam.Schwarz_maxlvl = description.get<int>("input_param.Schwarz_maxlvl", 2); inputParam.Schwarz_type = description.get<int>("input_param.Schwarz_type", 1); inputParam.AMG_type = description.get<int>("input_param.AMG_type", 1); inputParam.AMG_levels = description.get<int>("input_param.AMG_levels", 20); inputParam.AMG_cycle_type = description.get<int>("input_param.AMG_cycle_type", 1); inputParam.AMG_smoother = description.get<int>("input_param.AMG_smoother", 2); inputParam.AMG_relaxation = description.get<double>("input_param.AMG_relaxation", 1.100000e+00); inputParam.AMG_polynomial_degree = description.get<int>("input_param.AMG_polynomial_degree", 3); inputParam.AMG_presmooth_iter = description.get<int>("input_param.AMG_presmooth_iter", 2); inputParam.AMG_postsmooth_iter = description.get<int>("input_param.AMG_postsmooth_iter", 2); inputParam.AMG_coarse_dof = description.get<int>("input_param.AMG_coarse_dof", 100); inputParam.AMG_tol = description.get<double>("input_param.AMG_tol", 1.000000e-08); inputParam.AMG_maxit = description.get<int>("input_param.AMG_maxit", 1); inputParam.AMG_ILU_levels = description.get<int>("input_param.AMG_ILU_levels", 0); inputParam.AMG_coarse_scaling = description.get<int>("input_param.AMG_coarse_scaling", 0); inputParam.AMG_amli_degree = description.get<int>("input_param.AMG_amli_degree", 2); inputParam.AMG_nl_amli_krylov_type = description.get<int>("input_param.AMG_nl_amli_krylov_type", 6); inputParam.AMG_schwarz_levels = description.get<int>("input_param.AMG_schwarz_levels", 0); inputParam.AMG_coarsening_type = description.get<int>("input_param.AMG_coarsening_type", 1); inputParam.AMG_interpolation_type = description.get<int>("input_param.AMG_interpolation_type", 1); inputParam.AMG_strong_threshold = description.get<double>("input_param.AMG_strong_threshold", 3.000000e-01); inputParam.AMG_truncation_threshold = description.get<double>("input_param.AMG_truncation_threshold", 4.000000e-01); inputParam.AMG_max_row_sum = description.get<double>("input_param.AMG_max_row_sum", 9.000000e-01); inputParam.AMG_strong_coupled = description.get<double>("input_param.AMG_strong_coupled", 8.000000e-02); inputParam.AMG_max_aggregation = description.get<int>("input_param.AMG_max_aggregation", 20); inputParam.AMG_tentative_smooth = description.get<double>("input_param.AMG_tentative_smooth", 6.700000e-01); inputParam.AMG_smooth_filter = description.get<int>("input_param.AMG_smooth_filter", 0); return inputParam; } // ... initInputParams(...) itsolver_param initItsolverParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const { itsolver_param itsolverParams; itsolverParams.itsolver_type = description.get<int>("itsolver_param.itsolver_type", 1); itsolverParams.precond_type = description.get<int>("itsolver_param.precond_type", 2); itsolverParams.stop_type = description.get<int>("itsolver_param.stop_type", 1); itsolverParams.maxit = maxIter; itsolverParams.tol = precision; itsolverParams.restart = description.get<int>("itsolver_param.restart", 20); itsolverParams.print_level = description.get<int>("itsolver_param.print_level", 0); return itsolverParams; } // ... initItsolverParams(...) AMG_param initAMGParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const { AMG_param amgParams; amgParams.AMG_type = description.get<int>("AMG_param.AMG_type", 1); amgParams.print_level = description.get<int>("AMG_param.print_level", 0); amgParams.maxit = maxIter; amgParams.tol = precision; amgParams.max_levels = description.get<int>("AMG_param.max_levels", 20); amgParams.coarse_dof = description.get<int>("AMG_param.coarse_dof", 100); amgParams.cycle_type = description.get<int>("AMG_param.cycle_type", 1); amgParams.smoother = description.get<int>("AMG_param.smoother", 2); amgParams.smooth_order = description.get<int>("AMG_param.smooth_order", 1); amgParams.presmooth_iter = description.get<int>("AMG_param.presmooth_iter", 2); amgParams.postsmooth_iter = description.get<int>("AMG_param.postsmooth_iter", 2); amgParams.relaxation = description.get<double>("AMG_param.relaxation", 1.1); amgParams.polynomial_degree = description.get<int>("AMG_param.polynomial_degree", 3); amgParams.coarse_scaling = description.get<int>("AMG_param.coarse_scaling", 0); amgParams.amli_degree = description.get<int>("AMG_param.amli_degree", 2); double tmp = description.get<double>("AMG_param.amli_coef", 1.1); amgParams.amli_coef = &tmp; amgParams.nl_amli_krylov_type = description.get<int>("AMG_param.nl_amli_krylov_type", 6); amgParams.coarsening_type = description.get<int>("AMG_param.coarsening_type", 1); amgParams.interpolation_type = description.get<int>("AMG_param.interpolation_type", 1); amgParams.strong_threshold = description.get<double>("AMG_param.strong_threshold", 3.e-1); amgParams.max_row_sum = description.get<double>("AMG_param.max_row_sum", 9.0e-1); amgParams.truncation_threshold = description.get<double>("AMG_param.truncation_threshold", 1.0e-1); amgParams.strong_coupled = description.get<double>("AMG_param.strong_coupled", 8.0e-2); amgParams.max_aggregation = description.get<int>("AMG_param.max_aggregation", 20); amgParams.tentative_smooth = description.get<double>("AMG_param.tentative_smooth", 6.7e-1); amgParams.smooth_filter = description.get<int>("AMG_param.smooth_filter", 0); amgParams.ILU_levels = description.get<int>("AMG_param.ILU_levels", 0); amgParams.ILU_type = description.get<int>("AMG_param.ILU_type", 1); amgParams.ILU_lfil = description.get<int>("AMG_param.ILU_lfil", 0); amgParams.ILU_droptol = description.get<double>("AMG_param.ILU_droptol", 1.0e-1); amgParams.ILU_relax = description.get<double>("AMG_param.ILU_relax", 9.0e-1); amgParams.ILU_permtol = description.get<double>("AMG_param.ILU_permtol", 1.0e-3); amgParams.schwarz_levels = description.get<int>("AMG_param.schwarz_levels", 0); amgParams.schwarz_mmsize = description.get<int>("AMG_param.schwarz_mmsize", 200); amgParams.schwarz_maxlvl = description.get<int>("AMG_param.schwarz_maxlvl", 2); amgParams.schwarz_type = description.get<int>("AMG_param.schwarz_type", 1); return amgParams; } // ... initAMGParams(...) ILU_param initIluParams(const size_t& /*maxIter*/, const ScalarType& /*precision*/, const Dune::ParameterTree& description) const { ILU_param iluParams; iluParams.print_level = description.get<int>("ILU_param.print_level", 0); iluParams.ILU_type = description.get<int>("ILU_param.ILU_type", 1); iluParams.ILU_lfil = description.get<int>("ILU_param.ILU_lfil", 0); iluParams.ILU_droptol = description.get<double>("ILU_param.ILU_droptol", 1.0e-1); iluParams.ILU_relax = description.get<double>("ILU_param.ILU_relax", 9.0e-1); iluParams.ILU_permtol = description.get<double>("ILU_param.ILU_permtol", 1.0e-3); return iluParams; } // ... initIluParams(...) Schwarz_param initSchwarzParams(const size_t& /*maxIter*/, const ScalarType& /*precision*/, const Dune::ParameterTree& description) const { Schwarz_param schwarzParams; schwarzParams.print_level = description.get<int>("schwarzParams.print_level", 0); schwarzParams.schwarz_type = description.get<int>("schwarzParams.schwarz_type", 1); schwarzParams.schwarz_maxlvl = description.get<int>("schwarzParams.schwarz_maxlvl", 2); schwarzParams.schwarz_mmsize = description.get<int>("schwarzParams.schwarz_mmsize", 200); return schwarzParams; } // ... initSchwarzParams(...) }; // class AmgSolver } // namespace LA } // namespace XT } // namespace Dune # endif // HAVE_EIGEN #endif // HAVE_FASP #endif // DUNE_XT_LA_SOLVER_FASP_HH
53.635884
120
0.711531
dune-community
0e58ac0f89a74345cbb8d4ba7f6b0084e0a13a64
2,277
cpp
C++
my_vulkan/texture_sampler.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
my_vulkan/texture_sampler.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
3
2019-02-25T10:13:57.000Z
2020-11-11T14:46:14.000Z
my_vulkan/texture_sampler.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
#include "texture_sampler.hpp" #include "utils.hpp" namespace my_vulkan { texture_sampler_t::texture_sampler_t(VkDevice device, filter_mode_t filter_mode) : _device{device} { VkFilter filter; switch(filter_mode) { case filter_mode_t::linear: filter = VK_FILTER_LINEAR; break; case filter_mode_t::nearest: filter = VK_FILTER_NEAREST; break; case filter_mode_t::cubic: filter = VK_FILTER_CUBIC_IMG; break; } VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.pNext = 0; samplerInfo.flags = 0; samplerInfo.magFilter = filter; samplerInfo.minFilter = filter; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; vk_require( vkCreateSampler(device, &samplerInfo, nullptr, &_sampler), "creating texture sampler" ); } texture_sampler_t::texture_sampler_t(texture_sampler_t&& other) noexcept : _device{0} { *this = std::move(other); } texture_sampler_t& texture_sampler_t::operator=(texture_sampler_t&& other) noexcept { cleanup(); _sampler = other._sampler; std::swap(_device, other._device); return *this; } texture_sampler_t::~texture_sampler_t() { cleanup(); } void texture_sampler_t::cleanup() { if (_device) { vkDestroySampler(_device, _sampler, nullptr); _device = 0; } } VkSampler texture_sampler_t::get() { return _sampler; } }
29.571429
87
0.625823
pixelwise
0e5b6811ac90710d35f50afa1cb894e3193535a4
5,624
cc
C++
service/testing/epoll_test.cc
datacratic/soa
74eeda506feb522de9181aac4a5543c7766e600e
[ "Apache-2.0" ]
11
2015-11-10T09:56:37.000Z
2021-02-09T02:10:45.000Z
service/testing/epoll_test.cc
datacratic/soa
74eeda506feb522de9181aac4a5543c7766e600e
[ "Apache-2.0" ]
40
2015-01-08T12:16:37.000Z
2016-06-08T19:41:03.000Z
service/testing/epoll_test.cc
datacratic/soa
74eeda506feb522de9181aac4a5543c7766e600e
[ "Apache-2.0" ]
10
2015-01-05T21:46:46.000Z
2021-09-26T10:07:07.000Z
/* epoll_test.cc Wolfgang Sourdeau, 17 November 2014 Copyright (c) 2014 Datacratic. All rights reserved. Assumption tests for epoll */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <fcntl.h> #include <unistd.h> #include <sys/epoll.h> #include <atomic> #include <iostream> #include <thread> #include <boost/test/unit_test.hpp> #include <jml/arch/exception.h> #include <jml/arch/futex.h> #include <jml/arch/timers.h> #include <jml/utils/exc_assert.h> using namespace std; namespace { #if 1 /* Assumption test - this disproves the race condition initially suspected * with EPOLLONESHOT in the following scenario: - armed fd - (data received) - epoll_wait returns due to armed fd and data received - read fd - (data received) - rearmed fd - epoll_wait waits indefinitely due to data emitted before fd rearmed fd */ void thread1Fn(atomic<int> & stage, int epollFd, int pipeFds[2]) { uint32_t readData; struct epoll_event armEvent, event; armEvent.events = EPOLLIN | EPOLLONESHOT; ::fprintf(stderr, "thread 1: arming fd\n"); int rc = ::epoll_ctl(epollFd, EPOLL_CTL_ADD, pipeFds[0], &armEvent); if (rc == -1) { throw ML::Exception(errno, "epoll_ctl"); } stage = 1; ML::futex_wake(stage); ::fprintf(stderr, "thread 1: waiting 1\n"); while (true) { rc = ::epoll_wait(epollFd, &event, 1, -1); if (rc == -1) { if (errno == EINTR) { continue; } throw ML::Exception(errno, "epoll_wait"); } break; } ::fprintf(stderr, "thread 1: reading 1\n"); rc = ::read(pipeFds[0], &readData, sizeof(readData)); if (rc == -1) { throw ML::Exception(errno, "read"); } ExcAssertEqual(rc, sizeof(readData)); ExcAssertEqual(readData, 1); ML::sleep(1.0); ::fprintf(stderr, "thread 1: reading 2\n"); rc = ::read(pipeFds[0], &readData, sizeof(readData)); if (rc == -1) { throw ML::Exception(errno, "read"); } ExcAssertEqual(rc, sizeof(readData)); ExcAssertEqual(readData, 0x1fffffff); ML::sleep(1.0); rc = ::read(pipeFds[0], &readData, sizeof(readData)); ExcAssert(rc == -1); ExcAssert(errno == EWOULDBLOCK); stage = 2; ML::futex_wake(stage); ::fprintf(stderr, "thread 1: data read, awaiting final notification from thread" " 2\n"); while (stage.load() != 3) { ML::futex_wait(stage, 2); } ::fprintf(stderr, "thread 1: notified of final payload from thread 2\n"); ML::sleep(1.0); ::fprintf(stderr, "thread 1: rearming\n"); rc = ::epoll_ctl(epollFd, EPOLL_CTL_MOD, pipeFds[0], &armEvent); if (rc == -1) { throw ML::Exception(errno, "epoll_ctl"); } ::fprintf(stderr, "thread 1: epoll_wait for final payload\n"); while (true) { rc = ::epoll_wait(epollFd, &event, 1, 2000); if (rc == -1) { if (errno == EINTR) { continue; } throw ML::Exception(errno, "epoll_wait"); } else if (rc == 0) ::fprintf(stderr, "thread 1: second epoll wait has no event\n"); else if (rc > 0) ::fprintf(stderr, "thread 1: second epoll wait has %d events\n", rc); break; } /* This proves that the data written in thread 2 was properly received despite being sent before the rearming of our end of the pipe. */ BOOST_CHECK_EQUAL(rc, 1); } void thread2Fn(atomic<int> & stage, int epollFd, int pipeFds[2]) { ::fprintf(stderr, "thread 2: initial wait for thread1\n"); while (stage.load() != 1) { ML::futex_wait(stage, 0); } uint32_t writeData(1); int rc = ::write(pipeFds[1], &writeData, sizeof(writeData)); if (rc == -1) { throw ML::Exception(errno, "write"); } ExcAssert(rc == sizeof(writeData)); ::fprintf(stderr, "thread 2: payload 1 written\n"); writeData = 0x1fffffff; rc = ::write(pipeFds[1], &writeData, sizeof(writeData)); if (rc == -1) { throw ML::Exception(errno, "write"); } ExcAssert(rc == sizeof(writeData)); ::fprintf(stderr, "thread 2: payload 2 written\n"); ::fprintf(stderr, "thread 2: waiting thread 1\n"); while (stage.load() != 2) { ML::futex_wait(stage, 1); } ::fprintf(stderr, "thread 2: thread1 done reading, writing again\n"); writeData = 0x12345678; rc = ::write(pipeFds[1], &writeData, sizeof(writeData)); if (rc == -1) { throw ML::Exception(errno, "write"); } ExcAssert(rc == sizeof(writeData)); ::fprintf(stderr, "thread 2: payload 3 written\n"); ::fprintf(stderr, "thread 2: writing complete, notifying thread 1\n"); stage++; ML::futex_wake(stage); } } BOOST_AUTO_TEST_CASE( test_epolloneshot ) { int epollFd = ::epoll_create(666); if (epollFd == -1) { throw ML::Exception(errno, "epoll_create"); } int pipeFds[2]; if (::pipe2(pipeFds, O_NONBLOCK) == -1) { throw ML::Exception(errno, "pipe2"); } atomic<int> stage(0); /* receiving thread */ auto thread1Lda = [&] () { thread1Fn(stage, epollFd, pipeFds); ::fprintf(stderr, "thread1 done\n"); }; thread thread1(thread1Lda); /* sending thread */ auto thread2Lda = [&] () { thread2Fn(stage, epollFd, pipeFds); ::fprintf(stderr, "thread 2 done\n"); }; thread thread2(thread2Lda); thread2.join(); thread1.join(); ::close(pipeFds[0]); ::close(pipeFds[1]); ::close(epollFd); } #endif
26.403756
76
0.590683
datacratic
0e5ba627fe0d0520d8672e092355f9bad1916123
887
cpp
C++
Dynamic Programming/common sub sequence/cpp/CommonSubSeq.cpp
iabhimanyu/Algorithms
adefcd165e591d2338be8fc8a62629ff072620dd
[ "MIT" ]
715
2018-10-01T21:30:10.000Z
2022-03-23T09:14:10.000Z
Dynamic Programming/common sub sequence/cpp/CommonSubSeq.cpp
iabhimanyu/Algorithms
adefcd165e591d2338be8fc8a62629ff072620dd
[ "MIT" ]
157
2018-10-01T20:53:11.000Z
2021-08-03T07:00:58.000Z
Dynamic Programming/common sub sequence/cpp/CommonSubSeq.cpp
iabhimanyu/Algorithms
adefcd165e591d2338be8fc8a62629ff072620dd
[ "MIT" ]
1,225
2018-10-01T20:56:22.000Z
2022-02-22T04:00:27.000Z
/* Implementation of LCS problem using Dynamic Programming*/ #include <bits/stdc++.h> using namespace std; void lcs(string X, string Y){ int m = X.length(); int n = Y.length(); int L[m+1][n+1]; for (int i=0; i<=m; i++){ for (int j=0; j<=n; j++){ if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } int index = L[m][n]; char lcs[index+1]; lcs[index] = ' '; int i = m, j = n; while (i > 0 && j > 0){ if (X[i-1] == Y[j-1]){ lcs[index-1] = X[i-1]; i--; j--; index--; } else if (L[i-1][j] > L[i][j-1]) i--; else j--; } //output cout << "LCS of " << X << " and " << Y << " is " << lcs; } int main(){ string a,b; //input two strings cin>>a; cin>>b; lcs(a,b); return 0; }
18.102041
60
0.421646
iabhimanyu
0e5ecc3d0d0738ff380c02ec54d8eaff1b264017
8,227
cpp
C++
native/ugc.cpp
rfht/hlsteam-stub
5757ec73fb645fd809bfbf042f3b00296e714b36
[ "MIT" ]
3
2020-04-18T13:13:52.000Z
2021-04-09T22:40:45.000Z
native/ugc.cpp
rfht/hlsteam-stub
5757ec73fb645fd809bfbf042f3b00296e714b36
[ "MIT" ]
null
null
null
native/ugc.cpp
rfht/hlsteam-stub
5757ec73fb645fd809bfbf042f3b00296e714b36
[ "MIT" ]
1
2021-08-12T14:44:43.000Z
2021-08-12T14:44:43.000Z
#include "steamwrap.h" /* vdynamic *CallbackHandler::EncodeDownloadItem(int *d) { return nullptr; } vdynamic *CallbackHandler::EncodeItemInstalled(int *d) { return nullptr; } */ HL_PRIM varray *HL_NAME(get_subscribed_items)(){ printf("%s\n", __func__); return nullptr; } HL_PRIM int HL_NAME(get_item_state)(vuid publishedFileID){ printf("%s\n", __func__); return 0; } HL_PRIM bool HL_NAME(get_item_download_info)(vuid publishedFileID, double *downloaded, double *total ){ printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(download_item)(vuid publishedFileID, bool highPriority){ printf("%s\n", __func__); return false; } HL_PRIM vdynamic *HL_NAME(get_item_install_info)(vuid publishedFileID){ printf("%s\n", __func__); return NULL; } static void on_item_subscribed(vclosure *c, int *result, bool error) { printf("%s\n", __func__); } HL_PRIM void* HL_NAME(subscribe_item)(vuid publishedFileID, vclosure *closure) { printf("%s\n", __func__); return nullptr; } HL_PRIM void* HL_NAME(unsubscribe_item)(vuid publishedFileID, vclosure *closure) { printf("%s\n", __func__); return nullptr; } DEFINE_PRIM(_ARR, get_subscribed_items, _NO_ARG); DEFINE_PRIM(_I32, get_item_state, _UID); DEFINE_PRIM(_BOOL, get_item_download_info, _UID _REF(_F64) _REF(_F64)); DEFINE_PRIM(_BOOL, download_item, _UID _BOOL); DEFINE_PRIM(_DYN, get_item_install_info, _UID); DEFINE_PRIM(_CRESULT, subscribe_item, _UID _CALLB(_UID)); DEFINE_PRIM(_CRESULT, unsubscribe_item, _UID _CALLB(_UID)); //----------------------------------------------------------------------------------------------------------- // UGC QUERY //----------------------------------------------------------------------------------------------------------- HL_PRIM vuid HL_NAME(ugc_query_create_all_request)(int queryType, int matchingUGCType, int creatorAppID, int consumerAppID, int page){ printf("%s\n", __func__); return nullptr; } HL_PRIM vuid HL_NAME(ugc_query_create_user_request)(int uid, int listType, int matchingUGCType, int sortOrder, int creatorAppID, int consumerAppID, int page) { printf("%s\n", __func__); return nullptr; } HL_PRIM vuid HL_NAME(ugc_query_create_details_request)(varray *fileIDs){ printf("%s\n", __func__); return nullptr; } HL_PRIM bool HL_NAME(ugc_query_set_language)(vuid handle, vbyte *lang) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_set_search_text)(vuid handle, vbyte *search) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_add_required_tag)(vuid handle, vbyte *tagName) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_add_required_key_value_tag)(vuid handle, vbyte *pKey, vbyte *pValue) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_add_excluded_tag)(vuid handle, vbyte *tagName) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_set_return_metadata)(vuid handle, bool returnMetadata) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_set_return_key_value_tags)(vuid handle, bool returnKeyValueTags) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_query_set_return_children)(vuid handle, bool returnChildren) { printf("%s\n", __func__); return false; } static void on_query_completed(vclosure *c, int *result, bool error) { printf("%s\n", __func__); } HL_PRIM void* HL_NAME(ugc_query_send_request)(vuid cHandle, vclosure *closure){ printf("%s\n", __func__); return nullptr; } HL_PRIM bool HL_NAME(ugc_query_release_request)(vuid cHandle) { printf("%s\n", __func__); return false; } HL_PRIM varray *HL_NAME(ugc_query_get_key_value_tags)(vuid cHandle, int iIndex, int maxValueLength ){ printf("%s\n", __func__); return nullptr; } HL_PRIM varray *HL_NAME(ugc_query_get_children)(vuid cHandle, int iIndex, int maxChildren) { printf("%s\n", __func__); return nullptr; } HL_PRIM vbyte *HL_NAME(ugc_query_get_metadata)(vuid sHandle, int iIndex){ printf("%s\n", __func__); return nullptr; } HL_PRIM vdynamic *HL_NAME(ugc_query_get_result)(vuid sHandle, int iIndex){ printf("%s\n", __func__); return nullptr; } DEFINE_PRIM(_UID, ugc_query_create_all_request, _I32 _I32 _I32 _I32 _I32); DEFINE_PRIM(_UID, ugc_query_create_user_request, _I32 _I32 _I32 _I32 _I32 _I32 _I32); DEFINE_PRIM(_UID, ugc_query_create_details_request, _ARR); DEFINE_PRIM(_BOOL, ugc_query_set_language, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_query_set_search_text, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_query_add_required_tag, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_query_add_required_key_value_tag, _UID _BYTES _BYTES); DEFINE_PRIM(_BOOL, ugc_query_add_excluded_tag, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_query_set_return_metadata, _UID _BOOL); DEFINE_PRIM(_BOOL, ugc_query_set_return_key_value_tags, _UID _BOOL); DEFINE_PRIM(_BOOL, ugc_query_set_return_children, _UID _BOOL); DEFINE_PRIM(_CRESULT, ugc_query_send_request, _UID _CALLB(_DYN)); DEFINE_PRIM(_BOOL, ugc_query_release_request, _UID); DEFINE_PRIM(_ARR, ugc_query_get_key_value_tags, _UID _I32 _I32); DEFINE_PRIM(_ARR, ugc_query_get_children, _UID _I32 _I32); DEFINE_PRIM(_BYTES, ugc_query_get_metadata, _UID _I32); DEFINE_PRIM(_DYN, ugc_query_get_result, _UID _I32); //----------------------------------------------------------------------------------------------------------- // UGC UPDATE //----------------------------------------------------------------------------------------------------------- static void on_item_created(vclosure *c, int *result, bool error) { printf("%s\n", __func__); } HL_PRIM void* HL_NAME(ugc_item_create)(int appId, vclosure *closure) { printf("%s\n", __func__); return nullptr; } HL_PRIM vuid HL_NAME(ugc_item_start_update)(int id, vuid itemID) { printf("%s\n", __func__); return nullptr; } static void on_item_updated(vclosure *c, int *result, bool error) { printf("%s\n", __func__); } HL_PRIM void* HL_NAME(ugc_item_submit_update)(vuid updateHandle, vbyte *changeNotes, vclosure *closure){ printf("%s\n", __func__); return nullptr; } HL_PRIM bool HL_NAME(ugc_item_set_update_language)(vuid updateHandle, vbyte *lang) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_title)(vuid updateHandle, vbyte *title) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_description)(vuid updateHandle, vbyte *description){ printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_metadata)(vuid updateHandle, vbyte *metadata) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_tags)(vuid updateHandle, varray *tags){ printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_add_key_value_tag)(vuid updateHandle, vbyte *keyStr, vbyte *valueStr){ printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_remove_key_value_tags)(vuid updateHandle, vbyte *keyStr) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_visibility)(vuid updateHandle, int visibility) { printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_content)(vuid updateHandle, vbyte *path){ printf("%s\n", __func__); return false; } HL_PRIM bool HL_NAME(ugc_item_set_preview_image)(vuid updateHandle, vbyte *path){ printf("%s\n", __func__); return false; } DEFINE_PRIM(_CRESULT, ugc_item_create, _I32 _CALLB(_DYN)); DEFINE_PRIM(_UID, ugc_item_start_update, _I32 _UID); DEFINE_PRIM(_CRESULT, ugc_item_submit_update, _UID _BYTES _CALLB(_BOOL)); DEFINE_PRIM(_BOOL, ugc_item_set_update_language, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_item_set_title, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_item_set_description, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_item_set_metadata, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_item_set_tags, _UID _ARR); DEFINE_PRIM(_BOOL, ugc_item_add_key_value_tag, _UID _BYTES _BYTES); DEFINE_PRIM(_BOOL, ugc_item_remove_key_value_tags, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_item_set_visibility, _UID _I32); DEFINE_PRIM(_BOOL, ugc_item_set_content, _UID _BYTES); DEFINE_PRIM(_BOOL, ugc_item_set_preview_image, _UID _BYTES); HL_PRIM void HL_NAME(file_share)(){ printf("%s\n", __func__); } DEFINE_PRIM(_VOID, file_share, _NO_ARG);
30.812734
159
0.73198
rfht
0e5ef653e2f5d7b0a25571e20bd63aca77ba7b3b
3,617
cpp
C++
Sources/Fonts/FontType.cpp
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
43
2017-08-09T04:03:38.000Z
2018-07-17T15:25:32.000Z
Sources/Fonts/FontType.cpp
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
3
2018-01-23T06:44:41.000Z
2018-05-29T19:22:41.000Z
Sources/Fonts/FontType.cpp
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
6
2017-11-03T10:48:20.000Z
2018-04-28T21:44:59.000Z
#include "FontType.hpp" #include <tiny_msdf.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include "Files/Files.hpp" #include "Resources/Resources.hpp" #include "Graphics/Graphics.hpp" namespace acid { static const std::wstring_view NEHE = L" \t\r\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\"!`?'.,;:()[]{}<>|/@\\^$-%+=#_&~*"; template<typename T> constexpr double F26DOT6_TO_DOUBLE(T x) { return 1.0 / 64.0 * double(x); } std::shared_ptr<FontType> FontType::Create(const Node &node) { if (auto resource = Resources::Get()->Find<FontType>(node)) return resource; auto result = std::make_shared<FontType>("", 0, false); Resources::Get()->Add(node, std::dynamic_pointer_cast<Resource>(result)); node >> *result; result->Load(); return result; } std::shared_ptr<FontType> FontType::Create(const std::filesystem::path &filename, std::size_t size) { FontType temp(filename, size, false); Node node; node << temp; return Create(node); } FontType::FontType(std::filesystem::path filename, std::size_t size, bool load) : filename(std::move(filename)), size(size) { if (load) FontType::Load(); } FontType::~FontType() { Close(); } const Node &operator>>(const Node &node, FontType &fontType) { node["filename"].Get(fontType.filename); node["size"].Get(fontType.size); return node; } Node &operator<<(Node &node, const FontType &fontType) { node["filename"].Set(fontType.filename); node["size"].Set(fontType.size); return node; } void FontType::Open() { if (auto error = FT_Init_FreeType(&library)) throw std::runtime_error("Freetype failed to initialize"); auto fileLoaded = Files::Read(filename); if (!fileLoaded) { Log::Error("Font could not be loaded: ", filename, '\n'); return; } if (FT_New_Memory_Face(library, reinterpret_cast<FT_Byte *>(fileLoaded->data()), static_cast<FT_Long>(fileLoaded->size()), 0, &face) != 0) throw std::runtime_error("Freetype failed to create face from memory"); // Multiply pixel size by 64 as FreeType uses points instead of pixels internally. if (FT_Set_Char_Size(face, size * 64, size * 64, 96, 96) != 0) throw std::runtime_error("Freetype failed to set char size"); } void FontType::Close() { if (!IsOpen()) return; FT_Done_Face(face); face = nullptr; FT_Done_FreeType(library); library = nullptr; } void FontType::Load() { if (filename.empty()) return; #ifdef ACID_DEBUG auto debugStart = Time::Now(); #endif Open(); auto layerCount = NEHE.size(); //image = std::make_unique<Image2dArray>(Vector2ui(size, size), layerCount, VK_FORMAT_R32G32B32A32_SFLOAT); tinymsdf::Bitmap<float, 4> mtsdf(size, size); glyphs.resize(glyphs.size() + layerCount); for (auto c : NEHE) { bool success = !tinymsdf::GenerateMTSDF(mtsdf, face, c); auto id = indices.size(); indices[c] = id; glyphs[id].advance = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiAdvance); glyphs[id].x = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiBearingX); glyphs[id].y = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiBearingY); glyphs[id].w = F26DOT6_TO_DOUBLE(face->glyph->metrics.width); glyphs[id].h = F26DOT6_TO_DOUBLE(face->glyph->metrics.height); glyphs[id].pxRange = 2; //if (success) // image->SetPixels(mtsdf.pixels, id); } Close(); #ifdef ACID_DEBUG Log::Out("Font Type ", filename, " loaded ", glyphs.size(), " glyphs in ", (Time::Now() - debugStart).AsMilliseconds<float>(), "ms\n"); #endif } std::optional<FontType::Glyph> FontType::GetGlyph(wchar_t ascii) const { auto it = indices.find(ascii); if (it != indices.end()) { return glyphs[it->second]; } return std::nullopt; } }
26.40146
145
0.697263
Equilibrium-Games
0e606b0a8a475b3df31cfe975fe752e36b16ddd0
855
cpp
C++
day-9-6-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-9-6-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-9-6-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
/* 求四名同学在三次考试中的成绩 */ #include <stdio.h> void mat_add(const int a[4][3], const int b[4][3], int c[4][3]); void mat_print(const int m[4][3]); int main(void) { int sore1[4][3] = { {23, 13,23}, {23, 67, 89}, {34, 56, 67}, {89,98, 32} }; int sore2[4][3] = { {93, 43,33}, {23, 63, 82}, {34, 66, 87}, {69,93, 39} }; int sum[4][3]; mat_add(sore1, sore2, sum); printf("第一次考试的分数\n"); mat_print(sore1); printf("第二次考试的分数\n"); mat_print(sore2); puts("总分"); mat_print(sum); return 0; } void mat_add(const int a[4][3], const int b[4][3], int c[4][3]) { int i, j; for (i = 0; i < 4; i++) for (j = 0; j < 3; j++) c[i][j] = a[i][j] + b[i][j]; // 那个也是这个样子吗? } void mat_print(const int m[4][3]) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 3; j++) printf("%4d", m[i][j]); putchar('\n'); } }
21.923077
77
0.493567
duasong111
0e65e917d58fa56f2f129821a6101a06af7f15dd
4,961
cc
C++
google_apis/gaia/ubertoken_fetcher.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
google_apis/gaia/ubertoken_fetcher.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
google_apis/gaia/ubertoken_fetcher.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2014 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 "google_apis/gaia/ubertoken_fetcher.h" #include <vector> #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" #include "base/time/time.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_token_service.h" namespace { GaiaAuthFetcher* CreateGaiaAuthFetcher( GaiaAuthConsumer* consumer, const std::string& source, net::URLRequestContextGetter* request_context) { return new GaiaAuthFetcher(consumer, source, request_context); } } const int UbertokenFetcher::kMaxRetries = 3; UbertokenFetcher::UbertokenFetcher( OAuth2TokenService* token_service, UbertokenConsumer* consumer, const std::string& source, net::URLRequestContextGetter* request_context) : UbertokenFetcher(token_service, consumer, source, request_context, base::Bind(CreateGaiaAuthFetcher)) { } UbertokenFetcher::UbertokenFetcher( OAuth2TokenService* token_service, UbertokenConsumer* consumer, const std::string& source, net::URLRequestContextGetter* request_context, GaiaAuthFetcherFactory factory) : OAuth2TokenService::Consumer("uber_token_fetcher"), token_service_(token_service), consumer_(consumer), source_(source), request_context_(request_context), gaia_auth_fetcher_factory_(factory), retry_number_(0), second_access_token_request_(false) { DCHECK(token_service); DCHECK(consumer); DCHECK(request_context); } UbertokenFetcher::~UbertokenFetcher() { } void UbertokenFetcher::StartFetchingToken(const std::string& account_id) { DCHECK(!account_id.empty()); account_id_ = account_id; second_access_token_request_ = false; RequestAccessToken(); } void UbertokenFetcher::StartFetchingTokenWithAccessToken( const std::string& account_id, const std::string& access_token) { DCHECK(!account_id.empty()); DCHECK(!access_token.empty()); account_id_ = account_id; access_token_ = access_token; ExchangeTokens(); } void UbertokenFetcher::OnUberAuthTokenSuccess(const std::string& token) { consumer_->OnUbertokenSuccess(token); } void UbertokenFetcher::OnUberAuthTokenFailure( const GoogleServiceAuthError& error) { // Retry only transient errors. bool should_retry = error.state() == GoogleServiceAuthError::CONNECTION_FAILED || error.state() == GoogleServiceAuthError::SERVICE_UNAVAILABLE; if (should_retry) { if (retry_number_ < kMaxRetries) { // Calculate an exponential backoff with randomness of less than 1 sec. double backoff = base::RandDouble() + (1 << retry_number_); ++retry_number_; UMA_HISTOGRAM_ENUMERATION("Signin.UberTokenRetry", error.state(), GoogleServiceAuthError::NUM_STATES); retry_timer_.Stop(); retry_timer_.Start(FROM_HERE, base::TimeDelta::FromSecondsD(backoff), this, &UbertokenFetcher::ExchangeTokens); return; } } else { // The access token is invalid. Tell the token service. OAuth2TokenService::ScopeSet scopes; scopes.insert(GaiaConstants::kOAuth1LoginScope); token_service_->InvalidateAccessToken(account_id_, scopes, access_token_); // In case the access was just stale, try one more time. if (!second_access_token_request_) { second_access_token_request_ = true; RequestAccessToken(); return; } } UMA_HISTOGRAM_ENUMERATION("Signin.UberTokenFailure", error.state(), GoogleServiceAuthError::NUM_STATES); consumer_->OnUbertokenFailure(error); } void UbertokenFetcher::OnGetTokenSuccess( const OAuth2TokenService::Request* request, const std::string& access_token, const base::Time& expiration_time) { DCHECK(!access_token.empty()); access_token_ = access_token; access_token_request_.reset(); ExchangeTokens(); } void UbertokenFetcher::OnGetTokenFailure( const OAuth2TokenService::Request* request, const GoogleServiceAuthError& error) { access_token_request_.reset(); consumer_->OnUbertokenFailure(error); } void UbertokenFetcher::RequestAccessToken() { retry_number_ = 0; gaia_auth_fetcher_.reset(); retry_timer_.Stop(); OAuth2TokenService::ScopeSet scopes; scopes.insert(GaiaConstants::kOAuth1LoginScope); access_token_request_ = token_service_->StartRequest(account_id_, scopes, this); } void UbertokenFetcher::ExchangeTokens() { gaia_auth_fetcher_.reset( gaia_auth_fetcher_factory_.Run(this, source_, request_context_)); gaia_auth_fetcher_->StartTokenFetchForUberAuthExchange(access_token_); }
31.801282
78
0.729087
google-ar
0e6616c096e92c2c85f7599f6a5a81dfc094f72b
3,273
cpp
C++
src/python_bindings.cpp
johnlees/mandrake
f34deb1aeed730041398923c1c0d6e6d5ccb9611
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
16
2021-09-14T14:19:08.000Z
2022-02-02T23:51:04.000Z
src/python_bindings.cpp
johnlees/mandrake
f34deb1aeed730041398923c1c0d6e6d5ccb9611
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
10
2021-09-15T17:51:26.000Z
2022-01-20T11:22:26.000Z
src/python_bindings.cpp
johnlees/mandrake
f34deb1aeed730041398923c1c0d6e6d5ccb9611
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
1
2021-09-28T14:44:12.000Z
2021-09-28T14:44:12.000Z
// 2021 John Lees, Gerry Tonkin-Hill, Zhirong Yang // See LICENSE files #include "pairsnp.hpp" #include "sound.hpp" #include "wtsne.hpp" #include <pybind11/stl.h> namespace py = pybind11; PYBIND11_MODULE(SCE, m) { m.doc() = "Stochastic cluster embedding"; m.attr("version") = VERSION_INFO; // Results class (need to define here to be able to return this type) py::class_<sce_results, std::shared_ptr<sce_results>>(m, "sce_result") .def(py::init<const bool, const size_t, const uint64_t>()) .def("animated", &sce_results::is_animated) .def("n_frames", &sce_results::n_frames) .def("get_eq", &sce_results::get_eq) .def("get_embedding", &sce_results::get_embedding) .def("get_embedding_frame", &sce_results::get_embedding_frame, py::arg("frame")); // Exported functions m.def("wtsne", &wtsne, py::return_value_policy::take_ownership, "Run stochastic cluster embedding", py::arg("I_vec"), py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"), py::arg("maxIter"), py::arg("nRepuSamp") = 5, py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false, py::arg("n_workers") = 128, py::arg("n_threads") = 1, py::arg("seed") = 1); m.def("pairsnp", &pairsnp, py::return_value_policy::take_ownership, "Run pairsnp", py::arg("fasta"), py::arg("n_threads"), py::arg("dist"), py::arg("knn")); m.def("gen_audio", &sample_wave, py::return_value_policy::take_ownership, "Generate audio for animation", py::arg("frequencies"), py::arg("duration"), py::arg("sample_rate"), py::arg("n_threads")); #ifdef GPU_AVAILABLE // NOTE: python always uses fp64 so cannot easily template these (which // would just give one function name exported but with different type // prototypes). To do this would require numpy (python)/Eigen (C++) which // support both precisions. But easier just to stick with List (python)/ // std::vector (C++) and allow fp64->fp32 conversion when called // Use fp64 for double precision (slower, more accurate) m.def("wtsne_gpu_fp64", &wtsne_gpu<double>, py::return_value_policy::take_ownership, "Run stochastic cluster embedding with CUDA", py::arg("I_vec"), py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"), py::arg("maxIter"), py::arg("blockSize") = 128, py::arg("n_workers") = 128, py::arg("nRepuSamp") = 5, py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false, py::arg("cpu_threads") = 1, py::arg("device_id") = 0, py::arg("seed") = 1); // Use fp32 for single precision (faster, less accurate) m.def("wtsne_gpu_fp32", &wtsne_gpu<float>, py::return_value_policy::take_ownership, "Run stochastic cluster embedding with CUDA", py::arg("I_vec"), py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"), py::arg("maxIter"), py::arg("blockSize") = 128, py::arg("n_workers") = 128, py::arg("nRepuSamp") = 5, py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false, py::arg("cpu_threads") = 1, py::arg("device_id") = 0, py::arg("seed") = 1); #endif }
46.098592
79
0.62542
johnlees
0e66dadb9b0faf7b9e13c7b977595fcdd3541173
897
hpp
C++
include/version.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/version.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/version.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_CORE_VERSION_HPP_ #define BE_CORE_VERSION_HPP_ #include "macros.hpp" #define BE_CORE_VERSION_MAJOR 0 #define BE_CORE_VERSION_MINOR 1 #define BE_CORE_VERSION_REV 32 /*!! include('common/version', 'BE_CORE', 'bengine') !! 6 */ /* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */ #define BE_CORE_VERSION (BE_CORE_VERSION_MAJOR * 100000 + BE_CORE_VERSION_MINOR * 1000 + BE_CORE_VERSION_REV) #define BE_CORE_VERSION_STRING "bengine " BE_STRINGIFY(BE_CORE_VERSION_MAJOR) "." BE_STRINGIFY(BE_CORE_VERSION_MINOR) "." BE_STRINGIFY(BE_CORE_VERSION_REV) /* ######################### END OF GENERATED CODE ######################### */ #define BE_COPYRIGHT "Copyright (C) 2012-2017 Magic / More Magic, B. Crist" #define BE_LICENSE "Distributed under the MIT license as part of bengine" #define BE_URL "https://github.com/magicmoremagic/bengine" #endif
39
155
0.702341
magicmoremagic
0e68cf0eb44496c1dcb61eaaa213e80b23c2f918
26,546
cpp
C++
cross/cocos2d/cocos/2d/platform/android/nativeactivity.cpp
yobiya/tdd_game_sample
d3605c13f1fd97cd3929d5d3054f603edde839db
[ "MIT" ]
20
2015-01-04T03:15:01.000Z
2020-08-14T00:48:34.000Z
cocos2d/cocos/2d/platform/android/nativeactivity.cpp
kobakei/CCLocalNotification
c47ad6ff96409857ee6637892cc2618c1daf7ffa
[ "Apache-2.0" ]
null
null
null
cocos2d/cocos/2d/platform/android/nativeactivity.cpp
kobakei/CCLocalNotification
c47ad6ff96409857ee6637892cc2618c1daf7ffa
[ "Apache-2.0" ]
5
2015-06-15T02:26:05.000Z
2021-10-04T06:57:49.000Z
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "nativeactivity.h" #include <jni.h> #include <errno.h> #include <EGL/egl.h> #include <GLES/gl.h> #include <android/sensor.h> #include <android/log.h> #include <android_native_app_glue.h> #include <android/configuration.h> #include <pthread.h> #include <chrono> #include "CCDirector.h" #include "CCApplication.h" #include "CCEventType.h" #include "CCFileUtilsAndroid.h" #include "jni/JniHelper.h" #include "CCEGLView.h" #include "CCDrawingPrimitives.h" #include "CCShaderCache.h" #include "CCTextureCache.h" #include "CCEventDispatcher.h" #include "CCEventAcceleration.h" #include "CCEventKeyboard.h" #include "CCEventCustom.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOG_RENDER_DEBUG(...) // #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOG_EVENTS_DEBUG(...) // #define LOG_EVENTS_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) /* For debug builds, always enable the debug traces in this library */ #ifndef NDEBUG # define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #else # define LOGV(...) ((void)0) #endif void cocos_android_app_init(struct android_app* app); /** * Our saved state data. */ struct saved_state { float angle; int32_t x; int32_t y; }; /** * Shared state for our app. */ struct engine { struct android_app* app; ASensorManager* sensorManager; const ASensor* accelerometerSensor; ASensorEventQueue* sensorEventQueue; int animating; EGLDisplay display; EGLSurface surface; EGLContext context; int32_t width; int32_t height; struct saved_state state; }; static bool isContentRectChanged = false; static std::chrono::steady_clock::time_point timeRectChanged; static struct engine engine; static char* editboxText = NULL; extern EditTextCallback s_pfEditTextCallback; extern void* s_ctx; extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) { jsize size = env->GetArrayLength(text); pthread_mutex_lock(&(engine.app->mutex)); if (size > 0) { jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0); char* pBuf = (char*)malloc(size+1); if (pBuf != NULL) { memcpy(pBuf, data, size); pBuf[size] = '\0'; editboxText = pBuf; } env->ReleaseByteArrayElements(text, data, 0); } else { char* pBuf = (char*)malloc(1); pBuf[0] = '\0'; editboxText = pBuf; } pthread_cond_broadcast(&engine.app->cond); pthread_mutex_unlock(&(engine.app->mutex)); } } typedef struct cocos_dimensions { int w; int h; } cocos_dimensions; static void cocos_init(cocos_dimensions d, struct android_app* app) { LOGI("cocos_init(...)"); pthread_t thisthread = pthread_self(); LOGI("pthread_self() = %X", thisthread); cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager); if (!cocos2d::Director::getInstance()->getOpenGLView()) { cocos2d::EGLView *view = cocos2d::EGLView::getInstance(); view->setFrameSize(d.w, d.h); cocos_android_app_init(app); cocos2d::Application::getInstance()->run(); } else { cocos2d::GL::invalidateStateCache(); cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); cocos2d::DrawPrimitives::init(); cocos2d::VolatileTextureMgr::reloadAllTextures(); cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent); cocos2d::Director::getInstance()->setGLDefaultValues(); } } /** * Initialize an EGL context for the current display. */ static cocos_dimensions engine_init_display(struct engine* engine) { cocos_dimensions r; r.w = -1; r.h = -1; // initialize OpenGL ES and EGL /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ const EGLint attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 8, EGL_NONE }; EGLint w, h, dummy, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); /* Here, the application chooses the configuration it desires. In this * sample, we have a very simplified selection process, where we pick * the first EGLConfig that matches our criteria */ eglChooseConfig(display, attribs, &config, 1, &numConfigs); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, config, engine->app->window, NULL); const EGLint eglContextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; context = eglCreateContext(display, config, NULL, eglContextAttrs); if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return r; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; engine->state.angle = 0; r.w = w; r.h = h; return r; } /** * Invoke the dispatching of the next bunch of Runnables in the Java-Land */ static bool s_methodInitialized = false; static void dispatch_pending_runnables() { static cocos2d::JniMethodInfo info; if (!s_methodInitialized) { s_methodInitialized = cocos2d::JniHelper::getStaticMethodInfo( info, "org/cocos2dx/lib/Cocos2dxHelper", "dispatchPendingRunnables", "()V" ); if (!s_methodInitialized) { LOGW("Unable to dispatch pending Runnables!"); return; } } info.env->CallStaticVoidMethod(info.classID, info.methodID); } /** * Just the current frame in the display. */ static void engine_draw_frame(struct engine* engine) { LOG_RENDER_DEBUG("engine_draw_frame(...)"); pthread_t thisthread = pthread_self(); LOG_RENDER_DEBUG("pthread_self() = %X", thisthread); if (engine->display == NULL) { // No display. LOGW("engine_draw_frame : No display."); return; } dispatch_pending_runnables(); cocos2d::Director::getInstance()->mainLoop(); LOG_RENDER_DEBUG("engine_draw_frame : just called cocos' mainLoop()"); /* // Just fill the screen with a color. */ /* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */ /* ((float)engine->state.y)/engine->height, 1); */ /* glClear(GL_COLOR_BUFFER_BIT); */ if (s_pfEditTextCallback && editboxText) { s_pfEditTextCallback(editboxText, s_ctx); free(editboxText); editboxText = NULL; } eglSwapBuffers(engine->display, engine->surface); } /** * Tear down the EGL context currently associated with the display. */ static void engine_term_display(struct engine* engine) { if (engine->display != EGL_NO_DISPLAY) { eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (engine->context != EGL_NO_CONTEXT) { eglDestroyContext(engine->display, engine->context); } if (engine->surface != EGL_NO_SURFACE) { eglDestroySurface(engine->display, engine->surface); } eglTerminate(engine->display); } engine->animating = 0; engine->display = EGL_NO_DISPLAY; engine->context = EGL_NO_CONTEXT; engine->surface = EGL_NO_SURFACE; } /* * Get X, Y positions and ID's for all pointers */ static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { int pointerCount = AMotionEvent_getPointerCount(event); for(int i = 0; i < pointerCount; ++i) { ids[i] = AMotionEvent_getPointerId(event, i); xs[i] = AMotionEvent_getX(event, i); ys[i] = AMotionEvent_getY(event, i); } } /* * Handle Touch Inputs */ static int32_t handle_touch_input(AInputEvent *event) { pthread_t thisthread = pthread_self(); LOG_EVENTS_DEBUG("handle_touch_input(%X), pthread_self() = %X", event, thisthread); switch(AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_DOWN: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_DOWN"); int pointerId = AMotionEvent_getPointerId(event, 0); float xP = AMotionEvent_getX(event,0); float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_POINTER_DOWN: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_DOWN"); int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; int pointerId = AMotionEvent_getPointerId(event, pointerIndex); float xP = AMotionEvent_getX(event,pointerIndex); float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_MOVE: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); int pointerCount = AMotionEvent_getPointerCount(event); int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); return 1; } break; case AMOTION_EVENT_ACTION_UP: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_UP"); int pointerId = AMotionEvent_getPointerId(event, 0); float xP = AMotionEvent_getX(event,0); float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", xP, yP, pointerId); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_POINTER_UP: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_UP"); int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; int pointerId = AMotionEvent_getPointerId(event, pointerIndex); float xP = AMotionEvent_getX(event,pointerIndex); float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", xP, yP, pointerIndex); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_CANCEL: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); int pointerCount = AMotionEvent_getPointerCount(event); int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); return 1; } break; default: LOG_EVENTS_DEBUG("handle_touch_input() default case.... NOT HANDLE"); return 0; break; } } /* * Handle Key Inputs */ static int32_t handle_key_input(AInputEvent *event) { if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) { auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); switch (AKeyEvent_getKeyCode(event)) { case AKEYCODE_BACK: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); dispatcher->dispatchEvent(&event); } return 1; case AKEYCODE_MENU: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false); dispatcher->dispatchEvent(&event); } return 1; default: break; } } return 0; } /** * Process the next input event. */ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) { pthread_t thisthread = pthread_self(); LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread); struct engine* engine = (struct engine*)app->userData; if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { engine->animating = 1; engine->state.x = AMotionEvent_getX(event, 0); engine->state.y = AMotionEvent_getY(event, 0); return handle_touch_input(event); } else return handle_key_input(event); return 0; } void enableAccelerometerJni(void) { LOGI("enableAccelerometerJni()"); if (engine.accelerometerSensor != NULL) { ASensorEventQueue_enableSensor(engine.sensorEventQueue, engine.accelerometerSensor); // Set a default sample rate // We'd like to get 60 events per second (in us). ASensorEventQueue_setEventRate(engine.sensorEventQueue, engine.accelerometerSensor, (1000L/60)*1000); } } void disableAccelerometerJni(void) { LOGI("disableAccelerometerJni()"); if (engine.accelerometerSensor != NULL) { ASensorEventQueue_disableSensor(engine.sensorEventQueue, engine.accelerometerSensor); } } void setAccelerometerIntervalJni(float interval) { LOGI("setAccelerometerIntervalJni(%f)", interval); // We'd like to get 60 events per second (in us). ASensorEventQueue_setEventRate(engine.sensorEventQueue, engine.accelerometerSensor, interval * 1000000L); } /** * Process the next main command. */ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { struct engine* engine = (struct engine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: // The system has asked us to save our current state. Do so. engine->app->savedState = malloc(sizeof(struct saved_state)); *((struct saved_state*)engine->app->savedState) = engine->state; engine->app->savedStateSize = sizeof(struct saved_state); break; case APP_CMD_INIT_WINDOW: // The window is being shown, get it ready. if (engine->app->window != NULL) { cocos_dimensions d = engine_init_display(engine); if ((d.w > 0) && (d.h > 0)) { cocos2d::JniHelper::setJavaVM(app->activity->vm); cocos2d::JniHelper::setClassLoaderFrom(app->activity->clazz); // call Cocos2dxHelper.init() cocos2d::JniMethodInfo ccxhelperInit; if (!cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit, "org/cocos2dx/lib/Cocos2dxHelper", "init", "(Landroid/app/Activity;)V")) { LOGI("cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit) FAILED"); } ccxhelperInit.env->CallStaticVoidMethod(ccxhelperInit.classID, ccxhelperInit.methodID, app->activity->clazz); cocos_init(d, app); } engine->animating = 1; engine_draw_frame(engine); } break; case APP_CMD_TERM_WINDOW: // The window is being hidden or closed, clean it up. engine_term_display(engine); break; case APP_CMD_GAINED_FOCUS: if (cocos2d::Director::getInstance()->getOpenGLView()) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); engine->animating = 1; } break; case APP_CMD_LOST_FOCUS: { cocos2d::Application::getInstance()->applicationDidEnterBackground(); cocos2d::EventCustom backgroundEvent(EVENT_COME_TO_BACKGROUND); cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&backgroundEvent); // Also stop animating. engine->animating = 0; engine_draw_frame(engine); } break; } } static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { timeRectChanged = std::chrono::steady_clock::now(); isContentRectChanged = true; } static void process_input(struct android_app* app, struct android_poll_source* source) { AInputEvent* event = NULL; int processed = 0; while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) { LOGV("New input event: type=%d\n", AInputEvent_getType(event)); if (AInputQueue_preDispatchEvent(app->inputQueue, event)) { continue; } int32_t handled = 0; if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event); AInputQueue_finishEvent(app->inputQueue, event, handled); processed = 1; } if (processed == 0) { LOGE("Failure reading next input event: %s\n", strerror(errno)); } } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { // Make sure glue isn't stripped. app_dummy(); memset(&engine, 0, sizeof(engine)); state->userData = &engine; state->onAppCmd = engine_handle_cmd; state->onInputEvent = engine_handle_input; state->inputPollSource.process = process_input; engine.app = state; // Prepare to monitor accelerometer engine.sensorManager = ASensorManager_getInstance(); engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager, ASENSOR_TYPE_ACCELEROMETER); engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager, state->looper, LOOPER_ID_USER, NULL, NULL); if (state->savedState != NULL) { // We are starting with a previous saved state; restore from it. engine.state = *(struct saved_state*)state->savedState; } // Screen size change support state->activity->callbacks->onContentRectChanged = onContentRectChanged; // loop waiting for stuff to do. while (1) { // Read all pending events. int ident; int events; struct android_poll_source* source; // If not animating, we will block forever waiting for events. // If animating, we loop until all events are read, then continue // to draw the next frame of animation. while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events, (void**)&source)) >= 0) { // Process this event. if (source != NULL) { source->process(state, source); } // If a sensor has data, process it now. if (ident == LOOPER_ID_USER) { if (engine.accelerometerSensor != NULL) { ASensorEvent event; while (ASensorEventQueue_getEvents(engine.sensorEventQueue, &event, 1) > 0) { LOG_EVENTS_DEBUG("accelerometer: x=%f y=%f z=%f", event.acceleration.x, event.acceleration.y, event.acceleration.z); AConfiguration* _currentconf = AConfiguration_new(); AConfiguration_fromAssetManager(_currentconf, state->activity->assetManager); static int32_t _orientation = AConfiguration_getOrientation(_currentconf); if (ACONFIGURATION_ORIENTATION_LAND != _orientation) { // ACONFIGURATION_ORIENTATION_ANY // ACONFIGURATION_ORIENTATION_PORT // ACONFIGURATION_ORIENTATION_SQUARE cocos2d::Acceleration acc; acc.x = -event.acceleration.x/10; acc.y = -event.acceleration.y/10; acc.z = event.acceleration.z/10; acc.timestamp = 0; cocos2d::EventAcceleration accEvent(acc); auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&accEvent); } else { // ACONFIGURATION_ORIENTATION_LAND // swap x and y parameters cocos2d::Acceleration acc; acc.x = event.acceleration.y/10; acc.y = -event.acceleration.x/10; acc.z = event.acceleration.z/10; acc.timestamp = 0; cocos2d::EventAcceleration accEvent(acc); auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&accEvent); } } } } // Check if we are exiting. if (state->destroyRequested != 0) { engine_term_display(&engine); memset(&engine, 0, sizeof(engine)); s_methodInitialized = false; return; } } if (engine.animating) { // Done with events; draw next animation frame. engine.state.angle += .01f; if (engine.state.angle > 1) { engine.state.angle = 0; } // Drawing is throttled to the screen update rate, so there // is no need to do timing here. LOG_RENDER_DEBUG("android_main : engine.animating"); engine_draw_frame(&engine); } else { LOG_RENDER_DEBUG("android_main : !engine.animating"); } // Check if screen size changed if (isContentRectChanged) { std::chrono::duration<int, std::milli> duration( std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged)); // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime if (duration.count() > 30) { isContentRectChanged = false; int32_t newWidth = ANativeWindow_getWidth(engine.app->window); int32_t newHeight = ANativeWindow_getHeight(engine.app->window); cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); } } } }
35.206897
137
0.616515
yobiya
0e696d20715dc73afc4ae5c530b3ee4f16dbade6
106
cpp
C++
Engine/Math/Ray3D.cpp
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
27
2015-09-03T18:41:03.000Z
2022-01-17T20:38:54.000Z
Engine/Math/Ray3D.cpp
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
null
null
null
Engine/Math/Ray3D.cpp
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
8
2015-02-23T10:04:30.000Z
2020-09-04T10:56:22.000Z
/* Ray3D.cpp Written by Matthew Fisher a 3D ray represented by an origin point and a direction vector. */
17.666667
63
0.764151
techmatt
0e6aa6bb823ed1ac4ac96db47326af50a653daa5
87,738
cpp
C++
grid-test/export/macos/obj/src/hscript/Interp.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
grid-test/export/macos/obj/src/hscript/Interp.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
grid-test/export/macos/obj/src/hscript/Interp.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.4 #include <hxcpp.h> #ifndef INCLUDED_IntIterator #include <IntIterator.h> #endif #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_Type #include <Type.h> #endif #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_ds_BalancedTree #include <haxe/ds/BalancedTree.h> #endif #ifndef INCLUDED_haxe_ds_EnumValueMap #include <haxe/ds/EnumValueMap.h> #endif #ifndef INCLUDED_haxe_ds_IntMap #include <haxe/ds/IntMap.h> #endif #ifndef INCLUDED_haxe_ds_ObjectMap #include <haxe/ds/ObjectMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_hscript_CType #include <hscript/CType.h> #endif #ifndef INCLUDED_hscript_Const #include <hscript/Const.h> #endif #ifndef INCLUDED_hscript_Error #include <hscript/Error.h> #endif #ifndef INCLUDED_hscript_Expr #include <hscript/Expr.h> #endif #ifndef INCLUDED_hscript_Interp #include <hscript/Interp.h> #endif #ifndef INCLUDED_hscript__Interp_Stop #include <hscript/_Interp/Stop.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_f37559d470356c9e_53_new,"hscript.Interp","new",0xf7e71101,"hscript.Interp.new","hscript/Interp.hx",53,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_64_resetVariables,"hscript.Interp","resetVariables",0x6cebf7e7,"hscript.Interp.resetVariables","hscript/Interp.hx",64,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_74_resetVariables,"hscript.Interp","resetVariables",0x6cebf7e7,"hscript.Interp.resetVariables","hscript/Interp.hx",74,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_87_posInfos,"hscript.Interp","posInfos",0x444859d0,"hscript.Interp.posInfos","hscript/Interp.hx",87,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_97_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",97,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_98_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",98,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_99_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",99,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_100_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",100,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_101_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",101,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_102_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",102,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_103_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",103,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_104_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",104,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_105_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",105,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_106_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",106,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_107_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",107,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_108_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",108,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_109_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",109,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_110_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",110,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_111_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",111,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_112_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",112,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_113_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",113,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_114_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",114,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_115_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",115,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_117_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",117,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_118_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",118,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_119_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",119,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_120_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",120,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_121_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",121,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_122_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",122,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_123_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",123,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_124_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",124,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_125_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",125,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_126_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",126,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_127_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",127,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_128_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",128,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_90_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",90,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_131_assign,"hscript.Interp","assign",0xca66602e,"hscript.Interp.assign","hscript/Interp.hx",131,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_160_assignOp,"hscript.Interp","assignOp",0xf8e18cef,"hscript.Interp.assignOp","hscript/Interp.hx",160,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_158_assignOp,"hscript.Interp","assignOp",0xf8e18cef,"hscript.Interp.assignOp","hscript/Interp.hx",158,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_163_evalAssignOp,"hscript.Interp","evalAssignOp",0xa46efc2b,"hscript.Interp.evalAssignOp","hscript/Interp.hx",163,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_199_increment,"hscript.Interp","increment",0x1e81f590,"hscript.Interp.increment","hscript/Interp.hx",199,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_246_execute,"hscript.Interp","execute",0xe1c3af56,"hscript.Interp.execute","hscript/Interp.hx",246,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_258_exprReturn,"hscript.Interp","exprReturn",0x8cfbf144,"hscript.Interp.exprReturn","hscript/Interp.hx",258,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_273_duplicate,"hscript.Interp","duplicate",0x8d9a10ec,"hscript.Interp.duplicate","hscript/Interp.hx",273,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_285_restore,"hscript.Interp","restore",0x80670c6f,"hscript.Interp.restore","hscript/Interp.hx",285,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_293_error,"hscript.Interp","error",0xe68736a9,"hscript.Interp.error","hscript/Interp.hx",293,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_301_rethrow,"hscript.Interp","rethrow",0x0be155b4,"hscript.Interp.rethrow","hscript/Interp.hx",301,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_305_resolve,"hscript.Interp","resolve",0x7d16b80d,"hscript.Interp.resolve","hscript/Interp.hx",305,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_315_expr,"hscript.Interp","expr",0xec634974,"hscript.Interp.expr","hscript/Interp.hx",315,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_410_expr,"hscript.Interp","expr",0xec634974,"hscript.Interp.expr","hscript/Interp.hx",410,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_583_doWhileLoop,"hscript.Interp","doWhileLoop",0x813d4b4b,"hscript.Interp.doWhileLoop","hscript/Interp.hx",583,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_600_whileLoop,"hscript.Interp","whileLoop",0xce1b3216,"hscript.Interp.whileLoop","hscript/Interp.hx",600,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_616_makeIterator,"hscript.Interp","makeIterator",0x634d013b,"hscript.Interp.makeIterator","hscript/Interp.hx",616,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_626_forLoop,"hscript.Interp","forLoop",0xdf1ff72e,"hscript.Interp.forLoop","hscript/Interp.hx",626,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_646_isMap,"hscript.Interp","isMap",0x34ae9fb3,"hscript.Interp.isMap","hscript/Interp.hx",646,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_650_getMapValue,"hscript.Interp","getMapValue",0x1594fb8c,"hscript.Interp.getMapValue","hscript/Interp.hx",650,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_654_setMapValue,"hscript.Interp","setMapValue",0x20020298,"hscript.Interp.setMapValue","hscript/Interp.hx",654,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_657_get,"hscript.Interp","get",0xf7e1c137,"hscript.Interp.get","hscript/Interp.hx",657,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_673_set,"hscript.Interp","set",0xf7eadc43,"hscript.Interp.set","hscript/Interp.hx",673,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_680_fcall,"hscript.Interp","fcall",0x6ff6aee5,"hscript.Interp.fcall","hscript/Interp.hx",680,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_684_call,"hscript.Interp","call",0xeaff64dd,"hscript.Interp.call","hscript/Interp.hx",684,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_687_cnew,"hscript.Interp","cnew",0xeb093c1c,"hscript.Interp.cnew","hscript/Interp.hx",687,0xf078416e) namespace hscript{ void Interp_obj::__construct(){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_53_new) HXLINE( 55) this->locals = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 59) this->declared = ::Array_obj< ::Dynamic>::__new(); HXLINE( 60) this->resetVariables(); HXLINE( 61) this->initOps(); } Dynamic Interp_obj::__CreateEmpty() { return new Interp_obj; } void *Interp_obj::_hx_vtable = 0; Dynamic Interp_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< Interp_obj > _hx_result = new Interp_obj(); _hx_result->__construct(); return _hx_result; } bool Interp_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2a95eb9f; } void Interp_obj::resetVariables(){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_64_resetVariables) HXDLIN( 64) ::hscript::Interp _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 66) this->variables = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 71) { HXLINE( 71) ::Dynamic value = null(); HXDLIN( 71) this->variables->set(HX_("null",87,9e,0e,49),value); } HXLINE( 72) this->variables->set(HX_("true",4e,a7,03,4d),true); HXLINE( 73) this->variables->set(HX_("false",a3,35,4f,fb),false); HXLINE( 74) { HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::hscript::Interp,_gthis) HXARGC(1) void _hx_run(::cpp::VirtualArray el){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_74_resetVariables) HXLINE( 75) ::Dynamic inf = _gthis->posInfos(); HXLINE( 76) ::Dynamic v = el->shift(); HXLINE( 77) if ((el->get_length() > 0)) { HXLINE( 77) inf->__SetField(HX_("customParams",d7,51,18,ed),el,::hx::paccDynamic); } HXLINE( 78) ::Dynamic value = ::haxe::Log_obj::trace; HXDLIN( 78) value(::Std_obj::string(v),inf); } HX_END_LOCAL_FUNC1((void)) HXLINE( 74) ::Dynamic this1 = this->variables; HXDLIN( 74) ( ( ::haxe::ds::StringMap)(this1) )->set(HX_("trace",85,8e,1f,16),::Reflect_obj::makeVarArgs( ::Dynamic(new _hx_Closure_0(_gthis)))); } } HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,resetVariables,(void)) ::Dynamic Interp_obj::posInfos(){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_87_posInfos) HXDLIN( 87) return ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("fileName",e7,5a,43,62),HX_("hscript",73,8c,18,2c)) ->setFixed(1,HX_("lineNumber",dd,81,22,76),0)); } HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,posInfos,return ) void Interp_obj::initOps(){ HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::hscript::Interp,me) HXARGC(2) ::Dynamic _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_97_initOps) HXLINE( 97) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 97) return (_hx_tmp + me->expr(e2)); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_1, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_98_initOps) HXLINE( 98) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 98) return (( (Float)(_hx_tmp) ) - ( (Float)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_2, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_99_initOps) HXLINE( 99) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 99) return (( (Float)(_hx_tmp) ) * ( (Float)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_3, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_100_initOps) HXLINE( 100) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 100) return (( (Float)(_hx_tmp) ) / ( (Float)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_4, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_101_initOps) HXLINE( 101) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 101) return ::hx::Mod(_hx_tmp,me->expr(e2)); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_5, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_102_initOps) HXLINE( 102) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 102) return (( (int)(_hx_tmp) ) & ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_6, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_103_initOps) HXLINE( 103) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 103) return (( (int)(_hx_tmp) ) | ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_7, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_104_initOps) HXLINE( 104) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 104) return (( (int)(_hx_tmp) ) ^ ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_8, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_105_initOps) HXLINE( 105) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 105) return (( (int)(_hx_tmp) ) << ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_9, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_106_initOps) HXLINE( 106) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 106) return (( (int)(_hx_tmp) ) >> ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_10, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_107_initOps) HXLINE( 107) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 107) return ::hx::UShr(( (int)(_hx_tmp) ),( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_11, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_108_initOps) HXLINE( 108) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 108) return ::hx::IsEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_12, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_109_initOps) HXLINE( 109) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 109) return ::hx::IsNotEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_13, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_110_initOps) HXLINE( 110) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 110) return ::hx::IsGreaterEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_14, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_111_initOps) HXLINE( 111) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 111) return ::hx::IsLessEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_15, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_112_initOps) HXLINE( 112) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 112) return ::hx::IsGreater( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_16, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_113_initOps) HXLINE( 113) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 113) return ::hx::IsLess( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_17, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_114_initOps) HXLINE( 114) if (::hx::IsNotEq( me->expr(e1),true )) { HXLINE( 114) return ::hx::IsEq( me->expr(e2),true ); } else { HXLINE( 114) return true; } HXDLIN( 114) return false; } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_18, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_115_initOps) HXLINE( 115) if (::hx::IsEq( me->expr(e1),true )) { HXLINE( 115) return ::hx::IsEq( me->expr(e2),true ); } else { HXLINE( 115) return false; } HXDLIN( 115) return false; } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_19, ::hscript::Interp,me) HXARGC(2) ::IntIterator _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_117_initOps) HXLINE( 117) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 117) return ::IntIterator_obj::__alloc( HX_CTX ,( (int)(_hx_tmp) ),( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_20) HXARGC(2) ::Dynamic _hx_run( ::Dynamic v1, ::Dynamic v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_118_initOps) HXLINE( 118) return (v1 + v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_21) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_119_initOps) HXLINE( 119) return (v1 - v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_22) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_120_initOps) HXLINE( 120) return (v1 * v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_23) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_121_initOps) HXLINE( 121) return (v1 / v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_24) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_122_initOps) HXLINE( 122) return ::hx::Mod(v1,v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_25) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_123_initOps) HXLINE( 123) return (v1 & v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_26) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_124_initOps) HXLINE( 124) return (v1 | v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_27) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_125_initOps) HXLINE( 125) return (v1 ^ v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_28) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_126_initOps) HXLINE( 126) return (v1 << v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_29) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_127_initOps) HXLINE( 127) return (v1 >> v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_30) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_128_initOps) HXLINE( 128) return ::hx::UShr(v1,v2); } HX_END_LOCAL_FUNC2(return) HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_90_initOps) HXLINE( 91) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 93) this->binops = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 97) this->binops->set(HX_("+",2b,00,00,00), ::Dynamic(new _hx_Closure_0(me))); HXLINE( 98) this->binops->set(HX_("-",2d,00,00,00), ::Dynamic(new _hx_Closure_1(me))); HXLINE( 99) this->binops->set(HX_("*",2a,00,00,00), ::Dynamic(new _hx_Closure_2(me))); HXLINE( 100) this->binops->set(HX_("/",2f,00,00,00), ::Dynamic(new _hx_Closure_3(me))); HXLINE( 101) this->binops->set(HX_("%",25,00,00,00), ::Dynamic(new _hx_Closure_4(me))); HXLINE( 102) this->binops->set(HX_("&",26,00,00,00), ::Dynamic(new _hx_Closure_5(me))); HXLINE( 103) this->binops->set(HX_("|",7c,00,00,00), ::Dynamic(new _hx_Closure_6(me))); HXLINE( 104) this->binops->set(HX_("^",5e,00,00,00), ::Dynamic(new _hx_Closure_7(me))); HXLINE( 105) this->binops->set(HX_("<<",80,34,00,00), ::Dynamic(new _hx_Closure_8(me))); HXLINE( 106) this->binops->set(HX_(">>",40,36,00,00), ::Dynamic(new _hx_Closure_9(me))); HXLINE( 107) this->binops->set(HX_(">>>",fe,41,2f,00), ::Dynamic(new _hx_Closure_10(me))); HXLINE( 108) this->binops->set(HX_("==",60,35,00,00), ::Dynamic(new _hx_Closure_11(me))); HXLINE( 109) this->binops->set(HX_("!=",fc,1c,00,00), ::Dynamic(new _hx_Closure_12(me))); HXLINE( 110) this->binops->set(HX_(">=",3f,36,00,00), ::Dynamic(new _hx_Closure_13(me))); HXLINE( 111) this->binops->set(HX_("<=",81,34,00,00), ::Dynamic(new _hx_Closure_14(me))); HXLINE( 112) this->binops->set(HX_(">",3e,00,00,00), ::Dynamic(new _hx_Closure_15(me))); HXLINE( 113) this->binops->set(HX_("<",3c,00,00,00), ::Dynamic(new _hx_Closure_16(me))); HXLINE( 114) this->binops->set(HX_("||",80,6c,00,00), ::Dynamic(new _hx_Closure_17(me))); HXLINE( 115) this->binops->set(HX_("&&",40,21,00,00), ::Dynamic(new _hx_Closure_18(me))); HXLINE( 116) this->binops->set(HX_("=",3d,00,00,00),this->assign_dyn()); HXLINE( 117) this->binops->set(HX_("...",ee,0f,23,00), ::Dynamic(new _hx_Closure_19(me))); HXLINE( 118) this->assignOp(HX_("+=",b2,25,00,00), ::Dynamic(new _hx_Closure_20())); HXLINE( 119) this->assignOp(HX_("-=",70,27,00,00), ::Dynamic(new _hx_Closure_21())); HXLINE( 120) this->assignOp(HX_("*=",d3,24,00,00), ::Dynamic(new _hx_Closure_22())); HXLINE( 121) this->assignOp(HX_("/=",2e,29,00,00), ::Dynamic(new _hx_Closure_23())); HXLINE( 122) this->assignOp(HX_("%=",78,20,00,00), ::Dynamic(new _hx_Closure_24())); HXLINE( 123) this->assignOp(HX_("&=",57,21,00,00), ::Dynamic(new _hx_Closure_25())); HXLINE( 124) this->assignOp(HX_("|=",41,6c,00,00), ::Dynamic(new _hx_Closure_26())); HXLINE( 125) this->assignOp(HX_("^=",1f,52,00,00), ::Dynamic(new _hx_Closure_27())); HXLINE( 126) this->assignOp(HX_("<<=",bd,bb,2d,00), ::Dynamic(new _hx_Closure_28())); HXLINE( 127) this->assignOp(HX_(">>=",fd,41,2f,00), ::Dynamic(new _hx_Closure_29())); HXLINE( 128) this->assignOp(HX_(">>>=",7f,7c,2a,29), ::Dynamic(new _hx_Closure_30())); } HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,initOps,(void)) ::Dynamic Interp_obj::assign( ::hscript::Expr e1, ::hscript::Expr e2){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_131_assign) HXLINE( 132) ::Dynamic v = this->expr(e2); HXLINE( 133) switch((int)(e1->_hx_getIndex())){ case (int)1: { HXLINE( 134) ::String id = e1->_hx_getString(0); HXDLIN( 134) { HXLINE( 135) ::Dynamic l = this->locals->get(id); HXLINE( 136) if (::hx::IsNull( l )) { HXLINE( 137) this->variables->set(id,v); } else { HXLINE( 139) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic); } } } break; case (int)5: { HXLINE( 140) ::String f = e1->_hx_getString(1); HXDLIN( 140) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 141) v = this->set(this->expr(e),f,v); } break; case (int)16: { HXLINE( 142) ::hscript::Expr index = e1->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 142) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXDLIN( 142) { HXLINE( 143) ::Dynamic arr = this->expr(e); HXLINE( 144) ::Dynamic index1 = this->expr(index); HXLINE( 145) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 146) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v); } else { HXLINE( 149) arr->__SetItem(( (int)(index1) ),v); } } } break; default:{ HXLINE( 153) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(HX_("=",3d,00,00,00)); HXDLIN( 153) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } } HXLINE( 155) return v; } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,assign,return ) void Interp_obj::assignOp(::String op, ::Dynamic fop){ HX_BEGIN_LOCAL_FUNC_S3(::hx::LocalFunc,_hx_Closure_0,::String,op, ::hscript::Interp,me, ::Dynamic,fop) HXARGC(2) ::Dynamic _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_160_assignOp) HXLINE( 160) return me->evalAssignOp(op,fop,e1,e2); } HX_END_LOCAL_FUNC2(return) HX_STACKFRAME(&_hx_pos_f37559d470356c9e_158_assignOp) HXLINE( 159) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 160) this->binops->set(op, ::Dynamic(new _hx_Closure_0(op,me,fop))); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,assignOp,(void)) ::Dynamic Interp_obj::evalAssignOp(::String op, ::Dynamic fop, ::hscript::Expr e1, ::hscript::Expr e2){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_163_evalAssignOp) HXLINE( 164) ::Dynamic v; HXLINE( 165) switch((int)(e1->_hx_getIndex())){ case (int)1: { HXLINE( 166) ::String id = e1->_hx_getString(0); HXDLIN( 166) { HXLINE( 167) ::Dynamic l = this->locals->get(id); HXLINE( 168) ::Dynamic v1 = this->expr(e1); HXDLIN( 168) v = fop(v1,this->expr(e2)); HXLINE( 169) if (::hx::IsNull( l )) { HXLINE( 170) this->variables->set(id,v); } else { HXLINE( 172) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic); } } } break; case (int)5: { HXLINE( 173) ::String f = e1->_hx_getString(1); HXDLIN( 173) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXDLIN( 173) { HXLINE( 174) ::Dynamic obj = this->expr(e); HXLINE( 175) ::Dynamic v1 = this->get(obj,f); HXDLIN( 175) v = fop(v1,this->expr(e2)); HXLINE( 176) v = this->set(obj,f,v); } } break; case (int)16: { HXLINE( 177) ::hscript::Expr index = e1->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 177) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXDLIN( 177) { HXLINE( 178) ::Dynamic arr = this->expr(e); HXLINE( 179) ::Dynamic index1 = this->expr(index); HXLINE( 180) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 181) ::Dynamic v1 = ::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1); HXDLIN( 181) v = fop(v1,this->expr(e2)); HXLINE( 182) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v); } else { HXLINE( 185) ::Dynamic arr1 = arr->__GetItem(( (int)(index1) )); HXDLIN( 185) v = fop(arr1,this->expr(e2)); HXLINE( 186) arr->__SetItem(( (int)(index1) ),v); } } } break; default:{ HXLINE( 189) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op); HXDLIN( 189) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } } HXLINE( 191) return v; } HX_DEFINE_DYNAMIC_FUNC4(Interp_obj,evalAssignOp,return ) ::Dynamic Interp_obj::increment( ::hscript::Expr e,bool prefix,int delta){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_199_increment) HXDLIN( 199) switch((int)(e->_hx_getIndex())){ case (int)1: { HXLINE( 200) ::String id = e->_hx_getString(0); HXLINE( 201) ::Dynamic l = this->locals->get(id); HXLINE( 202) ::Dynamic v; HXDLIN( 202) if (::hx::IsNull( l )) { HXLINE( 202) v = this->variables->get(id); } else { HXLINE( 202) v = ::Dynamic(l->__Field(HX_("r",72,00,00,00),::hx::paccDynamic)); } HXLINE( 203) if (prefix) { HXLINE( 204) v = (v + delta); HXLINE( 205) if (::hx::IsNull( l )) { HXLINE( 205) this->variables->set(id,v); } else { HXLINE( 205) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic); } } else { HXLINE( 207) if (::hx::IsNull( l )) { HXLINE( 207) this->variables->set(id,(v + delta)); } else { HXLINE( 207) l->__SetField(HX_("r",72,00,00,00),(v + delta),::hx::paccDynamic); } } HXLINE( 208) return v; } break; case (int)5: { HXLINE( 209) ::String f = e->_hx_getString(1); HXDLIN( 209) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 210) ::Dynamic obj = this->expr(e1); HXLINE( 211) ::Dynamic v = this->get(obj,f); HXLINE( 212) if (prefix) { HXLINE( 213) v = (v + delta); HXLINE( 214) this->set(obj,f,v); } else { HXLINE( 216) this->set(obj,f,(v + delta)); } HXLINE( 217) return v; } break; case (int)16: { HXLINE( 218) ::hscript::Expr index = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 218) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 219) ::Dynamic arr = this->expr(e1); HXLINE( 220) ::Dynamic index1 = this->expr(index); HXLINE( 221) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 222) int v = ( (int)(::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1)) ); HXLINE( 223) if (prefix) { HXLINE( 224) v = (v + delta); HXLINE( 225) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v); } else { HXLINE( 228) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,(v + delta)); } HXLINE( 230) return v; } else { HXLINE( 233) int v = ( (int)(arr->__GetItem(( (int)(index1) ))) ); HXLINE( 234) if (prefix) { HXLINE( 235) v = (v + delta); HXLINE( 236) arr->__SetItem(( (int)(index1) ),v); } else { HXLINE( 238) arr->__SetItem(( (int)(index1) ),(v + delta)); } HXLINE( 239) return v; } } break; default:{ HXLINE( 242) ::String e; HXDLIN( 242) if ((delta > 0)) { HXLINE( 242) e = HX_("++",a0,25,00,00); } else { HXLINE( 242) e = HX_("--",60,27,00,00); } HXDLIN( 242) ::hscript::Error e1 = ::hscript::Error_obj::EInvalidOp(e); HXDLIN( 242) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e1)); } } HXLINE( 199) return null(); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,increment,return ) ::Dynamic Interp_obj::execute( ::hscript::Expr expr){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_246_execute) HXLINE( 247) this->depth = 0; HXLINE( 249) this->locals = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 253) this->declared = ::Array_obj< ::Dynamic>::__new(); HXLINE( 254) return this->exprReturn(expr); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,execute,return ) ::Dynamic Interp_obj::exprReturn( ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_258_exprReturn) HXDLIN( 258) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 259) return this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 258) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop e = _g1; HXLINE( 261) switch((int)(e->_hx_getIndex())){ case (int)0: { HXLINE( 262) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid break",b6,ee,24,9d))); } break; case (int)1: { HXLINE( 263) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid continue",d0,6a,b7,3f))); } break; case (int)2: { HXLINE( 265) ::Dynamic v = this->returnValue; HXLINE( 266) this->returnValue = null(); HXLINE( 267) return v; } break; } } else { HXDLIN( 258) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } HXDLIN( 258) return null(); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,exprReturn,return ) ::haxe::ds::StringMap Interp_obj::duplicate( ::haxe::ds::StringMap h){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_273_duplicate) HXLINE( 275) ::haxe::ds::StringMap h2 = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 279) { HXLINE( 279) ::Dynamic k = h->keys(); HXDLIN( 279) while(( (bool)(k->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){ HXLINE( 279) ::String k1 = ( (::String)(k->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) ); HXLINE( 280) h2->set(k1,h->get(k1)); } } HXLINE( 281) return h2; } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,duplicate,return ) void Interp_obj::restore(int old){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_285_restore) HXDLIN( 285) while((this->declared->length > old)){ HXLINE( 286) ::Dynamic d = this->declared->pop(); HXLINE( 287) this->locals->set(( (::String)(d->__Field(HX_("n",6e,00,00,00),::hx::paccDynamic)) ), ::Dynamic(d->__Field(HX_("old",a7,98,54,00),::hx::paccDynamic))); } } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,restore,(void)) ::Dynamic Interp_obj::error( ::hscript::Error e,::hx::Null< bool > __o_rethrow){ bool rethrow = __o_rethrow.Default(false); HX_STACKFRAME(&_hx_pos_f37559d470356c9e_293_error) HXDLIN( 293) if (rethrow) { HXDLIN( 293) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } else { HXDLIN( 293) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXDLIN( 293) return null(); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,error,return ) void Interp_obj::rethrow( ::Dynamic e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_301_rethrow) HXDLIN( 301) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,rethrow,(void)) ::Dynamic Interp_obj::resolve(::String id){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_305_resolve) HXLINE( 306) ::Dynamic l = this->locals->get(id); HXLINE( 307) if (::hx::IsNotNull( l )) { HXLINE( 308) return ::Dynamic(l->__Field(HX_("r",72,00,00,00),::hx::paccDynamic)); } HXLINE( 309) ::Dynamic v = this->variables->get(id); HXLINE( 310) bool _hx_tmp; HXDLIN( 310) if (::hx::IsNull( v )) { HXLINE( 310) _hx_tmp = !(this->variables->exists(id)); } else { HXLINE( 310) _hx_tmp = false; } HXDLIN( 310) if (_hx_tmp) { HXLINE( 311) ::hscript::Error e = ::hscript::Error_obj::EUnknownVariable(id); HXDLIN( 311) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 312) return v; } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,resolve,return ) ::Dynamic Interp_obj::expr( ::hscript::Expr e){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_315_expr) HXDLIN( 315) ::hscript::Interp _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 320) switch((int)(e->_hx_getIndex())){ case (int)0: { HXLINE( 321) ::hscript::Const c = e->_hx_getObject(0).StaticCast< ::hscript::Const >(); HXLINE( 322) switch((int)(c->_hx_getIndex())){ case (int)0: { HXLINE( 323) int v = c->_hx_getInt(0); HXDLIN( 323) return v; } break; case (int)1: { HXLINE( 324) Float f = c->_hx_getFloat(0); HXDLIN( 324) return f; } break; case (int)2: { HXLINE( 325) ::String s = c->_hx_getString(0); HXDLIN( 325) return s; } break; } } break; case (int)1: { HXLINE( 330) ::String id = e->_hx_getString(0); HXLINE( 331) return this->resolve(id); } break; case (int)2: { HXLINE( 332) ::hscript::CType _g = e->_hx_getObject(1).StaticCast< ::hscript::CType >(); HXDLIN( 332) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 332) ::String n = e->_hx_getString(0); HXLINE( 333) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 333) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),n) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n)))); HXLINE( 334) { HXLINE( 334) ::Dynamic this1 = this->locals; HXDLIN( 334) ::Dynamic value; HXDLIN( 334) if (::hx::IsNull( e1 )) { HXLINE( 334) value = null(); } else { HXLINE( 334) value = this->expr(e1); } HXDLIN( 334) ( ( ::haxe::ds::StringMap)(this1) )->set(n, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),value))); } HXLINE( 335) return null(); } break; case (int)3: { HXLINE( 336) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 337) return this->expr(e1); } break; case (int)4: { HXLINE( 338) ::Array< ::Dynamic> exprs = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 339) int old = this->declared->length; HXLINE( 340) ::Dynamic v = null(); HXLINE( 341) { HXLINE( 341) int _g = 0; HXDLIN( 341) while((_g < exprs->length)){ HXLINE( 341) ::hscript::Expr e = exprs->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 341) _g = (_g + 1); HXLINE( 342) v = this->expr(e); } } HXLINE( 343) this->restore(old); HXLINE( 344) return v; } break; case (int)5: { HXLINE( 345) ::String f = e->_hx_getString(1); HXDLIN( 345) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 346) return this->get(this->expr(e1),f); } break; case (int)6: { HXLINE( 347) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 347) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 347) ::String op = e->_hx_getString(0); HXLINE( 348) ::Dynamic fop = this->binops->get(op); HXLINE( 349) if (::hx::IsNull( fop )) { HXLINE( 349) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op); HXDLIN( 349) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 350) return fop(e1,e2); } break; case (int)7: { HXLINE( 351) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 351) bool prefix = e->_hx_getBool(1); HXDLIN( 351) ::String op = e->_hx_getString(0); HXLINE( 352) ::String _hx_switch_0 = op; if ( (_hx_switch_0==HX_("!",21,00,00,00)) ){ HXLINE( 354) return ::hx::IsNotEq( this->expr(e1),true ); HXDLIN( 354) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("++",a0,25,00,00)) ){ HXLINE( 358) return this->increment(e1,prefix,1); HXDLIN( 358) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("-",2d,00,00,00)) ){ HXLINE( 356) return -(this->expr(e1)); HXDLIN( 356) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("--",60,27,00,00)) ){ HXLINE( 360) return this->increment(e1,prefix,-1); HXDLIN( 360) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("~",7e,00,00,00)) ){ HXLINE( 365) return ~(( (int)(this->expr(e1)) )); HXDLIN( 365) goto _hx_goto_51; } /* default */{ HXLINE( 368) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op); HXDLIN( 368) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } _hx_goto_51:; } break; case (int)8: { HXLINE( 370) ::Array< ::Dynamic> params = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 370) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 371) ::cpp::VirtualArray args = ::cpp::VirtualArray_obj::__new(); HXLINE( 372) { HXLINE( 372) int _g = 0; HXDLIN( 372) while((_g < params->length)){ HXLINE( 372) ::hscript::Expr p = params->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 372) _g = (_g + 1); HXLINE( 373) args->push(this->expr(p)); } } HXLINE( 375) if ((e1->_hx_getIndex() == 5)) { HXLINE( 376) ::String f = e1->_hx_getString(1); HXDLIN( 376) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 377) ::Dynamic obj = this->expr(e); HXLINE( 378) if (::hx::IsNull( obj )) { HXLINE( 378) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f); HXDLIN( 378) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 379) return this->fcall(obj,f,args); } else { HXLINE( 381) return this->call(null(),this->expr(e1),args); } } break; case (int)9: { HXLINE( 383) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 383) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 383) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 384) if (::hx::IsEq( this->expr(econd),true )) { HXLINE( 384) return this->expr(e1); } else { HXLINE( 384) if (::hx::IsNull( e2 )) { HXLINE( 384) return null(); } else { HXLINE( 384) return this->expr(e2); } } } break; case (int)10: { HXLINE( 385) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 385) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 386) this->whileLoop(econd,e1); HXLINE( 387) return null(); } break; case (int)11: { HXLINE( 391) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 391) ::hscript::Expr it = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 391) ::String v = e->_hx_getString(0); HXLINE( 392) this->forLoop(v,it,e1); HXLINE( 393) return null(); } break; case (int)12: { HXLINE( 395) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SBreak_dyn())); } break; case (int)13: { HXLINE( 397) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SContinue_dyn())); } break; case (int)14: { HX_BEGIN_LOCAL_FUNC_S7(::hx::LocalFunc,_hx_Closure_0,::String,name, ::hscript::Expr,fexpr, ::hscript::Interp,_gthis,int,minParams, ::hscript::Interp,me,::Array< ::Dynamic>,params, ::haxe::ds::StringMap,capturedLocals) HXARGC(1) ::Dynamic _hx_run(::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_410_expr) HXLINE( 411) int f; HXDLIN( 411) if (::hx::IsNull( args )) { HXLINE( 411) f = 0; } else { HXLINE( 411) f = args->get_length(); } HXDLIN( 411) if ((f != params->length)) { HXLINE( 412) if ((args->get_length() < minParams)) { HXLINE( 413) ::String str = (((HX_("Invalid number of parameters. Got ",cb,2b,d9,b1) + args->get_length()) + HX_(", required ",ed,0c,66,93)) + minParams); HXLINE( 414) if (::hx::IsNotNull( name )) { HXLINE( 414) str = (str + ((HX_(" for function '",f6,90,ab,a0) + name) + HX_("'",27,00,00,00))); } HXLINE( 415) ::hscript::Error e = ::hscript::Error_obj::ECustom(str); HXDLIN( 415) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 418) ::cpp::VirtualArray args2 = ::cpp::VirtualArray_obj::__new(0); HXLINE( 419) int extraParams = (args->get_length() - minParams); HXLINE( 420) int pos = 0; HXLINE( 421) { HXLINE( 421) int _g = 0; HXDLIN( 421) while((_g < params->length)){ HXLINE( 421) ::Dynamic p = params->__get(_g); HXDLIN( 421) _g = (_g + 1); HXLINE( 422) if (( (bool)(p->__Field(HX_("opt",33,9c,54,00),::hx::paccDynamic)) )) { HXLINE( 423) if ((extraParams > 0)) { HXLINE( 424) pos = (pos + 1); HXDLIN( 424) args2->push(args->__get((pos - 1))); HXLINE( 425) extraParams = (extraParams - 1); } else { HXLINE( 427) args2->push(null()); } } else { HXLINE( 429) pos = (pos + 1); HXDLIN( 429) args2->push(args->__get((pos - 1))); } } } HXLINE( 430) args = args2; } HXLINE( 432) ::haxe::ds::StringMap old = me->locals; HXDLIN( 432) int depth = me->depth; HXLINE( 433) me->depth++; HXLINE( 434) me->locals = me->duplicate(capturedLocals); HXLINE( 435) { HXLINE( 435) int _g = 0; HXDLIN( 435) int _g1 = params->length; HXDLIN( 435) while((_g < _g1)){ HXLINE( 435) _g = (_g + 1); HXDLIN( 435) int i = (_g - 1); HXLINE( 436) me->locals->set(( (::String)(params->__get(i)->__Field(HX_("name",4b,72,ff,48),::hx::paccDynamic)) ), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),args->__get(i)))); } } HXLINE( 437) ::Dynamic r = null(); HXLINE( 438) if (_gthis->inTry) { HXLINE( 439) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 440) r = me->exprReturn(fexpr); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic e = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 442) me->locals = old; HXLINE( 443) me->depth = depth; HXLINE( 447) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } else { HX_STACK_DO_THROW(_hx_e); } } } else { HXLINE( 451) r = me->exprReturn(fexpr); } HXLINE( 452) me->locals = old; HXLINE( 453) me->depth = depth; HXLINE( 454) return r; } HX_END_LOCAL_FUNC1(return) HXLINE( 401) ::hscript::CType _g = e->_hx_getObject(3).StaticCast< ::hscript::CType >(); HXDLIN( 401) ::String name = e->_hx_getString(2); HXDLIN( 401) ::hscript::Expr fexpr = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 401) ::Array< ::Dynamic> params = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 402) ::haxe::ds::StringMap capturedLocals = this->duplicate(this->locals); HXLINE( 403) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 404) bool hasOpt = false; HXDLIN( 404) int minParams = 0; HXLINE( 405) { HXLINE( 405) int _g1 = 0; HXDLIN( 405) while((_g1 < params->length)){ HXLINE( 405) ::Dynamic p = params->__get(_g1); HXDLIN( 405) _g1 = (_g1 + 1); HXLINE( 406) if (( (bool)(p->__Field(HX_("opt",33,9c,54,00),::hx::paccDynamic)) )) { HXLINE( 407) hasOpt = true; } else { HXLINE( 409) minParams = (minParams + 1); } } } HXLINE( 410) ::Dynamic f = ::Dynamic(new _hx_Closure_0(name,fexpr,_gthis,minParams,me,params,capturedLocals)); HXLINE( 456) ::Dynamic f1 = ::Reflect_obj::makeVarArgs(f); HXLINE( 457) if (::hx::IsNotNull( name )) { HXLINE( 458) if ((this->depth == 0)) { HXLINE( 460) this->variables->set(name,f1); } else { HXLINE( 463) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 463) ::String name1 = name; HXDLIN( 463) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),name1) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(name)))); HXLINE( 464) ::Dynamic ref = ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),f1)); HXLINE( 465) this->locals->set(name,ref); HXLINE( 466) capturedLocals->set(name,ref); } } HXLINE( 469) return f1; } break; case (int)15: { HXLINE( 398) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 399) ::Dynamic _hx_tmp; HXDLIN( 399) if (::hx::IsNull( e1 )) { HXLINE( 399) _hx_tmp = null(); } else { HXLINE( 399) _hx_tmp = this->expr(e1); } HXDLIN( 399) this->returnValue = _hx_tmp; HXLINE( 400) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SReturn_dyn())); } break; case (int)16: { HXLINE( 512) ::hscript::Expr index = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 512) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 513) ::Dynamic arr = this->expr(e1); HXLINE( 514) ::Dynamic index1 = this->expr(index); HXLINE( 515) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 516) return ::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1); } else { HXLINE( 519) return arr->__GetItem(( (int)(index1) )); } } break; case (int)17: { HXLINE( 470) ::Array< ::Dynamic> arr = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 471) bool _hx_tmp; HXDLIN( 471) if ((arr->length > 0)) { HXLINE( 471) ::hscript::Expr _g = arr->__get(0).StaticCast< ::hscript::Expr >(); HXDLIN( 471) if ((_g->_hx_getIndex() == 6)) { HXLINE( 471) ::hscript::Expr _g1 = _g->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 471) ::hscript::Expr _g2 = _g->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 471) if ((_g->_hx_getString(0) == HX_("=>",61,35,00,00))) { HXLINE( 471) _hx_tmp = true; } else { HXLINE( 471) _hx_tmp = false; } } else { HXLINE( 471) _hx_tmp = false; } } else { HXLINE( 471) _hx_tmp = false; } HXDLIN( 471) if (_hx_tmp) { HXLINE( 472) bool isAllString = true; HXLINE( 473) bool isAllInt = true; HXLINE( 474) bool isAllObject = true; HXLINE( 475) bool isAllEnum = true; HXLINE( 476) ::cpp::VirtualArray keys = ::cpp::VirtualArray_obj::__new(0); HXLINE( 477) ::cpp::VirtualArray values = ::cpp::VirtualArray_obj::__new(0); HXLINE( 478) { HXLINE( 478) int _g = 0; HXDLIN( 478) while((_g < arr->length)){ HXLINE( 478) ::hscript::Expr e = arr->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 478) _g = (_g + 1); HXLINE( 479) if ((e->_hx_getIndex() == 6)) { HXLINE( 480) if ((e->_hx_getString(0) == HX_("=>",61,35,00,00))) { HXLINE( 480) ::hscript::Expr eValue = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 480) ::hscript::Expr eKey = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 480) { HXLINE( 481) ::Dynamic key = this->expr(eKey); HXLINE( 482) ::Dynamic value = this->expr(eValue); HXLINE( 483) if (isAllString) { HXLINE( 483) isAllString = ::Std_obj::isOfType(key,( ( ::Dynamic)(::hx::ClassOf< ::String >()) )); } else { HXLINE( 483) isAllString = false; } HXLINE( 484) if (isAllInt) { HXLINE( 484) isAllInt = ::Std_obj::isOfType(key,( ( ::Dynamic)(::hx::ClassOf< int >()) )); } else { HXLINE( 484) isAllInt = false; } HXLINE( 485) if (isAllObject) { HXLINE( 485) isAllObject = ::Reflect_obj::isObject(key); } else { HXLINE( 485) isAllObject = false; } HXLINE( 486) if (isAllEnum) { HXLINE( 486) isAllEnum = ::Reflect_obj::isEnumValue(key); } else { HXLINE( 486) isAllEnum = false; } HXLINE( 487) keys->push(key); HXLINE( 488) values->push(value); } } else { HXLINE( 490) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("=> expected",17,e5,65,e5))); } } else { HXLINE( 490) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("=> expected",17,e5,65,e5))); } } } HXLINE( 493) ::Dynamic map; HXLINE( 494) if (isAllInt) { HXLINE( 493) map = ::haxe::ds::IntMap_obj::__alloc( HX_CTX ); } else { HXLINE( 495) if (isAllString) { HXLINE( 493) map = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } else { HXLINE( 496) if (isAllEnum) { HXLINE( 493) map = ::haxe::ds::EnumValueMap_obj::__alloc( HX_CTX ); } else { HXLINE( 497) if (isAllObject) { HXLINE( 493) map = ::haxe::ds::ObjectMap_obj::__alloc( HX_CTX ); } else { HXLINE( 498) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Inconsistent key types",af,4f,50,a9))); } } } } HXLINE( 500) { HXLINE( 500) int _g1 = 0; HXDLIN( 500) int _g2 = keys->get_length(); HXDLIN( 500) while((_g1 < _g2)){ HXLINE( 500) _g1 = (_g1 + 1); HXDLIN( 500) int n = (_g1 - 1); HXLINE( 501) ::haxe::IMap_obj::set( ::hx::interface_check(map,0x09c2bd39),keys->__get(n),values->__get(n)); } } HXLINE( 503) return map; } else { HXLINE( 506) ::cpp::VirtualArray a = ::cpp::VirtualArray_obj::__new(); HXLINE( 507) { HXLINE( 507) int _g = 0; HXDLIN( 507) while((_g < arr->length)){ HXLINE( 507) ::hscript::Expr e = arr->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 507) _g = (_g + 1); HXLINE( 508) a->push(this->expr(e)); } } HXLINE( 510) return a; } } break; case (int)18: { HXLINE( 521) ::Array< ::Dynamic> params = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 521) ::String cl = e->_hx_getString(0); HXLINE( 522) ::cpp::VirtualArray a = ::cpp::VirtualArray_obj::__new(); HXLINE( 523) { HXLINE( 523) int _g = 0; HXDLIN( 523) while((_g < params->length)){ HXLINE( 523) ::hscript::Expr e = params->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 523) _g = (_g + 1); HXLINE( 524) a->push(this->expr(e)); } } HXLINE( 525) return this->cnew(cl,a); } break; case (int)19: { HXLINE( 526) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 527) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(this->expr(e1))); } break; case (int)20: { HXLINE( 528) ::hscript::CType _g = e->_hx_getObject(2).StaticCast< ::hscript::CType >(); HXDLIN( 528) ::hscript::Expr ecatch = e->_hx_getObject(3).StaticCast< ::hscript::Expr >(); HXDLIN( 528) ::String n = e->_hx_getString(1); HXDLIN( 528) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 529) int old = this->declared->length; HXLINE( 530) bool oldTry = this->inTry; HXLINE( 531) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 532) this->inTry = true; HXLINE( 533) ::Dynamic v = this->expr(e1); HXLINE( 534) this->restore(old); HXLINE( 535) this->inTry = oldTry; HXLINE( 536) return v; } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 531) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 538) this->inTry = oldTry; HXLINE( 539) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } else { HXLINE( 1) ::Dynamic err = _g1; HXLINE( 542) this->restore(old); HXLINE( 543) this->inTry = oldTry; HXLINE( 545) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 545) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),n) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n)))); HXLINE( 546) this->locals->set(n, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),err))); HXLINE( 547) ::Dynamic v = this->expr(ecatch); HXLINE( 548) this->restore(old); HXLINE( 549) return v; } } else { HX_STACK_DO_THROW(_hx_e); } } } break; case (int)21: { HXLINE( 551) ::Array< ::Dynamic> fl = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 552) ::Dynamic o = ::Dynamic(::hx::Anon_obj::Create(0)); HXLINE( 553) { HXLINE( 553) int _g = 0; HXDLIN( 553) while((_g < fl->length)){ HXLINE( 553) ::Dynamic f = fl->__get(_g); HXDLIN( 553) _g = (_g + 1); HXLINE( 554) ::String f1 = ( (::String)(f->__Field(HX_("name",4b,72,ff,48),::hx::paccDynamic)) ); HXDLIN( 554) this->set(o,f1,this->expr(f->__Field(HX_("e",65,00,00,00),::hx::paccDynamic))); } } HXLINE( 555) return o; } break; case (int)22: { HXLINE( 556) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 556) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 556) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 557) if (::hx::IsEq( this->expr(econd),true )) { HXLINE( 557) return this->expr(e1); } else { HXLINE( 557) return this->expr(e2); } } break; case (int)23: { HXLINE( 558) ::hscript::Expr def = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 558) ::Array< ::Dynamic> cases = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 558) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 559) ::Dynamic val = this->expr(e1); HXLINE( 560) bool match = false; HXLINE( 561) { HXLINE( 561) int _g = 0; HXDLIN( 561) while((_g < cases->length)){ HXLINE( 561) ::Dynamic c = cases->__get(_g); HXDLIN( 561) _g = (_g + 1); HXLINE( 562) { HXLINE( 562) int _g1 = 0; HXDLIN( 562) ::Array< ::Dynamic> _g2 = ( (::Array< ::Dynamic>)(c->__Field(HX_("values",e2,03,b7,4f),::hx::paccDynamic)) ); HXDLIN( 562) while((_g1 < _g2->length)){ HXLINE( 562) ::hscript::Expr v = _g2->__get(_g1).StaticCast< ::hscript::Expr >(); HXDLIN( 562) _g1 = (_g1 + 1); HXLINE( 563) if (::hx::IsEq( this->expr(v),val )) { HXLINE( 564) match = true; HXLINE( 565) goto _hx_goto_62; } } _hx_goto_62:; } HXLINE( 567) if (match) { HXLINE( 568) val = this->expr(c->__Field(HX_("expr",35,fd,1d,43),::hx::paccDynamic)); HXLINE( 569) goto _hx_goto_61; } } _hx_goto_61:; } HXLINE( 572) if (!(match)) { HXLINE( 573) if (::hx::IsNull( def )) { HXLINE( 573) val = null(); } else { HXLINE( 573) val = this->expr(def); } } HXLINE( 574) return val; } break; case (int)24: { HXLINE( 388) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 388) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 389) this->doWhileLoop(econd,e1); HXLINE( 390) return null(); } break; case (int)25: { HXLINE( 575) ::Array< ::Dynamic> _g = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 575) ::String _g1 = e->_hx_getString(0); HXDLIN( 575) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXLINE( 576) return this->expr(e1); } break; case (int)26: { HXLINE( 577) ::hscript::CType _g = e->_hx_getObject(1).StaticCast< ::hscript::CType >(); HXDLIN( 577) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 578) return this->expr(e1); } break; } HXLINE( 320) return null(); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,expr,return ) void Interp_obj::doWhileLoop( ::hscript::Expr econd, ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_583_doWhileLoop) HXLINE( 584) int old = this->declared->length; HXLINE( 585) while(true){ HXLINE( 586) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 587) this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 586) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 589) switch((int)(err->_hx_getIndex())){ case (int)0: { HXLINE( 591) goto _hx_goto_65; } break; case (int)1: { } break; case (int)2: { HXLINE( 592) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } break; } } else { HXLINE( 586) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } HXLINE( 585) if (!(::hx::IsEq( this->expr(econd),true ))) { HXLINE( 585) goto _hx_goto_65; } } _hx_goto_65:; HXLINE( 597) this->restore(old); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,doWhileLoop,(void)) void Interp_obj::whileLoop( ::hscript::Expr econd, ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_600_whileLoop) HXLINE( 601) int old = this->declared->length; HXLINE( 602) while(::hx::IsEq( this->expr(econd),true )){ HXLINE( 603) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 604) this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 603) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 606) switch((int)(err->_hx_getIndex())){ case (int)0: { HXLINE( 608) goto _hx_goto_67; } break; case (int)1: { } break; case (int)2: { HXLINE( 609) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } break; } } else { HXLINE( 603) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } } _hx_goto_67:; HXLINE( 613) this->restore(old); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,whileLoop,(void)) ::Dynamic Interp_obj::makeIterator( ::Dynamic v){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_616_makeIterator) HXLINE( 620) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 620) v = v->__Field(HX_("iterator",ee,49,9a,93),::hx::paccDynamic)(); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } } else { HX_STACK_DO_THROW(_hx_e); } } HXLINE( 622) bool _hx_tmp; HXDLIN( 622) if (::hx::IsNotNull( v->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic) )) { HXLINE( 622) _hx_tmp = ::hx::IsNull( v->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic) ); } else { HXLINE( 622) _hx_tmp = true; } HXDLIN( 622) if (_hx_tmp) { HXLINE( 622) ::hscript::Error e = ::hscript::Error_obj::EInvalidIterator(v); HXDLIN( 622) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 623) return v; } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,makeIterator,return ) void Interp_obj::forLoop(::String n, ::hscript::Expr it, ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_626_forLoop) HXLINE( 627) int old = this->declared->length; HXLINE( 628) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 628) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),n) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n)))); HXLINE( 629) ::Dynamic it1 = this->makeIterator(this->expr(it)); HXLINE( 630) while(( (bool)(it1->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){ HXLINE( 631) { HXLINE( 631) ::Dynamic this1 = this->locals; HXDLIN( 631) ( ( ::haxe::ds::StringMap)(this1) )->set(n, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),it1->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()))); } HXLINE( 632) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 633) this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 632) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 635) switch((int)(err->_hx_getIndex())){ case (int)0: { HXLINE( 637) goto _hx_goto_70; } break; case (int)1: { } break; case (int)2: { HXLINE( 638) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } break; } } else { HXLINE( 632) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } } _hx_goto_70:; HXLINE( 642) this->restore(old); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,forLoop,(void)) bool Interp_obj::isMap( ::Dynamic o){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_646_isMap) HXDLIN( 646) return ::Std_obj::isOfType(o,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) )); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,isMap,return ) ::Dynamic Interp_obj::getMapValue( ::Dynamic map, ::Dynamic key){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_650_getMapValue) HXDLIN( 650) return ::haxe::IMap_obj::get( ::hx::interface_check(map,0x09c2bd39),key); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,getMapValue,return ) void Interp_obj::setMapValue( ::Dynamic map, ::Dynamic key, ::Dynamic value){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_654_setMapValue) HXDLIN( 654) ::haxe::IMap_obj::set( ::hx::interface_check(map,0x09c2bd39),key,value); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,setMapValue,(void)) ::Dynamic Interp_obj::get( ::Dynamic o,::String f){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_657_get) HXLINE( 658) if (::hx::IsNull( o )) { HXLINE( 658) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f); HXDLIN( 658) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 659) return ::Reflect_obj::getProperty(o,f); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,get,return ) ::Dynamic Interp_obj::set( ::Dynamic o,::String f, ::Dynamic v){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_673_set) HXLINE( 674) if (::hx::IsNull( o )) { HXLINE( 674) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f); HXDLIN( 674) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 675) ::Reflect_obj::setProperty(o,f,v); HXLINE( 676) return v; } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,set,return ) ::Dynamic Interp_obj::fcall( ::Dynamic o,::String f,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_680_fcall) HXDLIN( 680) return this->call(o,this->get(o,f),args); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,fcall,return ) ::Dynamic Interp_obj::call( ::Dynamic o, ::Dynamic f,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_684_call) HXDLIN( 684) return ::Reflect_obj::callMethod(o,f,args); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,call,return ) ::Dynamic Interp_obj::cnew(::String cl,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_687_cnew) HXLINE( 688) ::hx::Class c = ::Type_obj::resolveClass(cl); HXLINE( 689) if (::hx::IsNull( c )) { HXLINE( 689) c = this->resolve(cl); } HXLINE( 690) return ::Type_obj::createInstance(c,args); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,cnew,return ) ::hx::ObjectPtr< Interp_obj > Interp_obj::__new() { ::hx::ObjectPtr< Interp_obj > __this = new Interp_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< Interp_obj > Interp_obj::__alloc(::hx::Ctx *_hx_ctx) { Interp_obj *__this = (Interp_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(Interp_obj), true, "hscript.Interp")); *(void **)__this = Interp_obj::_hx_vtable; __this->__construct(); return __this; } Interp_obj::Interp_obj() { } void Interp_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Interp); HX_MARK_MEMBER_NAME(variables,"variables"); HX_MARK_MEMBER_NAME(locals,"locals"); HX_MARK_MEMBER_NAME(binops,"binops"); HX_MARK_MEMBER_NAME(depth,"depth"); HX_MARK_MEMBER_NAME(inTry,"inTry"); HX_MARK_MEMBER_NAME(declared,"declared"); HX_MARK_MEMBER_NAME(returnValue,"returnValue"); HX_MARK_END_CLASS(); } void Interp_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(variables,"variables"); HX_VISIT_MEMBER_NAME(locals,"locals"); HX_VISIT_MEMBER_NAME(binops,"binops"); HX_VISIT_MEMBER_NAME(depth,"depth"); HX_VISIT_MEMBER_NAME(inTry,"inTry"); HX_VISIT_MEMBER_NAME(declared,"declared"); HX_VISIT_MEMBER_NAME(returnValue,"returnValue"); } ::hx::Val Interp_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"get") ) { return ::hx::Val( get_dyn() ); } if (HX_FIELD_EQ(inName,"set") ) { return ::hx::Val( set_dyn() ); } break; case 4: if (HX_FIELD_EQ(inName,"expr") ) { return ::hx::Val( expr_dyn() ); } if (HX_FIELD_EQ(inName,"call") ) { return ::hx::Val( call_dyn() ); } if (HX_FIELD_EQ(inName,"cnew") ) { return ::hx::Val( cnew_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"depth") ) { return ::hx::Val( depth ); } if (HX_FIELD_EQ(inName,"inTry") ) { return ::hx::Val( inTry ); } if (HX_FIELD_EQ(inName,"error") ) { return ::hx::Val( error_dyn() ); } if (HX_FIELD_EQ(inName,"isMap") ) { return ::hx::Val( isMap_dyn() ); } if (HX_FIELD_EQ(inName,"fcall") ) { return ::hx::Val( fcall_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"locals") ) { return ::hx::Val( locals ); } if (HX_FIELD_EQ(inName,"binops") ) { return ::hx::Val( binops ); } if (HX_FIELD_EQ(inName,"assign") ) { return ::hx::Val( assign_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"initOps") ) { return ::hx::Val( initOps_dyn() ); } if (HX_FIELD_EQ(inName,"execute") ) { return ::hx::Val( execute_dyn() ); } if (HX_FIELD_EQ(inName,"restore") ) { return ::hx::Val( restore_dyn() ); } if (HX_FIELD_EQ(inName,"rethrow") ) { return ::hx::Val( rethrow_dyn() ); } if (HX_FIELD_EQ(inName,"resolve") ) { return ::hx::Val( resolve_dyn() ); } if (HX_FIELD_EQ(inName,"forLoop") ) { return ::hx::Val( forLoop_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"declared") ) { return ::hx::Val( declared ); } if (HX_FIELD_EQ(inName,"posInfos") ) { return ::hx::Val( posInfos_dyn() ); } if (HX_FIELD_EQ(inName,"assignOp") ) { return ::hx::Val( assignOp_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"variables") ) { return ::hx::Val( variables ); } if (HX_FIELD_EQ(inName,"increment") ) { return ::hx::Val( increment_dyn() ); } if (HX_FIELD_EQ(inName,"duplicate") ) { return ::hx::Val( duplicate_dyn() ); } if (HX_FIELD_EQ(inName,"whileLoop") ) { return ::hx::Val( whileLoop_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"exprReturn") ) { return ::hx::Val( exprReturn_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"returnValue") ) { return ::hx::Val( returnValue ); } if (HX_FIELD_EQ(inName,"doWhileLoop") ) { return ::hx::Val( doWhileLoop_dyn() ); } if (HX_FIELD_EQ(inName,"getMapValue") ) { return ::hx::Val( getMapValue_dyn() ); } if (HX_FIELD_EQ(inName,"setMapValue") ) { return ::hx::Val( setMapValue_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"evalAssignOp") ) { return ::hx::Val( evalAssignOp_dyn() ); } if (HX_FIELD_EQ(inName,"makeIterator") ) { return ::hx::Val( makeIterator_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"resetVariables") ) { return ::hx::Val( resetVariables_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val Interp_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"depth") ) { depth=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"inTry") ) { inTry=inValue.Cast< bool >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"locals") ) { locals=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } if (HX_FIELD_EQ(inName,"binops") ) { binops=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"declared") ) { declared=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"variables") ) { variables=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"returnValue") ) { returnValue=inValue.Cast< ::Dynamic >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Interp_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("variables",b7,e2,62,82)); outFields->push(HX_("locals",a8,74,bf,59)); outFields->push(HX_("binops",cb,59,16,ed)); outFields->push(HX_("depth",03,f1,29,d7)); outFields->push(HX_("inTry",56,82,08,be)); outFields->push(HX_("declared",fa,58,bc,c4)); outFields->push(HX_("returnValue",a1,4c,95,3e)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo Interp_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,variables),HX_("variables",b7,e2,62,82)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,locals),HX_("locals",a8,74,bf,59)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,binops),HX_("binops",cb,59,16,ed)}, {::hx::fsInt,(int)offsetof(Interp_obj,depth),HX_("depth",03,f1,29,d7)}, {::hx::fsBool,(int)offsetof(Interp_obj,inTry),HX_("inTry",56,82,08,be)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(Interp_obj,declared),HX_("declared",fa,58,bc,c4)}, {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(Interp_obj,returnValue),HX_("returnValue",a1,4c,95,3e)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *Interp_obj_sStaticStorageInfo = 0; #endif static ::String Interp_obj_sMemberFields[] = { HX_("variables",b7,e2,62,82), HX_("locals",a8,74,bf,59), HX_("binops",cb,59,16,ed), HX_("depth",03,f1,29,d7), HX_("inTry",56,82,08,be), HX_("declared",fa,58,bc,c4), HX_("returnValue",a1,4c,95,3e), HX_("resetVariables",e8,46,d3,dc), HX_("posInfos",11,82,2e,5a), HX_("initOps",02,63,8b,cb), HX_("assign",2f,46,06,4c), HX_("assignOp",30,b5,c7,0e), HX_("evalAssignOp",ec,d8,94,19), HX_("increment",2f,06,ff,31), HX_("execute",35,0a,0d,cc), HX_("exprReturn",c5,6b,ed,86), HX_("duplicate",8b,21,17,a1), HX_("restore",4e,67,b0,6a), HX_("error",c8,cb,29,73), HX_("rethrow",93,b0,2a,f6), HX_("resolve",ec,12,60,67), HX_("expr",35,fd,1d,43), HX_("doWhileLoop",aa,01,97,3a), HX_("whileLoop",b5,42,98,e1), HX_("makeIterator",fc,dd,72,d8), HX_("forLoop",0d,52,69,c9), HX_("isMap",d2,34,51,c1), HX_("getMapValue",eb,b1,ee,ce), HX_("setMapValue",f7,b8,5b,d9), HX_("get",96,80,4e,00), HX_("set",a2,9b,57,00), HX_("fcall",04,44,99,fc), HX_("call",9e,18,ba,41), HX_("cnew",dd,ef,c3,41), ::String(null()) }; ::hx::Class Interp_obj::__mClass; void Interp_obj::__register() { Interp_obj _hx_dummy; Interp_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("hscript.Interp",8f,7c,f0,9a); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(Interp_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< Interp_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Interp_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Interp_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace hscript
45.063174
243
0.593745
VehpuS
0e6bd6d6bc339c0f81a55ce13fba199d7f92a883
2,451
cpp
C++
gm/imageresizetiled.cpp
llluiop/skia
0dd01ee5b5abc06935dced8430d5290c6ac3f958
[ "BSD-3-Clause" ]
1
2015-11-06T00:05:58.000Z
2015-11-06T00:05:58.000Z
gm/imageresizetiled.cpp
rgraebert/skia
33a4b46e9f24be6268855478b5c895f883fb4ac5
[ "BSD-3-Clause" ]
null
null
null
gm/imageresizetiled.cpp
rgraebert/skia
33a4b46e9f24be6268855478b5c895f883fb4ac5
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2014 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 "SkMatrixImageFilter.h" #include "SkRandom.h" #define WIDTH 640 #define HEIGHT 480 #define RESIZE_FACTOR SkIntToScalar(2) namespace skiagm { class ImageResizeTiledGM : public GM { public: ImageResizeTiledGM() { } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("imageresizetiled"); } virtual SkISize onISize() SK_OVERRIDE { return make_isize(WIDTH, HEIGHT); } virtual uint32_t onGetFlags() const SK_OVERRIDE { return kSkipTiled_Flag; } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { SkPaint paint; SkMatrix matrix; matrix.setScale(RESIZE_FACTOR, RESIZE_FACTOR); SkAutoTUnref<SkImageFilter> imageFilter( SkMatrixImageFilter::Create(matrix, SkPaint::kNone_FilterLevel)); paint.setImageFilter(imageFilter.get()); const SkScalar tile_size = SkIntToScalar(100); SkRect bounds; canvas->getClipBounds(&bounds); for (SkScalar y = 0; y < HEIGHT; y += tile_size) { for (SkScalar x = 0; x < WIDTH; x += tile_size) { canvas->save(); canvas->clipRect(SkRect::MakeXYWH(x, y, tile_size, tile_size)); canvas->scale(SkScalarInvert(RESIZE_FACTOR), SkScalarInvert(RESIZE_FACTOR)); canvas->saveLayer(NULL, &paint); const char* str[] = { "The quick", "brown fox", "jumped over", "the lazy dog.", }; SkPaint textPaint; textPaint.setAntiAlias(true); textPaint.setTextSize(SkIntToScalar(100)); int posY = 0; for (unsigned i = 0; i < SK_ARRAY_COUNT(str); i++) { posY += 100; canvas->drawText(str[i], strlen(str[i]), SkIntToScalar(0), SkIntToScalar(posY), textPaint); } canvas->restore(); canvas->restore(); } } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ImageResizeTiledGM(); ) }
29.178571
79
0.53774
llluiop
0e6f241d5b39be52ee550570a5563c2a42aa7e27
3,998
cpp
C++
driver/src/visitor/ScopedModifier.cpp
pranavsubramani/Birch
0a4bb698ed44353c8e8b93d234f2941d7511683c
[ "Apache-2.0" ]
null
null
null
driver/src/visitor/ScopedModifier.cpp
pranavsubramani/Birch
0a4bb698ed44353c8e8b93d234f2941d7511683c
[ "Apache-2.0" ]
null
null
null
driver/src/visitor/ScopedModifier.cpp
pranavsubramani/Birch
0a4bb698ed44353c8e8b93d234f2941d7511683c
[ "Apache-2.0" ]
null
null
null
/** * @file */ #include "src/visitor/ScopedModifier.hpp" birch::ScopedModifier::ScopedModifier(Package* currentPackage, Class* currentClass) : ContextualModifier(currentPackage, currentClass), inMember(0), inGlobal(0) { if (currentPackage) { scopes.push_back(currentPackage->scope); if (currentClass) { scopes.push_back(currentClass->scope); } } } birch::ScopedModifier::~ScopedModifier() { // } birch::Package* birch::ScopedModifier::modify(Package* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Expression* birch::ScopedModifier::modify(LambdaFunction* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Expression* birch::ScopedModifier::modify(Member* o) { o->left = o->left->accept(this); ++inMember; o->right = o->right->accept(this); --inMember; return o; } birch::Expression* birch::ScopedModifier::modify(Global* o) { ++inGlobal; o->single = o->single->accept(this); --inGlobal; return o; } birch::Statement* birch::ScopedModifier::modify(MemberFunction* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Function* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(BinaryOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(UnaryOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Program* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(AssignmentOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(ConversionOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Class* o) { this->currentClass = o; scopes.push_back(o->scope); o->typeParams = o->typeParams->accept(this); o->base = o->base->accept(this); scopes.push_back(o->initScope); o->params = o->params->accept(this); o->args = o->args->accept(this); scopes.pop_back(); o->braces = o->braces->accept(this); scopes.pop_back(); this->currentClass = nullptr; return o; } birch::Statement* birch::ScopedModifier::modify(If* o) { scopes.push_back(o->scope); o->cond = o->cond->accept(this); o->braces = o->braces->accept(this); scopes.pop_back(); scopes.push_back(o->falseScope); o->falseBraces = o->falseBraces->accept(this); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(For* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Parallel* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(While* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(DoWhile* o) { scopes.push_back(o->scope); o->braces = o->braces->accept(this); scopes.pop_back(); o->cond = o->cond->accept(this); return o; } birch::Statement* birch::ScopedModifier::modify(With* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Block* o) { scopes.push_back(o->scope); o->braces = o->braces->accept(this); scopes.pop_back(); return o; }
23.656805
72
0.690595
pranavsubramani
0e6f7fd5bbea687cc6ca4a486d5a07f877207dab
3,380
cc
C++
example/Mcached/mraft/floyd/example/simple/t1.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-27T09:10:11.000Z
2018-09-27T09:10:11.000Z
example/Mcached/mraft/floyd/example/simple/t1.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-16T07:17:29.000Z
2018-09-16T07:17:29.000Z
example/Mcached/mraft/floyd/example/simple/t1.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
null
null
null
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include <pthread.h> #include <signal.h> #include <iostream> #include <string> #include "floyd/include/floyd.h" #include "slash/include/testutil.h" using namespace floyd; uint64_t NowMicros() { struct timeval tv; gettimeofday(&tv, NULL); return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; } Floyd *f1, *f2, *f3, *f4, *f5; std::string keystr[1001000]; std::string valstr[1001000]; int val_size = 128; int thread_num = 4; int item_num = 10000; void *fun(void *arg) { int i = 1; Floyd *p; if (f1->IsLeader()) { p = f1; } else if (f2->IsLeader()) { p = f2; } else if (f3->IsLeader()) { p = f3; } else if (f4->IsLeader()) { p = f4; } else { p = f5; } while (i--) { for (int j = 0; j < item_num; j++) { p->Write(keystr[j], valstr[j]); } } } int main(int argc, char * argv[]) { if (argc > 1) { thread_num = atoi(argv[1]); } if (argc > 2) { val_size = atoi(argv[2]); } if (argc > 3) { item_num = atoi(argv[3]); } printf("multi threads test to get performance thread num %d key size %d item number %d\n", thread_num, val_size, item_num); Options op1("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8901, "./data1/"); slash::Status s = Floyd::Open(op1, &f1); printf("%s\n", s.ToString().c_str()); Options op2("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8902, "./data2/"); s = Floyd::Open(op2, &f2); printf("%s\n", s.ToString().c_str()); Options op3("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8903, "./data3/"); s = Floyd::Open(op3, &f3); printf("%s\n", s.ToString().c_str()); Options op4("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8904, "./data4/"); s = Floyd::Open(op4, &f4); printf("%s\n", s.ToString().c_str()); Options op5("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8905, "./data5/"); s = Floyd::Open(op5, &f5); printf("%s\n", s.ToString().c_str()); std::string msg; int i = 10; uint64_t st = NowMicros(), ed; for (int i = 0; i < item_num; i++) { keystr[i] = slash::RandomString(32); } for (int i = 0; i < item_num; i++) { valstr[i] = slash::RandomString(val_size); } while (1) { if (f1->HasLeader()) { f1->GetServerStatus(&msg); printf("%s\n", msg.c_str()); break; } printf("electing leader... sleep 2s\n"); sleep(2); } pthread_t pid[24]; st = NowMicros(); for (int i = 0; i < thread_num; i++) { pthread_create(&pid[i], NULL, fun, NULL); } for (int i = 0; i < thread_num; i++) { pthread_join(pid[i], NULL); } ed = NowMicros(); printf("write %d datas cost time microsecond(us) %ld, qps %llu\n", item_num * thread_num, ed - st, item_num * thread_num * 1000000LL / (ed - st)); getchar(); delete f2; delete f3; delete f4; delete f5; delete f1; return 0; }
27.04
148
0.595266
fasShare
0e702dca9016f0b45aac2e65410bd313a18e8745
34,122
hpp
C++
libs/boost_1_72_0/boost/spirit/home/support/char_encoding/unicode/uppercase_table.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/spirit/home/support/char_encoding/unicode/uppercase_table.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/spirit/home/support/char_encoding/unicode/uppercase_table.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) AUTOGENERATED. DO NOT EDIT!!! ==============================================================================*/ #include <boost/cstdint.hpp> namespace boost { namespace spirit { namespace ucd { namespace detail { static const ::boost::uint8_t uppercase_stage1[] = { 0, 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 8, 9, 6, 10, 6, 6, 11, 6, 6, 6, 6, 6, 6, 6, 12, 13, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 14, 15, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 16, 6, 6, 6, 6, 17, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}; static const ::boost::uint32_t uppercase_stage2[] = { // block 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 924, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 0, 216, 217, 218, 219, 220, 221, 222, 376, // block 1 0, 256, 0, 258, 0, 260, 0, 262, 0, 264, 0, 266, 0, 268, 0, 270, 0, 272, 0, 274, 0, 276, 0, 278, 0, 280, 0, 282, 0, 284, 0, 286, 0, 288, 0, 290, 0, 292, 0, 294, 0, 296, 0, 298, 0, 300, 0, 302, 0, 73, 0, 306, 0, 308, 0, 310, 0, 0, 313, 0, 315, 0, 317, 0, 319, 0, 321, 0, 323, 0, 325, 0, 327, 0, 0, 330, 0, 332, 0, 334, 0, 336, 0, 338, 0, 340, 0, 342, 0, 344, 0, 346, 0, 348, 0, 350, 0, 352, 0, 354, 0, 356, 0, 358, 0, 360, 0, 362, 0, 364, 0, 366, 0, 368, 0, 370, 0, 372, 0, 374, 0, 0, 377, 0, 379, 0, 381, 83, 579, 0, 0, 386, 0, 388, 0, 0, 391, 0, 0, 0, 395, 0, 0, 0, 0, 0, 401, 0, 0, 502, 0, 0, 0, 408, 573, 0, 0, 0, 544, 0, 0, 416, 0, 418, 0, 420, 0, 0, 423, 0, 0, 0, 0, 428, 0, 0, 431, 0, 0, 0, 435, 0, 437, 0, 0, 440, 0, 0, 0, 444, 0, 503, 0, 0, 0, 0, 0, 452, 452, 0, 455, 455, 0, 458, 458, 0, 461, 0, 463, 0, 465, 0, 467, 0, 469, 0, 471, 0, 473, 0, 475, 398, 0, 478, 0, 480, 0, 482, 0, 484, 0, 486, 0, 488, 0, 490, 0, 492, 0, 494, 0, 0, 497, 497, 0, 500, 0, 0, 0, 504, 0, 506, 0, 508, 0, 510, // block 2 0, 512, 0, 514, 0, 516, 0, 518, 0, 520, 0, 522, 0, 524, 0, 526, 0, 528, 0, 530, 0, 532, 0, 534, 0, 536, 0, 538, 0, 540, 0, 542, 0, 0, 0, 546, 0, 548, 0, 550, 0, 552, 0, 554, 0, 556, 0, 558, 0, 560, 0, 562, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, 0, 0, 0, 577, 0, 0, 0, 0, 582, 0, 584, 0, 586, 0, 588, 0, 590, 11375, 11373, 0, 385, 390, 0, 393, 394, 0, 399, 0, 400, 0, 0, 0, 0, 403, 0, 0, 404, 0, 0, 0, 0, 407, 406, 0, 11362, 0, 0, 0, 412, 0, 11374, 413, 0, 0, 415, 0, 0, 0, 0, 0, 0, 0, 11364, 0, 0, 422, 0, 0, 425, 0, 0, 0, 0, 430, 580, 433, 434, 581, 0, 0, 0, 0, 0, 439, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 3 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 921, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 880, 0, 882, 0, 0, 0, 886, 0, 0, 0, 1021, 1022, 1023, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 902, 904, 905, 906, 0, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 931, 932, 933, 934, 935, 936, 937, 938, 939, 908, 910, 911, 0, 914, 920, 0, 0, 0, 934, 928, 975, 0, 984, 0, 986, 0, 988, 0, 990, 0, 992, 0, 994, 0, 996, 0, 998, 0, 1000, 0, 1002, 0, 1004, 0, 1006, 922, 929, 1017, 0, 0, 917, 0, 0, 1015, 0, 0, 1018, 0, 0, 0, 0, // block 4 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 0, 1120, 0, 1122, 0, 1124, 0, 1126, 0, 1128, 0, 1130, 0, 1132, 0, 1134, 0, 1136, 0, 1138, 0, 1140, 0, 1142, 0, 1144, 0, 1146, 0, 1148, 0, 1150, 0, 1152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1162, 0, 1164, 0, 1166, 0, 1168, 0, 1170, 0, 1172, 0, 1174, 0, 1176, 0, 1178, 0, 1180, 0, 1182, 0, 1184, 0, 1186, 0, 1188, 0, 1190, 0, 1192, 0, 1194, 0, 1196, 0, 1198, 0, 1200, 0, 1202, 0, 1204, 0, 1206, 0, 1208, 0, 1210, 0, 1212, 0, 1214, 0, 0, 1217, 0, 1219, 0, 1221, 0, 1223, 0, 1225, 0, 1227, 0, 1229, 1216, 0, 1232, 0, 1234, 0, 1236, 0, 1238, 0, 1240, 0, 1242, 0, 1244, 0, 1246, 0, 1248, 0, 1250, 0, 1252, 0, 1254, 0, 1256, 0, 1258, 0, 1260, 0, 1262, 0, 1264, 0, 1266, 0, 1268, 0, 1270, 0, 1272, 0, 1274, 0, 1276, 0, 1278, // block 5 0, 1280, 0, 1282, 0, 1284, 0, 1286, 0, 1288, 0, 1290, 0, 1292, 0, 1294, 0, 1296, 0, 1298, 0, 1300, 0, 1302, 0, 1304, 0, 1306, 0, 1308, 0, 1310, 0, 1312, 0, 1314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 6 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42877, 0, 0, 0, 11363, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 8 0, 7680, 0, 7682, 0, 7684, 0, 7686, 0, 7688, 0, 7690, 0, 7692, 0, 7694, 0, 7696, 0, 7698, 0, 7700, 0, 7702, 0, 7704, 0, 7706, 0, 7708, 0, 7710, 0, 7712, 0, 7714, 0, 7716, 0, 7718, 0, 7720, 0, 7722, 0, 7724, 0, 7726, 0, 7728, 0, 7730, 0, 7732, 0, 7734, 0, 7736, 0, 7738, 0, 7740, 0, 7742, 0, 7744, 0, 7746, 0, 7748, 0, 7750, 0, 7752, 0, 7754, 0, 7756, 0, 7758, 0, 7760, 0, 7762, 0, 7764, 0, 7766, 0, 7768, 0, 7770, 0, 7772, 0, 7774, 0, 7776, 0, 7778, 0, 7780, 0, 7782, 0, 7784, 0, 7786, 0, 7788, 0, 7790, 0, 7792, 0, 7794, 0, 7796, 0, 7798, 0, 7800, 0, 7802, 0, 7804, 0, 7806, 0, 7808, 0, 7810, 0, 7812, 0, 7814, 0, 7816, 0, 7818, 0, 7820, 0, 7822, 0, 7824, 0, 7826, 0, 7828, 0, 0, 0, 0, 0, 7776, 0, 0, 0, 0, 0, 7840, 0, 7842, 0, 7844, 0, 7846, 0, 7848, 0, 7850, 0, 7852, 0, 7854, 0, 7856, 0, 7858, 0, 7860, 0, 7862, 0, 7864, 0, 7866, 0, 7868, 0, 7870, 0, 7872, 0, 7874, 0, 7876, 0, 7878, 0, 7880, 0, 7882, 0, 7884, 0, 7886, 0, 7888, 0, 7890, 0, 7892, 0, 7894, 0, 7896, 0, 7898, 0, 7900, 0, 7902, 0, 7904, 0, 7906, 0, 7908, 0, 7910, 0, 7912, 0, 7914, 0, 7916, 0, 7918, 0, 7920, 0, 7922, 0, 7924, 0, 7926, 0, 7928, 0, 7930, 0, 7932, 0, 7934, // block 9 7944, 7945, 7946, 7947, 7948, 7949, 7950, 7951, 0, 0, 0, 0, 0, 0, 0, 0, 7960, 7961, 7962, 7963, 7964, 7965, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7976, 7977, 7978, 7979, 7980, 7981, 7982, 7983, 0, 0, 0, 0, 0, 0, 0, 0, 7992, 7993, 7994, 7995, 7996, 7997, 7998, 7999, 0, 0, 0, 0, 0, 0, 0, 0, 8008, 8009, 8010, 8011, 8012, 8013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8025, 0, 8027, 0, 8029, 0, 8031, 0, 0, 0, 0, 0, 0, 0, 0, 8040, 8041, 8042, 8043, 8044, 8045, 8046, 8047, 0, 0, 0, 0, 0, 0, 0, 0, 8122, 8123, 8136, 8137, 8138, 8139, 8154, 8155, 8184, 8185, 8170, 8171, 8186, 8187, 0, 0, 8072, 8073, 8074, 8075, 8076, 8077, 8078, 8079, 0, 0, 0, 0, 0, 0, 0, 0, 8088, 8089, 8090, 8091, 8092, 8093, 8094, 8095, 0, 0, 0, 0, 0, 0, 0, 0, 8104, 8105, 8106, 8107, 8108, 8109, 8110, 8111, 0, 0, 0, 0, 0, 0, 0, 0, 8120, 8121, 0, 8124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 921, 0, 0, 0, 0, 8140, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8152, 8153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8168, 8169, 0, 0, 0, 8172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8188, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 10 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553, 8554, 8555, 8556, 8557, 8558, 8559, 0, 0, 0, 0, 8579, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 11 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9398, 9399, 9400, 9401, 9402, 9403, 9404, 9405, 9406, 9407, 9408, 9409, 9410, 9411, 9412, 9413, 9414, 9415, 9416, 9417, 9418, 9419, 9420, 9421, 9422, 9423, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 12 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11264, 11265, 11266, 11267, 11268, 11269, 11270, 11271, 11272, 11273, 11274, 11275, 11276, 11277, 11278, 11279, 11280, 11281, 11282, 11283, 11284, 11285, 11286, 11287, 11288, 11289, 11290, 11291, 11292, 11293, 11294, 11295, 11296, 11297, 11298, 11299, 11300, 11301, 11302, 11303, 11304, 11305, 11306, 11307, 11308, 11309, 11310, 0, 0, 11360, 0, 0, 0, 570, 574, 0, 11367, 0, 11369, 0, 11371, 0, 0, 0, 0, 0, 0, 11378, 0, 0, 11381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11392, 0, 11394, 0, 11396, 0, 11398, 0, 11400, 0, 11402, 0, 11404, 0, 11406, 0, 11408, 0, 11410, 0, 11412, 0, 11414, 0, 11416, 0, 11418, 0, 11420, 0, 11422, 0, 11424, 0, 11426, 0, 11428, 0, 11430, 0, 11432, 0, 11434, 0, 11436, 0, 11438, 0, 11440, 0, 11442, 0, 11444, 0, 11446, 0, 11448, 0, 11450, 0, 11452, 0, 11454, 0, 11456, 0, 11458, 0, 11460, 0, 11462, 0, 11464, 0, 11466, 0, 11468, 0, 11470, 0, 11472, 0, 11474, 0, 11476, 0, 11478, 0, 11480, 0, 11482, 0, 11484, 0, 11486, 0, 11488, 0, 11490, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 13 4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 14 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42560, 0, 42562, 0, 42564, 0, 42566, 0, 42568, 0, 42570, 0, 42572, 0, 42574, 0, 42576, 0, 42578, 0, 42580, 0, 42582, 0, 42584, 0, 42586, 0, 42588, 0, 42590, 0, 0, 0, 42594, 0, 42596, 0, 42598, 0, 42600, 0, 42602, 0, 42604, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42624, 0, 42626, 0, 42628, 0, 42630, 0, 42632, 0, 42634, 0, 42636, 0, 42638, 0, 42640, 0, 42642, 0, 42644, 0, 42646, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42786, 0, 42788, 0, 42790, 0, 42792, 0, 42794, 0, 42796, 0, 42798, 0, 0, 0, 42802, 0, 42804, 0, 42806, 0, 42808, 0, 42810, 0, 42812, 0, 42814, 0, 42816, 0, 42818, 0, 42820, 0, 42822, 0, 42824, 0, 42826, 0, 42828, 0, 42830, 0, 42832, 0, 42834, 0, 42836, 0, 42838, 0, 42840, 0, 42842, 0, 42844, 0, 42846, 0, 42848, 0, 42850, 0, 42852, 0, 42854, 0, 42856, 0, 42858, 0, 42860, 0, 42862, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42873, 0, 42875, 0, 0, 42878, 0, 42880, 0, 42882, 0, 42884, 0, 42886, 0, 0, 0, 0, 42891, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 16 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65313, 65314, 65315, 65316, 65317, 65318, 65319, 65320, 65321, 65322, 65323, 65324, 65325, 65326, 65327, 65328, 65329, 65330, 65331, 65332, 65333, 65334, 65335, 65336, 65337, 65338, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 17 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66560, 66561, 66562, 66563, 66564, 66565, 66566, 66567, 66568, 66569, 66570, 66571, 66572, 66573, 66574, 66575, 66576, 66577, 66578, 66579, 66580, 66581, 66582, 66583, 66584, 66585, 66586, 66587, 66588, 66589, 66590, 66591, 66592, 66593, 66594, 66595, 66596, 66597, 66598, 66599, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; inline ::boost::uint32_t uppercase_lookup(::boost::uint32_t ch) { ::boost::uint32_t block_offset = uppercase_stage1[ch / 256] * 256; return uppercase_stage2[block_offset + ch % 256]; } } // namespace detail } // namespace ucd } // namespace spirit } // namespace boost
69.636735
80
0.370523
henrywarhurst
0e70deb4357fff835a0badeff42683287d3c0720
677
cpp
C++
solutions/1066/union_find.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
44
2016-05-11T06:41:14.000Z
2021-12-20T13:45:41.000Z
solutions/1066/union_find.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
null
null
null
solutions/1066/union_find.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
10
2016-06-25T08:55:20.000Z
2018-07-06T05:52:53.000Z
#include <iostream> #include <map> using namespace std; map<string, string> s; string represent(string n1) { if (s[n1].empty() || s[n1] == n1) { s[n1] = n1; } else { s[n1] = represent(s[n1]); } return s[n1]; } void merge(string n1, string n2) { s[represent(n1)] = represent(n2); } string find(string n1, string n2) { return represent(n1) == represent(n2) ? "yes" : "no"; } int main(void) { int n; cin >> n; int op; string n1, n2; for (int i = 0; i < n; ++i) { cin >> op >> n1 >> n2; if (op) cout << find(n1, n2) << endl; else merge(n1, n2); } return 0; }
15.744186
57
0.487445
buptlxb
0e715472e2692b00d0d0bc907f97db25fa5abcf1
348
cc
C++
tests/cpp/metric/test_metric.cc
cnheider/xgboost
e7fbc8591fa7277ee4c474b7371c48c11b34cbde
[ "Apache-2.0" ]
40
2017-02-05T07:58:44.000Z
2022-01-25T22:53:00.000Z
tests/cpp/metric/test_metric.cc
cnheider/xgboost
e7fbc8591fa7277ee4c474b7371c48c11b34cbde
[ "Apache-2.0" ]
26
2017-06-01T05:41:01.000Z
2020-11-30T08:56:48.000Z
tests/cpp/metric/test_metric.cc
cnheider/xgboost
e7fbc8591fa7277ee4c474b7371c48c11b34cbde
[ "Apache-2.0" ]
27
2017-04-12T13:15:48.000Z
2020-04-12T08:43:51.000Z
// Copyright by Contributors #include <xgboost/metric.h> #include "../helpers.h" TEST(Metric, UnknownMetric) { EXPECT_ANY_THROW(xgboost::Metric::Create("unknown_name")); EXPECT_NO_THROW(xgboost::Metric::Create("rmse")); EXPECT_ANY_THROW(xgboost::Metric::Create("unknown_name@1")); EXPECT_NO_THROW(xgboost::Metric::Create("error@0.5")); }
29
62
0.735632
cnheider
0e722eed8c45c96f945f86eea8b4167941be023f
737
hpp
C++
src/lib/ecl/matrix/matrix/Scalar.hpp
shening/PX4-1.34-Vision-Fix
1e696bc1c2dae71ba7b277d40106a5b6c0a1a050
[ "BSD-3-Clause" ]
24
2019-08-13T02:39:01.000Z
2022-03-03T15:44:54.000Z
src/lib/ecl/matrix/matrix/Scalar.hpp
shening/PX4-1.34-Vision-Fix
1e696bc1c2dae71ba7b277d40106a5b6c0a1a050
[ "BSD-3-Clause" ]
4
2020-11-16T02:03:09.000Z
2021-08-19T08:16:48.000Z
src/lib/ecl/matrix/matrix/Scalar.hpp
shening/PX4-1.34-Vision-Fix
1e696bc1c2dae71ba7b277d40106a5b6c0a1a050
[ "BSD-3-Clause" ]
11
2019-07-28T09:11:40.000Z
2022-03-17T08:08:27.000Z
/** * @file Scalar.hpp * * Defines conversion of matrix to scalar. * * @author James Goppert <james.goppert@gmail.com> */ #pragma once #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "math.hpp" namespace matrix { template<typename Type> class Scalar { public: virtual ~Scalar() {}; Scalar() : _value() { } Scalar(const Matrix<Type, 1, 1> & other) { _value = other(0,0); } Scalar(float other) { _value = other; } operator Type() { return _value; } private: Type _value; }; typedef Scalar<float> Scalarf; } // namespace matrix /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
13.160714
54
0.587517
shening
0e740451d792f20641256e992647134aab9abfd4
767
cpp
C++
foo_dsp_effect/main.cpp
jpbattaille/foobar2000-plugins
2e52c26a9ab5e65091338e600a2c433d8b600704
[ "Unlicense" ]
null
null
null
foo_dsp_effect/main.cpp
jpbattaille/foobar2000-plugins
2e52c26a9ab5e65091338e600a2c433d8b600704
[ "Unlicense" ]
null
null
null
foo_dsp_effect/main.cpp
jpbattaille/foobar2000-plugins
2e52c26a9ab5e65091338e600a2c433d8b600704
[ "Unlicense" ]
null
null
null
#include "../SDK/foobar2000.h" #include "SoundTouch/SoundTouch.h" #include "dsp_guids.h" #define MYVERSION "0.42" static pfc::string_formatter g_get_component_about() { pfc::string_formatter about; about << "A special effect DSP for foobar2000.\n"; about << "Written by mudlord (mudlord@protonmail.com).\n"; about << "Portions by Jon Watte, Jezar Wakefield, Chris Snowhill.\n"; about << "Using SoundTouch library version " << SOUNDTOUCH_VERSION << "\n"; about << "SoundTouch (c) Olli Parviainen\n"; about << "\n"; about << "License: https://github.com/mudlord/foobar2000-plugins/blob/master/LICENSE.md"; return about; } DECLARE_COMPONENT_VERSION_COPY( "Effect DSP", MYVERSION, g_get_component_about() ); VALIDATE_COMPONENT_FILENAME("foo_dsp_effect.dll");
29.5
90
0.73794
jpbattaille
0e744b167659afb78c417ea63bdb4f005dff6ff3
7,804
cpp
C++
cores/n64/GLideN64/src/Graphics/Context.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
7
2020-07-20T12:11:35.000Z
2021-12-23T02:09:19.000Z
cores/n64/GLideN64/src/Graphics/Context.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
null
null
null
cores/n64/GLideN64/src/Graphics/Context.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
1
2020-08-29T16:36:48.000Z
2020-08-29T16:36:48.000Z
#include "Context.h" #include "OpenGLContext/opengl_ContextImpl.h" using namespace graphics; Context gfxContext; bool Context::Multisampling = false; bool Context::BlitFramebuffer = false; bool Context::WeakBlitFramebuffer = false; bool Context::DepthFramebufferTextures = false; bool Context::ShaderProgramBinary = false; bool Context::ImageTextures = false; bool Context::IntegerTextures = false; bool Context::ClipControl = false; bool Context::FramebufferFetch = false; bool Context::TextureBarrier = false; bool Context::EglImage = false; bool Context::EglImageFramebuffer = false; Context::Context() {} Context::~Context() { m_impl.reset(); } void Context::init() { m_impl.reset(new opengl::ContextImpl); m_impl->init(); m_fbTexFormats.reset(m_impl->getFramebufferTextureFormats()); Multisampling = m_impl->isSupported(SpecialFeatures::Multisampling); BlitFramebuffer = m_impl->isSupported(SpecialFeatures::BlitFramebuffer); WeakBlitFramebuffer = m_impl->isSupported(SpecialFeatures::WeakBlitFramebuffer); DepthFramebufferTextures = m_impl->isSupported(SpecialFeatures::DepthFramebufferTextures); ShaderProgramBinary = m_impl->isSupported(SpecialFeatures::ShaderProgramBinary); ImageTextures = m_impl->isSupported(SpecialFeatures::ImageTextures); IntegerTextures = m_impl->isSupported(SpecialFeatures::IntegerTextures); ClipControl = m_impl->isSupported(SpecialFeatures::ClipControl); FramebufferFetch = m_impl->isSupported(SpecialFeatures::FramebufferFetch); TextureBarrier = m_impl->isSupported(SpecialFeatures::TextureBarrier); EglImage = m_impl->isSupported(SpecialFeatures::EglImage); EglImageFramebuffer = m_impl->isSupported(SpecialFeatures::EglImageFramebuffer); } void Context::destroy() { m_impl->destroy(); m_impl.reset(); } void Context::setClampMode(ClampMode _mode) { m_impl->setClampMode(_mode); } ClampMode Context::getClampMode() { return m_impl->getClampMode(); } void Context::enable(EnableParam _parameter, bool _enable) { m_impl->enable(_parameter, _enable); } u32 Context::isEnabled(EnableParam _parameter) { return m_impl->isEnabled(_parameter); } void Context::cullFace(CullModeParam _parameter) { m_impl->cullFace(_parameter); } void Context::enableDepthWrite(bool _enable) { m_impl->enableDepthWrite(_enable); } void Context::setDepthCompare(CompareParam _mode) { m_impl->setDepthCompare(_mode); } void Context::setViewport(s32 _x, s32 _y, s32 _width, s32 _height) { m_impl->setViewport(_x, _y, _width, _height); } void Context::setScissor(s32 _x, s32 _y, s32 _width, s32 _height) { m_impl->setScissor(_x, _y, _width, _height); } void Context::setBlending(BlendParam _sfactor, BlendParam _dfactor) { m_impl->setBlending(_sfactor, _dfactor); } void Context::setBlendColor(f32 _red, f32 _green, f32 _blue, f32 _alpha) { m_impl->setBlendColor(_red, _green, _blue, _alpha); } void Context::clearColorBuffer(f32 _red, f32 _green, f32 _blue, f32 _alpha) { m_impl->clearColorBuffer(_red, _green, _blue, _alpha); } void Context::clearDepthBuffer() { m_impl->clearDepthBuffer(); } void Context::setPolygonOffset(f32 _factor, f32 _units) { m_impl->setPolygonOffset(_factor, _units); } ObjectHandle Context::createTexture(Parameter _target) { return m_impl->createTexture(_target); } void Context::deleteTexture(ObjectHandle _name) { m_impl->deleteTexture(_name); } void Context::init2DTexture(const InitTextureParams & _params) { m_impl->init2DTexture(_params); } void Context::update2DTexture(const UpdateTextureDataParams & _params) { m_impl->update2DTexture(_params); } void Context::setTextureParameters(const TexParameters & _parameters) { m_impl->setTextureParameters(_parameters); } void Context::bindTexture(const BindTextureParameters & _params) { m_impl->bindTexture(_params); } void Context::setTextureUnpackAlignment(s32 _param) { m_impl->setTextureUnpackAlignment(_param); } s32 Context::getTextureUnpackAlignment() const { return m_impl->getTextureUnpackAlignment(); } s32 Context::getMaxTextureSize() const { return m_impl->getMaxTextureSize(); } void Context::bindImageTexture(const BindImageTextureParameters & _params) { m_impl->bindImageTexture(_params); } u32 Context::convertInternalTextureFormat(u32 _format) const { return m_impl->convertInternalTextureFormat(_format); } void Context::textureBarrier() { m_impl->textureBarrier(); } /*---------------Framebuffer-------------*/ const FramebufferTextureFormats & Context::getFramebufferTextureFormats() { return *m_fbTexFormats.get(); } ObjectHandle Context::createFramebuffer() { return m_impl->createFramebuffer(); } void Context::deleteFramebuffer(ObjectHandle _name) { m_impl->deleteFramebuffer(_name); } void Context::bindFramebuffer(BufferTargetParam _target, ObjectHandle _name) { m_impl->bindFramebuffer(_target, _name); } ObjectHandle Context::createRenderbuffer() { return m_impl->createRenderbuffer(); } void Context::initRenderbuffer(const InitRenderbufferParams & _params) { m_impl->initRenderbuffer(_params); } void Context::addFrameBufferRenderTarget(const FrameBufferRenderTarget & _params) { m_impl->addFrameBufferRenderTarget(_params); } bool Context::blitFramebuffers(const BlitFramebuffersParams & _params) { return m_impl->blitFramebuffers(_params); } void Context::setDrawBuffers(u32 _num) { m_impl->setDrawBuffers(_num); } PixelReadBuffer * Context::createPixelReadBuffer(size_t _sizeInBytes) { return m_impl->createPixelReadBuffer(_sizeInBytes); } ColorBufferReader * Context::createColorBufferReader(CachedTexture * _pTexture) { return m_impl->createColorBufferReader(_pTexture); } /*---------------Shaders-------------*/ bool Context::isCombinerProgramBuilderObsolete() { return m_impl->isCombinerProgramBuilderObsolete(); } void Context::resetCombinerProgramBuilder() { m_impl->resetCombinerProgramBuilder(); } CombinerProgram * Context::createCombinerProgram(Combiner & _color, Combiner & _alpha, const CombinerKey & _key) { return m_impl->createCombinerProgram(_color, _alpha, _key); } bool Context::saveShadersStorage(const Combiners & _combiners) { return m_impl->saveShadersStorage(_combiners); } bool Context::loadShadersStorage(Combiners & _combiners) { return m_impl->loadShadersStorage(_combiners); } ShaderProgram * Context::createDepthFogShader() { return m_impl->createDepthFogShader(); } TexrectDrawerShaderProgram * Context::createTexrectDrawerDrawShader() { return m_impl->createTexrectDrawerDrawShader(); } ShaderProgram * Context::createTexrectDrawerClearShader() { return m_impl->createTexrectDrawerClearShader(); } ShaderProgram * Context::createTexrectCopyShader() { return m_impl->createTexrectCopyShader(); } ShaderProgram * Context::createTexrectColorAndDepthCopyShader() { return m_impl->createTexrectColorAndDepthCopyShader(); } ShaderProgram * Context::createGammaCorrectionShader() { return m_impl->createGammaCorrectionShader(); } ShaderProgram * Context::createOrientationCorrectionShader() { return m_impl->createOrientationCorrectionShader(); } ShaderProgram * Context::createFXAAShader() { return m_impl->createFXAAShader(); } TextDrawerShaderProgram * Context::createTextDrawerShader() { return m_impl->createTextDrawerShader(); } void Context::resetShaderProgram() { m_impl->resetShaderProgram(); } void Context::drawTriangles(const DrawTriangleParameters & _params) { m_impl->drawTriangles(_params); } void Context::drawRects(const DrawRectParameters & _params) { m_impl->drawRects(_params); } void Context::drawLine(f32 _width, SPVertex * _vertices) { m_impl->drawLine(_width, _vertices); } f32 Context::getMaxLineWidth() { return m_impl->getMaxLineWidth(); } bool Context::isError() const { return m_impl->isError(); } bool Context::isFramebufferError() const { return m_impl->isFramebufferError(); }
22.489914
112
0.782035
wulfebw